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

Property is never written, only read - Misleading message when constructor is given for readonly entity

Open siggidiel opened this issue 1 year ago • 0 comments

I have a readonly entity:

<?php
declare(strict_types=1);

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\UuidV7;

#[ORM\Entity(repositoryClass: UserRepository::class, readOnly: true)]
class User
{
    #[ORM\Id]
    #[ORM\Column(type: 'uuid')]
    private UuidV7 $id;

    #[ORM\Column]
    private string $name;

    public function __construct(UuidV7 $id = null)
    {
        $this->id = $id ?? new UuidV7();
    }

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

    public function getName(): string
    {
        return $this->name;
    }
}

PHPStan (Doctrine Extension) is throwing analyse errors:

------ ---------------------------------------------------------------------------------- 
  Line   src/Entity/User.php                                                               
 ------ ---------------------------------------------------------------------------------- 
  18     Property App\Entity\User::$name is never written, only read.             
         💡 See: https://phpstan.org/developing-extensions/always-read-written-properties  
 ------ ---------------------------------------------------------------------------------- 

Although my entity is marked as readonly: true PHPStan is still throwing these errors. Reason is, because I have added a constructor which sets the property with an initial ID. If I remove the constructor, everything is fine.

Question might be now: "Why do you even set any property if your entity is readonly?"

Reason: This entity is used inside a project which should not be able to persist entity data. I copied this entity from my other project but removed all setters. I kept the constructor to create entities inside my unit tests. But yeah, you would be right here, it still does not really make sense.

Suggestion: Instead of this misleading error message, which took me hours to realize it probably would be better to write something like:

Entity is marked as readonly but property App\Entity\User::$id is written

What do you think?

siggidiel avatar Jul 18 '24 15:07 siggidiel