ApiLegacyRequestService.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Service\ApiLegacy;
  3. use App\Service\Rest\ApiRequestService;
  4. use JetBrains\PhpStorm\Pure;
  5. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  6. use Symfony\Component\HttpKernel\Exception\HttpException;
  7. use Symfony\Component\Security\Core\Authentication\Token\NullToken;
  8. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  9. use Symfony\Bundle\SecurityBundle\Security;
  10. use Symfony\Contracts\HttpClient\HttpClientInterface;
  11. use Symfony\Contracts\HttpClient\ResponseInterface;
  12. use App\Entity\Access\Access;
  13. /**
  14. * Service d'appel à l'API opentalent V1
  15. */
  16. class ApiLegacyRequestService extends ApiRequestService
  17. {
  18. #[Pure]
  19. public function __construct(
  20. HttpClientInterface $apiLegacyClient,
  21. private readonly Security $security,
  22. private readonly JWTTokenManagerInterface $jwtManager,
  23. readonly private string $internalRequestsToken
  24. )
  25. {
  26. parent::__construct($apiLegacyClient);
  27. }
  28. /**
  29. * @param string $method
  30. * @param string $url
  31. * @param array<mixed> $parameters
  32. * @param array<mixed> $options
  33. */
  34. public function request(
  35. string $method,
  36. string $url,
  37. array $parameters = [],
  38. array $options = []
  39. ): ResponseInterface {
  40. $token = $this->security->getToken();
  41. $headers = [
  42. 'Accept' => '*/*',
  43. 'Charset' => 'UTF-8',
  44. 'Accept-Encoding' => 'gzip, deflate, br',
  45. 'Content-Type' => 'application/ld+json',
  46. ];
  47. /** @var Access $activeUser */
  48. $activeUser = $token->getUser();
  49. $jwt = null;
  50. if ($token instanceof SwitchUserToken) {
  51. /** @var Access|null $originalUser */
  52. $originalUser = $token->getOriginalToken()->getUser();
  53. if ($originalUser === null) {
  54. throw new HttpException(500, 'Request error : Switch original user missing');
  55. }
  56. $jwt = $this->jwtManager->create($originalUser->getPerson());
  57. $headers['x-accessid'] = $originalUser->getId();
  58. $headers['x-switch-access'] = $activeUser->getId();
  59. } elseif ($token !== null && !($token instanceof NullToken) && $token->getUser() !== null) {
  60. $jwt = $this->jwtManager->create($activeUser->getPerson());
  61. $headers['x-accessid'] = $activeUser->getId();
  62. }
  63. if ($jwt !== null) {
  64. $headers['authorization'] = 'BEARER ' . $jwt;
  65. }
  66. // Add the internal requests token
  67. $headers['internal-requests-token'] = $this->internalRequestsToken;
  68. $options['headers'] = array_merge($options['headers'] ?? [], $headers);
  69. return parent::request($method, $url, $parameters, $options);
  70. }
  71. }