【问题标题】:PHPDoc wrapper object propertyPHPDoc 包装对象属性
【发布时间】:2021-07-13 23:59:34
【问题描述】:

遇到了一个卡住的情况,会产生不必要的 IDE 警告,并可能导致清理使用过的代码。

我认为最好的解决方案是在正确的位置添加一些 PHPDoc,但由于某些限制而无法找到正确的位置,如下面的示例所述。

IDE:PhpStorm

结果:

<?php

/*
 * Generic result class, widely used, so can't touch it ¯\_(ツ)_/¯
 */
class Result {
  public $data;

  public function __construct() {
    return $this;
  }

  public function setData($data) {
    $this->data = $data;
    return $this;
  }
}

客户:

<?php

class Customer {
  public string $name  = '';
  public string $email = '';

  public function __construct() {
    $this->name = 'John Smith';
    $this->email = 'test@example.com';
  }

  public function getCustomer(): Result {
    return (new Result())->setData(new self());
  }

  public function reverseName(): string { // ❌ Unused element: 'reverseName'
    $parts = explode(' ', $this->name);
    return implode(' ', array_reverse($parts));
  }
}

控制器:

<?php

require_once 'vendor/autoload.php';

$john = (new Customer())->getCustomer();
// ℹ️ $john->data is an instance of the Customer class.
// How should I tell to the IDE this ^ ❓
$reversedName = $john->data->reverseName(); // ❌ Cannot find declaration to go when trying to navigate to the method
exit($reversedName);

尝试了很多很多选项,但唯一有效的方法是将 PHPDoc 添加到 Result$data 属性。不能碰它,因为它在项目中被广泛使用...

LE:Customer类有很多类似reverseName()的方法,所以将data属性赋值给一个新变量也很难写:/** @var Customer $john */ $john = (new Customer())-&gt;getCustomer()-&gt;data

【问题讨论】:

  • /** @var Customer $johnData */ $johnData = (new Customer())-&gt;getCustomer()-&gt;data; -- 类似这样的东西。基本上:将$object-&gt;data 放入一个单独的变量中并输入提示。
  • 确实,这也行,但是有很多代码需要重构。更新了问题。谢谢!
  • this 可用时,应该很快可以通过 Psalm 或 PHPstan 实现(应该很快)。

标签: php phpstorm phpdoc


【解决方案1】:

您可以尝试使用另一个名为 advanced metadata的 PhpStorm 功能。

首先你需要用下一种方式配置元数据

namespace PHPSTORM_META {
    override(\App\Result::getData(0), map(['' => '@']));
}

然后将 getter 添加到您的 Result 类中

public function getData()
{
    return $this->data;
}

然后在接下来的方式中使用这个getter

$john->getData(Customer::class)->reverseName();

主要思想是使用类名作为getter方法的参数,PhpStorm会知道这个getter将返回什么类对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-08
    • 2015-12-03
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2016-05-15
    • 2019-09-01
    • 1970-01-01
    相关资源
    最近更新 更多