1

I have this:

/**
 * @var string[]
 */
 #[ORM\Column(type: 'json', nullable: true)]
 private array $roles = [];

How can I change string[] to php8 attribute ?

Something like #[Array(string)]

I am working with Symfony and Doctrine, and I am trying to fix phpstan errors at level 9

Talha Amir
  • 11
  • 2
  • 3
    Attributes are backed by classes, and core has provided very few attributes so far, and none specific to typing of arrays. To the best of my knowledge, neither Symfony nor Doctrine have any attributes for this either. The closest might be something from assert. However, on Level 9 I'm not seeing any errors: https://phpstan.org/r/ed9f4718-315d-4034-aee8-186ce70f9282, and I believe what you have is the current recommended best practice – Chris Haas Jun 21 '23 at 13:21
  • @ChrisHaas this can be added as an answer, this will be true until PHP supports native attributes to type the content of arrays. – A.L Jun 26 '23 at 14:26

2 Answers2

2

Attributes are backed by classes, and PHP core has provided very few attributes so far, and none specific to typing of arrays (or typing of anything for that matter). If core ever decides to support a typed-array syntax, it would probably come with generics, and I would assume they would use the existing type declaration system, instead of an attribute.

To the best of my knowledge, neither Symfony nor Doctrine have any attributes for this either. The closest might be something from Symfony's assert.

But no matter what, at this time you will need to have code backing the attribute. That code will either need to be custom-written by you, brought in by a third-party library, or an IDE. That code will also need to be specifically supported by whichever static analyzer tool you are using.

As to this last bit, PHPStan at least appears to be completely fine with the docblock syntax which is still the recommended path, and on Level 9 I'm not seeing any errors: https://phpstan.org/r/ed9f4718-315d-4034-aee8-186ce70f9282

Chris Haas
  • 53,986
  • 12
  • 141
  • 274
0

Concerning symfony constraints. You could use the All constraint

When applied to an array (or Traversable object), this constraint allows you to apply a collection of constraints to each element of the array.

#[Assert\All([
    new Assert\Type('string'),
])]
#[ORM\Column(type: 'json', nullable: true)]
private array $roles = [];

Which mean you could remove the phpdoc mentioning @var string[] that would be redundant.

Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • I think the OP want the code to ease auto-completion from the IDE. Will these attributes allow that? – A.L Jun 22 '23 at 13:44
  • The question is “How can I change `string[]` to php8 attribute ?” but this answer start with “Concerning symfony constraints”. – A.L Jun 26 '23 at 14:25