Completed
Push — master ( ab4a72...99f0f9 )
by Sergey
05:20
created

BelongsToRelationship::get()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.005

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 27
ccs 16
cts 17
cp 0.9412
rs 8.439
cc 5
eloc 15
nc 7
nop 0
crap 5.005
1
<?php
2
3
namespace Isswp101\Persimmon\Relationship;
4
5
use Isswp101\Persimmon\ElasticsearchModel;
6
use Isswp101\Persimmon\Exceptions\ParentModelNotFoundException;
7
8
class BelongsToRelationship
9
{
10
    /**
11
     * @var ElasticsearchModel
12
     */
13
    protected $child;
14
15
    /**
16
     * @var ElasticsearchModel
17
     */
18
    protected $parentClass;
19
20 6
    public function __construct(ElasticsearchModel $child, $parentClass)
21
    {
22 6
        $this->child = $child;
23 6
        $this->parentClass = $parentClass;
24 6
    }
25
26
    /**
27
     * Associate parent document.
28
     *
29
     * @param ElasticsearchModel $parent
30
     */
31 2
    public function associate(ElasticsearchModel $parent)
32
    {
33 2
        $this->child->setParent($parent);
34 2
    }
35
36
    /**
37
     * Return parent model.
38
     *
39
     * @return ElasticsearchModel|null
40
     */
41 4
    public function get()
42
    {
43 4
        $parent = $this->child->getParent();
44
45 4
        if ($parent) {
46
            return $parent;
47
        }
48
49 4
        $parentClass = $this->parentClass;
50
51 4
        $parentId = $this->child->getParentId();
52
53 4
        $innerHits = $this->child->getInnerHits();
54
55 4
        if ($innerHits) {
56 2
            $attributes = $innerHits->getParent($parentClass::getType());
57 2
            $parent = new $parentClass($attributes);
58 4
        } elseif ($parentId) {
59 2
            $parent = $parentClass::find($parentId);
60 2
        }
61
62 4
        if ($parent) {
63 4
            $this->child->setParent($parent);
64 4
        }
65
66 4
        return $parent;
67
    }
68
69
    /**
70
     * Return parent model.
71
     *
72
     * @throws ParentModelNotFoundException
73
     * @return ElasticsearchModel
74
     */
75 4
    public function getOrFail()
76
    {
77 4
        $model = $this->get();
78
79 4
        if (is_null($model)) {
80
            throw new ParentModelNotFoundException($this->parentClass, $this->child->getParentId());
81
        }
82
83 4
        return $model;
84
    }
85
}
86