John Davidson

symfony - Using Enum as string in PHP with PhpStan

0 comments
Message:


I'm experimenting with PHP enums in a Symfony 6 application and I thought I found a very nice use case for those. Everything works, but phpstan keeps complaining about the type I return.


 ------ -----------------------------------------------------------------------------------------------------------------------------------------------
Line src/Entity/User.php
------ -----------------------------------------------------------------------------------------------------------------------------------------------
93 Return type (array<App\Security\Roles>) of method App\Entity\User::getRoles() should be compatible with return type (array<string>) of method
Symfony\Component\Security\Core\User\UserInterface::getRoles()
------ -----------------------------------------------------------------------------------------------------------------------------------------------

My Enum looks like this:


namespace App\Security;

enum Roles: string
{
case Admin = 'ROLE_ADMIN';
case User = 'ROLE_USER';
}

In my User entity which implements Symfony\Component\Security\Core\User\UserInterface, I have this:


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

return array_unique($roles);
}

/**
* @param array<Roles> $roles
*/
public function setRoles(array $roles): self
{
$this->roles = $roles;

return $this;
}

I understand that phpstan expects the array to contain a string as defined in the interface,


/**
* @return string[]
*/
public function getRoles(): array;

But is there a way to work around this? I would really prefer to be able to leverage an Enum. Isn't the point of adding a type to the enum being able to use it as that type? Also worth mentioning that I use strict types everywhere and everything works except for phpstan being not too happy with my type.



My Answer:
) of method App\Entity\User::getRoles() should be array, but string is returned.

Rate this post

4 of 5 based on 7555 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us