Passed
Push — related-record-fixes ( efcb4a...afa92b )
by Alex
03:42
created

RelationshipIterator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 50
rs 10

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
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