Completed
Push — master ( c2ba24...974176 )
by Sergey
28:36 queued 13:30
created

ElasticsearchModel::belongsTo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Isswp101\Persimmon;
4
5
use Elasticsearch\Client;
6
use Illuminate\Support\Collection;
7
use Isswp101\Persimmon\Collection\ElasticsearchCollection;
8
use Isswp101\Persimmon\DAL\ElasticsearchDAL;
9
use Isswp101\Persimmon\Exceptions\ModelNotFoundException;
10
use Isswp101\Persimmon\QueryBuilder\QueryBuilder;
11
use Isswp101\Persimmon\Relationship\BelongsToRelationship;
12
use Isswp101\Persimmon\Relationship\HasManyRelationship;
13
use Isswp101\Persimmon\Traits\Elasticsearchable;
14
use Isswp101\Persimmon\Traits\Paginationable;
15
use Isswp101\Persimmon\Traits\Relationshipable;
16
17
class ElasticsearchModel extends Model
18
{
19
    use Elasticsearchable, Paginationable, Relationshipable;
20
21
    /**
22
     * @var ElasticsearchDAL
23
     */
24
    public $_dal;
25
26
    public function __construct(array $attributes = [])
27
    {
28
        $this->validateModelEndpoint();
29
30
        parent::__construct($attributes);
31
    }
32
33
    public function injectDependencies()
34
    {
35
        // @TODO: move logger to DAL
36
        $this->injectDataAccessLayer(new ElasticsearchDAL($this, app(Client::class)));
37
        // $this->injectLogger(app(Log::class));
1 ignored issue
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
38
    }
39
40
    public static function findWithParentId($id, $parent, array $columns = ['*'])
41
    {
42
        /** @var static $model */
43
        $model = parent::find($id, $columns, ['parent' => $parent]);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (find() instead of findWithParentId()). Are you sure this is correct? If so, you might want to change this to $this->find().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
44
45
        if ($model) {
46
            $model->setParentId($parent);
47
        }
48
49
        return $model;
50
    }
51
52
    /**
53
     * Execute the query and get the result.
54
     *
55
     * @param QueryBuilder|array $query
56
     * @return ElasticsearchCollection|static[]
57
     */
58
    public static function search($query = [])
59
    {
60
        if ($query instanceof QueryBuilder) {
61
            $query = $query->build();
62
        }
63
        $model = static::createInstance();
64
        return $model->_dal->search($query);
65
    }
66
67
    /**
68
     * Execute the query and get the first result.
69
     *
70
     * @param QueryBuilder|array $query
71
     * @return static
72
     */
73
    public static function first($query = [])
74
    {
75
        if ($query instanceof QueryBuilder) {
76
            $query = $query->build();
77
        }
78
        $query['from'] = 0;
79
        $query['size'] = 1;
80
        return static::search($query)->first();
81
    }
82
83
    /**
84
     * Execute the query and get the first result or throw an exception.
85
     *
86
     * @param QueryBuilder|array $query
87
     * @throws ModelNotFoundException
88
     * @return static
89
     */
90
    public static function firstOrFail($query = [])
91
    {
92
        $model = static::first($query);
93
        if (is_null($model)) {
94
            throw new ModelNotFoundException(get_called_class());
95
        }
96
        return $model;
97
    }
98
99
    /**
100
     * Apply the callback to the documents of the given query.
101
     *
102
     * @param QueryBuilder|array $query
103
     * @param callable $callback
104
     * @param int $limit
105
     * @return int hits.total
106
     */
107
    public static function map($query = [], callable $callback, $limit = -1)
108
    {
109
        if ($query instanceof QueryBuilder) {
110
            $query = $query->build();
111
        }
112
113
        $query['from'] = array_get($query, 'from', 0);
114
        $query['size'] = array_get($query, 'size', 50);
115
116
        $i = 0;
117
        $models = static::search($query);
118
        $total = $models->getTotal();
119
        while ($models) {
120
            foreach ($models as $model) {
121
                $callback($model);
122
                $i++;
123
            }
124
125
            $query['from'] += $query['size'];
126
127
            if ($i >= $total || ($limit > 0 && $i >= $limit)) {
128
                break;
129
            }
130
131
            $models = static::search($query);
132
        }
133
134
        return $total;
135
    }
136
137
    /**
138
     * Execute the query and get all items.
139
     *
140
     * @param QueryBuilder|array $query
141
     * @return Collection
142
     */
143
    public static function all($query = [])
144
    {
145
        if ($query instanceof QueryBuilder) {
146
            $query = $query->build();
147
        }
148
        $collection = collect();
149
        static::map($query, function (ElasticsearchModel $document) use ($collection) {
150
            $collection->put($document->getId(), $document);
151
        });
152
        return $collection;
153
    }
154
155
    protected function belongsTo($class)
156
    {
157
        return new BelongsToRelationship($this, $class);
158
    }
159
160
    protected function hasMany($class)
161
    {
162
        return new HasManyRelationship($this, $class);
163
    }
164
}