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