|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* This file is part of Esi\Api. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) Eric Sizemore <[email protected]> |
|
9
|
|
|
* |
|
10
|
|
|
* This source file is subject to the MIT license. For the full |
|
11
|
|
|
* copyright and license information, please view the LICENSE |
|
12
|
|
|
* file that was distributed with this source code. |
|
13
|
|
|
*/ |
|
14
|
|
|
|
|
15
|
|
|
namespace Esi\Api\Traits; |
|
16
|
|
|
|
|
17
|
|
|
use JsonException; |
|
18
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
19
|
|
|
use stdClass; |
|
20
|
|
|
|
|
21
|
|
|
use function json_decode; |
|
22
|
|
|
|
|
23
|
|
|
use const JSON_THROW_ON_ERROR; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Trait to add a few json response related functions to a class. |
|
27
|
|
|
* |
|
28
|
|
|
* Note: expects an object implementing Psr\Http\Message\ResponseInterface. |
|
29
|
|
|
*/ |
|
30
|
|
|
trait ParseJsonResponse |
|
31
|
|
|
{ |
|
32
|
|
|
/** |
|
33
|
|
|
* Returns the jSON data as-is from the API. |
|
34
|
|
|
*/ |
|
35
|
3 |
|
public function raw(ResponseInterface $response): string |
|
36
|
|
|
{ |
|
37
|
3 |
|
return $response->getBody()->getContents(); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Decodes the jSON returned from the API. Returns as an associative array. |
|
42
|
|
|
* |
|
43
|
|
|
* @throws JsonException |
|
44
|
|
|
* |
|
45
|
|
|
* @return array<mixed> |
|
46
|
|
|
*/ |
|
47
|
1 |
|
public function toArray(ResponseInterface $response): array |
|
48
|
|
|
{ |
|
49
|
1 |
|
$json = json_decode($this->raw($response), true, flags: JSON_THROW_ON_ERROR); |
|
50
|
|
|
|
|
51
|
|
|
//@codeCoverageIgnoreStart |
|
52
|
|
|
if (!\is_array($json)) { |
|
53
|
|
|
throw new JsonException(); |
|
54
|
|
|
} |
|
55
|
|
|
//@codeCoverageIgnoreEnd |
|
56
|
|
|
|
|
57
|
1 |
|
return $json; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Decodes the jSON returned from the API. Returns as an array of objects. |
|
62
|
|
|
* |
|
63
|
|
|
* @throws JsonException |
|
64
|
|
|
*/ |
|
65
|
1 |
|
public function toObject(ResponseInterface $response): stdClass |
|
66
|
|
|
{ |
|
67
|
1 |
|
$json = json_decode($this->raw($response), false, flags: JSON_THROW_ON_ERROR); |
|
68
|
|
|
|
|
69
|
|
|
//@codeCoverageIgnoreStart |
|
70
|
|
|
if (!$json instanceof stdClass) { |
|
71
|
|
|
throw new JsonException(); |
|
72
|
|
|
} |
|
73
|
|
|
//@codeCoverageIgnoreEnd |
|
74
|
|
|
|
|
75
|
1 |
|
return $json; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|