Skip to content

Instantly share code, notes, and snippets.

@hakre
Last active December 17, 2015 21:29
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 hakre/5675168 to your computer and use it in GitHub Desktop.
Save hakre/5675168 to your computer and use it in GitHub Desktop.
<?php
/**
* Class SimpleXMLElementXpathObject
*
* Object properties are mapped to Xpath queries
*/
class SimpleXMLElementXpathObject implements IteratorAggregate, JsonSerializable
{
private $anchor;
private $props;
public function __construct(SimpleXMLElement $anchor, array $props) {
$this->anchor = $anchor;
$this->props = $props;
}
public function __isset($name) {
if (!isset($this->props[$name])) {
return false;
}
return null !== $this->getXpathProp($name);
}
public function __get($name) {
if (!isset($this->props[$name])) {
trigger_error(sprintf('Undefined property %s', $name));
return NULL;
}
return $this->getXpathProp($name);
}
private function getXpathProp($name) {
$xpath = $this->props[$name];
$result = $this->anchor->xpath($xpath);
if ($result === FALSE) {
return $result;
}
if ($result) {
return $result[0];
}
return NULL;
}
public function getIterator() {
return new PropertyIterator($this, array_keys($this->props));
}
public function getArrayCopy() {
return iterator_to_array($this);
}
public function jsonSerialize() {
return (object)array_map('strval', $this->getArrayCopy());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment