Completed
Push — master ( 0bc6c0...2c7298 )
by Rudi
02:18
created

Sequence::sum()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
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 ($values && is_array($values) || $values instanceof Traversable) {
27
            $this->push(...$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->push(...$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
    /**
184
     * @inheritDoc
185
     */
186
    public function push(...$values)
187
    {
188
        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...
189
            array_push($this->internal, ...$values);
190
            $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...
191
        }
192
    }
193
194
    /**
195
     * @inheritDoc
196
     */
197
    public function reduce(callable $callback, $initial = null)
198
    {
199
        return array_reduce($this->internal, $callback, $initial);
200
    }
201
202
    /**
203
     * @inheritDoc
204
     */
205
    public function remove(int $index)
206
    {
207
        $this->checkRange($index);
208
209
        $value = array_splice($this->internal, $index, 1, null)[0];
210
        $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...
211
212
        return $value;
213
    }
214
215
    /**
216
     * @inheritDoc
217
     */
218
    public function reverse()
219
    {
220
        $this->internal = array_reverse($this->internal);
221
    }
222
223
    /**
224
     * @inheritDoc
225
     */
226
    public function reversed(): \Ds\Sequence
227
    {
228
        return new self(array_reverse($this->internal));
229
    }
230
231
    private function reverseRange(int $a, int $b)
232
    {
233
        $swap = function(&$a, &$b) {
234
            $t = $a;
235
            $a = $b;
236
            $b = $t;
237
        };
238
239
        // End of range exclusive
240
        $b--;
241
242
        while ($b > $a) {
243
            $swap($this->internal[$a++], $this->internal[$b--]);
244
        }
245
    }
246
247
    private function normalizeRotations(int $rotations, int $count)
248
    {
249
        if ($rotations < 0) {
250
            return $count - (abs($rotations) % $count);
251
        }
252
253
        return $rotations % $count;
254
    }
255
256
    /**
257
     * @inheritDoc
258
     */
259
    public function rotate(int $rotations)
260
    {
261
        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...
262
            return;
263
        }
264
265
        $n = count($this);
266
        $r = $this->normalizeRotations($rotations, $n);
267
268
        if ($r > 0) {
269
            $this->reverseRange(0,  $r);
270
            $this->reverseRange($r, $n);
271
            $this->reverseRange(0,  $n);
272
        }
273
    }
274
275
    /**
276
     * @inheritDoc
277
     */
278
    public function set(int $index, $value)
279
    {
280
        $this->checkRange($index);
281
        $this->internal[$index] = $value;
282
    }
283
284
    /**
285
     * @inheritDoc
286
     */
287 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...
288
    {
289
        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...
290
            throw new UnderflowException();
291
        }
292
293
        $value = array_shift($this->internal);
294
        $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...
295
296
        return $value;
297
    }
298
299
    /**
300
     * @inheritDoc
301
     */
302
    public function slice(int $offset, int $length = null): \Ds\Sequence
303
    {
304
        if (func_num_args() === 1) {
305
            return new self(array_slice($this->internal, $offset));
306
        }
307
308
        return new self(array_slice($this->internal, $offset, $length));
309
    }
310
311
    /**
312
     * @inheritDoc
313
     */
314
    public function sort(callable $comparator = null)
315
    {
316
        if ($comparator) {
317
            usort($this->internal, $comparator);
318
        } else {
319
            sort($this->internal);
320
        }
321
    }
322
323
    /**
324
     * @inheritDoc
325
     */
326
    public function sorted(callable $comparator = null): \Ds\Sequence
327
    {
328
        $internal = $this->internal;
329
330
        if ($comparator) {
331
            usort($internal, $comparator);
332
        } else {
333
            sort($internal);
334
        }
335
336
        return new self($internal);
337
    }
338
339
    /**
340
     * @inheritDoc
341
     */
342
    public function sum()
343
    {
344
        return array_sum($this->internal);
345
    }
346
347
    /**
348
     * @inheritDoc
349
     */
350
    public function unshift(...$values)
351
    {
352
        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...
353
            array_unshift($this->internal, ...$values);
354
            $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...
355
        }
356
    }
357
358
    /**
359
     *
360
     *
361
     * @param int $index
362
     */
363
    private function checkRange(int $index)
364
    {
365
        if ($index < 0 || $index >= count($this->internal)) {
366
            throw new OutOfRangeException();
367
        }
368
    }
369
370
    /**
371
     *
372
     */
373
    public function getIterator()
374
    {
375
        foreach ($this->internal as $value) {
376
            yield $value;
377
        }
378
    }
379
380
    /**
381
     * @inheritdoc
382
     */
383
    public function clear()
384
    {
385
        $this->internal = [];
386
        $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...
387
    }
388
389
    /**
390
     * @inheritdoc
391
     */
392
    public function offsetSet($offset, $value)
393
    {
394
        if ($offset === null) {
395
            $this->push($value);
396
        } else {
397
            $this->set($offset, $value);
398
        }
399
    }
400
401
    /**
402
     * @inheritdoc
403
     */
404
    public function &offsetGet($offset)
405
    {
406
        $this->checkRange($offset);
407
        return $this->internal[$offset];
408
    }
409
410
    /**
411
     * @inheritdoc
412
     */
413
    public function offsetUnset($offset)
414
    {
415
        // Unset should be quiet, so we shouldn't allow 'remove' to throw.
416
        if (is_integer($offset) && $offset >= 0 && $offset < count($this)) {
417
            $this->remove($offset);
418
        }
419
    }
420
421
    /**
422
     * @inheritdoc
423
     */
424
    public function offsetExists($offset)
425
    {
426
        if ($offset < 0 || $offset >= count($this)) {
427
            return false;
428
        }
429
430
        return $this->get($offset) !== null;
431
    }
432
}
433