Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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