Completed
Push — master ( be5d10...3892c2 )
by Sergey
07:31
created

HasManyRelationship::save()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 10
ccs 7
cts 8
cp 0.875
rs 9.4285
c 1
b 0
f 0
cc 3
eloc 5
nc 4
nop 1
crap 3.0175
1
<?php
2
3
namespace Isswp101\Persimmon\Relationship;
4
5
use Isswp101\Persimmon\Collection\ElasticsearchCollection;
6
use Isswp101\Persimmon\ElasticsearchModel;
7
use Isswp101\Persimmon\QueryBuilder\Filters\ParentFilter;
8
use Isswp101\Persimmon\QueryBuilder\QueryBuilder;
9
10
class HasManyRelationship
11
{
12
    /**
13
     * @var ElasticsearchModel
14
     */
15
    protected $parent;
16
17
    /**
18
     * @var ElasticsearchModel
19
     */
20
    protected $childClassName;
21
22 2
    public function __construct(ElasticsearchModel $parent, $childClassName)
23
    {
24 2
        $this->parent = $parent;
25 2
        $this->childClassName = $childClassName;
26 2
    }
27
28
    /**
29
     * Find all children.
30
     *
31
     * @return ElasticsearchCollection|ElasticsearchModel[]
32
     */
33 1
    public function get()
34
    {
35 1
        $child = $this->childClassName;
36 1
        $query = new QueryBuilder();
37 1
        $query->filter(new ParentFilter($this->parent->getId()));
38 1
        $collection = $child::search($query);
39 1
        $collection->each(function (ElasticsearchModel $model) {
40 1
            $model->setParent($this->parent);
41 1
        });
42 1
        return $collection;
43
    }
44
45
    /**
46
     * Find model by id.
47
     *
48
     * @param mixed $id
49
     * @return ElasticsearchModel|null
50
     */
51 1
    public function find($id)
52
    {
53 1
        $child = $this->childClassName;
54 1
        $model = $child::findWithParentId($id, $this->parent->getId());
55 1
        if ($model) {
56 1
            $model->setParent($this->parent);
57 1
        }
58 1
        return $model;
59
    }
60
61
    /**
62
     * Save children.
63
     *
64
     * @param ElasticsearchModel|ElasticsearchModel[] $child
65
     */
66 1
    public function save($child)
67
    {
68
        /** @var ElasticsearchModel[] $children */
69 1
        $children = !is_array($child) ? [$child] : $child;
70
        // @TODO: use bulk if count($children) > 1
71 1
        foreach ($children as $child) {
72 1
            $child->setParent($this->parent);
73 1
            $child->save();
74 1
        }
75 1
    }
76
}
77