Completed
Push — master ( 2bc3d9...4d44a5 )
by Sergey
15:01
created

ElasticsearchModel::firstOrFail()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 4
Ratio 44.44 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 4
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace Isswp101\Persimmon;
4
5
use Elasticsearch\Client;
6
use Illuminate\Database\Eloquent\ModelNotFoundException;
7
use Illuminate\Support\Collection;
8
use Isswp101\Persimmon\Collection\ElasticsearchCollection;
9
use Isswp101\Persimmon\DAL\ElasticsearchDAL;
10
use Isswp101\Persimmon\QueryBuilder\QueryBuilder;
11
use Isswp101\Persimmon\Traits\Elasticsearchable;
12
use Isswp101\Persimmon\Traits\Mappingable;
13
use Isswp101\Persimmon\Traits\Relationshipable;
14
use ReflectionClass;
15
16
class ElasticsearchModel extends Model
17
{
18
    use Elasticsearchable, Mappingable, Relationshipable;
19
20
    /**
21
     * @var ElasticsearchDAL
22
     */
23
    public $_dal;
24
25
    public function __construct(array $attributes = [])
26
    {
27
        $this->validateIndexAndType();
28
29
        parent::__construct($attributes);
30
    }
31
32
    public function injectDependencies()
33
    {
34
        // @TODO: move logger to DAL
35
        $this->injectDataAccessLayer(new ElasticsearchDAL($this, app(Client::class)));
36
        // $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...
37
    }
38
39
    public static function findWithParentId($id, $parentId, array $columns = ['*'])
40
    {
41
        /** @var static $model */
42
        $model = parent::find($id, $columns, ['parent_id' => $parentId]);
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...
43
44
        if ($model) {
45
            $model->setParentId($parentId);
46
        }
47
48
        return $model;
49
    }
50
51
    /**
52
     * Execute the query and get the result.
53
     *
54
     * @param QueryBuilder|array $query
55
     * @return ElasticsearchCollection|static[]
56
     */
57
    public static function search($query = [])
58
    {
59
        if ($query instanceof QueryBuilder) {
60
            $query = $query->build();
61
        }
62
        $model = static::createInstance();
63
        return $model->_dal->search($query);
64
    }
65
66
    /**
67
     * Execute the query and get the first result.
68
     *
69
     * @param QueryBuilder|array $query
70
     * @return static
71
     */
72
    public static function first($query = [])
73
    {
74
        if ($query instanceof QueryBuilder) {
75
            $query = $query->build();
76
        }
77
        $query['from'] = 0;
78
        $query['size'] = 1;
79
        return static::search($query)->first();
80
    }
81
82
    /**
83
     * Execute the query and get the first result or throw an exception.
84
     *
85
     * @param QueryBuilder|array $query
86
     * @return static
87
     * @throws ModelNotFoundException
88
     */
89
    public static function firstOrFail($query = [])
90
    {
91
        $model = static::first($query);
92 View Code Duplication
        if (is_null($model)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
93
            $reflect = new ReflectionClass(get_called_class());
94
            throw new ModelNotFoundException(sprintf('Model `%s` not found', $reflect->getShortName()));
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
}