|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Noodlehaus\StringParser; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Noodlehaus\Exception\ParseException; |
|
7
|
|
|
use Noodlehaus\Exception\UnsupportedFormatException; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* PHP string parser |
|
11
|
|
|
* |
|
12
|
|
|
* @package Config |
|
13
|
|
|
* @author Jesus A. Domingo <[email protected]> |
|
14
|
|
|
* @author Hassan Khan <[email protected]> |
|
15
|
|
|
* @link https://github.com/noodlehaus/config |
|
16
|
|
|
* @license MIT |
|
17
|
|
|
*/ |
|
18
|
|
|
class Php implements StringParserInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* {@inheritDoc} |
|
22
|
|
|
* Loads a PHP string and gets its' contents as an array |
|
23
|
|
|
* |
|
24
|
|
|
* @throws ParseException If the PHP file throws an exception |
|
25
|
|
|
* @throws UnsupportedFormatException If the PHP file does not return an array |
|
26
|
|
|
*/ |
|
27
|
12 |
|
public function parse($configuration) |
|
28
|
|
|
{ |
|
29
|
|
|
// Strip PHP start and end tags |
|
30
|
12 |
|
$configuration = str_replace('<?php', '', $configuration); |
|
31
|
12 |
|
$configuration = str_replace('<?', '', $configuration); |
|
32
|
12 |
|
$configuration = str_replace('?>', '', $configuration); |
|
33
|
|
|
|
|
34
|
|
|
// Eval the string, if it throws an exception, rethrow it |
|
35
|
|
|
try { |
|
36
|
12 |
|
$temp = eval($configuration); |
|
|
|
|
|
|
37
|
6 |
|
} catch (Exception $exception) { |
|
|
|
|
|
|
38
|
3 |
|
throw new ParseException( |
|
39
|
|
|
[ |
|
40
|
3 |
|
'message' => 'PHP file threw an exception', |
|
41
|
3 |
|
'exception' => $exception, |
|
42
|
|
|
] |
|
43
|
1 |
|
); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
// If we have a callable, run it and expect an array back |
|
47
|
9 |
|
if (is_callable($temp)) { |
|
48
|
3 |
|
$temp = call_user_func($temp); |
|
49
|
1 |
|
} |
|
50
|
|
|
|
|
51
|
|
|
// Check for array, if its anything else, throw an exception |
|
52
|
9 |
|
if (!is_array($temp)) { |
|
53
|
3 |
|
throw new UnsupportedFormatException('PHP file does not return an array'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
6 |
|
return $temp; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
On one hand,
evalmight be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM,evalprevents some optimization that they perform.