1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Noodlehaus\Parser; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Noodlehaus\Exception\ParseException; |
7
|
|
|
use Noodlehaus\Exception\UnsupportedFormatException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* PHP parser |
11
|
|
|
* |
12
|
|
|
* @package Config |
13
|
|
|
* @author Jesus A. Domingo <[email protected]> |
14
|
|
|
* @author Hassan Khan <[email protected]> |
15
|
|
|
* @author Filip Š <[email protected]> |
16
|
|
|
* @link https://github.com/noodlehaus/config |
17
|
|
|
* @license MIT |
18
|
|
|
*/ |
19
|
|
|
class Php implements ParserInterface |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* {@inheritDoc} |
23
|
|
|
* Loads a PHP string and gets its' contents as an array |
24
|
|
|
* |
25
|
|
|
* @throws ParseException If the PHP string throws an exception |
26
|
|
|
* @throws UnsupportedFormatException If the PHP string does not return an array |
27
|
|
|
*/ |
28
|
12 |
|
public function parse($config, $filename = null) |
29
|
|
|
{ |
30
|
|
|
// Strip PHP start and end tags |
31
|
12 |
|
$config = str_replace('<?php', '', $config); |
32
|
12 |
|
$config = str_replace('<?', '', $config); |
33
|
12 |
|
$config = str_replace('?>', '', $config); |
34
|
|
|
|
35
|
|
|
// Eval the string, if it throws an exception, rethrow it |
36
|
|
|
try { |
37
|
12 |
|
$temp = eval($config); |
|
|
|
|
38
|
6 |
|
} catch (Exception $exception) { |
|
|
|
|
39
|
3 |
|
throw new ParseException( |
40
|
|
|
[ |
41
|
3 |
|
'message' => 'PHP string threw an exception', |
42
|
3 |
|
'exception' => $exception, |
43
|
|
|
] |
44
|
1 |
|
); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// If we have a callable, run it and expect an array back |
48
|
9 |
|
if (is_callable($temp)) { |
49
|
3 |
|
$temp = call_user_func($temp); |
50
|
1 |
|
} |
51
|
|
|
|
52
|
|
|
// Check for array, if its anything else, throw an exception |
53
|
9 |
|
if (!is_array($temp)) { |
54
|
3 |
|
throw new UnsupportedFormatException('PHP string does not return an array'); |
55
|
|
|
} |
56
|
|
|
|
57
|
6 |
|
return $temp; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* {@inheritDoc} |
62
|
|
|
*/ |
63
|
3 |
|
public static function getSupportedExtensions() |
64
|
|
|
{ |
65
|
3 |
|
return ['php']; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
On one hand,
eval
might 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,eval
prevents some optimization that they perform.