Client.php 2.6 KB

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