Client.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. var_dump($ret->getContent(false));
  72. return false;
  73. }
  74. }