basic async-interop support; generator consumer missing
[m6w6/seekat] / lib / API / Iterator.php
1 <?php
2
3 namespace seekat\API;
4
5 use http\Url;
6 use seekat\API;
7
8 final class Iterator implements \Iterator
9 {
10 /**
11 * The endpoint
12 * @var API
13 */
14 private $api;
15
16 /**
17 * The iterator's data
18 * @var array
19 */
20 private $data;
21
22 /**
23 * The current key
24 * @var int|string
25 */
26 private $key;
27
28 /**
29 * The current data entry
30 * @var mixed
31 */
32 private $cur;
33
34 /**
35 * Create a new iterator over $data returning \seekat\API instances
36 *
37 * @var API $api The endpoint
38 * @var array|object $data
39 */
40 function __construct(API $api) {
41 $this->api = $api;
42 $this->data = (array) $api->export()["data"];
43 }
44
45 /**
46 * Get the current key
47 *
48 * @return int|string
49 */
50 function key() {
51 return $this->key;
52 }
53
54 /**
55 * Get the current data entry
56 *
57 * @return API
58 */
59 function current() {
60 return $this->cur;
61 }
62
63 function next() {
64 if (list($key, $cur) = each($this->data)) {
65 $this->key = $key;
66 if ($this->api->$key->exists("url", $url)) {
67 $url = new Url($url);
68 $this->cur = $this->api->withUrl($url)->withData($cur);
69 } else {
70 $this->cur = $this->api->$key->withData($cur);
71 }
72 } else {
73 $this->key = null;
74 $this->cur = null;
75 }
76 }
77
78 function valid() {
79 return isset($this->cur);
80 }
81
82 function rewind() {
83 if (is_array($this->data)) {
84 reset($this->data);
85 $this->next();
86 }
87 }
88 }