Passed
Pull Request — master (#1)
by Roman
08:20
created

Collection::find()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 12
cp 0
rs 9.2568
c 0
b 0
f 0
cc 5
nc 12
nop 2
crap 30
1
<?php
2
3
namespace lroman242\LaravelCassandra;
4
5
use \Cassandra\Rows;
6
use lroman242\LaravelCassandra\Eloquent\Model;
7
use Illuminate\Support\Arr;
8
use Illuminate\Contracts\Support\Arrayable;
9
use Illuminate\Database\Eloquent\Collection as BaseCollection;
10
11
class Collection extends BaseCollection
12
{
13
    /**
14
     * Cassandra rows instance
15
     *
16
     * @var \Cassandra\Rows
17
     */
18
    private $rows;
19
20
    /**
21
     * Items model
22
     *
23
     * @var Model
24
     */
25
    private $model;
26
27
    /**
28
     * Create a new collection.
29
     *
30
     * @param  mixed  $items
31
     * @param  Model  $model
32
     */
33 19
    public function __construct($items = [], Model $model = null)
34
    {
35 19
        if ($items instanceof Rows) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Rows does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
36 19
            $this->rows = $items;
37
        }
38 19
        $this->model = $model;
39
40 19
        parent::__construct($this->prepareItems($items));
41 19
    }
42
43
    /**
44
     * Prepare items for collection
45
     *
46
     * @return array|Model[]
47
     */
48 19
    protected function prepareItems($items)
49
    {
50 19
        if ($this->model !== null && $items instanceof Rows) {
0 ignored issues
show
Bug introduced by
The class Cassandra\Rows does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
51 13
            $models = [];
52
53 13
            foreach ($items as $row) {
54 11
                $models[] = $this->model->newFromBuilder($row);
55
            }
56
57 13
            return $models;
58
        } else {
59 19
            return $items;
60
        }
61
    }
62
63
    /**
64
     * Next page token
65
     *
66
     * @return mixed
67
     */
68
    public function getNextPageToken()
69
    {
70
        return $this->rows->pagingStateToken();
71
    }
72
73
    /**
74
     * Last page indicator
75
     * @return bool
76
     */
77 19
    public function isLastPage()
78
    {
79 19
        return $this->rows->isLastPage();
80
    }
81
82
    /**
83
     * Get next page
84
     *
85
     * @return Collection
86
     */
87
    public function nextPage()
88
    {
89
        if (!$this->isLastPage()) {
90
            return new self($this->rows->nextPage(), $this->model);
91
        }
92
    }
93
94
    /**
95
     * Get rows instance
96
     *
97
     * @return \Cassandra\Rows
98
     */
99 13
    public function getRows()
100
    {
101 13
        return $this->rows;
102
    }
103
104
    /**
105
     * Update current collection with results from
106
     * the next page
107
     *
108
     * @return Collection
109
     */
110
    public function appendNextPage()
111
    {
112
        $nextPage = $this->nextPage();
113
114
        if ($nextPage) {
115
            $this->items = array_merge($this->items, $nextPage->toArray());
116
            $this->rows = $nextPage->getRows();
117
        }
118
119
        return $this;
120
    }
121
122
    /**
123
     * Find a model in the collection by key.
124
     *
125
     * @param  mixed  $key
126
     * @param  mixed  $default
127
     * @return \Illuminate\Database\Eloquent\Model|static
128
     */
129
    public function find($key, $default = null)
130
    {
131
        if ($key instanceof Model) {
132
            $key = $key->getKey();
133
        }
134
135
        if ($key instanceof Arrayable) {
136
            $key = $key->toArray();
137
        }
138
139
        if (is_array($key)) {
140
            if ($this->isEmpty()) {
141
                return new static([], $this->model);
142
            }
143
144
            return $this->whereIn($this->first()->getKeyName(), $key);
145
        }
146
147
        return Arr::first($this->items, function ($model) use ($key) {
148
            return $model->getKey() == $key;
149
        }, $default);
150
    }
151
152
    /**
153
     * Merge the collection with the given items.
154
     *
155
     * @param  \ArrayAccess|array  $items
156
     * @return static
157
     */
158
    public function merge($items)
159
    {
160
        $dictionary = $this->getDictionary();
161
162
        foreach ($items as $item) {
163
            $dictionary[(string) $item->getKey()] = $item;
164
        }
165
166
        return new static(array_values($dictionary), $this->model);
167
    }
168
169
    /**
170
     * Reload a fresh model instance from the database for all the entities.
171
     *
172
     * @param  array|string  $with
173
     * @return static
174
     */
175
    public function fresh($with = [])
176
    {
177
        if ($this->isEmpty()) {
178
            return new static([], $this->model);
179
        }
180
181
        $model = $this->first();
182
183
        $freshModels = $model->newQueryWithoutScopes()
184
            ->with(is_string($with) ? func_get_args() : $with)
185
            ->whereIn($model->getKeyName(), $this->modelKeys())
186
            ->get()
187
            ->getDictionary();
188
189
        return $this->map(function ($model) use ($freshModels) {
190
            return $model->exists && isset($freshModels[(string) $model->getKey()])
191
                ? $freshModels[(string) $model->getKey()] : null;
192
        });
193
    }
194
195
    /**
196
     * Diff the collection with the given items.
197
     *
198
     * @param  \ArrayAccess|array  $items
199
     * @return static
200
     */
201 View Code Duplication
    public function diff($items)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
202
    {
203
        $diff = new static([], $this->model);
204
205
        $dictionary = $this->getDictionary($items);
206
207
        foreach ($this->items as $item) {
208
            if (!isset($dictionary[(string) $item->getKey()])) {
209
                $diff->add($item);
210
            }
211
        }
212
213
        return $diff;
214
    }
215
216
    /**
217
     * Intersect the collection with the given items.
218
     *
219
     * @param  \ArrayAccess|array  $items
220
     * @return static
221
     */
222 View Code Duplication
    public function intersect($items)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
223
    {
224
        $intersect = new static([], $this->model);
225
226
        $dictionary = $this->getDictionary($items);
227
228
        foreach ($this->items as $item) {
229
            if (isset($dictionary[(string) $item->getKey()])) {
230
                $intersect->add($item);
231
            }
232
        }
233
234
        return $intersect;
235
    }
236
237
    /**
238
     * Return only unique items from the collection.
239
     *
240
     * @param  string|callable|null  $key
241
     * @param  bool  $strict
242
     * @return static|\Illuminate\Support\Collection
243
     */
244
    public function unique($key = null, $strict = false)
245
    {
246
        if (!is_null($key)) {
247
            return parent::unique($key, $strict);
248
        }
249
250
        return new static(array_values($this->getDictionary()), $this->model);
251
    }
252
253
    /**
254
     * Returns only the models from the collection with the specified keys.
255
     *
256
     * @param  mixed  $keys
257
     * @return static
258
     */
259
    public function only($keys)
260
    {
261
        if (is_null($keys)) {
262
            return new static($this->items, $this->model);
263
        }
264
265
        $dictionary = Arr::only($this->getDictionary(), $keys);
266
267
        return new static(array_values($dictionary), $this->model);
268
    }
269
270
    /**
271
     * Returns all models in the collection except the models with specified keys.
272
     *
273
     * @param  mixed  $keys
274
     * @return static
275
     */
276
    public function except($keys)
277
    {
278
        $dictionary = Arr::except($this->getDictionary(), $keys);
279
280
        return new static(array_values($dictionary), $this->model);
281
    }
282
283
284
    /**
285
     * Get a dictionary keyed by primary keys.
286
     *
287
     * @param  \ArrayAccess|array|null  $items
288
     * @return array
289
     */
290
    public function getDictionary($items = null)
291
    {
292
        $items = is_null($items) ? $this->items : $items;
293
294
        $dictionary = [];
295
296
        foreach ($items as $value) {
297
            $dictionary[(string) $value->getKey()] = $value;
298
        }
299
300
        return $dictionary;
301
    }
302
}
303