0

使用一个新的应用程序通过 PHPStan 的级别,我达到了第 3 级,并开始从我的所有模型测试装置中获取错误消息。基本格式如下:

 ------  
  Line   tests/TestCase/Model/Table/UsersTableTest.php                                                                                           
 ------ 
  43     Property Visualize\Test\TestCase\Model\Table\UsersTableTest::$Users (Visualize\Model\Table\UsersTable) does not accept Cake\ORM\Table.  
 ------  

此错误所指的代码是:

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp(): void
    {
        parent::setUp();
        $config = $this->getTableLocator()->exists('Users') ? [] : ['className' => UsersTable::class];
        $this->Users = $this->getTableLocator()->get('Users', $config);
    }

此设置代码是使用 cake bake 构建的,所以我不确定它在寻找什么。有其他人知道什么会为我解决这个问题吗?

编辑:我做了一些进一步的搜索。我能找到与此堆栈相关联的唯一版本的 getTableLocator() 函数位于 TableRegistry 类中。该类又具有一个名为 get() 的函数,该函数确实返回了一个 \Cake\Orm\Table 类型的对象:

    /**
     * Get a table instance from the registry.
     *
     * See options specification in {@link TableLocator::get()}.
     *
     * @param string $alias The alias name you want to get.
     * @param array $options The options you want to build the table with.
     * @return \Cake\ORM\Table
     * @deprecated 3.6.0 Use {@link \Cake\ORM\Locator\TableLocator::get()} instead. Will be removed in 5.0.
     */
    public static function get(string $alias, array $options = []): Table
    {
        return static::getTableLocator()->get($alias, $options);
    }

那么这是否意味着我的测试应该期待 \Cake\ORM\Table 类?TBH,我还没有在测试模型方面做很多事情(你可能已经猜到了),因此我不确定这样做的后果。

4

1 回答 1

2

问题是如何推断$this->getTableLocator()->get('Users', $config);它应该返回Visualize\Model\Table\UsersTable

如果您想出可以从抽象语法树以及其他地方(如配置)推断出的逻辑,则可以编写动态返回类型扩展。

扩展https://github.com/CakeDC/cakephp-phpstan可能已经解决了这个问题,这个类肯定看起来像这样:https ://github.com/CakeDC/cakephp-phpstan/blob/master/src/类型/TableLocatorDynamicReturnTypeExtension.php

于 2021-07-30T17:42:58.490 回答