1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zurbaev\ApiClient\Commands; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Zurbaev\ApiClient\Contracts\ApiResourceInterface; |
7
|
|
|
|
8
|
|
|
abstract class ListResourcesCommand extends ResourceCommand |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Get the payload's items key. |
12
|
|
|
* |
13
|
|
|
* @return string |
14
|
|
|
*/ |
15
|
|
|
abstract protected function itemsKey(); |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Determines if current command is list command. |
19
|
|
|
* |
20
|
|
|
* @return bool |
21
|
|
|
*/ |
22
|
|
|
public function isListCommand(): bool |
23
|
|
|
{ |
24
|
|
|
return true; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* HTTP request method. |
29
|
|
|
* |
30
|
|
|
* @return string |
31
|
|
|
*/ |
32
|
|
|
public function requestMethod() |
33
|
|
|
{ |
34
|
|
|
return 'GET'; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Handle command response. |
39
|
|
|
* |
40
|
|
|
* @param ResponseInterface $response |
41
|
|
|
* @param ApiResourceInterface $owner |
42
|
|
|
* |
43
|
|
|
* @throws \InvalidArgumentException |
44
|
|
|
* |
45
|
|
|
* @return mixed |
46
|
|
|
*/ |
47
|
|
|
public function handleResponse(ResponseInterface $response, ApiResourceInterface $owner) |
48
|
|
|
{ |
49
|
|
|
$json = json_decode((string) $response->getBody(), true); |
50
|
|
|
$data = $this->getItemsFromJsonResponse($json); |
51
|
|
|
|
52
|
|
|
if (is_null($data)) { |
53
|
|
|
throw new \InvalidArgumentException('Given response is not a '.$this->resourcePath().' response.'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $this->createResourcesFromJsonData($data, $response, $owner); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Get the items list from given JSON response. |
61
|
|
|
* |
62
|
|
|
* @param array $json |
63
|
|
|
* |
64
|
|
|
* @return array|null |
65
|
|
|
*/ |
66
|
|
|
protected function getItemsFromJsonResponse(array $json) |
67
|
|
|
{ |
68
|
|
|
return $json[$this->itemsKey()] ?? null; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Create resources list from given JSON response. |
73
|
|
|
* |
74
|
|
|
* @param array $data |
75
|
|
|
* @param ResponseInterface $response |
76
|
|
|
* @param ApiResourceInterface $owner |
77
|
|
|
* |
78
|
|
|
* @return array |
79
|
|
|
*/ |
80
|
|
|
protected function createResourcesFromJsonData(array $data, ResponseInterface $response, ApiResourceInterface $owner) |
|
|
|
|
81
|
|
|
{ |
82
|
|
|
$items = []; |
83
|
|
|
$className = $this->resourceClass(); |
84
|
|
|
|
85
|
|
|
foreach ($data as $item) { |
86
|
|
|
$items[] = new $className($owner->getApi(), $item, $owner); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return $items; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.