-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.php
590 lines (512 loc) · 14.3 KB
/
Parser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php
/*
* This File is part of the Selene\Module\Xml package
*
* (c) Thomas Appel <[email protected]>
*
* For full copyright and license information, please refer to the LICENSE file
* that was distributed with this package.
*/
namespace Selene\Module\Xml;
use \Selene\Module\Xml\Dom\DOMElement;
use \Selene\Module\Xml\Dom\DOMDocument;
use \Selene\Module\Xml\Loader\Loader;
use \Selene\Module\Xml\Loader\LoaderInterface;
use \Selene\Module\Common\Helper\clearValue;
use \Selene\Module\Common\Helper\ListHelper;
use \Selene\Module\Common\Helper\StringHelper;
use \Selene\Module\Common\Traits\Getter;
/**
* @class Parser
* @package Selene\Module\Xml
* @version $Id$
*/
class Parser implements ParserInterface
{
use Getter;
/**
* pluralizer
*
* @var callable
*/
private $pluralizer;
/**
* keyNormalizer
*
* @var callable
*/
private $keyNormalizer;
/**
* options
*
* @var array
*/
private $options;
/**
* Creates a new `Parser` instance.
*
* @param LoaderInterface $loader
*/
public function __construct(LoaderInterface $loader = null)
{
$this->loader = $loader ?: new Loader($this->getLoaderConfig());
$this->options = [];
}
/**
* Toggle on/off merging attributes to array keys.
*
* @param boolean $merge
*
* @access public
* @return void
*/
public function setMergeAttributes($merge)
{
$this->options['merge_attributes'] = (bool)$merge;
}
/**
* Set the attributes key name.
*
* The default key will be `@attributes`.
* This will be ignored if merging attributes is active.
*
* @param string $key
*
* @access public
* @return void
*/
public function setAttributesKey($key)
{
$this->options['attribute_key'] = $key;
}
/**
* Get the attributes key.
*
* Defaults to `@attributes`.
*
* @access public
* @return string
*/
public function getAttributesKey()
{
return $this->getDefault($this->options, 'attribute_key', '@attributes');
}
/**
* Set the list identifier key.
*
* Elements that match with that key will always be considered a list,
* as long as thy have any parent element.
*
* @param string $key
*
* @access public
* @return void
*/
public function setIndexKey($key)
{
$this->options['list_key'] = $key;
}
/**
* getIndexKey
*
* @access public
* @return mixed
*/
public function getIndexKey()
{
return $this->getListKey();
}
/**
* Set a custom function to normalize an xml node name to a php array key name.
*
* By default, hyphens are converted to underscores.
*
* @param callable $normalizer
*
* @access public
* @return void
*/
public function setKeyNormalizer(callable $normalizer)
{
$this->keyNormalizer = $normalizer;
}
/**
* Set the pluralizer.
*
* @param callable $pluralizer
*
* @access public
* @return void
*/
public function setPluralizer(callable $pluralizer = null)
{
$this->pluralizer = $pluralizer;
}
/**
* Parses a `\DOMDocument` into an array.
*
* @param \DOMDocument $xml
*
* @access public
* @return array
*/
public function parseDom(\DOMDocument $xml)
{
if (!$xml instanceof DOMDocument) {
$xml = $this->convertDocument($xml);
}
if (!$root = $xml->documentElement) {
throw new \InvalidArgumentException('DOM has no root element');
}
return [$xml->documentElement->nodeName => $this->parseDomElement($root)];
}
/**
* Parses an xml string or file into an array.
*
* @param string $xml
*
* @access public
* @return array
*/
public function parse($xml)
{
$opts = $this->getLoaderConfig();
$opts[LoaderInterface::FROM_STRING] = !(is_file($xml) && stream_is_local($xml));
return $this->parseDom($this->loader->load($xml, $opts));
}
/**
* Parse the contents of a `DOMElement` to an array.
*
* @param DOMElement $xml
*
* @access public
* @return null|array
*/
public function parseDomElement(DOMElement $xml)
{
$attributes = $this->parseElementAttributes($xml);
$hasAttributes = (bool)$attributes;
$text = $this->prepareTextValue($xml, current($attributes) ?: null);
$result = $this->parseElementNodes($xml->xpath('./child::*'), $xml->nodeName);
if ($hasAttributes) {
if (null !== $text) {
$result['value'] = $text;
}
if ($this->mergeAttributes()) {
$attributes = $attributes[$this->getAttributesKey()];
}
$result = array_merge($attributes, $result);
return $result;
}
if (null !== $text) {
if (!empty($result)) {
$result['value'] = $text;
} else {
$result = $text;
}
return $result;
}
return (!(bool)$result && null === $text) ? null : $result;
}
/**
* Get the php equivalent of an input value derived from any king of xml.
*
* @param mixed $val
* @param mixed $default
* @param ParserInterface $parser
*
* @access public
* @return mixed
*/
public static function getPhpValue($val, $default = null, ParserInterface $parser = null)
{
if ($val instanceof DOMElement) {
$parser = $parser ?: new static;
return $parser->parseDomElement($val);
}
if (0 === strlen($val)) {
return $default;
}
if (is_numeric($val)) {
return StringHelper::strStartsWith($val, '0x') ? hexdec($val) :
(ctype_digit($val) ? intval($val) : floatval($val));
}
if (($lval = strtolower($val)) === 'true' || $lval === 'false') {
return $lval === 'true' ? true : false;
}
return $val;
}
/**
* Get the text of a `DOMElement` excluding the contents
* of its child elements.
*
* @param DOMElement $element
* @param boolean $concat
*
* @access private
* @return string|array returns an array of strings if `$concat` is `false`
*/
public static function getElementText(DOMElement $element, $concat = true)
{
$textNodes = [];
foreach ($element->xpath('./text()') as $text) {
if ($value = \clearValue($text->nodeValue)) {
$textNodes[] = $value;
}
}
return $concat ? implode($textNodes) : $textNodes;
}
/**
* Convert hyphens to underscores.
*
* @param string $name
*
* @static
* @access public
* @return string
*/
public static function fixNodeName($name)
{
return strtr(StringHelper::strLowDash($name), ['-' => '_']);
}
/**
* Get the list identifier key.
*
* @access protected
* @return string
*/
protected function getListKey()
{
return $this->getDefault($this->options, 'list_key', null);
}
/**
* Check if a given string is the list identifier.
*
* @param string $name
* @param string $prefix
*
* @access protected
* @return boolean
*/
protected function isListKey($name, $prefix = null)
{
return $this->prefixKey($this->getListKey(), $prefix) === $name;
}
/**
* Determine weather to merge attributes or not.
*
* @access protected
* @return boolean
*/
protected function mergeAttributes()
{
return $this->getDefault($this->options, 'merge_attributes', false);
}
/**
* getLoaderConfig
*
* @access protected
* @return mixed
*/
protected function getLoaderConfig()
{
return [
LoaderInterface::FROM_STRING => false,
LoaderInterface::SIMPLEXML => false,
LoaderInterface::DOM_CLASS => __NAMESPACE__.'\\Dom\DOMDocument',
LoaderInterface::SIMPLEXML_CLASS => __NAMESPACE__.'\\SimpleXMLElement'
];
}
/**
* Normalize a node key
*
* @param mixed $key
*
* @access protected
* @return mixed
*/
protected function normalizeKey($key)
{
if (null !== $this->keyNormalizer) {
return call_user_func($this->keyNormalizer, $key);
}
return static::fixNodeName($key);
}
/**
* Convert boolean like and numeric values to their php equivalent values.
*
* @param DOMElement $xml the element to get the value from
* @param array $attributes
* @return mixed
*/
private function prepareTextValue(DOMElement $xml, array $attributes = null)
{
$text = static::getElementText($xml, true);
return (isset($attributes['type']) && 'text' === $attributes['type']) ?
clearValue($text) :
static::getPhpValue($text, null, $this);
}
/**
* Parse a nodelist into a array
*
* @param \DOMNodeList|array $children elements to parse
* @param string $parentName node name of the parent element
*
* @access private
* @return array
*/
private function parseElementNodes($children, $parentName = null)
{
$result = [];
foreach ($children as $child) {
$prefix = $child->prefix ?: null;
$oname = $this->normalizeKey($child->nodeName);
$name = $this->prefixKey($oname, $prefix);
if (isset($result[$name])) {
$this->parseSetResultNodes($child, $name, $result);
continue;
}
$this->parseUnsetResultNodes($child, $name, $oname, $parentName, $result, $prefix);
}
return $result;
}
/**
* Parse a `DOMElement` if a result key is set.
*
* @param DOMElement $child
* @param string $name
* @param array $result
*
* @access private
* @return mixed|boolean the result, else `false` if no result.
*/
private function parseSetResultNodes(DOMElement $child, $name, array &$result = null)
{
if (!(is_array($result[$name]) && ListHelper::arrayIsList($result[$name]))) {
return false;
}
$value = static::getPhpValue($child, null, $this);
if (is_array($value) && ListHelper::arrayIsList($value)) {
return $result[$name] = array_merge($result[$name], $value);
}
return $result[$name][] = $value;
}
/**
* Parse a `DOMElement` if a result key is unset.
*
* @param DOMElement $child
* @param string $name
* @param string $oname
* @param string $pName
* @param array $result
* @param string $prefix
*
* @access private
* @return mixed the result
*/
private function parseUnsetResultNodes(DOMElement $child, $name, $oname, $pName, array &$result, $prefix = null)
{
$value = static::getPhpValue($child, null, $this);
if ($this->isListKey($name, $prefix) || $this->isEqualOrPluralOf($this->normalizeKey($pName), $oname)) {
return $result[] = $value;
}
if (1 < $this->getEqualNodes($child, $prefix)->length) {
return $result[$name][] = $value;
}
return $result[$name] = $value;
}
/**
* Parse element attributes into an array.
*
* @param DOMElement $xml
*
* @access private
* @return array
*/
private function parseElementAttributes(DOMElement $xml)
{
$elementAttrs = $xml->xpath('./@*');
$attrs = [];
if (0 === $elementAttrs->length) {
return $attrs;
}
foreach ($elementAttrs as $key => $attribute) {
$value = static::getPhpValue($attribute->nodeValue, null, $this);
$name = $this->normalizeKey($attribute->nodeName);
$attrs[$this->prefixKey($name, $attribute->prefix ?: null)] = $value;
}
return [$this->getAttributesKey() => $attrs];
}
/**
* Check if the input string is a plural or equal to a given comparative string.
*
* @param string $name the input string
* @param string $singular the string to compare with
*
* @access private
* @return boolean
*/
private function isEqualOrPluralOf($name, $singular)
{
return 0 === strnatcmp($name, $singular) || 0 === strnatcmp($name, $this->pluralize($singular));
}
/**
* Attempt to pluralize a string.
*
* @param string $singular
*
* @access private
* @return string
*/
private function pluralize($singular)
{
if (null === $this->pluralizer) {
return $singular;
}
return call_user_func($this->pluralizer, $singular);
}
/**
* A lookahead to find sibling elements with similar names.
*
* @param DOMElement $node the node in charge.
* @param string $prefix the element prefix
*
* @access protected
* @return \DOMNodeList
*/
private function getEqualNodes(DOMElement $node, $prefix = null)
{
$name = $this->prefixKey($node->nodeName, $prefix);
return $node->xpath(
sprintf(".|following-sibling::*[name() = '%s']|preceding-sibling::*[name() = '%s']", $name, $name)
);
}
/**
* Prepend a string.
*
* Will pass-through the original string if `$prefix` is `null`.
*
* @param string $key the key to prefix
* @param string $prefix the prefix
*
* @access private
* @return string
*/
private function prefixKey($key, $prefix = null)
{
return $prefix ? sprintf('%s:%s', $prefix, $key) : $key;
}
/**
* Converts a `\DOMDocument`that is not an instance of
* `Selene\Module\Dom\DOMDocument`.
*
* @param \DOMDocument $xml the document to convert
*
* @access private
* @return DOMDocument
*/
private function convertDocument(\DOMDocument $xml)
{
return $this->loader->load($xml->saveXML(), [LoaderInterface::FROM_STRING => true]);
}
}