|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* parser for PHP serialized array |
|
4
|
|
|
*/ |
|
5
|
|
|
namespace xKerman\Restricted; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Parser for PHP serialiezed array |
|
9
|
|
|
*/ |
|
10
|
|
|
class ArrayParser implements ParserInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* parse given `$source` as PHP serialized array |
|
14
|
|
|
* |
|
15
|
|
|
* @param Source $source parser input |
|
16
|
|
|
* @return array |
|
17
|
|
|
* @throws UnserializeFailedException |
|
18
|
|
|
*/ |
|
19
|
16 |
|
public function parse(Source $source) |
|
20
|
1 |
|
{ |
|
21
|
16 |
|
$source->consume('a'); |
|
22
|
14 |
|
$source->consume(':'); |
|
23
|
|
|
|
|
24
|
14 |
|
list($length, $source) = $this->parseLength($source); |
|
25
|
11 |
|
$result = []; |
|
26
|
|
|
|
|
27
|
11 |
|
$source->consume(':'); |
|
28
|
10 |
|
$source->consume('{'); |
|
29
|
|
|
|
|
30
|
8 |
|
for ($i = 0; $i < $length; ++$i) { |
|
31
|
5 |
|
list($key, $source) = $this->parseKey($source); |
|
32
|
4 |
|
list($value, $source) = $this->parseValue($source); |
|
33
|
3 |
|
$result[$key] = $value; |
|
34
|
3 |
|
} |
|
35
|
|
|
|
|
36
|
5 |
|
$source->consume('}'); |
|
37
|
3 |
|
return [$result, $source]; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* parse given `$source` as array length |
|
42
|
|
|
* |
|
43
|
|
|
* @param Source $source input |
|
44
|
|
|
* @return array |
|
45
|
|
|
* @throws UnserializeFailedException |
|
46
|
|
|
*/ |
|
47
|
14 |
|
private function parseLength($source) |
|
48
|
|
|
{ |
|
49
|
14 |
|
$parser = new NumberLiteralParser(); |
|
50
|
14 |
|
list($length, $source) = $parser->parse($source); |
|
51
|
12 |
|
if ($length < 0) { |
|
52
|
1 |
|
return $source->triggerError(); |
|
53
|
|
|
} |
|
54
|
11 |
|
return [$length, $source]; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* parse given `$source` as array key (s.t. integer|string) |
|
59
|
|
|
* |
|
60
|
|
|
* @param Source $source input |
|
61
|
|
|
* @return array |
|
62
|
|
|
* @throws UnserializeFailedException |
|
63
|
|
|
*/ |
|
64
|
5 |
|
private function parseKey($source) |
|
65
|
|
|
{ |
|
66
|
5 |
|
switch ($source->peek()) { |
|
67
|
5 |
|
case 'i': |
|
68
|
4 |
|
$parser = new IntegerParser(); |
|
69
|
4 |
|
break; |
|
70
|
3 |
|
case 's': |
|
71
|
1 |
|
$parser = new StringParser(); |
|
72
|
1 |
|
break; |
|
73
|
2 |
|
default: |
|
74
|
2 |
|
return $source->triggerError(); |
|
75
|
5 |
|
} |
|
76
|
4 |
|
return $parser->parse($source); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* parse given `$source` as array value |
|
81
|
|
|
* |
|
82
|
|
|
* @param Source $source input |
|
83
|
|
|
* @return array |
|
84
|
|
|
* @throws UnserializeFailedException |
|
85
|
|
|
*/ |
|
86
|
4 |
|
private function parseValue($source) |
|
87
|
|
|
{ |
|
88
|
4 |
|
$parser = new ExpressionParser(); |
|
89
|
4 |
|
return $parser->parse($source); |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|