From af663cf27cf7cd92a2eed265eda98a67d793488b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Fastr=C3=A9?= Date: Tue, 12 Dec 2023 22:33:57 +0100 Subject: [PATCH] Create the helper ChillSecurity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit En symfony 5.4 le typage a été vraiment amélioré, et phpstan peut détecter plus d'erreur potentielles. Mais le problème est que Symfony "type" les `User` avec son propre `Symfony\Component\Security\Core\User\UserInterface` alors qu'on a besoin de `Chill\MainBundle\Entity\User`. Imaginons qu'on a ceci: ```php namespace Chill\Bundle\Service; final readonly class SomeService { public function myMethod(\Chill\MainBundle\Entity\User $user): void { // ... } } ``` Quand on l'appelle dans un contrôleur ou dans un service: ```php namespace Chill\Bundle\Service; use Symfony\Component\Security\Core\Security; final readonly OtherService { public function __construct(private Security $security, private SomeService $service) {} public function __invoke(): void { $this->service->myMethod($this->security->getUser()); } } ``` PHPstan va se plaindre: ``` Parameter #1 $user of method SomeService::myMethod() expects Chill\MainBundle\Entity\User, Symfony\Component\Security\Core\User\UserInterface|null given. ``` Du coup, j'ai créé ce service: ```php service->myMethod($this->security->getUser()); } } ``` Et tout va bien se passer. Ca sera dans la version de chill qui fait passer à symfony 5.4. --- .../Security/ChillSecurity.php | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/Bundle/ChillMainBundle/Security/ChillSecurity.php diff --git a/src/Bundle/ChillMainBundle/Security/ChillSecurity.php b/src/Bundle/ChillMainBundle/Security/ChillSecurity.php new file mode 100644 index 000000000..eb21d00df --- /dev/null +++ b/src/Bundle/ChillMainBundle/Security/ChillSecurity.php @@ -0,0 +1,54 @@ +security->getUser(); + } + + public function getUser(): User + { + $user = $this->security->getUser(); + + if (!$user instanceof User) { + throw new \LogicException(sprintf('authenticated user should be an instance of %s, %s given', User::class, null !== $user ? $user::class : self::class)); + } + + return $user; + } + + public function isGranted($attribute, $subject = null): bool + { + return $this->security->isGranted($attribute, $subject); + } + + public function getToken(): ?TokenInterface + { + return $this->security->getToken(); + } +}