/
class.xmlelement.php
934 lines (821 loc) · 25.5 KB
/
class.xmlelement.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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
<?php
/**
* @package toolkit
*/
/**
* `XMLElement` is a class used to simulate PHP's `DOMElement`
* class. Each object is a representation of a HTML element
* and can store it's children in an array. When an `XMLElement`
* is generated, it is output as an XML string.
*/
class XMLElement implements IteratorAggregate
{
/**
* This is an array of HTML elements that are self closing.
* @var array
*/
protected static $no_end_tags = array(
'area', 'base', 'br', 'col', 'hr', 'img', 'input', 'link', 'meta', 'param'
);
/**
* The name of the HTML Element, eg. 'p'
* @var string
*/
private $_name;
/**
* The value of this `XMLElement` as a string
* @var string
*/
private $_value = array();
/**
* Any additional attributes can be included in an associative array
* with the key being the name and the value being the value of the
* attribute.
* @var array
*/
private $_attributes = array();
/**
* Children of this `XMLElement`, which will also be `XMLElement`'s
* @var array
*/
private $_children = array();
/**
* Any processing instructions that the XSLT should know about when a
* `XMLElement` is generated
* @var array
*/
private $_processingInstructions = array();
/**
* The DTD the should be output when a `XMLElement` is generated, defaults to null.
* @var string
*/
private $_dtd = null;
/**
* The encoding of the `XMLElement`, defaults to 'utf-8'
* @var string
*/
private $_encoding = 'utf-8';
/**
* The version of the XML that is used for generation, defaults to '1.0'
* @var string
*/
private $_version = '1.0';
/**
* The type of element, defaults to 'xml'. Used when determining the style
* of end tag for this element when generated
* @var string
*/
private $_elementStyle = 'xml';
/**
* When set to true this will include the XML declaration will be
* output when the `XMLElement` is generated. Defaults to `false`.
* @var boolean
*/
private $_includeHeader = false;
/**
* Specifies whether this HTML element has an closing element, or if
* it self closing. Defaults to `true`.
* eg. `<p></p>` or `<input />`
* @var boolean
*/
private $_selfclosing = true;
/**
* Specifies whether attributes need to have a value or if they can
* be shorthand. Defaults to `true`. An example of this would be:
* `<option selected>Value</option>`
* @var boolean
*/
private $_allowEmptyAttributes = true;
/**
* The constructor for the `XMLElement`
*
* @param string $name
* The name of the `XMLElement`, 'p'.
* @param string|XMLElement $value (optional)
* The value of this `XMLElement`, it can be a string
* or another `XMLElement` object.
* @param array $attributes (optional)
* Any additional attributes can be included in an associative array with
* the key being the name and the value being the value of the attribute.
* Attributes set from this array will override existing attributes
* set by previous params.
* @param boolean $createHandle
* Whether this function should convert the `$name` to a handle. Defaults to
* `false`.
*/
public function __construct($name, $value = null, array $attributes = array(), $createHandle = false)
{
$this->setName($name, $createHandle);
$this->setValue($value);
if (is_array($attributes) && !empty($attributes)) {
$this->setAttributeArray($attributes);
}
}
/**
* Accessor for `$_name`
*
* @return string
*/
public function getName()
{
return $this->_name;
}
/**
* Accessor for `$_value`
*
* @return string|XMLElement
*/
public function getValue()
{
$value = '';
if (is_array($this->_value)) {
foreach ($this->_value as $v) {
if ($v instanceof XMLElement) {
$value .= $v->generate();
} else {
$value .= $v;
}
}
} elseif (!is_null($this->_value)) {
$value = $this->_value;
}
return $value;
}
/**
* Retrieves the value of an attribute by name
*
* @param string $name
* @return string
*/
public function getAttribute($name)
{
if (!isset($this->_attributes[$name])) {
return null;
}
return $this->_attributes[$name];
}
/**
* Accessor for `$this->_attributes`
*
* @return array
*/
public function getAttributes()
{
return $this->_attributes;
}
/**
* Retrieves a child-element by position
*
* @since Symphony 2.3
* @param integer $position
* @return XMLElement
*/
public function getChild($position)
{
if (!isset($this->_children[$this->getRealIndex($position)])) {
return null;
}
return $this->_children[$this->getRealIndex($position)];
}
/**
* Accessor for `$this->_children`
*
* @return array
*/
public function getChildren()
{
return $this->_children;
}
/**
* Accessor for `$this->_children`, returning only `XMLElement` children,
* not text nodes.
*
* @return XMLElementChildrenFilter
*/
public function getIterator()
{
return new XMLElementChildrenFilter(new ArrayIterator($this->_children));
}
/**
* Retrieves child-element by name and position. If no child is found,
* `NULL` will be returned.
*
* @since Symphony 2.3
* @param string $name
* @param integer $position
* @return XMLElement
*/
public function getChildByName($name, $position)
{
$result = array_values($this->getChildrenByName($name));
if (!isset($result[$position])) {
return null;
}
return $result[$position];
}
/**
* Accessor to return an associative array of all `$this->_children`
* whose's name matches the given `$name`. If no children are found,
* an empty array will be returned.
*
* @since Symphony 2.2.2
* @param string $name
* @return array
* An associative array where the key is the `$index` of the child
* in `$this->_children`
*/
public function getChildrenByName($name)
{
$result = array();
foreach ($this as $i => $child) {
if ($child->getName() != $name) {
continue;
}
$result[$i] = $child;
}
return $result;
}
/**
* Adds processing instructions to this `XMLElement`
*
* @param string $pi
*/
public function addProcessingInstruction($pi)
{
$this->_processingInstructions[] = $pi;
}
/**
* Sets the DTD for this `XMLElement`
*
* @param string $dtd
*/
public function setDTD($dtd)
{
$this->_dtd = $dtd;
}
/**
* Sets the encoding for this `XMLElement` for when
* it's generated.
*
* @param string $value
*/
public function setEncoding($value)
{
$this->_encoding = $value;
}
/**
* Sets the version for the XML declaration of this
* `XMLElement`
*
* @param string $value
*/
public function setVersion($value)
{
$this->_version = $value;
}
/**
* Sets the style of the `XMLElement`. Used when the
* `XMLElement` is being generated to determine whether
* needs to be closed, is self closing or is standalone.
*
* @param string $style (optional)
* Defaults to 'xml', any other value will trigger the
* XMLElement to be closed by itself or left standalone
* if it is in the `XMLElement::no_end_tags`.
*/
public function setElementStyle($style = 'xml')
{
$this->_elementStyle = $style;
}
/**
* Sets whether this `XMLElement` needs to output an
* XML declaration or not. This normally is only set to
* true for the parent `XMLElement`, eg. 'html'.
*
* @param bool|string $value (optional)
* Defaults to false
*/
public function setIncludeHeader($value = false)
{
$this->_includeHeader = $value;
}
/**
* Sets whether this `XMLElement` is self closing or not.
*
* @param bool|string $value (optional)
* Defaults to true
*/
public function setSelfClosingTag($value = true)
{
$this->_selfclosing = $value;
}
/**
* Specifies whether attributes need to have a value
* or if they can be shorthand on this `XMLElement`.
*
* @param bool|string $value (optional)
* Defaults to true
*/
public function setAllowEmptyAttributes($value = true)
{
$this->_allowEmptyAttributes = $value;
}
/**
* Sets the name of this `XMLElement`, ie. 'p' => <p />
*
* @since Symphony 2.3.2
* @param string $name
* The name of the `XMLElement`, 'p'.
* @param boolean $createHandle
* Whether this function should convert the `$name` to a handle. Defaults to
* `false`.
*/
public function setName($name, $createHandle = false)
{
$this->_name = ($createHandle) ? Lang::createHandle($name) : $name;
}
/**
* Sets the value of the `XMLElement`. Checks to see
* whether the value should be prepended or appended
* to the children.
*
* @param string|XMLElement|array $value
* Defaults to true.
*/
public function setValue($value)
{
if (is_array($value)) {
$value = implode(', ', $value);
}
if (!is_null($value)) {
$this->_value = $value;
$this->appendChild($value);
}
}
/**
* This function will remove all text attributes from the `XMLElement` node
* and replace them with the given value.
*
* @since Symphony 2.4
* @param string|XMLElement|array $value
*/
public function replaceValue($value)
{
foreach ($this->_children as $i => $child) {
if ($child instanceof XMLElement) {
continue;
}
unset($this->_children[$i]);
}
$this->setValue($value);
}
/**
* Sets an attribute
*
* @param string $name
* The name of the attribute
* @param string $value
* The value of the attribute
*/
public function setAttribute($name, $value)
{
$this->_attributes[$name] = $value;
}
/**
* A convenience method to quickly add multiple attributes to
* an `XMLElement`
*
* @param array $attributes
* Associative array with the key being the name and
* the value being the value of the attribute.
*/
public function setAttributeArray(array $attributes = null)
{
if (!is_array($attributes) || empty($attributes)) {
return;
}
foreach ($attributes as $name => $value) {
$this->setAttribute($name, $value);
}
}
/**
* A convenience method that encapsulate validation of a child node.
* This should prevent generate errors by catching them earlier.
*
* @since Symphony 2.5.0
* @param XMLElement $child
* The child to validate
*
*/
private function validateChild($child)
{
if ($this === $child) {
throw new Exception(__('Can not add the element itself as one of its child'));
}
}
/**
* This function expects an array of `XMLElement` that will completely
* replace the contents of `$this->_children`. Take care when using
* this function.
*
* @since Symphony 2.2.2
* @param array $children
* An array of XMLElement's to act as the children for the current
* XMLElement instance
* @return boolean
*/
public function setChildren(array $children = null)
{
foreach ($children as $child) {
$this->validateChild($child);
}
$this->_children = $children;
return true;
}
/**
* Adds an `XMLElement` to the children array
*
* @param XMLElement|string $child
* @return boolean
*/
public function appendChild($child)
{
$this->validateChild($child);
$this->_children[] = $child;
return true;
}
/**
* A convenience method to add children to an `XMLElement`
* quickly.
*
* @param array $children
*/
public function appendChildArray(array $children = null)
{
if (is_array($children) && !empty($children)) {
foreach ($children as $child) {
$this->appendChild($child);
}
}
}
/**
* Adds an `XMLElement` to the start of the children
* array, this will mean it is output before any other
* children when the `XMLElement` is generated
*
* @param XMLElement $child
*/
public function prependChild(XMLElement $child)
{
array_unshift($this->_children, $child);
}
/**
* A convenience method to quickly add a CSS class to this `XMLElement`'s
* existing class attribute. If the attribute does not exist, it will
* be created.
*
* @since Symphony 2.2.2
* @param string $class
* The CSS classname to add to this `XMLElement`
*/
public function addClass($class)
{
$current = preg_split('%\s+%', $this->getAttribute('class'), 0, PREG_SPLIT_NO_EMPTY);
$added = preg_split('%\s+%', $class, 0, PREG_SPLIT_NO_EMPTY);
$current = array_merge($current, $added);
$classes = implode(' ', $current);
$this->setAttribute('class', $classes);
}
/**
* A convenience method to quickly remove a CSS class from an
* `XMLElement`'s existing class attribute. If the attribute does not
* exist, this method will do nothing.
*
* @since Symphony 2.2.2
* @param string $class
* The CSS classname to remove from this `XMLElement`
*/
public function removeClass($class)
{
$classes = preg_split('%\s+%', $this->getAttribute('class'), 0, PREG_SPLIT_NO_EMPTY);
$removed = preg_split('%\s+%', $class, 0, PREG_SPLIT_NO_EMPTY);
$classes = array_diff($classes, $removed);
$classes = implode(' ', $classes);
$this->setAttribute('class', $classes);
}
/**
* Returns the number of children this `XMLElement` has.
* @return integer
*/
public function getNumberOfChildren()
{
return count($this->_children);
}
/**
* Given the position of the child in the `$this->_children`,
* this function will unset the child at that position. This function
* is not reversible. This function does not alter the key's of
* `$this->_children` after removing a child
*
* @since Symphony 2.2.2
* @param integer $index
* The index of the child to be removed. If the index given is negative
* it will be calculated from the end of `$this->_children`.
* @return boolean
* true if child was successfully removed, false otherwise.
*/
public function removeChildAt($index)
{
if (!is_numeric($index)) {
return false;
}
$index = $this->getRealIndex($index);
if (!isset($this->_children[$index])) {
return false;
}
unset($this->_children[$index]);
return true;
}
/**
* Given a desired index, and an `XMLElement`, this function will insert
* the child at that index in `$this->_children` shuffling all children
* greater than `$index` down one. If the `$index` given is greater then
* the number of children for this `XMLElement`, the `$child` will be
* appended to the current `$this->_children` array.
*
* @since Symphony 2.2.2
* @param integer $index
* The index where the `$child` should be inserted. If this is negative
* the index will be calculated from the end of `$this->_children`.
* @param XMLElement $child
* The XMLElement to insert at the desired `$index`
* @return boolean
*/
public function insertChildAt($index, XMLElement $child = null)
{
if (!is_numeric($index)) {
return false;
}
$this->validateChild($child);
if ($index >= $this->getNumberOfChildren()) {
return $this->appendChild($child);
}
$start = array_slice($this->_children, 0, $index);
$end = array_slice($this->_children, $index);
$merge = array_merge($start, array(
$index => $child
), $end);
return $this->setChildren($merge);
}
/**
* Given the position of the child to replace, and an `XMLElement`
* of the replacement child, this function will replace one child
* with another
*
* @since Symphony 2.2.2
* @param integer $index
* The index of the child to be replaced. If the index given is negative
* it will be calculated from the end of `$this->_children`.
* @param XMLElement $child
* An XMLElement of the new child
* @return boolean
*/
public function replaceChildAt($index, XMLElement $child = null)
{
if (!is_numeric($index)) {
return false;
}
$this->validateChild($child);
$index = $this->getRealIndex($index);
if (!isset($this->_children[$index])) {
return false;
}
$this->_children[$index] = $child;
return true;
}
/**
* Given an `$index`, return the real index in `$this->_children`
* depending on if the value is negative or not. Negative values
* will work from the end of an array.
*
* @since Symphony 2.2.2
* @param integer $index
* Positive indexes are returned as is, negative indexes are deducted
* from the end of `$this->_children`
* @return integer
*/
private function getRealIndex($index)
{
if ($index >= 0) {
return $index;
}
return $this->getNumberOfChildren() + $index;
}
/**
* This function strips characters that are not allowed in XML
*
* @since Symphony 2.3
* @link http://www.w3.org/TR/xml/#charsets
* @link http://www.phpedit.net/snippet/Remove-Invalid-XML-Characters
* @param string $value
* @return string
*/
public static function stripInvalidXMLCharacters($value)
{
if (Lang::isUnicodeCompiled()) {
return preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $value);
} else {
$ret = '';
if (empty($value)) {
return $ret;
}
$length = strlen($value);
for ($i=0; $i < $length; $i++) {
$current = ord($value{$i});
if (($current == 0x9) ||
($current == 0xA) ||
($current == 0xD) ||
(($current >= 0x20) && ($current <= 0xD7FF)) ||
(($current >= 0xE000) && ($current <= 0xFFFD)) ||
(($current >= 0x10000) && ($current <= 0x10FFFF))) {
$ret .= chr($current);
}
}
return $ret;
}
}
/**
* This function will turn the `XMLElement` into a string
* representing the element as it would appear in the markup.
* The result is valid XML.
*
* @param boolean $indent
* Defaults to false
* @param integer $tab_depth
* Defaults to 0, indicates the number of tabs (\t) that this
* element should be indented by in the output string
* @param boolean $has_parent
* Defaults to false, set to true when the children are being
* generated. Only the parent will output an XML declaration
* if `$this->_includeHeader` is set to true.
* @return string
*/
public function generate($indent = false, $tab_depth = 0, $has_parent = false)
{
$result = null;
$newline = ($indent ? PHP_EOL : null);
if (!$has_parent) {
if ($this->_includeHeader) {
$result .= sprintf(
'<?xml version="%s" encoding="%s" ?>%s',
$this->_version,
$this->_encoding,
$newline
);
}
if ($this->_dtd) {
$result .= $this->_dtd . $newline;
}
if (is_array($this->_processingInstructions) && !empty($this->_processingInstructions)) {
$result .= implode(PHP_EOL, $this->_processingInstructions);
}
}
$result .= ($indent ? str_repeat("\t", $tab_depth) : null) . '<' . $this->getName();
$attributes = $this->getAttributes();
if (!empty($attributes)) {
foreach ($attributes as $attribute => $value) {
$length = strlen($value);
if ($length !== 0 || $length === 0 && $this->_allowEmptyAttributes) {
$result .= sprintf(' %s="%s"', $attribute, $value);
}
}
}
$value = $this->getValue();
$added_newline = false;
if ($this->getNumberOfChildren() > 0 || strlen($value) !== 0 || !$this->_selfclosing) {
$result .= '>';
foreach ($this->_children as $i => $child) {
if (!($child instanceof XMLElement)) {
$result .= $child;
} else {
if ($added_newline === false) {
$added_newline = true;
$result .= $newline;
}
$child->setElementStyle($this->_elementStyle);
$result .= $child->generate($indent, $tab_depth + 1, true);
}
}
$result .= sprintf(
"%s</%s>%s",
($indent && $added_newline ? str_repeat("\t", $tab_depth) : null),
$this->getName(),
$newline
);
// Empty elements:
} else {
if ($this->_elementStyle === 'xml') {
$result .= ' />';
} elseif (in_array($this->_name, XMLElement::$no_end_tags) || (substr($this->getName(), 0, 3) === '!--')) {
$result .= '>';
} else {
$result .= sprintf("></%s>", $this->getName());
}
$result .= $newline;
}
return $result;
}
/**
* Given a string of XML, this function will convert it to an `XMLElement`
* object and return the result.
*
* @since Symphony 2.4
* @param string $root_element
* @param string $xml
* A string of XML
* @return XMLElement
*/
public static function convertFromXMLString($root_element, $xml)
{
$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML($xml);
return self::convertFromDOMDocument($root_element, $doc);
}
/**
* Given a `DOMDocument`, this function will convert it to an `XMLElement`
* object and return the result.
*
* @since Symphony 2.4
* @param string $root_element
* @param DOMDOcument $doc
* @return XMLElement
*/
public static function convertFromDOMDocument($root_element, DOMDocument $doc)
{
$xpath = new DOMXPath($doc);
$root = new XMLElement($root_element);
foreach ($xpath->query('.') as $node) {
self::convertNode($root, $node);
}
return $root;
}
/**
* This helper function is used by `XMLElement::convertFromDOMDocument`
* to recursively convert `DOMNode` into an `XMLElement` structure
*
* @since Symphony 2.4
* @param XMLElement $root
* @param DOMNOde $node
* @return XMLElement
*/
private static function convert(XMLElement $root = null, DOMNode $node)
{
$el = new XMLElement($node->tagName);
self::convertNode($el, $node);
if (is_null($root)) {
return $el;
} else {
$root->appendChild($el);
}
}
/**
* Given a DOMNode, this function will help replicate it as an
* XMLElement object
*
* @since Symphony 2.5.2
* @param XMLElement $element
* @param DOMNode $node
*/
private static function convertNode(XMLElement $element, DOMNode $node)
{
if ($node->hasAttributes()) {
foreach ($node->attributes as $name => $attrEl) {
$element->setAttribute($name, General::sanitize($attrEl->value));
}
}
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
if ($childNode instanceof DOMCdataSection) {
$element->setValue(General::wrapInCDATA($childNode->data));
} elseif ($childNode instanceof DOMText) {
if ($childNode->isWhitespaceInElementContent() === false) {
$element->setValue(General::sanitize($childNode->data));
}
} elseif ($childNode instanceof DOMElement) {
self::convert($element, $childNode);
}
}
}
}
}
/**
* Creates a filter that only returns XMLElement items
*/
class XMLElementChildrenFilter extends FilterIterator
{
public function accept()
{
$item = $this->getInnerIterator()->current();
return $item instanceof XMLElement;
}
}