Passed
Push — related-record-fixes ( 29f78d...35bdc2 )
by Alex
03:08
created

RelationshipIterator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 64
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A validate() 0 10 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
     * Validate if the given relation path can be resolved.
40
     *
41
     * @return bool
42
     */
43
    public function validate()
44
    {
45
        try {
46
            $this->resolve();
47
        } catch (InvalidRelationPathException $e) {
48
            return false;
49
        }
50
51
        return true;
52
    }
53
54
    /**
55
     * Resolve the relationship from the primary record.
56
     *
57
     * @throws InvalidRelationPathException
58
     *
59
     * @return Collection|Model|null
60
     */
61
    public function resolve()
62
    {
63
        return array_reduce(explode('.', $this->path), function ($resolved, $relation) {
64
            if (is_null($resolved) || in_array($relation, $this->record->getHidden())) {
65
                throw new InvalidRelationPathException($this->path);
66
            }
67
68
            return $resolved->{$relation};
69
        }, $this->record);
70
    }
71
}
72