Completed
Pull Request — master (#3)
by
unknown
02:44
created

LazyCollection::diff()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace IlluminateAgnostic\Arr\Support;
4
5
use ArrayIterator;
6
use Closure;
7
use IlluminateAgnostic\Arr\Support\Traits\EnumeratesValues;
8
use IlluminateAgnostic\Arr\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 236
    public function __construct($source = null)
30
    {
31 236
        if ($source instanceof Closure || $source instanceof self) {
32 165
            $this->source = $source;
33 236
        } elseif (is_null($source)) {
34 26
            $this->source = static::empty();
35
        } else {
36 236
            $this->source = $this->getArrayableItems($source);
37
        }
38 236
    }
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 195
    public function all()
94
    {
95 195
        if (is_array($this->source)) {
96 111
            return $this->source;
97
        }
98
99 163
        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
    public function avg($callback = null)
109
    {
110
        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
    public function median($key = null)
120
    {
121
        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
    public function mode($key = null)
131
    {
132
        return $this->collect()->mode($key);
133
    }
134
135
    /**
136
     * Collapse the collection of items into a single array.
137
     *
138
     * @return static
139
     */
140
    public function collapse()
141
    {
142
        return new static(function () {
143
            foreach ($this as $values) {
144
                if (is_array($values) || $values instanceof Enumerable) {
145
                    foreach ($values as $value) {
146
                        yield $value;
147
                    }
148
                }
149
            }
150
        });
151
    }
152
153
    /**
154
     * Determine if an item exists in the enumerable.
155
     *
156 1
     * @param  mixed  $key
157
     * @param  mixed  $operator
158 1
     * @param  mixed  $value
159
     * @return bool
160
     */
161
    public function contains($key, $operator = null, $value = null)
162
    {
163
        if (func_num_args() === 1 && $this->useAsCallable($key)) {
164
            $placeholder = new stdClass;
165
166
            return $this->first($key, $placeholder) !== $placeholder;
167 6
        }
168
169 6
        if (func_num_args() === 1) {
170
            $needle = $key;
171
172
            foreach ($this as $value) {
173
                if ($value == $needle) {
174
                    return true;
175
                }
176
            }
177
178 4
            return false;
179
        }
180 4
181
        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 3
     * @return static
189
     */
190
    public function crossJoin(...$arrays)
191 3
    {
192 3
        return $this->passthru('crossJoin', func_get_args());
193 3
    }
194 3
195
    /**
196
     * Get the items that are not present in the given items.
197
     *
198 3
     * @param  mixed  $items
199
     * @return static
200
     */
201
    public function diff($items)
202
    {
203
        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 4
     * @param  mixed  $items
210
     * @param  callable  $callback
211 4
     * @return static
212 4
     */
213
    public function diffUsing($items, callable $callback)
214 4
    {
215
        return $this->passthru('diffUsing', func_get_args());
216
    }
217 3
218 2
    /**
219
     * Get the items whose keys and values are not present in the given items.
220 2
     *
221 2
     * @param  mixed  $items
222 2
     * @return static
223
     */
224
    public function diffAssoc($items)
225
    {
226 2
        return $this->passthru('diffAssoc', func_get_args());
227
    }
228
229 3
    /**
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
    public function diffAssocUsing($items, callable $callback)
237
    {
238 1
        return $this->passthru('diffAssocUsing', func_get_args());
239
    }
240 1
241
    /**
242
     * Get the items whose keys are not present in the given items.
243
     *
244
     * @param  mixed  $items
245
     * @return static
246
     */
247
    public function diffKeys($items)
248
    {
249 3
        return $this->passthru('diffKeys', func_get_args());
250
    }
251 3
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
    public function diffKeysUsing($items, callable $callback)
260
    {
261 2
        return $this->passthru('diffKeysUsing', func_get_args());
262
    }
263 2
264
    /**
265
     * Retrieve duplicate items.
266
     *
267
     * @param  callable|null  $callback
268
     * @param  bool  $strict
269
     * @return static
270
     */
271
    public function duplicates($callback = null, $strict = false)
272 2
    {
273
        return $this->passthru('duplicates', func_get_args());
274 2
    }
275
276
    /**
277
     * Retrieve duplicate items using strict comparison.
278
     *
279
     * @param  callable|null  $callback
280
     * @return static
281
     */
282
    public function duplicatesStrict($callback = null)
283
    {
284 1
        return $this->passthru('duplicatesStrict', func_get_args());
285
    }
286 1
287
    /**
288
     * Get all items except for those with the specified keys.
289
     *
290
     * @param  mixed  $keys
291
     * @return static
292
     */
293
    public function except($keys)
294
    {
295 2
        return $this->passthru('except', func_get_args());
296
    }
297 2
298
    /**
299
     * Run a filter over each of the items.
300
     *
301
     * @param  callable|null  $callback
302
     * @return static
303
     */
304
    public function filter(callable $callback = null)
305
    {
306
        if (is_null($callback)) {
307 1
            $callback = function ($value) {
308
                return (bool) $value;
309 1
            };
310
        }
311
312
        return new static(function () use ($callback) {
313
            foreach ($this as $key => $value) {
314
                if ($callback($value, $key)) {
315
                    yield $key => $value;
316
                }
317
            }
318
        });
319 3
    }
320
321 3
    /**
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
    public function first(callable $callback = null, $default = null)
329
    {
330 1
        $iterator = $this->getIterator();
331
332 1
        if (is_null($callback)) {
333
            if (! $iterator->valid()) {
334
                return value($default);
335
            }
336
337
            return $iterator->current();
338
        }
339
340
        foreach ($iterator as $key => $value) {
341 2
            if ($callback($value, $key)) {
342
                return $value;
343 2
            }
344
        }
345
346
        return value($default);
347
    }
348
349
    /**
350
     * Get a flattened list of the items in the collection.
351
     *
352 26
     * @param  int  $depth
353
     * @return static
354 26
     */
355
    public function flatten($depth = INF)
356 1
    {
357 1
        $instance = new static(function () use ($depth) {
358
            foreach ($this as $item) {
359
                if (! is_array($item) && ! $item instanceof Enumerable) {
360
                    yield $item;
361 26
                } elseif ($depth === 1) {
362 26
                    yield from $item;
363 26
                } else {
364
                    yield from (new static($item))->flatten($depth - 1);
365
                }
366 26
            }
367
        });
368
369
        return $instance->values();
370
    }
371
372
    /**
373
     * Flip the items in the collection.
374
     *
375
     * @return static
376 10
     */
377
    public function flip()
378 10
    {
379
        return new static(function () {
380 10
            foreach ($this as $key => $value) {
381 3
                yield $value => $key;
382 1
            }
383
        });
384
    }
385 2
386
    /**
387
     * Get an item by key.
388 7
     *
389 7
     * @param  mixed  $key
390 6
     * @param  mixed  $default
391
     * @return mixed
392
     */
393
    public function get($key, $default = null)
394 6
    {
395
        if (is_null($key)) {
396
            return;
397
        }
398
399
        foreach ($this as $outerKey => $outerValue) {
400
            if ($outerKey == $key) {
401
                return $outerValue;
402
            }
403 3
        }
404
405
        return value($default);
406 3
    }
407 3
408 3
    /**
409 3
     * Group an associative array by a field or using a callback.
410 2
     *
411
     * @param  array|callable|string  $groupBy
412 3
     * @param  bool  $preserveKeys
413
     * @return static
414
     */
415 3
    public function groupBy($groupBy, $preserveKeys = false)
416
    {
417 3
        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 1
     */
426
    public function keyBy($keyBy)
427
    {
428 1
        return new static(function () use ($keyBy) {
429 1
            $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 1
            foreach ($this as $key => $item) {
432
                $resolvedKey = $keyBy($item, $key);
433
434
                if (is_object($resolvedKey)) {
435
                    $resolvedKey = (string) $resolvedKey;
436
                }
437
438
                yield $resolvedKey => $item;
439
            }
440
        });
441 7
    }
442
443 7
    /**
444 1
     * Determine if an item exists in the collection by key.
445
     *
446
     * @param  mixed  $key
447 6
     * @return bool
448 6
     */
449 6
    public function has($key)
450
    {
451
        $keys = array_flip(is_array($key) ? $key : func_get_args());
452
        $count = count($keys);
453
454
        foreach ($this as $key => $value) {
455
            if (array_key_exists($key, $keys) && --$count == 0) {
456
                return true;
457
            }
458
        }
459
460
        return false;
461
    }
462
463 10
    /**
464
     * Concatenate values of a given key as a string.
465 10
     *
466
     * @param  string  $value
467
     * @param  string  $glue
468
     * @return string
469
     */
470
    public function implode($value, $glue = null)
471
    {
472
        return $this->collect()->implode(...func_get_args());
473
    }
474 4
475
    /**
476
     * Intersect the collection with the given items.
477 4
     *
478
     * @param  mixed  $items
479 4
     * @return static
480 4
     */
481
    public function intersect($items)
482 4
    {
483 1
        return $this->passthru('intersect', func_get_args());
484
    }
485
486 4
    /**
487
     * Intersect the collection with the given items by key.
488 4
     *
489
     * @param  mixed  $items
490
     * @return static
491
     */
492
    public function intersectByKeys($items)
493
    {
494
        return $this->passthru('intersectByKeys', func_get_args());
495
    }
496
497 2
    /**
498
     * Determine if the items is empty or not.
499 2
     *
500 2
     * @return bool
501
     */
502 2
    public function isEmpty()
503 2
    {
504 2
        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, Aws\Api\Parser\DecodingEventStreamIterator, Aws\Api\Parser\EventParsingIterator, Aws\CloudTrail\LogFileIterator, Aws\CloudTrail\LogRecordIterator, Aws\ResultPaginator, CachingIterator, CallbackFilterIterator, Carbon\CarbonPeriod, CoreTestIterator, DirectoryIterator, Elastica\Bulk\ResponseSet, Elastica\Multi\ResultSet, Elastica\ResultSet, Elastica\ScanAndScroll, Elastica\Scroll, EmptyIterator, File_Iterator, 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, PhpAmqpLib\Wire\AMQPAbstractCollection, PhpAmqpLib\Wire\AMQPArray, PhpAmqpLib\Wire\AMQPTable, Predis\Collection\Iterator\CursorBasedIterator, Predis\Collection\Iterator\HashKey, Predis\Collection\Iterator\Keyspace, Predis\Collection\Iterator\ListKey, Predis\Collection\Iterator\SetKey, Predis\Collection\Iterator\SortedSetKey, Predis\Monitor\Consumer, Predis\PubSub\AbstractConsumer, Predis\PubSub\Consumer, Predis\Response\Iterator\MultiBulk, Predis\Response\Iterator\MultiBulkIterator, Predis\Response\Iterator\MultiBulkTuple, RecursiveArrayIterator, RecursiveCachingIterator, RecursiveCallbackFilterIterator, RecursiveDirectoryIterator, RecursiveFilterIterator, RecursiveIteratorIterator, RecursiveRegexIterator, RecursiveTreeIterator, RegexIterator, SQLiteResult, SebastianBergmann\CodeCoverage\Node\Iterator, SimpleIteratorForTesting, SimpleXMLIterator, SplDoublyLinkedList, SplFileObject, SplFixedArray, SplHeap, SplMaxHeap, SplMinHeap, SplObjectStorage, SplPriorityQueue, SplQueue, SplStack, SplTempFileObject, Symfony\Component\Finder...or\CustomFilterIterator, Symfony\Component\Finder...DateRangeFilterIterator, Symfony\Component\Finder...epthRangeFilterIterator, Symfony\Component\Finder...DirectoryFilterIterator, Symfony\Component\Finder...\FileTypeFilterIterator, Symfony\Component\Finder...lecontentFilterIterator, Symfony\Component\Finder...\FilenameFilterIterator, Symfony\Component\Finder\Iterator\FilterIterator, Symfony\Component\Finder...tiplePcreFilterIterator, Symfony\Component\Finder...ator\PathFilterIterator, Symfony\Component\Finder...ursiveDirectoryIterator, Symfony\Component\Finder...SizeRangeFilterIterator, Symfony\Component\Finder...rator\InnerNameIterator, Symfony\Component\Finder...rator\InnerSizeIterator, Symfony\Component\Finder...rator\InnerTypeIterator, Symfony\Component\Finder\Tests\Iterator\Iterator, Symfony\Component\Finder...or\MockFileListIterator, Symfony\Component\Finder...tiplePcreFilterIterator, Symfony\Component\Form\E...r\ViolationPathIterator, Symfony\Component\Form\FormErrorIterator, Symfony\Component\Form\U...nheritDataAwareIterator, Symfony\Component\Form\Util\OrderedHashMapIterator, Symfony\Component\Proper...ss\PropertyPathIterator, Symfony\Component\VarDum...\Caster\MyArrayIterator, Symfony\Component\VarDum...\Caster\MyArrayIterator, TestIterator, TestIterator2, TheSeer\Tokenizer\TokenCollection, TwigTestFoo, Twig\Util\TemplateDirIterator, Twig_Util_TemplateDirIterator, Zend\EventManager\ResponseCollection.

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 2
     * 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
    public function join($glue, $finalGlue = '')
515
    {
516
        return $this->collect()->join(...func_get_args());
517
    }
518 1
519
    /**
520 1
     * Get the keys of the collection items.
521
     *
522
     * @return static
523
     */
524
    public function keys()
525
    {
526
        return new static(function () {
527
            foreach ($this as $key => $value) {
528
                yield $key;
529 2
            }
530
        });
531 2
    }
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 2
    public function last(callable $callback = null, $default = null)
541
    {
542 2
        $needle = $placeholder = new stdClass;
543
544
        foreach ($this as $key => $value) {
545
            if (is_null($callback) || $callback($value, $key)) {
546
                $needle = $value;
547
            }
548
        }
549
550 12
        return $needle === $placeholder ? value($default) : $needle;
551
    }
552 12
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
    public function pluck($value, $key = null)
561
    {
562 1
        return new static(function () use ($value, $key) {
563
            [$value, $key] = $this->explodePluckParameters($value, $key);
564 1
565
            foreach ($this as $item) {
566
                $itemValue = data_get($item, $value);
567
568
                if (is_null($key)) {
569
                    yield $itemValue;
570
                } else {
571
                    $itemKey = data_get($item, $key);
572 3
573
                    if (is_object($itemKey) && method_exists($itemKey, '__toString')) {
574
                        $itemKey = (string) $itemKey;
575 3
                    }
576 3
577
                    yield $itemKey => $itemValue;
578 3
                }
579
            }
580
        });
581
    }
582
583
    /**
584
     * Run a map over each of the items.
585
     *
586
     * @param  callable  $callback
587
     * @return static
588 4
     */
589
    public function map(callable $callback)
590 4
    {
591
        return new static(function () use ($callback) {
592 4
            foreach ($this as $key => $value) {
593 3
                yield $key => $callback($value, $key);
594 2
            }
595
        });
596
    }
597
598 4
    /**
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
    public function mapToDictionary(callable $callback)
607
    {
608 4
        return $this->passthru('mapToDictionary', func_get_args());
609
    }
610
611 4
    /**
612
     * Run an associative map over each of the items.
613 4
     *
614 4
     * The callback should return an associative array with a single key/value pair.
615
     *
616 4
     * @param  callable  $callback
617 4
     * @return static
618
     */
619 2
    public function mapWithKeys(callable $callback)
620
    {
621 2
        return new static(function () use ($callback) {
622
            foreach ($this as $key => $value) {
623
                yield from $callback($value, $key);
624
            }
625 2
        });
626
    }
627
628 4
    /**
629
     * Merge the collection with the given items.
630
     *
631
     * @param  mixed  $items
632
     * @return static
633
     */
634
    public function merge($items)
635
    {
636
        return $this->passthru('merge', func_get_args());
637 68
    }
638
639
    /**
640 68
     * Recursively merge the collection with the given items.
641 65
     *
642
     * @param  mixed  $items
643 68
     * @return static
644
     */
645
    public function mergeRecursive($items)
646
    {
647
        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 4
     * @return static
655
     */
656 4
    public function combine($values)
657
    {
658
        return new static(function () use ($values) {
659
            $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
            $errorMessage = 'Both parameters should have an equal number of elements';
662
663
            foreach ($this as $key) {
664
                if (! $values->valid()) {
665
                    trigger_error($errorMessage, E_USER_WARNING);
666
667 5
                    break;
668
                }
669
670 5
                yield $key => $values->current();
671 5
672
                $values->next();
673 5
            }
674
675
            if ($values->valid()) {
676
                trigger_error($errorMessage, E_USER_WARNING);
677
            }
678
        });
679
    }
680
681
    /**
682 3
     * Union the collection with the given items.
683
     *
684 3
     * @param  mixed  $items
685
     * @return static
686
     */
687
    public function union($items)
688
    {
689
        return $this->passthru('union', func_get_args());
690
    }
691
692
    /**
693 3
     * Create a new collection consisting of every n-th element.
694
     *
695 3
     * @param  int  $step
696
     * @param  int  $offset
697
     * @return static
698
     */
699
    public function nth($step, $offset = 0)
700
    {
701
        return new static(function () use ($step, $offset) {
702
            $position = 0;
703
704 2
            foreach ($this as $item) {
705
                if ($position % $step === $offset) {
706
                    yield $item;
707 2
                }
708
709 2
                $position++;
710
            }
711 2
        });
712 2
    }
713
714
    /**
715
     * Get the items with the specified keys.
716
     *
717
     * @param  mixed  $keys
718 2
     * @return static
719
     */
720 2
    public function only($keys)
721
    {
722
        if ($keys instanceof Enumerable) {
723 2
            $keys = $keys->all();
724
        } elseif (! is_null($keys)) {
725
            $keys = is_array($keys) ? $keys : func_get_args();
726 2
        }
727
728
        return new static(function () use ($keys) {
729
            if (is_null($keys)) {
730
                yield from $this;
731
            } else {
732
                $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
                foreach ($this as $key => $value) {
735 3
                    if (array_key_exists($key, $keys)) {
736
                        yield $key => $value;
737 3
738
                        unset($keys[$key]);
739
740
                        if (empty($keys)) {
741
                            break;
742
                        }
743
                    }
744
                }
745
            }
746
        });
747 1
    }
748
749
    /**
750 1
     * Push all of the given items onto the collection.
751
     *
752 1
     * @param  iterable  $source
753 1
     * @return static
754 1
     */
755
    public function concat($source)
756
    {
757 1
        return (new static(function () use ($source) {
758
            yield from $this;
759 1
            yield from $source;
760
        }))->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 1
     *
769
     * @throws \InvalidArgumentException
770 1
     */
771 1
    public function random($number = null)
772 1
    {
773 1
        $result = $this->collect()->random(...func_get_args());
774
775
        return is_null($number) ? $result : new static($result);
776
    }
777 1
778 1
    /**
779
     * Reduce the collection to a single value.
780 1
     *
781
     * @param  callable  $callback
782 1
     * @param  mixed  $initial
783 1
     * @return mixed
784 1
     */
785
    public function reduce(callable $callback, $initial = null)
786 1
    {
787
        $result = $initial;
788 1
789 1
        foreach ($this as $value) {
790
            $result = $callback($result, $value);
791
        }
792
793
        return $result;
794 1
    }
795
796
    /**
797
     * Replace the collection items with the given items.
798
     *
799
     * @param  mixed  $items
800
     * @return static
801
     */
802
    public function replace($items)
803 15
    {
804
        return new static(function () use ($items) {
805
            $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 15
807 15
            foreach ($this as $key => $value) {
808 15
                if (array_key_exists($key, $items)) {
809
                    yield $key => $items[$key];
810
811
                    unset($items[$key]);
812
                } else {
813
                    yield $key => $value;
814
                }
815
            }
816
817
            foreach ($items as $key => $value) {
818
                yield $key => $value;
819 3
            }
820
        });
821 3
    }
822
823 2
    /**
824
     * Recursively replace the collection items with the given items.
825
     *
826
     * @param  mixed  $items
827
     * @return static
828
     */
829
    public function replaceRecursive($items)
830
    {
831
        return $this->passthru('replaceRecursive', func_get_args());
832
    }
833 7
834
    /**
835 7
     * Reverse items order.
836
     *
837 7
     * @return static
838 6
     */
839
    public function reverse()
840
    {
841 7
        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 3
     */
851
    public function search($value, $strict = false)
852
    {
853 3
        $predicate = $this->useAsCallable($value)
854
            ? $value
855 3
            : function ($item) use ($value, $strict) {
856 3
                return $strict ? $item === $value : $item == $value;
857 2
            };
858
859 2
        foreach ($this as $key => $item) {
860
            if ($predicate($item, $key)) {
861 3
                return $key;
862
            }
863
        }
864
865 3
        return false;
866
    }
867
868 3
    /**
869
     * Shuffle the items in the collection.
870
     *
871
     * @param  int  $seed
872
     * @return static
873
     */
874
    public function shuffle($seed = null)
875
    {
876
        return $this->passthru('shuffle', func_get_args());
877 3
    }
878
879 3
    /**
880
     * Skip the first {$count} items.
881
     *
882
     * @param  int  $count
883
     * @return static
884
     */
885
    public function skip($count)
886
    {
887 1
        return new static(function () use ($count) {
888
            $iterator = $this->getIterator();
889 1
890
            while ($iterator->valid() && $count--) {
891
                $iterator->next();
892
            }
893
894
            while ($iterator->valid()) {
895
                yield $iterator->key() => $iterator->current();
896
897
                $iterator->next();
898
            }
899 3
        });
900
    }
901 3
902 2
    /**
903
     * Get a slice of items from the enumerable.
904 3
     *
905 3
     * @param  int  $offset
906
     * @param  int  $length
907 3
     * @return static
908 3
     */
909 2
    public function slice($offset, $length = null)
910
    {
911
        if ($offset < 0 || $length < 0) {
912
            return $this->passthru('slice', func_get_args());
913 2
        }
914
915
        $instance = $this->skip($offset);
916
917
        return is_null($length) ? $instance : $instance->take($length);
918
    }
919
920
    /**
921
     * Split a collection into a certain number of groups.
922 1
     *
923
     * @param  int  $numberOfGroups
924 1
     * @return static
925
     */
926
    public function split($numberOfGroups)
927
    {
928
        return $this->passthru('split', func_get_args());
929
    }
930
931
    /**
932
     * Chunk the collection into chunks of the given size.
933 5
     *
934
     * @param  int  $size
935
     * @return static
936 5
     */
937
    public function chunk($size)
938 5
    {
939 4
        if ($size <= 0) {
940
            return static::empty();
941
        }
942 5
943 5
        return new static(function () use ($size) {
944
            $iterator = $this->getIterator();
945 4
946
            while ($iterator->valid()) {
947 5
                $chunk = [];
948
949
                while (true) {
950
                    $chunk[$iterator->key()] = $iterator->current();
951
952
                    if (count($chunk) < $size) {
953
                        $iterator->next();
954
955
                        if (! $iterator->valid()) {
956
                            break;
957 8
                        }
958
                    } else {
959 8
                        break;
960 4
                    }
961
                }
962
963 4
                yield new static($chunk);
964
965 4
                $iterator->next();
966
            }
967
        });
968
    }
969
970
    /**
971
     * Sort through each item with a callback.
972
     *
973
     * @param  callable|null  $callback
974 7
     * @return static
975
     */
976 7
    public function sort(callable $callback = null)
977
    {
978
        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 3
     * @param  int  $options
986
     * @param  bool  $descending
987 3
     * @return static
988 2
     */
989
    public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
990
    {
991
        return $this->passthru('sortBy', func_get_args());
992 1
    }
993
994 1
    /**
995 1
     * Sort the collection in descending order using the given callback.
996
     *
997 1
     * @param  callable|string  $callback
998 1
     * @param  int  $options
999
     * @return static
1000 1
     */
1001 1
    public function sortByDesc($callback, $options = SORT_REGULAR)
1002
    {
1003 1
        return $this->passthru('sortByDesc', func_get_args());
1004 1
    }
1005
1006
    /**
1007 1
     * Sort the collection keys.
1008
     *
1009
     * @param  int  $options
1010
     * @param  bool  $descending
1011 1
     * @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 2
    public function sortKeysDesc($options = SORT_REGULAR)
1025
    {
1026 2
        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 1
    public function take($limit)
1036
    {
1037 1
        if ($limit < 0) {
1038
            return $this->passthru('take', func_get_args());
1039
        }
1040
1041
        return new static(function () use ($limit) {
1042
            $iterator = $this->getIterator();
1043
1044
            while ($limit--) {
1045
                if (! $iterator->valid()) {
1046
                    break;
1047
                }
1048 4
1049
                yield $iterator->key() => $iterator->current();
1050 4
1051
                if ($limit) {
1052
                    $iterator->next();
1053
                }
1054
            }
1055
        });
1056
    }
1057
1058
    /**
1059
     * Pass each item in the collection to the given callback, lazily.
1060 1
     *
1061
     * @param  callable  $callback
1062 1
     * @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 1
        });
1073
    }
1074 1
1075
    /**
1076
     * Reset the keys on the underlying array.
1077
     *
1078
     * @return static
1079
     */
1080
    public function values()
1081
    {
1082
        return new static(function () {
1083 1
            foreach ($this as $item) {
1084
                yield $item;
1085 1
            }
1086
        });
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 5
     *
1095
     * @param  mixed ...$items
1096 5
     * @return static
1097 1
     */
1098
    public function zip($items)
1099
    {
1100
        $iterables = func_get_args();
1101 4
1102
        return new static(function () use ($iterables) {
1103 4
            $iterators = Collection::make($iterables)->map(function ($iterable) {
1104 4
                return $this->makeIterator($iterable);
1105 1
            })->prepend($this->getIterator());
1106
1107
            while ($iterators->contains->valid()) {
1108 4
                yield new static($iterators->map->current());
1109
1110 4
                $iterators->each->next();
1111 3
            }
1112
        });
1113
    }
1114 4
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
    public function pad($size, $value)
1123
    {
1124
        if ($size < 0) {
1125
            return $this->passthru('pad', func_get_args());
1126
        }
1127
1128
        return new static(function () use ($size, $value) {
1129
            $yielded = 0;
1130
1131
            foreach ($this as $index => $item) {
1132
                yield $index => $item;
1133
1134
                $yielded++;
1135
            }
1136
1137
            while ($yielded++ < $size) {
1138
                yield $value;
1139 47
            }
1140
        });
1141
    }
1142 47
1143 47
    /**
1144
     * Get the values iterator.
1145 47
     *
1146
     * @return \Traversable
1147
     */
1148
    public function getIterator()
1149
    {
1150
        return $this->makeIterator($this->source);
1151
    }
1152
1153
    /**
1154
     * Count the number of items in the collection.
1155
     *
1156
     * @return int
1157 1
     */
1158
    public function count()
1159 1
    {
1160
        if (is_array($this->source)) {
1161
            return count($this->source);
1162
        }
1163 1
1164 1
        return iterator_count($this->getIterator());
1165
    }
1166 1
1167 1
    /**
1168
     * Make an iterator from the given source.
1169 1
     *
1170
     * @param  mixed  $source
1171 1
     * @return \Traversable
1172
     */
1173
    protected function makeIterator($source)
1174
    {
1175
        if ($source instanceof IteratorAggregate) {
1176
            return $source->getIterator();
1177
        }
1178
1179
        if (is_array($source)) {
1180
            return new ArrayIterator($source);
1181 1
        }
1182
1183 1
        return $source();
1184 1
    }
1185
1186
    /**
1187
     * Explode the "value" and "key" arguments passed to "pluck".
1188 1
     *
1189
     * @param  string|array  $value
1190 1
     * @param  string|array|null  $key
1191 1
     * @return array
1192
     */
1193 1
    protected function explodePluckParameters($value, $key)
1194
    {
1195
        $value = is_string($value) ? explode('.', $value) : $value;
1196 1
1197 1
        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);
1198
1199 1
        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 200
     * @return static
1208
     */
1209 200
    protected function passthru($method, array $params)
1210
    {
1211
        return new static(function () use ($method, $params) {
1212
            yield from $this->collect()->$method(...$params);
1213
        });
1214
    }
1215
}
1216