|
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 |
|
$parser = new LengthParser(); |
|
25
|
14 |
|
list($length, $source) = $parser->parse($source); |
|
26
|
11 |
|
$result = array(); |
|
27
|
|
|
|
|
28
|
11 |
|
$source->consume(':'); |
|
29
|
10 |
|
$source->consume('{'); |
|
30
|
|
|
|
|
31
|
8 |
|
for ($i = 0; $i < $length; ++$i) { |
|
32
|
5 |
|
list($key, $source) = $this->parseKey($source); |
|
33
|
4 |
|
list($value, $source) = $this->parseValue($source); |
|
34
|
3 |
|
$result[$key] = $value; |
|
35
|
3 |
|
} |
|
36
|
|
|
|
|
37
|
5 |
|
$source->consume('}'); |
|
38
|
3 |
|
return array($result, $source); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* parse given `$source` as array key (s.t. integer|string) |
|
43
|
|
|
* |
|
44
|
|
|
* @param Source $source input |
|
45
|
|
|
* @return array |
|
46
|
|
|
* @throws UnserializeFailedException |
|
47
|
|
|
*/ |
|
48
|
5 |
|
private function parseKey($source) |
|
49
|
|
|
{ |
|
50
|
5 |
|
switch ($source->peek()) { |
|
51
|
5 |
|
case 'i': |
|
52
|
4 |
|
$parser = new IntegerParser(); |
|
53
|
4 |
|
break; |
|
54
|
3 |
|
case 's': |
|
55
|
1 |
|
$parser = new StringParser(); |
|
56
|
1 |
|
break; |
|
57
|
2 |
|
default: |
|
58
|
2 |
|
return $source->triggerError(); |
|
59
|
5 |
|
} |
|
60
|
4 |
|
return $parser->parse($source); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* parse given `$source` as array value |
|
65
|
|
|
* |
|
66
|
|
|
* @param Source $source input |
|
67
|
|
|
* @return array |
|
68
|
|
|
* @throws UnserializeFailedException |
|
69
|
|
|
*/ |
|
70
|
4 |
|
private function parseValue($source) |
|
71
|
|
|
{ |
|
72
|
4 |
|
$parser = new ExpressionParser(); |
|
73
|
4 |
|
return $parser->parse($source); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|