Created
November 22, 2013 11:48
-
-
Save SenseException/7598668 to your computer and use it in GitHub Desktop.
Accessing XML like an array (readonly)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class FrozenXmlArrayAccess implements ArrayAccess | |
{ | |
/** | |
* @var SimpleXMLElement | |
*/ | |
private $xml; | |
/** | |
* @param SimpleXMLElement $xml | |
*/ | |
public function __construct(SimpleXMLElement $xml) | |
{ | |
$this->xml = $xml; | |
} | |
/** | |
* @param string|int $offset | |
* | |
* @return SimpleXMLElement | |
*/ | |
private function getElement($offset) | |
{ | |
if (false !== $this->xml->$offset->asXML()) { | |
$xml = $this->xml->$offset; | |
} | |
else { | |
$xml = $this->xml[$offset]; | |
} | |
return $xml; | |
} | |
/** | |
* @param mixed $offset | |
* | |
* @return bool | |
*/ | |
public function offsetExists($offset) | |
{ | |
return !is_null($this->getElement($offset)); | |
} | |
/** | |
* @param mixed $offset | |
* | |
* @return FrozenXmlArrayAccess | |
* | |
* @throws RuntimeException | |
*/ | |
public function offsetGet($offset) | |
{ | |
if ($this->xml->getName() == $offset) { | |
return $this; | |
} | |
$xml = $this->getElement($offset); | |
if (is_null($xml)) { | |
throw new RuntimeException('unknown node or attribute "' . $offset . '"'); | |
} | |
return new self($xml); | |
} | |
/** | |
* This method is not used since this class is readonly | |
* | |
* @param mixed $offset | |
* @param mixed $value | |
* | |
* @throws RuntimeException | |
*/ | |
public function offsetSet($offset, $value) | |
{ | |
throw new RuntimeException('This is readonly. writing to "' . (string) $offset . '" with value "' . (string) $value . '" not possible'); | |
} | |
/** | |
* This method is not used since this class is readonly | |
* | |
* @param mixed $offset | |
* | |
* @throws RuntimeException | |
*/ | |
public function offsetUnset($offset) | |
{ | |
throw new RuntimeException('This is readonly. Unsetting "' . (string) $offset . '" not possible'); | |
} | |
/** | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return (string) $this->xml; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment