aboutsummaryrefslogtreecommitdiff
path: root/engine/classes/ElggXMLElement.php
blob: 65a13912c5d83deb6300048ffe6aa83d713cc638 (plain)
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
<?php
/**
 * A parser for XML that uses SimpleXMLElement
 *
 * @package    Elgg.Core
 * @subpackage XML
 */
class ElggXMLElement {
	/**
	 * @var SimpleXMLElement
	 */
	private $_element;

	/**
	 * Creates an ElggXMLParser from a string or existing SimpleXMLElement
	 * 
	 * @param string|SimpleXMLElement $xml The XML to parse
	 */
	public function __construct($xml) {
		if ($xml instanceof SimpleXMLElement) {
			$this->_element = $xml;
		} else {
			$this->_element = new SimpleXMLElement($xml);
		}
	}

	/**
	 * @return string The name of the element
	 */
	public function getName() {
		return $this->_element->getName();
	}

	/**
	 * @return array:string The attributes
	 */
	public function getAttributes() {
		//include namespace declarations as attributes
		$xmlnsRaw = $this->_element->getNamespaces();
		$xmlns = array();
		foreach ($xmlnsRaw as $key => $val) {
			$label = 'xmlns' . ($key ? ":$key" : $key);
			$xmlns[$label] = $val;
		}
		//get attributes and merge with namespaces
		$attrRaw = $this->_element->attributes();
		$attr = array();
		foreach ($attrRaw as $key => $val) {
			$attr[$key] = $val;
		}
		$attr = array_merge((array) $xmlns, (array) $attr);
		$result = array();
		foreach ($attr as $key => $val) {
			$result[$key] = (string) $val;
		}
		return $result;
	}

	/**
	 * @return string CData
	 */
	public function getContent() {
		return (string) $this->_element;
	}

	/**
	 * @return array:ElggXMLElement Child elements
	 */
	public function getChildren() {
		$children = $this->_element->children();
		$result = array();
		foreach ($children as $val) {
			$result[] = new ElggXMLElement($val);
		}

		return $result;
	}

	function __get($name) {
		switch ($name) {
			case 'name':
				return $this->getName();
				break;
			case 'attributes':
				return $this->getAttributes();
				break;
			case 'content':
				return $this->getContent();
				break;
			case 'children':
				return $this->getChildren();
				break;
		}
		return null;
	}

	function __isset($name) {
		switch ($name) {
			case 'name':
				return $this->getName() !== null;
				break;
			case 'attributes':
				return $this->getAttributes() !== null;
				break;
			case 'content':
				return $this->getContent() !== null;
				break;
			case 'children':
				return $this->getChildren() !== null;
				break;
		}
		return false;
	}

}