1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kevintweber\HtmlTokenizer\Tokens; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* A TokenCollection is a group of tokens designed to act similar to |
7
|
|
|
* an array. |
8
|
|
|
*/ |
9
|
|
|
class TokenCollection implements \ArrayAccess, \IteratorAggregate |
10
|
|
|
{ |
11
|
|
|
/** @var array[Token] */ |
12
|
|
|
private $tokens; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Constructor |
16
|
|
|
*/ |
17
|
13 |
|
public function __construct() |
18
|
|
|
{ |
19
|
13 |
|
$this->tokens = array(); |
20
|
13 |
|
} |
21
|
|
|
|
22
|
6 |
|
public function toArray() : array |
23
|
|
|
{ |
24
|
6 |
|
$result = array(); |
25
|
6 |
|
foreach ($this->tokens as $token) { |
26
|
5 |
|
$result[] = $token->toArray(); |
27
|
|
|
} |
28
|
|
|
|
29
|
6 |
|
return $result; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Required by the ArrayAccess interface. |
34
|
|
|
*/ |
35
|
2 |
|
public function offsetExists($offset) |
36
|
|
|
{ |
37
|
2 |
|
return array_key_exists($offset, $this->tokens); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Required by the ArrayAccess interface. |
42
|
|
|
*/ |
43
|
1 |
|
public function offsetGet($offset) |
44
|
|
|
{ |
45
|
1 |
|
return $this->tokens[$offset]; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Required by the ArrayAccess interface. |
50
|
|
|
*/ |
51
|
12 |
|
public function offsetSet($offset, $value) |
52
|
|
|
{ |
53
|
12 |
|
if (!$value instanceof Token) { |
54
|
1 |
|
throw new \InvalidArgumentException('Value must be of type Token.'); |
55
|
|
|
} |
56
|
|
|
|
57
|
11 |
|
if ($offset === null) { |
58
|
10 |
|
$this->tokens[] = $value; |
59
|
|
|
|
60
|
10 |
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
$this->tokens[$offset] = $value; |
64
|
1 |
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Required by the ArrayAccess interface. |
68
|
|
|
*/ |
69
|
1 |
|
public function offsetUnset($offset) |
70
|
|
|
{ |
71
|
1 |
|
unset($this->tokens[$offset]); |
72
|
1 |
|
} |
73
|
|
|
|
74
|
2 |
|
public function count() : int |
75
|
|
|
{ |
76
|
2 |
|
return count($this->tokens); |
77
|
|
|
} |
78
|
|
|
|
79
|
3 |
|
public function isEmpty() : bool |
80
|
|
|
{ |
81
|
3 |
|
return empty($this->tokens); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* Required by the IteratorAggregate interface. |
86
|
|
|
*/ |
87
|
1 |
|
public function getIterator() |
88
|
|
|
{ |
89
|
1 |
|
return new \ArrayIterator($this->tokens); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|