Passed
Push — related-record-fixes ( f693a7...7848aa )
by Alex
06:34
created

RelationshipIterator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 48
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A resolve() 0 10 3
1
<?php
2
3
namespace Huntie\JsonApi\Support;
4
5
use InvalidArgumentException;
6
use Huntie\JsonApi\Exceptions\InvalidRelationPathException;
7
8
class RelationshipIterator
9
{
10
    /**
11
     * The primary record.
12
     */
13
    private $record;
14
15
    /**
16
     * The path to the relation.
17
     *
18
     * @var string
19
     */
20
    private $path;
21
22
    /**
23
     * Create a new RelationshipIterator instance.
24
     *
25
     * @param Model  $record The primary record
26
     * @param string $path   The path to the relation
27
     */
28
    public function __construct($record, $path)
29
    {
30
        if (!preg_match('/[A-Za-z.]+/', $path)) {
31
            throw new InvalidArgumentException('The relationship path must be a valid string');
32
        }
33
34
        $this->record = $record;
35
        $this->path = $path;
36
    }
37
38
    /**
39
     * Resolve the relationship from the primary record.
40
     *
41
     * @throws InvalidRelationPathException
42
     *
43
     * @return Collection|Model|null
44
     */
45
    public function resolve()
46
    {
47
        return array_reduce(explode('.', $this->path), function ($resolved, $relation) {
48
            if (is_null($resolved) || in_array($relation, $this->record->getHidden())) {
49
                throw new InvalidRelationPathException($this->path);
50
            }
51
52
            return $resolved->{$relation};
53
        }, $this->record);
54
    }
55
}
56