1 | <?php |
||
9 | class RequestLauncher |
||
10 | { |
||
11 | /** |
||
12 | * The API client ID issued by EMT. |
||
13 | * |
||
14 | * @var string |
||
15 | */ |
||
16 | protected $clientId; |
||
17 | |||
18 | /** |
||
19 | * The API passkey issued by EMT. |
||
20 | * |
||
21 | * @var string |
||
22 | */ |
||
23 | protected $passkey; |
||
24 | |||
25 | /** |
||
26 | * The Guzzle HTTP client. |
||
27 | * |
||
28 | * @var \GuzzleHttp\Client |
||
29 | */ |
||
30 | protected $client; |
||
31 | |||
32 | /** |
||
33 | * Create a new RequestLauncher instance with the provided client ID and |
||
34 | * passkey. |
||
35 | * |
||
36 | * An optional Guzzle HTTP client can be provided as well. |
||
37 | * |
||
38 | * @param string $clientId |
||
39 | * @param string $passkey |
||
40 | * @param \GuzzleHttp\ClientInterface $client |
||
41 | */ |
||
42 | 45 | public function __construct($clientId, $passkey, ClientInterface $client = null) |
|
52 | |||
53 | /** |
||
54 | * Authenticate and execute an arbitrary request. |
||
55 | * |
||
56 | * This method adds the relevant authentication parameters to the request |
||
57 | * and decodes the returned response. |
||
58 | * |
||
59 | * @param string $endpoint |
||
60 | * @param array $params |
||
61 | * @return \stdClass |
||
62 | * @throws \RuntimeException |
||
63 | */ |
||
64 | 9 | public function launchRequest($endpoint, $params = []) |
|
65 | 1 | { |
|
66 | 9 | $authParams = ['idClient' => $this->clientId, 'passKey' => $this->passkey]; |
|
67 | 9 | $response = $this->client->post( |
|
68 | 9 | $endpoint, |
|
69 | 9 | ['form_params' => array_merge($params, $authParams)] |
|
70 | 3 | ); |
|
71 | |||
72 | 9 | $decoded = json_decode((string) $response->getBody()); |
|
73 | 9 | if ($decoded === null) { |
|
74 | 3 | throw new RuntimeException('Response payload could not be parsed as JSON'); |
|
75 | } |
||
76 | |||
77 | 6 | if (isset($decoded->ReturnCode)) { |
|
78 | 3 | $returnCode = $decoded->ReturnCode; |
|
79 | 3 | throw new RuntimeException("Request returned error code '{$returnCode}' ('{$decoded->Description}')"); |
|
80 | } |
||
81 | |||
82 | 3 | return $decoded; |
|
83 | } |
||
84 | |||
85 | /** |
||
86 | * Return the HTTP client used by this instance. |
||
87 | * |
||
88 | * @return \GuzzleHttp\ClientInterface |
||
89 | */ |
||
90 | 3 | public function getHttpClient() |
|
94 | } |
||
95 |