cakephp-phpstan
cakephp-phpstan copied to clipboard
`fetchTable()` does not properly resolve when used via LocatorAwareTrait in a service class
<?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.
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
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.
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.
Is there a solution for traits and fetchTable() yet?
I could not find a good solution for this issue.
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?
Yes, sent https://github.com/CakeDC/cakephp-phpstan/pull/19
Closed per #19, please reopen if needed. Thanks,