cakephp-phpstan icon indicating copy to clipboard operation
cakephp-phpstan copied to clipboard

`fetchTable()` does not properly resolve when used via LocatorAwareTrait in a service class

Open LordSimal opened this issue 1 year ago • 7 comments

<?php
declare(strict_types=1);

namespace App\Service;

use Cake\ORM\Locator\LocatorAwareTrait;

class TestService {
    use LocatorAwareTrait;

    public function test(): void
    {
        $table = $this->fetchTable('MyModel');
        $entity = $table->newEmptyEntity();
        $name = $entity->name;
    }

}

does give the following error

 ------ ------------------------------------------------------------------------- 
  Line   src/Service/TestService.php                                              
 ------ ------------------------------------------------------------------------- 
  15     Access to an undefined property Cake\Datasource\EntityInterface::$name.  
 ------ ------------------------------------------------------------------------- 

but the same 3 lines inside e.g. a controller action work fine.

LordSimal avatar Mar 21 '23 20:03 LordSimal

Just looked through the other issues and this is related to phpstan not supporting trait methods via DynamicReturnTypeExtension https://github.com/phpstan/phpstan/issues/5761

LordSimal avatar Mar 21 '23 20:03 LordSimal

Yes, trait is not supported. If you have a base Service class that uses LocatorAwareTrait you could have phpstan config as it is done at https://github.com/CakeDC/cakephp-phpstan/blob/master/extension.neon#L13 . Note that $this->getTableLocator()->get('MyModel') should not cause error with phpstan.

rochamarcelo avatar Mar 23 '23 13:03 rochamarcelo

yea, i have always defaulted to $this->getTableLocator()->get('MyModel') till now 😁 But it was a question recently in our slack support chat so I just opened this issue so it is documented.

LordSimal avatar Mar 23 '23 13:03 LordSimal

Is there a solution for traits and fetchTable() yet?

dereuromark avatar Sep 28 '23 17:09 dereuromark

I could not find a good solution for this issue.

rochamarcelo avatar Sep 29 '23 11:09 rochamarcelo

Interesting: For me

$this->fetchTable('DatabaseLog.DatabaseLogs')->removeDuplicates();

works, but

protected ?string $defaultTable = 'DatabaseLog.DatabaseLogs';

and

$this->fetchTable()->removeDuplicates();

results in

34     Call to an undefined method Cake\ORM\Table::removeDuplicates().

Probably the defaultTable property should be read for empty argument?

dereuromark avatar Oct 08 '23 02:10 dereuromark

Yes, sent https://github.com/CakeDC/cakephp-phpstan/pull/19

rochamarcelo avatar Oct 08 '23 17:10 rochamarcelo

Closed per #19, please reopen if needed. Thanks,

steinkel avatar Jul 28 '24 19:07 steinkel