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
|
|
|
/** @var ParserInterface ExpressionParser parser for unserialize expression */ |
13
|
|
|
private $expressionParser; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* constructor |
17
|
|
|
* |
18
|
|
|
* @param ParserInterface $parser parser for unserialize expression |
19
|
|
|
*/ |
20
|
50 |
|
public function __construct(ParserInterface $parser) |
21
|
|
|
{ |
22
|
50 |
|
$this->expressionParser = $parser; |
23
|
50 |
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* parse given `$source` as PHP serialized array |
27
|
|
|
* |
28
|
|
|
* @param Source $source parser input |
29
|
|
|
* @return array |
30
|
|
|
* @throws UnserializeFailedException |
31
|
|
|
*/ |
32
|
16 |
|
public function parse(Source $source) |
33
|
|
|
{ |
34
|
16 |
|
$matched = $source->match('/\Ga:[+]?[0-9]+:{/'); |
35
|
8 |
|
$length = intval(substr($matched, 2, -2), 10); |
36
|
|
|
|
37
|
8 |
|
$result = array(); |
38
|
8 |
|
for ($i = 0; $i < $length; ++$i) { |
39
|
5 |
|
list($key, $source) = $this->parseKey($source); |
40
|
4 |
|
list($value, $source) = $this->parseValue($source); |
41
|
3 |
|
$result[$key] = $value; |
42
|
3 |
|
} |
43
|
|
|
|
44
|
5 |
|
$source->consume('}'); |
45
|
3 |
|
return array($result, $source); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* parse given `$source` as array key (s.t. integer|string) |
50
|
|
|
* |
51
|
|
|
* @param Source $source input |
52
|
|
|
* @return array |
53
|
|
|
* @throws UnserializeFailedException |
54
|
|
|
*/ |
55
|
5 |
|
private function parseKey($source) |
56
|
|
|
{ |
57
|
5 |
|
switch ($source->peek()) { |
58
|
5 |
|
case 'i': |
59
|
4 |
|
$parser = new IntegerParser(); |
60
|
4 |
|
break; |
61
|
3 |
|
case 's': |
62
|
1 |
|
$parser = new StringParser(); |
63
|
1 |
|
break; |
64
|
2 |
|
default: |
65
|
2 |
|
return $source->triggerError(); |
66
|
5 |
|
} |
67
|
4 |
|
return $parser->parse($source); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* parse given `$source` as array value |
72
|
|
|
* |
73
|
|
|
* @param Source $source input |
74
|
|
|
* @return array |
75
|
|
|
* @throws UnserializeFailedException |
76
|
|
|
*/ |
77
|
4 |
|
private function parseValue($source) |
78
|
|
|
{ |
79
|
4 |
|
return $this->expressionParser->parse($source); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|