blob: 63d4455af791a75dbb2f0685b81b8a15c6c7e748 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
<?php
namespace OpenCloud\Common\Resource;
use OpenCloud\Common\Transport\Utils;
class Iterator
{
private $requestFn;
private $resourceFn;
private $limit;
private $count;
private $resourcesKey;
private $markerKey;
private $mapFn;
private $currentMarker;
public function __construct(array $options, callable $requestFn, callable $resourceFn)
{
$this->limit = isset($options['limit']) ? $options['limit'] : false;
$this->count = 0;
if (isset($options['resourcesKey'])) {
$this->resourcesKey = $options['resourcesKey'];
}
if (isset($options['markerKey'])) {
$this->markerKey = $options['markerKey'];
}
if (isset($options['mapFn']) && is_callable($options['mapFn'])) {
$this->mapFn = $options['mapFn'];
}
$this->requestFn = $requestFn;
$this->resourceFn = $resourceFn;
}
private function fetchResources()
{
if ($this->shouldNotSendAnotherRequest()) {
return false;
}
$response = call_user_func($this->requestFn, $this->currentMarker);
$json = Utils::flattenJson(Utils::jsonDecode($response), $this->resourcesKey);
if ($response->getStatusCode() === 204 || empty($json)) {
return false;
}
return $json;
}
private function assembleResource(array $data)
{
$resource = call_user_func($this->resourceFn, $data);
// Invoke user-provided fn if provided
if ($this->mapFn) {
call_user_func_array($this->mapFn, [&$resource]);
}
// Update marker if operation supports it
if ($this->markerKey) {
$this->currentMarker = $resource->{$this->markerKey};
}
return $resource;
}
private function totalReached()
{
return $this->limit && $this->count >= $this->limit;
}
private function shouldNotSendAnotherRequest()
{
return $this->totalReached() || ($this->count > 0 && !$this->markerKey);
}
public function __invoke()
{
while ($resources = $this->fetchResources()) {
foreach ($resources as $resourceData) {
if ($this->totalReached()) {
break;
}
$this->count++;
yield $this->assembleResource($resourceData);
}
}
}
}
|