1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Noodlehaus\Parser; |
4
|
|
|
|
5
|
|
|
use Noodlehaus\Exception\ParseException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* XML parser |
9
|
|
|
* |
10
|
|
|
* @package Config |
11
|
|
|
* @author Jesus A. Domingo <[email protected]> |
12
|
|
|
* @author Hassan Khan <[email protected]> |
13
|
|
|
* @author Filip Š <[email protected]> |
14
|
|
|
* @link https://github.com/noodlehaus/config |
15
|
|
|
* @license MIT |
16
|
|
|
*/ |
17
|
|
|
class Xml implements ParserInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* {@inheritDoc} |
21
|
|
|
* Parses an XML file as an array |
22
|
|
|
* |
23
|
|
|
* @throws ParseException If there is an error parsing the XML file |
24
|
|
|
*/ |
25
|
6 |
|
public function parseFile($filename) |
26
|
|
|
{ |
27
|
6 |
|
libxml_use_internal_errors(true); |
28
|
6 |
|
$data = simplexml_load_file($filename, null, LIBXML_NOERROR); |
29
|
|
|
|
30
|
6 |
|
return (array)$this->parse($data, $filename); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* {@inheritDoc} |
35
|
|
|
* Parses an XML string as an array |
36
|
|
|
* |
37
|
|
|
* @throws ParseException If there is an error parsing the XML string |
38
|
|
|
*/ |
39
|
3 |
|
public function parseString($config) |
40
|
|
|
{ |
41
|
3 |
|
libxml_use_internal_errors(true); |
42
|
3 |
|
$data = simplexml_load_string($config, null, LIBXML_NOERROR); |
43
|
3 |
|
return (array)$this->parse($data); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Completes parsing of XML data |
48
|
|
|
* |
49
|
|
|
* @param array $data |
50
|
|
|
* @param string $filename |
51
|
|
|
* |
52
|
|
|
* @return array|null |
53
|
|
|
* |
54
|
|
|
* @throws ParseException If there is an error parsing the XML data |
55
|
|
|
*/ |
56
|
6 |
|
protected function parse($data = null, $filename = null) |
57
|
|
|
{ |
58
|
6 |
|
if ($data === false) { |
59
|
3 |
|
$errors = libxml_get_errors(); |
60
|
3 |
|
$latestError = array_pop($errors); |
61
|
|
|
$error = [ |
62
|
3 |
|
'message' => $latestError->message, |
63
|
3 |
|
'type' => $latestError->level, |
64
|
3 |
|
'code' => $latestError->code, |
65
|
3 |
|
'file' => $filename, |
66
|
3 |
|
'line' => $latestError->line, |
67
|
|
|
]; |
68
|
3 |
|
throw new ParseException($error); |
69
|
|
|
} |
70
|
|
|
|
71
|
3 |
|
$data = json_decode(json_encode($data), true); |
72
|
|
|
|
73
|
3 |
|
return $data; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* {@inheritDoc} |
78
|
|
|
*/ |
79
|
3 |
|
public static function getSupportedExtensions() |
80
|
|
|
{ |
81
|
3 |
|
return ['xml']; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|