|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Handler for PHP serialiezed array |
|
5
|
|
|
*/ |
|
6
|
|
View Code Duplication |
class xKerman_Restricted_ArrayHandler implements xKerman_Restricted_HandlerInterface |
|
|
|
|
|
|
7
|
|
|
{ |
|
8
|
|
|
/** @var ParserInterface $expressionParser parser for unserialize expression */ |
|
9
|
|
|
private $expressionParser; |
|
10
|
|
|
/** @var integer */ |
|
11
|
|
|
const CLOSE_BRACE_LENGTH = 1; |
|
12
|
|
|
/** |
|
13
|
|
|
* constructor |
|
14
|
|
|
* |
|
15
|
|
|
* @param ParserInterface $expressionParser parser for unserialize expression |
|
|
|
|
|
|
16
|
|
|
*/ |
|
17
|
|
|
public function __construct(xKerman_Restricted_ParserInterface $expressionParser) |
|
18
|
|
|
{ |
|
19
|
|
|
$this->expressionParser = $expressionParser; |
|
|
|
|
|
|
20
|
|
|
} |
|
21
|
|
|
/** |
|
22
|
|
|
* parse given `$source` as PHP serialized array |
|
23
|
|
|
* |
|
24
|
|
|
* @param Source $source parser input |
|
|
|
|
|
|
25
|
|
|
* @param string $args array length |
|
26
|
|
|
* @return array |
|
27
|
|
|
* @throws UnserializeFailedException |
|
28
|
|
|
*/ |
|
29
|
|
|
public function handle(xKerman_Restricted_Source $source, $args) |
|
30
|
|
|
{ |
|
31
|
|
|
$length = intval($args, 10); |
|
32
|
|
|
$result = array(); |
|
33
|
|
|
for ($i = 0; $i < $length; ++$i) { |
|
34
|
|
|
list($key, $source) = $this->parseKey($source); |
|
35
|
|
|
list($value, $source) = $this->expressionParser->parse($source); |
|
36
|
|
|
$result[$key] = $value; |
|
37
|
|
|
} |
|
38
|
|
|
$source->consume('}', self::CLOSE_BRACE_LENGTH); |
|
39
|
|
|
return array($result, $source); |
|
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
|
|
|
private function parseKey($source) |
|
49
|
|
|
{ |
|
50
|
|
|
list($key, $source) = $this->expressionParser->parse($source); |
|
51
|
|
|
if (!is_integer($key) && !is_string($key)) { |
|
52
|
|
|
return $source->triggerError(); |
|
53
|
|
|
} |
|
54
|
|
|
return array($key, $source); |
|
55
|
|
|
} |
|
56
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.