Passed
Branch related-record-fixes (1a5bc9)
by Alex
02:41
created

RelationshipIterator::resolve()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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