AccessProfileProvider.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\State\Provider\Access;
  4. use ApiPlatform\Metadata\GetCollection;
  5. use ApiPlatform\Metadata\Operation;
  6. use ApiPlatform\State\ProviderInterface;
  7. use App\ApiResources\Profile\AccessProfile;
  8. use App\Entity\Access\Access;
  9. use App\Service\Access\AccessProfileCreator;
  10. use Exception;
  11. use RuntimeException;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  14. use Symfony\Bundle\SecurityBundle\Security;
  15. /**
  16. * Class AccessProfileProvider : custom provider pour assurer l'alimentation de la réponse du GET my_profile
  17. * @package App\DataProvider\Access
  18. */
  19. final class AccessProfileProvider implements ProviderInterface
  20. {
  21. public function __construct(
  22. private Security $security,
  23. private AccessProfileCreator $accessProfileCreator
  24. )
  25. { }
  26. /**
  27. * @param Operation $operation
  28. * @param mixed[] $uriVariables
  29. * @param mixed[] $context
  30. * @return AccessProfile|null
  31. * @throws Exception
  32. */
  33. public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?AccessProfile
  34. {
  35. if($operation instanceof GetCollection) {
  36. throw new RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
  37. }
  38. /** @var Access $access */
  39. $access = $this->security->getUser();
  40. $originalAccess = null;
  41. $token = $this->security->getToken();
  42. if($token instanceof SwitchUserToken){
  43. /** @var Access $originalAccess */
  44. $originalAccess = $token->getOriginalToken()->getUser();
  45. }
  46. return $this->accessProfileCreator->getAccessProfile($access, $originalAccess);
  47. }
  48. }