Completed
Push — master ( 7aefdd...988c00 )
by Rudi
02:20
created

Sequence::pushAll()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
namespace Ds\Traits;
3
4
use Error;
5
use OutOfRangeException;
6
use Traversable;
7
use UnderflowException;
8
9
/**
10
 * Sequence
11
 *
12
 * @package Ds\Traits
13
 */
14
trait Sequence
15
{
16
    /**
17
     * @var array
18
     */
19
    private $internal = [];
20
21
    /**
22
     * @inheritDoc
23
     */
24
    public function __construct($values = null)
25
    {
26
        if (func_num_args()) {
27
            $this->pushAll($values);
28
        }
29
    }
30
31
    /**
32
     * @inheritdoc
33
     */
34
    public function toArray(): array
35
    {
36
        return $this->internal;
37
    }
38
39
    /**
40
     * @inheritdoc
41
     */
42
    public function apply(callable $callback)
43
    {
44
        foreach ($this->internal as &$value) {
45
            $value = $callback($value);
46
        }
47
    }
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public function merge($values): \Ds\Sequence
53
    {
54
        $merged = $this->copy();
0 ignored issues
show
Bug introduced by
It seems like copy() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
55
        $merged->pushAll($values);
56
57
        return $merged;
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63
    public function count(): int
64
    {
65
        return count($this->internal);
66
    }
67
68
    /**
69
     * @inheritDoc
70
     */
71 View Code Duplication
    public function contains(...$values): bool
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...
72
    {
73
        if ( ! $values) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $values of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
74
            return false;
75
        }
76
77
        foreach ($values as $value) {
78
            if ($this->find($value) === false) {
79
                return false;
80
            }
81
        }
82
83
        return true;
84
    }
85
86
    /**
87
     * @inheritDoc
88
     */
89
    public function filter(callable $callback = null): \Ds\Sequence
90
    {
91
        if ($callback) {
92
            return new self(array_filter($this->internal, $callback));
93
        }
94
95
        return new self(array_filter($this->internal));
96
    }
97
98
    /**
99
     * @inheritDoc
100
     */
101
    public function find($value)
102
    {
103
        return array_search($value, $this->internal, true);
104
    }
105
106
    /**
107
     * @inheritDoc
108
     */
109
    public function first()
110
    {
111
        if (empty($this->internal)) {
112
            throw new UnderflowException();
113
        }
114
115
        return $this->internal[0];
116
    }
117
118
    /**
119
     * @inheritDoc
120
     */
121
    public function get(int $index)
122
    {
123
        $this->checkRange($index);
124
125
        return $this->internal[$index];
126
    }
127
128
    /**
129
     * @inheritDoc
130
     */
131
    public function insert(int $index, ...$values)
132
    {
133
        if ($index < 0 || $index > count($this->internal)) {
134
            throw new OutOfRangeException();
135
        }
136
137
        array_splice($this->internal, $index, 0, $values);
138
    }
139
140
    /**
141
     * @inheritDoc
142
     */
143
    public function join(string $glue = null): string
144
    {
145
        return implode($glue, $this->internal);
146
    }
147
148
    /**
149
     * @inheritDoc
150
     */
151
    public function last()
152
    {
153
        if ($this->isEmpty()) {
0 ignored issues
show
Bug introduced by
It seems like isEmpty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
154
            throw new UnderflowException();
155
        }
156
157
        return end($this->internal);
158
    }
159
160
    /**
161
     * @inheritDoc
162
     */
163
    public function map(callable $callback): \Ds\Sequence
164
    {
165
        return new self(array_map($callback, $this->internal));
166
    }
167
168
    /**
169
     * @inheritDoc
170
     */
171 View Code Duplication
    public function pop()
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...
172
    {
173
        if ($this->isEmpty()) {
0 ignored issues
show
Bug introduced by
It seems like isEmpty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
174
            throw new UnderflowException();
175
        }
176
177
        $value = array_pop($this->internal);
178
        $this->adjustCapacity();
0 ignored issues
show
Bug introduced by
It seems like adjustCapacity() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
179
180
        return $value;
181
    }
182
183
    private function pushAll($values)
184
    {
185
        foreach ($values as $value) {
186
            $this->internal[] = $value;
187
        }
188
189
        $this->adjustCapacity();
0 ignored issues
show
Bug introduced by
It seems like adjustCapacity() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
190
    }
191
192
    /**
193
     * @inheritDoc
194
     */
195
    public function push(...$values)
196
    {
197
        $this->pushAll($values);
198
    }
199
200
    /**
201
     * @inheritDoc
202
     */
203
    public function reduce(callable $callback, $initial = null)
204
    {
205
        return array_reduce($this->internal, $callback, $initial);
206
    }
207
208
    /**
209
     * @inheritDoc
210
     */
211
    public function remove(int $index)
212
    {
213
        $this->checkRange($index);
214
215
        $value = array_splice($this->internal, $index, 1, null)[0];
216
        $this->adjustCapacity();
0 ignored issues
show
Bug introduced by
It seems like adjustCapacity() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
217
218
        return $value;
219
    }
220
221
    /**
222
     * @inheritDoc
223
     */
224
    public function reverse()
225
    {
226
        $this->internal = array_reverse($this->internal);
227
    }
228
229
    /**
230
     * @inheritDoc
231
     */
232
    public function reversed(): \Ds\Sequence
233
    {
234
        return new self(array_reverse($this->internal));
235
    }
236
237
    private function reverseRange(int $a, int $b)
238
    {
239
        $swap = function(&$a, &$b) {
240
            $t = $a;
241
            $a = $b;
242
            $b = $t;
243
        };
244
245
        // End of range exclusive
246
        $b--;
247
248
        while ($b > $a) {
249
            $swap($this->internal[$a++], $this->internal[$b--]);
250
        }
251
    }
252
253
    private function normalizeRotations(int $rotations, int $count)
254
    {
255
        if ($rotations < 0) {
256
            return $count - (abs($rotations) % $count);
257
        }
258
259
        return $rotations % $count;
260
    }
261
262
    /**
263
     * @inheritDoc
264
     */
265
    public function rotate(int $rotations)
266
    {
267
        if ($this->isEmpty()) {
0 ignored issues
show
Bug introduced by
It seems like isEmpty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
268
            return;
269
        }
270
271
        $n = count($this);
272
        $r = $this->normalizeRotations($rotations, $n);
273
274
        if ($r > 0) {
275
            $this->reverseRange(0,  $r);
276
            $this->reverseRange($r, $n);
277
            $this->reverseRange(0,  $n);
278
        }
279
    }
280
281
    /**
282
     * @inheritDoc
283
     */
284
    public function set(int $index, $value)
285
    {
286
        $this->checkRange($index);
287
        $this->internal[$index] = $value;
288
    }
289
290
    /**
291
     * @inheritDoc
292
     */
293 View Code Duplication
    public function shift()
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...
294
    {
295
        if ($this->isEmpty()) {
0 ignored issues
show
Bug introduced by
It seems like isEmpty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
296
            throw new UnderflowException();
297
        }
298
299
        $value = array_shift($this->internal);
300
        $this->adjustCapacity();
0 ignored issues
show
Bug introduced by
It seems like adjustCapacity() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
301
302
        return $value;
303
    }
304
305
    /**
306
     * @inheritDoc
307
     */
308
    public function slice(int $offset, int $length = null): \Ds\Sequence
309
    {
310
        if (func_num_args() === 1) {
311
            return new self(array_slice($this->internal, $offset));
312
        }
313
314
        return new self(array_slice($this->internal, $offset, $length));
315
    }
316
317
    /**
318
     * @inheritDoc
319
     */
320
    public function sort(callable $comparator = null)
321
    {
322
        if ($comparator) {
323
            usort($this->internal, $comparator);
324
        } else {
325
            sort($this->internal);
326
        }
327
    }
328
329
    /**
330
     * @inheritDoc
331
     */
332
    public function sorted(callable $comparator = null): \Ds\Sequence
333
    {
334
        $internal = $this->internal;
335
336
        if ($comparator) {
337
            usort($internal, $comparator);
338
        } else {
339
            sort($internal);
340
        }
341
342
        return new self($internal);
343
    }
344
345
    /**
346
     * @inheritDoc
347
     */
348
    public function sum()
349
    {
350
        return array_sum($this->internal);
351
    }
352
353
    /**
354
     * @inheritDoc
355
     */
356
    public function unshift(...$values)
357
    {
358
        if ($values) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $values of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
359
            array_unshift($this->internal, ...$values);
360
            $this->adjustCapacity();
0 ignored issues
show
Bug introduced by
It seems like adjustCapacity() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
361
        }
362
    }
363
364
    /**
365
     *
366
     *
367
     * @param int $index
368
     */
369
    private function checkRange(int $index)
370
    {
371
        if ($index < 0 || $index >= count($this->internal)) {
372
            throw new OutOfRangeException();
373
        }
374
    }
375
376
    /**
377
     *
378
     */
379
    public function getIterator()
380
    {
381
        foreach ($this->internal as $value) {
382
            yield $value;
383
        }
384
    }
385
386
    /**
387
     * @inheritdoc
388
     */
389
    public function clear()
390
    {
391
        $this->internal = [];
392
        $this->capacity = self::MIN_CAPACITY;
0 ignored issues
show
Bug introduced by
The property capacity does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
393
    }
394
395
    /**
396
     * @inheritdoc
397
     */
398
    public function offsetSet($offset, $value)
399
    {
400
        if ($offset === null) {
401
            $this->push($value);
402
        } else {
403
            $this->set($offset, $value);
404
        }
405
    }
406
407
    /**
408
     * @inheritdoc
409
     */
410
    public function &offsetGet($offset)
411
    {
412
        $this->checkRange($offset);
413
        return $this->internal[$offset];
414
    }
415
416
    /**
417
     * @inheritdoc
418
     */
419
    public function offsetUnset($offset)
420
    {
421
        // Unset should be quiet, so we shouldn't allow 'remove' to throw.
422
        if (is_integer($offset) && $offset >= 0 && $offset < count($this)) {
423
            $this->remove($offset);
424
        }
425
    }
426
427
    /**
428
     * @inheritdoc
429
     */
430
    public function offsetExists($offset)
431
    {
432
        if ($offset < 0 || $offset >= count($this)) {
433
            return false;
434
        }
435
436
        return $this->get($offset) !== null;
437
    }
438
}
439