Completed
Push — master ( 1c9d7f...2f9336 )
by Antonio Carlos
01:51
created

LazyCollection   F

Complexity

Total Complexity 169

Size/Duplication

Total Lines 1204
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 95.56%

Importance

Changes 0
Metric Value
dl 0
loc 1204
ccs 323
cts 338
cp 0.9556
rs 0.8
c 0
b 0
f 0
wmc 169
lcom 1
cbo 4

72 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 4
A empty() 0 4 1
A times() 0 14 4
A range() 0 8 2
A all() 0 8 2
A avg() 0 4 1
A median() 0 4 1
A mode() 0 4 1
A collapse() 0 12 5
B contains() 0 22 6
A crossJoin() 0 4 1
A diff() 0 4 1
A diffUsing() 0 4 1
A diffAssoc() 0 4 1
A diffAssocUsing() 0 4 1
A diffKeys() 0 4 1
A diffKeysUsing() 0 4 1
A duplicates() 0 4 1
A duplicatesStrict() 0 4 1
A except() 0 4 1
A filter() 0 16 4
A first() 0 20 5
A flatten() 0 16 5
A flip() 0 8 2
A get() 0 14 4
A groupBy() 0 4 1
A keyBy() 0 16 3
A has() 0 13 5
A implode() 0 4 1
A intersect() 0 4 1
A intersectByKeys() 0 4 1
A isEmpty() 0 4 1
A join() 0 4 1
A keys() 0 8 2
A last() 0 12 5
A pluck() 0 22 5
A map() 0 8 2
A mapToDictionary() 0 4 1
A mapWithKeys() 0 8 2
A merge() 0 4 1
A mergeRecursive() 0 4 1
A combine() 0 24 4
A union() 0 4 1
A nth() 0 14 3
B only() 0 28 8
A concat() 0 7 1
A random() 0 6 2
A reduce() 0 10 2
A replace() 0 20 4
A replaceRecursive() 0 4 1
A reverse() 0 4 1
A search() 0 16 5
A shuffle() 0 4 1
A skip() 0 16 4
A slice() 0 10 4
A split() 0 4 1
B chunk() 0 32 6
A sort() 0 4 1
A sortBy() 0 4 1
A sortByDesc() 0 4 1
A sortKeys() 0 4 1
A sortKeysDesc() 0 4 1
A take() 0 22 5
A tapEach() 0 10 2
A values() 0 8 2
A zip() 0 16 2
A pad() 0 20 4
A getIterator() 0 4 1
A count() 0 8 2
A makeIterator() 0 12 3
A explodePluckParameters() 0 8 4
A passthru() 0 6 1

How to fix   Complexity   

Complex Class

Complex classes like LazyCollection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LazyCollection, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace IlluminateAgnostic\Collection\Support;
4
5
use ArrayIterator;
6
use Closure;
7
use IlluminateAgnostic\Collection\Support\Traits\EnumeratesValues;
8
use IlluminateAgnostic\Collection\Support\Traits\Macroable;
9
use IteratorAggregate;
10
use stdClass;
11
12
class LazyCollection implements Enumerable
13
{
14
    use EnumeratesValues, Macroable;
15
16
    /**
17
     * The source from which to generate items.
18
     *
19
     * @var callable|static
20
     */
21
    public $source;
22
23
    /**
24
     * Create a new lazy collection instance.
25
     *
26
     * @param  mixed  $source
27
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
28
     */
29 231
    public function __construct($source = null)
30
    {
31 231
        if ($source instanceof Closure || $source instanceof self) {
32 160
            $this->source = $source;
33 231
        } elseif (is_null($source)) {
34 26
            $this->source = static::empty();
35
        } else {
36 231
            $this->source = $this->getArrayableItems($source);
37
        }
38 231
    }
39
40
    /**
41
     * Create a new instance with no items.
42
     *
43
     * @return static
44
     */
45 28
    public static function empty()
46
    {
47 28
        return new static([]);
48
    }
49
50
    /**
51
     * Create a new instance by invoking the callback a given amount of times.
52
     *
53
     * @param  int  $number
54
     * @param  callable  $callback
55
     * @return static
56
     */
57 1
    public static function times($number, callable $callback = null)
58
    {
59 1
        if ($number < 1) {
60 1
            return new static;
61
        }
62
63
        $instance = new static(function () use ($number) {
64 1
            for ($current = 1; $current <= $number; $current++) {
65 1
                yield $current;
66
            }
67 1
        });
68
69 1
        return is_null($callback) ? $instance : $instance->map($callback);
70
    }
71
72
    /**
73
     * Create an enumerable with the given range.
74
     *
75
     * @param  int  $from
76
     * @param  int  $to
77
     * @return static
78
     */
79
    public static function range($from, $to)
80
    {
81
        return new static(function () use ($from, $to) {
82
            for (; $from <= $to; $from++) {
83
                yield $from;
84
            }
85
        });
86
    }
87
88
    /**
89
     * Get all items in the enumerable.
90
     *
91
     * @return array
92
     */
93 190
    public function all()
94
    {
95 190
        if (is_array($this->source)) {
96 110
            return $this->source;
97
        }
98
99 158
        return iterator_to_array($this->getIterator());
100
    }
101
102
    /**
103
     * Get the average value of a given key.
104
     *
105
     * @param  callable|string|null  $callback
106
     * @return mixed
107
     */
108 1
    public function avg($callback = null)
109
    {
110 1
        return $this->collect()->avg($callback);
111
    }
112
113
    /**
114
     * Get the median of a given key.
115
     *
116
     * @param  string|array|null $key
117
     * @return mixed
118
     */
119 6
    public function median($key = null)
120
    {
121 6
        return $this->collect()->median($key);
122
    }
123
124
    /**
125
     * Get the mode of a given key.
126
     *
127
     * @param  string|array|null  $key
128
     * @return array|null
129
     */
130 4
    public function mode($key = null)
131
    {
132 4
        return $this->collect()->mode($key);
133
    }
134
135
    /**
136
     * Collapse the collection of items into a single array.
137
     *
138
     * @return static
139
     */
140 3
    public function collapse()
141
    {
142
        return new static(function () {
143 3
            foreach ($this as $values) {
144 3
                if (is_array($values) || $values instanceof Enumerable) {
145 3
                    foreach ($values as $value) {
146 3
                        yield $value;
147
                    }
148
                }
149
            }
150 3
        });
151
    }
152
153
    /**
154
     * Determine if an item exists in the enumerable.
155
     *
156
     * @param  mixed  $key
157
     * @param  mixed  $operator
158
     * @param  mixed  $value
159
     * @return bool
160
     */
161 4
    public function contains($key, $operator = null, $value = null)
162
    {
163 4
        if (func_num_args() === 1 && $this->useAsCallable($key)) {
164 4
            $placeholder = new stdClass;
165
166 4
            return $this->first($key, $placeholder) !== $placeholder;
167
        }
168
169 3
        if (func_num_args() === 1) {
170 2
            $needle = $key;
171
172 2
            foreach ($this as $value) {
173 2
                if ($value == $needle) {
174 2
                    return true;
175
                }
176
            }
177
178 2
            return false;
179
        }
180
181 3
        return $this->contains($this->operatorForWhere(...func_get_args()));
182
    }
183
184
    /**
185
     * Cross join the given iterables, returning all possible permutations.
186
     *
187
     * @param  array  ...$arrays
188
     * @return static
189
     */
190 1
    public function crossJoin(...$arrays)
191
    {
192 1
        return $this->passthru('crossJoin', func_get_args());
193
    }
194
195
    /**
196
     * Get the items that are not present in the given items.
197
     *
198
     * @param  mixed  $items
199
     * @return static
200
     */
201 3
    public function diff($items)
202
    {
203 3
        return $this->passthru('diff', func_get_args());
204
    }
205
206
    /**
207
     * Get the items that are not present in the given items, using the callback.
208
     *
209
     * @param  mixed  $items
210
     * @param  callable  $callback
211
     * @return static
212
     */
213 2
    public function diffUsing($items, callable $callback)
214
    {
215 2
        return $this->passthru('diffUsing', func_get_args());
216
    }
217
218
    /**
219
     * Get the items whose keys and values are not present in the given items.
220
     *
221
     * @param  mixed  $items
222
     * @return static
223
     */
224 2
    public function diffAssoc($items)
225
    {
226 2
        return $this->passthru('diffAssoc', func_get_args());
227
    }
228
229
    /**
230
     * Get the items whose keys and values are not present in the given items.
231
     *
232
     * @param  mixed  $items
233
     * @param  callable  $callback
234
     * @return static
235
     */
236 1
    public function diffAssocUsing($items, callable $callback)
237
    {
238 1
        return $this->passthru('diffAssocUsing', func_get_args());
239
    }
240
241
    /**
242
     * Get the items whose keys are not present in the given items.
243
     *
244
     * @param  mixed  $items
245
     * @return static
246
     */
247 2
    public function diffKeys($items)
248
    {
249 2
        return $this->passthru('diffKeys', func_get_args());
250
    }
251
252
    /**
253
     * Get the items whose keys are not present in the given items.
254
     *
255
     * @param  mixed   $items
256
     * @param  callable  $callback
257
     * @return static
258
     */
259 1
    public function diffKeysUsing($items, callable $callback)
260
    {
261 1
        return $this->passthru('diffKeysUsing', func_get_args());
262
    }
263
264
    /**
265
     * Retrieve duplicate items.
266
     *
267
     * @param  callable|null  $callback
268
     * @param  bool  $strict
269
     * @return static
270
     */
271 3
    public function duplicates($callback = null, $strict = false)
272
    {
273 3
        return $this->passthru('duplicates', func_get_args());
274
    }
275
276
    /**
277
     * Retrieve duplicate items using strict comparison.
278
     *
279
     * @param  callable|null  $callback
280
     * @return static
281
     */
282 1
    public function duplicatesStrict($callback = null)
283
    {
284 1
        return $this->passthru('duplicatesStrict', func_get_args());
285
    }
286
287
    /**
288
     * Get all items except for those with the specified keys.
289
     *
290
     * @param  mixed  $keys
291
     * @return static
292
     */
293 2
    public function except($keys)
294
    {
295 2
        return $this->passthru('except', func_get_args());
296
    }
297
298
    /**
299
     * Run a filter over each of the items.
300
     *
301
     * @param  callable|null  $callback
302
     * @return static
303
     */
304 22
    public function filter(callable $callback = null)
305
    {
306 22
        if (is_null($callback)) {
307
            $callback = function ($value) {
308 1
                return (bool) $value;
309 1
            };
310
        }
311
312
        return new static(function () use ($callback) {
313 22
            foreach ($this as $key => $value) {
314 22
                if ($callback($value, $key)) {
315 22
                    yield $key => $value;
316
                }
317
            }
318 22
        });
319
    }
320
321
    /**
322
     * Get the first item from the enumerable passing the given truth test.
323
     *
324
     * @param  callable|null  $callback
325
     * @param  mixed  $default
326
     * @return mixed
327
     */
328 10
    public function first(callable $callback = null, $default = null)
329
    {
330 10
        $iterator = $this->getIterator();
331
332 10
        if (is_null($callback)) {
333 3
            if (! $iterator->valid()) {
334 1
                return value($default);
335
            }
336
337 2
            return $iterator->current();
338
        }
339
340 7
        foreach ($iterator as $key => $value) {
341 7
            if ($callback($value, $key)) {
342 6
                return $value;
343
            }
344
        }
345
346 6
        return value($default);
347
    }
348
349
    /**
350
     * Get a flattened list of the items in the collection.
351
     *
352
     * @param  int  $depth
353
     * @return static
354
     */
355 3
    public function flatten($depth = INF)
356
    {
357
        $instance = new static(function () use ($depth) {
358 3
            foreach ($this as $item) {
359 3
                if (! is_array($item) && ! $item instanceof Enumerable) {
360 3
                    yield $item;
361 3
                } elseif ($depth === 1) {
362 2
                    yield from $item;
363
                } else {
364 3
                    yield from (new static($item))->flatten($depth - 1);
365
                }
366
            }
367 3
        });
368
369 3
        return $instance->values();
370
    }
371
372
    /**
373
     * Flip the items in the collection.
374
     *
375
     * @return static
376
     */
377 1
    public function flip()
378
    {
379
        return new static(function () {
380 1
            foreach ($this as $key => $value) {
381 1
                yield $value => $key;
382
            }
383 1
        });
384
    }
385
386
    /**
387
     * Get an item by key.
388
     *
389
     * @param  mixed  $key
390
     * @param  mixed  $default
391
     * @return mixed
392
     */
393 7
    public function get($key, $default = null)
394
    {
395 7
        if (is_null($key)) {
396 1
            return;
397
        }
398
399 6
        foreach ($this as $outerKey => $outerValue) {
400 6
            if ($outerKey == $key) {
401 6
                return $outerValue;
402
            }
403
        }
404
405
        return value($default);
406
    }
407
408
    /**
409
     * Group an associative array by a field or using a callback.
410
     *
411
     * @param  array|callable|string  $groupBy
412
     * @param  bool  $preserveKeys
413
     * @return static
414
     */
415 10
    public function groupBy($groupBy, $preserveKeys = false)
416
    {
417 10
        return $this->passthru('groupBy', func_get_args());
418
    }
419
420
    /**
421
     * Key an associative array by a field or using a callback.
422
     *
423
     * @param  callable|string  $keyBy
424
     * @return static
425
     */
426 4
    public function keyBy($keyBy)
427
    {
428
        return new static(function () use ($keyBy) {
429 4
            $keyBy = $this->valueRetriever($keyBy);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $keyBy, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
430
431 4
            foreach ($this as $key => $item) {
432 4
                $resolvedKey = $keyBy($item, $key);
433
434 4
                if (is_object($resolvedKey)) {
435 1
                    $resolvedKey = (string) $resolvedKey;
436
                }
437
438 4
                yield $resolvedKey => $item;
439
            }
440 4
        });
441
    }
442
443
    /**
444
     * Determine if an item exists in the collection by key.
445
     *
446
     * @param  mixed  $key
447
     * @return bool
448
     */
449 2
    public function has($key)
450
    {
451 2
        $keys = array_flip(is_array($key) ? $key : func_get_args());
452 2
        $count = count($keys);
453
454 2
        foreach ($this as $key => $value) {
455 2
            if (array_key_exists($key, $keys) && --$count == 0) {
456 2
                return true;
457
            }
458
        }
459
460 2
        return false;
461
    }
462
463
    /**
464
     * Concatenate values of a given key as a string.
465
     *
466
     * @param  string  $value
467
     * @param  string  $glue
468
     * @return string
469
     */
470 1
    public function implode($value, $glue = null)
471
    {
472 1
        return $this->collect()->implode(...func_get_args());
473
    }
474
475
    /**
476
     * Intersect the collection with the given items.
477
     *
478
     * @param  mixed  $items
479
     * @return static
480
     */
481 2
    public function intersect($items)
482
    {
483 2
        return $this->passthru('intersect', func_get_args());
484
    }
485
486
    /**
487
     * Intersect the collection with the given items by key.
488
     *
489
     * @param  mixed  $items
490
     * @return static
491
     */
492 2
    public function intersectByKeys($items)
493
    {
494 2
        return $this->passthru('intersectByKeys', func_get_args());
495
    }
496
497
    /**
498
     * Determine if the items is empty or not.
499
     *
500
     * @return bool
501
     */
502 12
    public function isEmpty()
503
    {
504 12
        return ! $this->getIterator()->valid();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Traversable as the method valid() does only exist in the following implementations of said interface: APCUIterator, AppendIterator, ArrayIterator, CachingIterator, CallbackFilterIterator, Carbon\CarbonPeriod, DirectoryIterator, EmptyIterator, FilesystemIterator, FilterIterator, Generator, GlobIterator, HttpMessage, HttpRequestPool, Imagick, ImagickPixelIterator, InfiniteIterator, Issue523, IteratorIterator, LimitIterator, MongoCommandCursor, MongoCursor, MongoGridFSCursor, MultipleIterator, NoRewindIterator, PHPUnit\Framework\TestSuiteIterator, PHPUnit\Runner\Filter\ExcludeGroupFilterIterator, PHPUnit\Runner\Filter\GroupFilterIterator, PHPUnit\Runner\Filter\IncludeGroupFilterIterator, PHPUnit\Runner\Filter\NameFilterIterator, PHP_Token_Stream, ParentIterator, Phar, PharData, PharIo\Manifest\AuthorCollectionIterator, PharIo\Manifest\AuthorElementCollection, PharIo\Manifest\BundledComponentCollectionIterator, PharIo\Manifest\ComponentElementCollection, PharIo\Manifest\ElementCollection, PharIo\Manifest\ExtElementCollection, PharIo\Manifest\RequirementCollectionIterator, RecursiveArrayIterator, RecursiveCachingIterator, RecursiveCallbackFilterIterator, RecursiveDirectoryIterator, RecursiveFilterIterator, RecursiveIteratorIterator, RecursiveRegexIterator, RecursiveTreeIterator, RegexIterator, SQLiteResult, SebastianBergmann\CodeCoverage\Node\Iterator, SebastianBergmann\FileIterator\Iterator, SimpleXMLIterator, SplDoublyLinkedList, SplFileObject, SplFixedArray, SplHeap, SplMaxHeap, SplMinHeap, SplObjectStorage, SplPriorityQueue, SplQueue, SplStack, SplTempFileObject, Symfony\Component\VarDum...\Caster\MyArrayIterator, TestIterator, TestIterator2, TheSeer\Tokenizer\TokenCollection.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
505
    }
506
507
    /**
508
     * Join all items from the collection using a string. The final items can use a separate glue string.
509
     *
510
     * @param  string  $glue
511
     * @param  string  $finalGlue
512
     * @return string
513
     */
514 1
    public function join($glue, $finalGlue = '')
515
    {
516 1
        return $this->collect()->join(...func_get_args());
517
    }
518
519
    /**
520
     * Get the keys of the collection items.
521
     *
522
     * @return static
523
     */
524 3
    public function keys()
525
    {
526
        return new static(function () {
527 3
            foreach ($this as $key => $value) {
528 3
                yield $key;
529
            }
530 3
        });
531
    }
532
533
    /**
534
     * Get the last item from the collection.
535
     *
536
     * @param  callable|null  $callback
537
     * @param  mixed  $default
538
     * @return mixed
539
     */
540 4
    public function last(callable $callback = null, $default = null)
541
    {
542 4
        $needle = $placeholder = new stdClass;
543
544 4
        foreach ($this as $key => $value) {
545 3
            if (is_null($callback) || $callback($value, $key)) {
546 2
                $needle = $value;
547
            }
548
        }
549
550 4
        return $needle === $placeholder ? value($default) : $needle;
551
    }
552
553
    /**
554
     * Get the values of a given key.
555
     *
556
     * @param  string|array  $value
557
     * @param  string|null  $key
558
     * @return static
559
     */
560 4
    public function pluck($value, $key = null)
561
    {
562
        return new static(function () use ($value, $key) {
563 4
            [$value, $key] = $this->explodePluckParameters($value, $key);
564
565 4
            foreach ($this as $item) {
566 4
                $itemValue = data_get($item, $value);
567
568 4
                if (is_null($key)) {
569 4
                    yield $itemValue;
570
                } else {
571 2
                    $itemKey = data_get($item, $key);
572
573 2
                    if (is_object($itemKey) && method_exists($itemKey, '__toString')) {
574
                        $itemKey = (string) $itemKey;
575
                    }
576
577 2
                    yield $itemKey => $itemValue;
578
                }
579
            }
580 4
        });
581
    }
582
583
    /**
584
     * Run a map over each of the items.
585
     *
586
     * @param  callable  $callback
587
     * @return static
588
     */
589 68
    public function map(callable $callback)
590
    {
591
        return new static(function () use ($callback) {
592 68
            foreach ($this as $key => $value) {
593 65
                yield $key => $callback($value, $key);
594
            }
595 68
        });
596
    }
597
598
    /**
599
     * Run a dictionary map over the items.
600
     *
601
     * The callback should return an associative array with a single key/value pair.
602
     *
603
     * @param  callable  $callback
604
     * @return static
605
     */
606 4
    public function mapToDictionary(callable $callback)
607
    {
608 4
        return $this->passthru('mapToDictionary', func_get_args());
609
    }
610
611
    /**
612
     * Run an associative map over each of the items.
613
     *
614
     * The callback should return an associative array with a single key/value pair.
615
     *
616
     * @param  callable  $callback
617
     * @return static
618
     */
619 5
    public function mapWithKeys(callable $callback)
620
    {
621
        return new static(function () use ($callback) {
622 5
            foreach ($this as $key => $value) {
623 5
                yield from $callback($value, $key);
624
            }
625 5
        });
626
    }
627
628
    /**
629
     * Merge the collection with the given items.
630
     *
631
     * @param  mixed  $items
632
     * @return static
633
     */
634 3
    public function merge($items)
635
    {
636 3
        return $this->passthru('merge', func_get_args());
637
    }
638
639
    /**
640
     * Recursively merge the collection with the given items.
641
     *
642
     * @param  mixed  $items
643
     * @return static
644
     */
645 3
    public function mergeRecursive($items)
646
    {
647 3
        return $this->passthru('mergeRecursive', func_get_args());
648
    }
649
650
    /**
651
     * Create a collection by using this collection for keys and another for its values.
652
     *
653
     * @param  mixed  $values
654
     * @return static
655
     */
656 2
    public function combine($values)
657
    {
658
        return new static(function () use ($values) {
659 2
            $values = $this->makeIterator($values);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $values, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
660
661 2
            $errorMessage = 'Both parameters should have an equal number of elements';
662
663 2
            foreach ($this as $key) {
664 2
                if (! $values->valid()) {
665
                    trigger_error($errorMessage, E_USER_WARNING);
666
667
                    break;
668
                }
669
670 2
                yield $key => $values->current();
671
672 2
                $values->next();
673
            }
674
675 2
            if ($values->valid()) {
676
                trigger_error($errorMessage, E_USER_WARNING);
677
            }
678 2
        });
679
    }
680
681
    /**
682
     * Union the collection with the given items.
683
     *
684
     * @param  mixed  $items
685
     * @return static
686
     */
687 3
    public function union($items)
688
    {
689 3
        return $this->passthru('union', func_get_args());
690
    }
691
692
    /**
693
     * Create a new collection consisting of every n-th element.
694
     *
695
     * @param  int  $step
696
     * @param  int  $offset
697
     * @return static
698
     */
699 1
    public function nth($step, $offset = 0)
700
    {
701
        return new static(function () use ($step, $offset) {
702 1
            $position = 0;
703
704 1
            foreach ($this as $item) {
705 1
                if ($position % $step === $offset) {
706 1
                    yield $item;
707
                }
708
709 1
                $position++;
710
            }
711 1
        });
712
    }
713
714
    /**
715
     * Get the items with the specified keys.
716
     *
717
     * @param  mixed  $keys
718
     * @return static
719
     */
720 1
    public function only($keys)
721
    {
722 1
        if ($keys instanceof Enumerable) {
723 1
            $keys = $keys->all();
724 1
        } elseif (! is_null($keys)) {
725 1
            $keys = is_array($keys) ? $keys : func_get_args();
726
        }
727
728
        return new static(function () use ($keys) {
729 1
            if (is_null($keys)) {
730 1
                yield from $this;
731
            } else {
732 1
                $keys = array_flip($keys);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $keys, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
733
734 1
                foreach ($this as $key => $value) {
735 1
                    if (array_key_exists($key, $keys)) {
736 1
                        yield $key => $value;
737
738 1
                        unset($keys[$key]);
739
740 1
                        if (empty($keys)) {
741 1
                            break;
742
                        }
743
                    }
744
                }
745
            }
746 1
        });
747
    }
748
749
    /**
750
     * Push all of the given items onto the collection.
751
     *
752
     * @param  iterable  $source
753
     * @return static
754
     */
755 15
    public function concat($source)
756
    {
757
        return (new static(function () use ($source) {
758 15
            yield from $this;
759 15
            yield from $source;
760 15
        }))->values();
761
    }
762
763
    /**
764
     * Get one or a specified number of items randomly from the collection.
765
     *
766
     * @param  int|null  $number
767
     * @return static|mixed
768
     *
769
     * @throws \InvalidArgumentException
770
     */
771 3
    public function random($number = null)
772
    {
773 3
        $result = $this->collect()->random(...func_get_args());
774
775 2
        return is_null($number) ? $result : new static($result);
776
    }
777
778
    /**
779
     * Reduce the collection to a single value.
780
     *
781
     * @param  callable  $callback
782
     * @param  mixed  $initial
783
     * @return mixed
784
     */
785 7
    public function reduce(callable $callback, $initial = null)
786
    {
787 7
        $result = $initial;
788
789 7
        foreach ($this as $value) {
790 6
            $result = $callback($result, $value);
791
        }
792
793 7
        return $result;
794
    }
795
796
    /**
797
     * Replace the collection items with the given items.
798
     *
799
     * @param  mixed  $items
800
     * @return static
801
     */
802 3
    public function replace($items)
803
    {
804
        return new static(function () use ($items) {
805 3
            $items = $this->getArrayableItems($items);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $items, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
806
807 3
            foreach ($this as $key => $value) {
808 3
                if (array_key_exists($key, $items)) {
809 2
                    yield $key => $items[$key];
810
811 2
                    unset($items[$key]);
812
                } else {
813 3
                    yield $key => $value;
814
                }
815
            }
816
817 3
            foreach ($items as $key => $value) {
818
                yield $key => $value;
819
            }
820 3
        });
821
    }
822
823
    /**
824
     * Recursively replace the collection items with the given items.
825
     *
826
     * @param  mixed  $items
827
     * @return static
828
     */
829 3
    public function replaceRecursive($items)
830
    {
831 3
        return $this->passthru('replaceRecursive', func_get_args());
832
    }
833
834
    /**
835
     * Reverse items order.
836
     *
837
     * @return static
838
     */
839 1
    public function reverse()
840
    {
841 1
        return $this->passthru('reverse', func_get_args());
842
    }
843
844
    /**
845
     * Search the collection for a given value and return the corresponding key if successful.
846
     *
847
     * @param  mixed  $value
848
     * @param  bool  $strict
849
     * @return mixed
850
     */
851 3
    public function search($value, $strict = false)
852
    {
853 3
        $predicate = $this->useAsCallable($value)
854 2
            ? $value
855
            : function ($item) use ($value, $strict) {
856 3
                return $strict ? $item === $value : $item == $value;
857 3
            };
858
859 3
        foreach ($this as $key => $item) {
860 3
            if ($predicate($item, $key)) {
861 2
                return $key;
862
            }
863
        }
864
865 2
        return false;
866
    }
867
868
    /**
869
     * Shuffle the items in the collection.
870
     *
871
     * @param  int  $seed
872
     * @return static
873
     */
874 1
    public function shuffle($seed = null)
875
    {
876 1
        return $this->passthru('shuffle', func_get_args());
877
    }
878
879
    /**
880
     * Skip the first {$count} items.
881
     *
882
     * @param  int  $count
883
     * @return static
884
     */
885 5
    public function skip($count)
886
    {
887
        return new static(function () use ($count) {
888 5
            $iterator = $this->getIterator();
889
890 5
            while ($iterator->valid() && $count--) {
891 4
                $iterator->next();
892
            }
893
894 5
            while ($iterator->valid()) {
895 5
                yield $iterator->key() => $iterator->current();
896
897 4
                $iterator->next();
898
            }
899 5
        });
900
    }
901
902
    /**
903
     * Get a slice of items from the enumerable.
904
     *
905
     * @param  int  $offset
906
     * @param  int  $length
907
     * @return static
908
     */
909 8
    public function slice($offset, $length = null)
910
    {
911 8
        if ($offset < 0 || $length < 0) {
912 4
            return $this->passthru('slice', func_get_args());
913
        }
914
915 4
        $instance = $this->skip($offset);
916
917 4
        return is_null($length) ? $instance : $instance->take($length);
918
    }
919
920
    /**
921
     * Split a collection into a certain number of groups.
922
     *
923
     * @param  int  $numberOfGroups
924
     * @return static
925
     */
926 7
    public function split($numberOfGroups)
927
    {
928 7
        return $this->passthru('split', func_get_args());
929
    }
930
931
    /**
932
     * Chunk the collection into chunks of the given size.
933
     *
934
     * @param  int  $size
935
     * @return static
936
     */
937 3
    public function chunk($size)
938
    {
939 3
        if ($size <= 0) {
940 2
            return static::empty();
941
        }
942
943
        return new static(function () use ($size) {
944 1
            $iterator = $this->getIterator();
945
946 1
            while ($iterator->valid()) {
947 1
                $chunk = [];
948
949 1
                while (true) {
950 1
                    $chunk[$iterator->key()] = $iterator->current();
951
952 1
                    if (count($chunk) < $size) {
953 1
                        $iterator->next();
954
955 1
                        if (! $iterator->valid()) {
956 1
                            break;
957
                        }
958
                    } else {
959 1
                        break;
960
                    }
961
                }
962
963 1
                yield new static($chunk);
964
965 1
                $iterator->next();
966
            }
967 1
        });
968
    }
969
970
    /**
971
     * Sort through each item with a callback.
972
     *
973
     * @param  callable|null  $callback
974
     * @return static
975
     */
976 2
    public function sort(callable $callback = null)
977
    {
978 2
        return $this->passthru('sort', func_get_args());
979
    }
980
981
    /**
982
     * Sort the collection using the given callback.
983
     *
984
     * @param  callable|string  $callback
985
     * @param  int  $options
986
     * @param  bool  $descending
987
     * @return static
988
     */
989 4
    public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
990
    {
991 4
        return $this->passthru('sortBy', func_get_args());
992
    }
993
994
    /**
995
     * Sort the collection in descending order using the given callback.
996
     *
997
     * @param  callable|string  $callback
998
     * @param  int  $options
999
     * @return static
1000
     */
1001 1
    public function sortByDesc($callback, $options = SORT_REGULAR)
1002
    {
1003 1
        return $this->passthru('sortByDesc', func_get_args());
1004
    }
1005
1006
    /**
1007
     * Sort the collection keys.
1008
     *
1009
     * @param  int  $options
1010
     * @param  bool  $descending
1011
     * @return static
1012
     */
1013 1
    public function sortKeys($options = SORT_REGULAR, $descending = false)
1014
    {
1015 1
        return $this->passthru('sortKeys', func_get_args());
1016
    }
1017
1018
    /**
1019
     * Sort the collection keys in descending order.
1020
     *
1021
     * @param  int $options
1022
     * @return static
1023
     */
1024 1
    public function sortKeysDesc($options = SORT_REGULAR)
1025
    {
1026 1
        return $this->passthru('sortKeysDesc', func_get_args());
1027
    }
1028
1029
    /**
1030
     * Take the first or last {$limit} items.
1031
     *
1032
     * @param  int  $limit
1033
     * @return static
1034
     */
1035 5
    public function take($limit)
1036
    {
1037 5
        if ($limit < 0) {
1038 1
            return $this->passthru('take', func_get_args());
1039
        }
1040
1041
        return new static(function () use ($limit) {
1042 4
            $iterator = $this->getIterator();
1043
1044 4
            while ($limit--) {
1045 4
                if (! $iterator->valid()) {
1046 1
                    break;
1047
                }
1048
1049 4
                yield $iterator->key() => $iterator->current();
1050
1051 4
                if ($limit) {
1052 3
                    $iterator->next();
1053
                }
1054
            }
1055 4
        });
1056
    }
1057
1058
    /**
1059
     * Pass each item in the collection to the given callback, lazily.
1060
     *
1061
     * @param  callable  $callback
1062
     * @return static
1063
     */
1064
    public function tapEach(callable $callback)
1065
    {
1066
        return new static(function () use ($callback) {
1067
            foreach ($this as $key => $value) {
1068
                $callback($value, $key);
1069
1070
                yield $key => $value;
1071
            }
1072
        });
1073
    }
1074
1075
    /**
1076
     * Reset the keys on the underlying array.
1077
     *
1078
     * @return static
1079
     */
1080 46
    public function values()
1081
    {
1082
        return new static(function () {
1083 46
            foreach ($this as $item) {
1084 46
                yield $item;
1085
            }
1086 46
        });
1087
    }
1088
1089
    /**
1090
     * Zip the collection together with one or more arrays.
1091
     *
1092
     * e.g. new LazyCollection([1, 2, 3])->zip([4, 5, 6]);
1093
     *      => [[1, 4], [2, 5], [3, 6]]
1094
     *
1095
     * @param  mixed ...$items
1096
     * @return static
1097
     */
1098 1
    public function zip($items)
1099
    {
1100 1
        $iterables = func_get_args();
1101
1102
        return new static(function () use ($iterables) {
1103
            $iterators = Collection::make($iterables)->map(function ($iterable) {
1104 1
                return $this->makeIterator($iterable);
1105 1
            })->prepend($this->getIterator());
1106
1107 1
            while ($iterators->contains->valid()) {
1108 1
                yield new static($iterators->map->current());
1109
1110 1
                $iterators->each->next();
1111
            }
1112 1
        });
1113
    }
1114
1115
    /**
1116
     * Pad collection to the specified length with a value.
1117
     *
1118
     * @param  int  $size
1119
     * @param  mixed  $value
1120
     * @return static
1121
     */
1122 1
    public function pad($size, $value)
1123
    {
1124 1
        if ($size < 0) {
1125 1
            return $this->passthru('pad', func_get_args());
1126
        }
1127
1128
        return new static(function () use ($size, $value) {
1129 1
            $yielded = 0;
1130
1131 1
            foreach ($this as $index => $item) {
1132 1
                yield $index => $item;
1133
1134 1
                $yielded++;
1135
            }
1136
1137 1
            while ($yielded++ < $size) {
1138 1
                yield $value;
1139
            }
1140 1
        });
1141
    }
1142
1143
    /**
1144
     * Get the values iterator.
1145
     *
1146
     * @return \Traversable
1147
     */
1148 195
    public function getIterator()
1149
    {
1150 195
        return $this->makeIterator($this->source);
1151
    }
1152
1153
    /**
1154
     * Count the number of items in the collection.
1155
     *
1156
     * @return int
1157
     */
1158 9
    public function count()
1159
    {
1160 9
        if (is_array($this->source)) {
1161 4
            return count($this->source);
1162
        }
1163
1164 5
        return iterator_count($this->getIterator());
1165
    }
1166
1167
    /**
1168
     * Make an iterator from the given source.
1169
     *
1170
     * @param  mixed  $source
1171
     * @return \Traversable
1172
     */
1173 195
    protected function makeIterator($source)
1174
    {
1175 195
        if ($source instanceof IteratorAggregate) {
1176 28
            return $source->getIterator();
1177
        }
1178
1179 195
        if (is_array($source)) {
1180 133
            return new ArrayIterator($source);
1181
        }
1182
1183 156
        return $source();
1184
    }
1185
1186
    /**
1187
     * Explode the "value" and "key" arguments passed to "pluck".
1188
     *
1189
     * @param  string|array  $value
1190
     * @param  string|array|null  $key
1191
     * @return array
1192
     */
1193 4
    protected function explodePluckParameters($value, $key)
1194
    {
1195 4
        $value = is_string($value) ? explode('.', $value) : $value;
1196
1197 4
        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);
1198
1199 4
        return [$value, $key];
1200
    }
1201
1202
    /**
1203
     * Pass this lazy collection through a method on the collection class.
1204
     *
1205
     * @param  string  $method
1206
     * @param  array  $params
1207
     * @return static
1208
     */
1209 68
    protected function passthru($method, array $params)
1210
    {
1211
        return new static(function () use ($method, $params) {
1212 67
            yield from $this->collect()->$method(...$params);
1213 68
        });
1214
    }
1215
}
1216