PHPStan 和 Doctrine:$id 永远不会写,只能读

PHPStan and Doctrine: $id is never written, only read

我将 PHP8、symfony5 和 doctrine2 与 phpstan 一起使用,但出现以下错误:

Property App\Entity\User::$id is never written, only read.  

代码:

<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Table(name="`user`")
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    public const ROLE_USER = 'ROLE_USER';
    public const ROLE_ADMIN = 'ROLE_ADMIN';

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="boolean")
     */
    private $isVerified = false;

    public function __construct()
    {
        $this->audioSessions = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUserIdentifier(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function isVerified(): bool
    {
        return $this->isVerified;
    }

    public function setIsVerified(bool $isVerified): self
    {
        $this->isVerified = $isVerified;

        return $this;
    }
}

代码是正确的,PHPStan 也承认,如下所述:https://phpstan.org/blog/detecting-unused-private-properties-methods-constants#what-if-my-code-is-%E2%80%9Cspecial%E2%80%9D%3F

那么我如何解决 PHPStan 中的这些错误消息?

我尝试安装 https://github.com/phpstan/phpstan-doctrine 并在我的 phpstan.neon 文件中启用它:

includes:
    - vendor/phpstan/phpstan-doctrine/extension.neon
    - vendor/phpstan/phpstan-doctrine/rules.neon

但错误仍然存​​在。

您需要配置 objectManagerLoader 以便扩展可以看到实体元数据。 这将允许 DQL 验证,并在访问 $entityManager->getRepository() 时推断出正确的实体 repositoryClass。添加到您的 phpstan.neon:

parameters:
    doctrine:
        objectManagerLoader: tests/object-manager.php

Symfony 5 示例:

// tests/object-manager.php

use App\Kernel;
use Symfony\Component\Dotenv\Dotenv;

require __DIR__ . '/../vendor/autoload.php';

(new Dotenv())->bootEnv(__DIR__ . '/../.env');

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel->boot();
return $kernel->getContainer()->get('doctrine')->getManager();

来自文档: https://github.com/phpstan/phpstan-doctrine#configuration

我正在使用 phpstan 忽略错误 (https://phpstan.org/user-guide/ignoring-errors)。为了缩小范围,我的路径只设置为实体目录。

# ./phpstan.neon

parameters:
    ignoreErrors:
        -
          message: '#Property [a-zA-Z0-9\_]+::$id is never written, only read.#'
          path: src/Entity/*

自此 RFC is implemented, PHPStan implemented this feature in the 1.4 version. Unforthunully, there is no @readonly attribute (at least for the moment) that can be used with PHP < 8. For more detail, feel free to see this issue.