EncodedCollection.php
1.81 KB
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
<?php
namespace ACP\Storage;
use AC\ListScreen;
use ACP\Storage\Decoder\ListScreenDecoder;
use Iterator;
use LogicException;
final class EncodedCollection implements Iterator
{
private $data;
private $decoder_factory;
public function __construct(array $encoded_list_screens, AbstractDecoderFactory $decoder_factory)
{
$this->decoder_factory = $decoder_factory;
$this->data = $encoded_list_screens;
$this->validate();
}
public static function is_valid_collection(array $encoded_list_screens): bool
{
foreach ($encoded_list_screens as $encoded_list_screen) {
if ( ! is_array($encoded_list_screen)) {
return false;
}
}
return true;
}
private function validate(): void
{
if ( ! self::is_valid_collection($this->data)) {
throw new LogicException('Invalid collection found. Expected array of arrays.');
}
}
public function decode(array $encoded_list_screen): ?ListScreen
{
$decoder = $this->decoder_factory->create($encoded_list_screen);
return $decoder instanceof ListScreenDecoder
? $decoder->get_list_screen()
: null;
}
public function can_decode(array $encoded_list_screen): bool
{
return $this->decoder_factory
->create($encoded_list_screen)
->has_required_version();
}
/**
* @return array
*/
public function current()
{
return current($this->data);
}
public function next()
{
return next($this->data);
}
public function key()
{
return key($this->data);
}
public function valid()
{
return $this->key() !== null;
}
public function rewind()
{
reset($this->data);
}
}