for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
namespace Huntie\JsonApi\Support;
use InvalidArgumentException;
use Huntie\JsonApi\Exceptions\InvalidRelationPathException;
class RelationshipIterator
{
/**
* The primary record.
*/
private $record;
* The path to the relation.
*
* @var string
private $path;
* Create a new RelationshipIterator instance.
* @param Model $record The primary record
* @param string $path The path to the relation
public function __construct($record, $path)
if (!preg_match('/[A-Za-z.]+/', $path)) {
throw new InvalidArgumentException('The relationship path must be a valid string');
}
$this->record = $record;
$this->path = $path;
* Validate if the given relation path can be resolved.
* @return bool
public function validate()
try {
$this->resolve();
} catch (InvalidRelationPathException $e) {
return false;
return true;
* Resolve the relationship from the primary record.
* @throws InvalidRelationPathException
* @return Collection|Model|null
public function resolve()
return array_reduce(explode('.', $this->path), function ($resolved, $relation) {
if (is_null($resolved) || in_array($relation, $this->record->getHidden())) {
throw new InvalidRelationPathException($this->path);
return $resolved->{$relation};
}, $this->record);