Client.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace DNB;
  3. use Symfony\Component\HttpClient\HttpClient;
  4. use Symfony\Contracts\HttpClient\HttpClientInterface;
  5. final class Client {
  6. private HttpClientInterface $client;
  7. private ClientConfig $clientConfig;
  8. private object $auth;
  9. public function __construct(ClientConfig $clientConfig) {
  10. $this->clientConfig = $clientConfig;
  11. $this->client = HttpClient::create(
  12. [
  13. 'headers' => [
  14. 'cache-control' => 'no-cache',
  15. ]
  16. ]
  17. );
  18. $this->auth = $this->authenticate();
  19. }
  20. private function getUrl(string $endpoint, string $path): string {
  21. return sprintf(
  22. 'https://%s.azurewebsites.net/%s', rtrim($endpoint, '/'), ltrim($path, '/')
  23. );
  24. }
  25. public function authenticate(): object {
  26. $request = $this->client->request(
  27. 'POST',
  28. $this->getUrl($this->clientConfig->get()->auth_endpoint, '/connect/token'), [
  29. 'body' => [
  30. 'grant_type' => 'client_credentials',
  31. 'client_id' => $this->clientConfig->get()->id,
  32. 'client_secret' => $this->clientConfig->get()->secret
  33. ]
  34. ]
  35. );
  36. $result = $request->toArray();
  37. return new class (
  38. $result['access_token'],
  39. $result['token_type']
  40. ) {
  41. private string $token;
  42. private string $type;
  43. public function __construct(
  44. string $token,
  45. string $type
  46. ) {
  47. $this->token = $token;
  48. $this->type = $type;
  49. }
  50. public function getHeader(): string {
  51. return sprintf("%s %s", $this->type, $this->token);
  52. }
  53. };
  54. }
  55. private function getAuthClient(): HttpClientInterface {
  56. return $this->client->withOptions([
  57. 'headers' => [
  58. 'Authorization' => $this->auth->getHeader(),
  59. ]
  60. ]);
  61. }
  62. public function orderProspectus(
  63. Prospectus $prospectus
  64. ): bool {
  65. $ret = $this->getAuthClient()->request(
  66. "POST",
  67. 'https://uat-process-externalpart.azurewebsites.net/api/v1/autoprospect/orderprospect', [
  68. 'json' => $prospectus->toPostParams(),
  69. ]
  70. );
  71. try {
  72. $ret->getContent();
  73. return true;
  74. } catch (\Exception $e) {
  75. $content = $ret->getContent(false);
  76. throw new \InvalidArgumentException(!empty($content) ? $content : $e->getMessage(), $e->getCode(), $e);
  77. }
  78. return false;
  79. }
  80. }