|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Copyright © Thomas Klein, All rights reserved. |
|
4
|
|
|
* See LICENSE bundled with this library for license details. |
|
5
|
|
|
*/ |
|
6
|
|
|
declare(strict_types=1); |
|
7
|
|
|
|
|
8
|
|
|
namespace Zoho\Desk\Client; |
|
9
|
|
|
|
|
10
|
|
|
use Zoho\Desk\Exception\InvalidRequestException; |
|
11
|
|
|
use function curl_errno; |
|
12
|
|
|
use function curl_error; |
|
13
|
|
|
use function curl_exec; |
|
14
|
|
|
use function curl_getinfo; |
|
15
|
|
|
use function is_array; |
|
16
|
|
|
use function json_decode; |
|
17
|
|
|
use function mb_substr; |
|
18
|
|
|
use function rtrim; |
|
19
|
|
|
use const CURLINFO_HEADER_SIZE; |
|
20
|
|
|
use const CURLINFO_HTTP_CODE; |
|
21
|
|
|
|
|
22
|
|
|
final class Request implements RequestInterface |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* @var resource |
|
26
|
|
|
*/ |
|
27
|
|
|
private $curlResource; |
|
28
|
|
|
|
|
29
|
|
|
public function __construct($curlResource) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->curlResource = $curlResource; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function execute(): ResponseInterface |
|
35
|
|
|
{ |
|
36
|
|
|
$response = curl_exec($this->curlResource); |
|
37
|
|
|
|
|
38
|
|
|
if ($response === false) { |
|
39
|
|
|
throw InvalidRequestException::createRequestErrorException( |
|
40
|
|
|
curl_error($this->curlResource), |
|
41
|
|
|
curl_errno($this->curlResource) |
|
42
|
|
|
); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$responseInfo = curl_getinfo($this->curlResource); |
|
46
|
|
|
$responseCode = curl_getinfo($this->curlResource, CURLINFO_HTTP_CODE); |
|
47
|
|
|
$headerSize = curl_getinfo($this->curlResource, CURLINFO_HEADER_SIZE); |
|
48
|
|
|
$body = json_decode(mb_substr($response, $headerSize), true) ?: []; |
|
|
|
|
|
|
49
|
|
|
curl_close($this->curlResource); |
|
50
|
|
|
|
|
51
|
|
|
if (!$responseInfo || $responseCode >= 400) { |
|
52
|
|
|
throw new InvalidRequestException($this->buildErrorMessage($body)); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return new Response($body, $responseInfo); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
private function buildErrorMessage(array $body): string |
|
59
|
|
|
{ |
|
60
|
|
|
$message = 'An error occurred on the API gateway.'; |
|
61
|
|
|
|
|
62
|
|
|
if (isset($body['message'])) { |
|
63
|
|
|
$message = $body['message']; |
|
64
|
|
|
|
|
65
|
|
|
if (isset($body['errors']) && is_array($body['errors'])) { |
|
66
|
|
|
$message .= ': '; |
|
67
|
|
|
foreach ($body['errors'] as $error) { |
|
68
|
|
|
$message .= $error['fieldName'] . ' is ' . $error['errorType'] . ', '; |
|
69
|
|
|
} |
|
70
|
|
|
$message = rtrim($message, ', ') . '.'; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return $message; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|