MobytService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Mobyt;
  4. use App\Service\Rest\ApiRequestService;
  5. use App\Tests\Service\Mobyt\MobytServiceTest;
  6. use JetBrains\PhpStorm\Pure;
  7. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  8. use Symfony\Contracts\HttpClient\HttpClientInterface;
  9. /**
  10. * Service d'appel à l'API Mobyt
  11. */
  12. class MobytService extends ApiRequestService
  13. {
  14. private string $userId;
  15. private string $sessionKey;
  16. /** @noinspection SenselessProxyMethodInspection */
  17. #[Pure]
  18. public function __construct(
  19. HttpClientInterface $mobyt_client
  20. )
  21. {
  22. parent::__construct($mobyt_client);
  23. }
  24. /**
  25. * Send a connexion request to mobyt and get the user id and session key from the response
  26. *
  27. * @param string $login
  28. * @param string $password
  29. * @return void
  30. */
  31. protected function connect(string $login, string $password): void
  32. {
  33. $responseContent = $this->getContent('login',[],
  34. [
  35. 'headers' => [
  36. 'Content-Type: application/json',
  37. 'Authorization: Basic '. base64_encode($login.':'.$password),
  38. ]
  39. ]
  40. );
  41. [$this->userId, $this->sessionKey] = explode(';', $responseContent);
  42. }
  43. protected function getUserId(): string
  44. {
  45. return $this->userId;
  46. }
  47. protected function getSessionKey(): string
  48. {
  49. return $this->sessionKey;
  50. }
  51. /**
  52. * Get a mobyt user status by its opentalent organization login and password
  53. *
  54. * @param string $login
  55. * @param string $password
  56. * @return mixed[]
  57. * @throws \JsonException
  58. */
  59. public function getUserStatus(string $login, string $password): array
  60. {
  61. $this->connect($login, $password);
  62. return $this->getJsonContent(
  63. 'status',
  64. ['getMoney' => 'true', 'typeAliases' => 'true'],
  65. [
  66. 'headers' => [ 'user_key' => $this->getUserId(), 'Session_key' => $this->getSessionKey() ]
  67. ]
  68. );
  69. }
  70. /**
  71. * Test if login and pass are correct
  72. *
  73. * @param string $login
  74. * @param string $password
  75. * @return bool
  76. * @see MobytServiceTest::testHasCredentialsCorrect()
  77. */
  78. public function hasCredentialsCorrect(string $login, string $password): bool
  79. {
  80. try{
  81. $this->connect($login, $password);
  82. }catch (NotFoundHttpException){
  83. return false;
  84. }
  85. return true;
  86. }
  87. }