Last active
December 17, 2015 21:29
-
-
Save hakre/5675168 to your computer and use it in GitHub Desktop.
This file contains 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 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