Skip to content

Commit

Permalink
graph traverser handle also objects which implement JsonSerializable,…
Browse files Browse the repository at this point in the history
… ArrayObject or Traversable
  • Loading branch information
chriskapp committed Dec 6, 2015
1 parent 42f50da commit 1860165
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions library/PSX/Data/Record/GraphTraverser.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@

namespace PSX\Data\Record;

use ArrayObject;
use InvalidArgumentException;
use JsonSerializable;
use PSX\Data\RecordInterface;
use PSX\Util\CurveArray;
use Traversable;

/**
* GraphTraverser
Expand All @@ -35,6 +38,8 @@ class GraphTraverser
{
public function traverse($record, VisitorInterface $visitor)
{
$record = $this->reveal($record);

if (!self::isObject($record)) {
throw new InvalidArgumentException('Provided value must be an object type');
}
Expand Down Expand Up @@ -72,6 +77,8 @@ protected function traverseObject($object, VisitorInterface $visitor)

protected function traverseValue($value, VisitorInterface $visitor)
{
$value = $this->reveal($value);

if (self::isObject($value)) {
$this->traverseObject($value, $visitor);
} elseif (self::isArray($value)) {
Expand All @@ -91,6 +98,28 @@ protected function traverseValue($value, VisitorInterface $visitor)
}
}

/**
* Method which reveals the true value of an object if it has a known
* interface. Note this resolves also all Traversable instances to an array
*
* @param mixed $object
* @return mixed
*/
protected function reveal($object)
{
if ($object instanceof RecordInterface) {
return $object;
} elseif ($object instanceof JsonSerializable) {
return $object->jsonSerialize();
} elseif ($object instanceof ArrayObject) {
return $object->getArrayCopy();
} elseif ($object instanceof Traversable) {
return iterator_to_array($object);
}

return $object;
}

public static function isObject($value)
{
return $value instanceof RecordInterface || $value instanceof \stdClass || (is_array($value) && CurveArray::isAssoc($value));
Expand Down

0 comments on commit 1860165

Please sign in to comment.