|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* handler for PHP serialized array |
|
4
|
|
|
*/ |
|
5
|
|
|
namespace xKerman\Restricted; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Handler for PHP serialiezed array |
|
9
|
|
|
*/ |
|
10
|
|
|
class ArrayHandler implements HandlerInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var ParserInterface $expressionParser parser for unserialize expression */ |
|
13
|
|
|
private $expressionParser; |
|
14
|
|
|
|
|
15
|
|
|
/** @var integer */ |
|
16
|
|
|
const CLOSE_BRACE_LENGTH = 1; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* constructor |
|
20
|
|
|
* |
|
21
|
|
|
* @param ParserInterface $expressionParser parser for unserialize expression |
|
22
|
|
|
*/ |
|
23
|
107 |
|
public function __construct(ParserInterface $expressionParser) |
|
24
|
|
|
{ |
|
25
|
107 |
|
$this->expressionParser = $expressionParser; |
|
26
|
107 |
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* parse given `$source` as PHP serialized array |
|
30
|
|
|
* |
|
31
|
|
|
* @param Source $source parser input |
|
32
|
|
|
* @param string $args array length |
|
33
|
|
|
* @return array |
|
34
|
|
|
* @throws UnserializeFailedException |
|
35
|
|
|
*/ |
|
36
|
9 |
|
public function handle(Source $source, $args) |
|
37
|
|
|
{ |
|
38
|
9 |
|
$length = intval($args, 10); |
|
39
|
|
|
|
|
40
|
9 |
|
$result = array(); |
|
41
|
9 |
|
for ($i = 0; $i < $length; ++$i) { |
|
42
|
6 |
|
list($key, $source) = $this->parseKey($source); |
|
43
|
5 |
|
list($value, $source) = $this->expressionParser->parse($source); |
|
44
|
4 |
|
$result[$key] = $value; |
|
45
|
4 |
|
} |
|
46
|
|
|
|
|
47
|
6 |
|
$source->consume('}', self::CLOSE_BRACE_LENGTH); |
|
48
|
4 |
|
return array($result, $source); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* parse given `$source` as array key (s.t. integer|string) |
|
53
|
|
|
* |
|
54
|
|
|
* @param Source $source input |
|
55
|
|
|
* @return array |
|
56
|
|
|
* @throws UnserializeFailedException |
|
57
|
|
|
*/ |
|
58
|
6 |
|
private function parseKey($source) |
|
59
|
|
|
{ |
|
60
|
6 |
|
list($key, $source) = $this->expressionParser->parse($source); |
|
61
|
6 |
|
if (!is_integer($key) && !is_string($key)) { |
|
62
|
1 |
|
return $source->triggerError(); |
|
63
|
|
|
} |
|
64
|
5 |
|
return array($key, $source); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|