Skip to content

Instantly share code, notes, and snippets.

@SenseException
Created November 22, 2013 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SenseException/7598668 to your computer and use it in GitHub Desktop.
Save SenseException/7598668 to your computer and use it in GitHub Desktop.
Accessing XML like an array (readonly)
<?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