symfony

Get user instead of Userinterface


How to get User class instead of Userinterface when i do :

$this->security->getUser() (Security is Symfony\Component\Security\Core\Security;)

By Example (and its just an example :), i have this custom function :

public function getUser(User $user){
}

and when i do that :

public function __construct(
        Security $security,
    ) {
        $this->security = $security;
    }

getUser($this->security->getUser());

I have a warning :

getUser expects App\Entity\User, Symfony\Component\Security\Core\User\UserInterface|null given.


Solution

  • When a code analysis tool like phpstan or psalm warns you about a type mismatch there are multiple ways to deal with it.

    Most likely you want to change your method signature and then handle the cases, the message complains about, e.g. like this:

    public function getUser(UserInterface $user = null)
    {
        if (null === $user || ! $user instanceof User) {
            // do something about the wrong types, that you might get from getSecurity()->getUser(), e.g. return or throw an exception
            throw new Exception(sprintf('Expected App\\Entity\\User, got %s', $user === null ? 'null' : get_class($user)));
        }
    
        ... your logic
    }
    

    Now your method accepts both the interface and null that might get in there. You could also do the error handling before calling your getUser method and leave it as is, so instead of just getUser($this->security->getUser());:

    $temporaryUser = $this->security->getUser();
    
    if (!$temporaryUser instanceof User) {
        throw new Exception(sprintf('Expected App\\Entity\\User, got %s', $user === null ? 'null' : get_class($user))); 
    }
    
    getUser($temporaryUser);
    

    If you are sure that the code will not run into problems, you can also ignore certain error messages by creating a phpstan.neon in your project root. See: https://github.com/phpstan/phpstan#ignore-error-messages-with-regular-expressions