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

Type missmatch with nullable simple_array

Open micheh opened this issue 2 years ago • 4 comments

When using simple_array with nullable=true, PHPStan thinks the property should be nullable. But that is not the case, as the simple_array type always returns an empty array, even if the database value is null.

For example an User entity with the following property:

/**
 * @var list<string>
 * @ORM\Column(type="simple_array", nullable=true)
 */
private $affiliations = [];

PHPStan reports: Property User::$affiliations type mapping mismatch: database can contain array|null but property expects array<int, string>.

But Doctrine will convert an empty array to the database value null and convert null back to an empty php array.

https://github.com/doctrine/dbal/blob/757ce1ff885093bfdeb41414bc6bfca22c958b54/src/Types/SimpleArrayType.php#L46-L48

micheh avatar Oct 30 '21 09:10 micheh

This error means that the database can contain an array that isn't array<int, string>.

ondrejmirtes avatar Nov 03 '21 15:11 ondrejmirtes

@ondrejmirtes Hmm, but if I use array<mixed> I get the same error. If I use array<mixed>|null, the error disappears. But this is not correct in my opinion.

The doctrine type also uses explode to create the array, therefore it should always be a string array, no?

micheh avatar Nov 03 '21 16:11 micheh

@ondrejmirtes Is it possible that you revisit this? I still think this is a false positive, as Doctrine makes sure that the PHP value is never null, even if the database column is nullable.

micheh avatar Nov 16 '21 16:11 micheh

Just dropping in the up-to-date mapping syntax for better findability:

#[ORM\Column(type: Types::SIMPLE_ARRAY, nullable: true)]
private array $foo = [];

ThomasLandauer avatar Mar 11 '24 10:03 ThomasLandauer