• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

voku / Arrayy / 24327721426

13 Apr 2026 05:45AM UTC coverage: 89.336% (-0.02%) from 89.36%
24327721426

Pull #155

github

web-flow
Merge cbaf5472b into b6ddb08f8
Pull Request #155: Tighten PHPStan ignore handling and replace broad suppressions with targeted fixes

12 of 15 new or added lines in 4 files covered. (80.0%)

87 existing lines in 2 files now uncovered.

2488 of 2785 relevant lines covered (89.34%)

100.69 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.61
/src/Arrayy.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Arrayy;
6

7
use Arrayy\TypeCheck\TypeCheckArray;
8
use Arrayy\TypeCheck\TypeCheckInterface;
9
use Arrayy\TypeCheck\TypeCheckPhpDoc;
10

11
/**
12
 * Arrayy - Methods to manage arrays.
13
 *
14
 * ## πŸ‡·πŸ‡Ί Русским Π³Ρ€Π°ΠΆΠ΄Π°Π½Π°ΠΌ
15
 * Π’ Π£ΠΊΡ€Π°ΠΈΠ½Π΅ сСйчас ΠΈΠ΄Π΅Ρ‚ Π²ΠΎΠΉΠ½Π°. Π‘ΠΈΠ»Π°ΠΌΠΈ Π Π€ наносятся ΡƒΠ΄Π°Ρ€Ρ‹ ΠΏΠΎ граТданской инфраструктурС Π² [Π₯Π°Ρ€ΡŒΠΊΠΎΠ²Π΅][1], [КиСвС][2], [Π§Π΅Ρ€Π½ΠΈΠ³ΠΎΠ²Π΅][3], [Π‘ΡƒΠΌΠ°Ρ…][4], [Π˜Ρ€ΠΏΠ΅Π½Π΅][5] ΠΈ дСсятках Π΄Ρ€ΡƒΠ³ΠΈΡ… Π³ΠΎΡ€ΠΎΠ΄ΠΎΠ². Π“ΠΈΠ±Π½ΡƒΡ‚ люди - ΠΈ граТданскоС насСлСниС, ΠΈ Π²ΠΎΠ΅Π½Π½Ρ‹Π΅, Π² Ρ‚ΠΎΠΌ числС российскиС ΠΏΡ€ΠΈΠ·Ρ‹Π²Π½ΠΈΠΊΠΈ, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… бросили Π²ΠΎΠ΅Π²Π°Ρ‚ΡŒ. Π§Ρ‚ΠΎΠ±Ρ‹ Π»ΠΈΡˆΠΈΡ‚ΡŒ собствСнный Π½Π°Ρ€ΠΎΠ΄ доступа ΠΊ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΠΈ, ΠΏΡ€Π°Π²ΠΈΡ‚Π΅Π»ΡŒΡΡ‚Π²ΠΎ Π Π€ Π·Π°ΠΏΡ€Π΅Ρ‚ΠΈΠ»ΠΎ Π½Π°Π·Ρ‹Π²Π°Ρ‚ΡŒ Π²ΠΎΠΉΠ½Ρƒ Π²ΠΎΠΉΠ½ΠΎΠΉ, Π·Π°ΠΊΡ€Ρ‹Π»ΠΎ нСзависимыС БМИ ΠΈ ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π΅Ρ‚ сСйчас ряд диктаторских Π·Π°ΠΊΠΎΠ½ΠΎΠ². Π­Ρ‚ΠΈ Π·Π°ΠΊΠΎΠ½Ρ‹ ΠΏΡ€ΠΈΠ·Π²Π°Π½Ρ‹ Π·Π°Ρ‚ΠΊΠ½ΡƒΡ‚ΡŒ Ρ€ΠΎΡ‚ всСм, ΠΊΡ‚ΠΎ ΠΏΡ€ΠΎΡ‚ΠΈΠ² Π²ΠΎΠΉΠ½Ρ‹. Π—Π° ΠΎΠ±Ρ‹Ρ‡Π½Ρ‹ΠΉ ΠΏΡ€ΠΈΠ·Ρ‹Π² ΠΊ ΠΌΠΈΡ€Ρƒ сСйчас ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΡ‚ΡŒ нСсколько Π»Π΅Ρ‚ Ρ‚ΡŽΡ€ΡŒΠΌΡ‹.
16
 * НС ΠΌΠΎΠ»Ρ‡ΠΈΡ‚Π΅! ΠœΠΎΠ»Ρ‡Π°Π½ΠΈΠ΅ - Π·Π½Π°ΠΊ вашСго согласия с ΠΏΠΎΠ»ΠΈΡ‚ΠΈΠΊΠΎΠΉ российского ΠΏΡ€Π°Π²ΠΈΡ‚Π΅Π»ΡŒΡΡ‚Π²Π°.
17
 *  **Π’Ρ‹ ΠΌΠΎΠΆΠ΅Ρ‚Π΅ ΡΠ΄Π΅Π»Π°Ρ‚ΡŒ Π²Ρ‹Π±ΠΎΡ€ НЕ ΠœΠžΠ›Π§ΠΠ’Π¬.**
18
 * ---
19
 * ## πŸ‡ΊπŸ‡Έ To people of Russia
20
 * There is a war in Ukraine right now. The forces of the Russian Federation are attacking civilian infrastructure in [Kharkiv][1], [Kyiv][2], [Chernihiv][3], [Sumy][4], [Irpin][5] and dozens of other cities. People are dying – both civilians and military servicemen, including Russian conscripts who were thrown into the fighting. In order to deprive its own people of access to information, the government of the Russian Federation has forbidden calling a war a war, shut down independent media and is passing a number of dictatorial laws. These laws are meant to silence all those who are against war. You can be jailed for multiple years for simply calling for peace.
21
 * Do not be silent! Silence is a sign that you accept the Russian government's policy.
22
 * **You can choose NOT TO BE SILENT.**
23
 * ---
24
 * - [1] https://cloudfront-us-east-2.images.arcpublishing.com/reuters/P7K2MSZDGFMIJPDD7CI2GIROJI.jpg "Kharkiv under attack"
25
 * - [2] https://gdb.voanews.com/01bd0000-0aff-0242-fad0-08d9fc92c5b3_cx0_cy5_cw0_w1023_r1_s.jpg "Kyiv under attack"
26
 * - [3] https://ichef.bbci.co.uk/news/976/cpsprodpb/163DD/production/_123510119_hi074310744.jpg "Chernihiv under attack"
27
 * - [4] https://www.youtube.com/watch?v=8K-bkqKKf2A "Sumy under attack"
28
 * - [5] https://cloudfront-us-east-2.images.arcpublishing.com/reuters/K4MTMLEHTRKGFK3GSKAT4GR3NE.jpg "Irpin under attack"
29
 *
30
 * For the full copyright and license information, please view the LICENSE
31
 * file that was distributed with this source code.
32
 *
33
 * @template TKey of array-key
34
 * @template T
35
 * @extends \ArrayObject<TKey,T>
36
 * @implements \IteratorAggregate<TKey,T>
37
 * @implements \ArrayAccess<TKey,T>
38
 */
39
class Arrayy extends \ArrayObject implements \IteratorAggregate, \ArrayAccess, \Serializable, \JsonSerializable, \Countable
40
{
41
    const ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES = '!!!!Arrayy_Helper_Types_For_All_Properties!!!!';
42

43
    const ARRAYY_HELPER_WALK = '!!!!Arrayy_Helper_Walk!!!!';
44

45
    /**
46
     * @var array
47
     *
48
     * @phpstan-var array<array-key|TKey,T>
49
     */
50
    protected $array = [];
51

52
    /**
53
     * @var \Arrayy\ArrayyRewindableGenerator|null
54
     *
55
     * @phpstan-var \Arrayy\ArrayyRewindableGenerator<TKey,T>|null
56
     */
57
    protected $generator;
58

59
    /**
60
     * @var string
61
     *
62
     * @phpstan-var class-string<\Arrayy\ArrayyIterator<TKey,T>>
63
     */
64
    protected $iteratorClass = ArrayyIterator::class;
65

66
    /**
67
     * @var non-empty-string
68
     */
69
    protected $pathSeparator = '.';
70

71
    /**
72
     * @var bool
73
     */
74
    protected $checkPropertyTypes = false;
75

76
    /**
77
     * @var bool
78
     */
79
    protected $checkForMissingPropertiesInConstructor = false;
80

81
    /**
82
     * @var bool
83
     */
84
    protected $checkPropertiesMismatchInConstructor = false;
85

86
    /**
87
     * @var bool
88
     */
89
    protected $checkPropertiesMismatch = true;
90

91
    /**
92
     * @var array<array-key,TypeCheckInterface>|TypeCheckArray<array-key,TypeCheckInterface>
93
     */
94
    protected $properties = [];
95

96
    /**
97
     * Initializes
98
     *
99
     * @param mixed  $data                         <p>
100
     *                                             Should be an array or a generator, otherwise it will try
101
     *                                             to convert it into an array.
102
     *                                             </p>
103
     * @param string $iteratorClass                optional <p>
104
     *                                             You can overwrite the ArrayyIterator, but mostly you don't
105
     *                                             need this option.
106
     *                                             </p>
107
     * @param bool   $checkPropertiesInConstructor optional <p>
108
     *                                             You need to extend the "Arrayy"-class and you need to set
109
     *                                             the $checkPropertiesMismatchInConstructor class property
110
     *                                             to
111
     *                                             true, otherwise this option didn't not work anyway.
112
     *                                             </p>
113
     *
114
     * @phpstan-param class-string<\Arrayy\ArrayyIterator<TKey,T>> $iteratorClass
115
     */
116
    public function __construct(
117
        $data = [],
118
        string $iteratorClass = ArrayyIterator::class,
119
        bool $checkPropertiesInConstructor = true
120
    ) {
121
        $data = $this->fallbackForArray($data);
3,762 ✔
122

123
        // used only for serialize + unserialize, all other methods are overwritten
124
        /**
125
         * @psalm-suppress InvalidArgument - why?
126
         */
127
        parent::__construct([], 0, $iteratorClass);
3,756 ✔
128

129
        $this->setInitialValuesAndProperties($data, $checkPropertiesInConstructor);
3,756 ✔
130

131
        $this->setIteratorClass($iteratorClass);
3,732 ✔
132
    }
133

134
    /**
135
     * @return void
136
     */
137
    public function __clone()
138
    {
139
        if (!\is_array($this->properties)) {
159 ✔
140
            $this->properties = clone $this->properties;
3 ✔
141
        }
142

143
        if ($this->generator !== null) {
159 ✔
144
            $this->generator = clone $this->generator;
3 ✔
145
        }
146
    }
147

148
    /**
149
     * Call object as function.
150
     *
151
     * @param mixed $key
152
     *
153
     * @return mixed
154
     *
155
     * @phpstan-param TKey $key
156
     * @phpstan-return false|T|array<TKey,T>
157
     */
158
    public function __invoke($key = null)
159
    {
160
        if ($key !== null) {
3 ✔
161
            $this->generatorToArray();
3 ✔
162

163
            return $this->array[$key] ?? false;
3 ✔
164
        }
165

166
        /** @var array<TKey,T> $return */
167
        $return = $this->toArray();
×
168

169
        return $return;
×
170
    }
171

172
    /**
173
     * Whether or not an element exists by key.
174
     *
175
     * @param mixed $key
176
     *
177
     * @return bool
178
     *              <p>True is the key/index exists, otherwise false.</p>
179
     *
180
     * @phpstan-param TKey $key
181
     */
182
    public function __isset($key): bool
183
    {
184
        return $this->offsetExists($key);
3 ✔
185
    }
186

187
    /**
188
     * Assigns a value to the specified element.
189
     *
190
     * @param mixed $key
191
     * @param mixed $value
192
     *
193
     * @return void
194
     *
195
     * @phpstan-param TKey $key
196
     * @phpstan-param T $value
197
     */
198
    public function __set($key, $value)
199
    {
200
        $this->internalSet($key, $value);
9 ✔
201
    }
202

203
    /**
204
     * magic to string
205
     *
206
     * @return string
207
     */
208
    public function __toString(): string
209
    {
210
        return $this->toString();
45 ✔
211
    }
212

213
    /**
214
     * Unset element by key.
215
     *
216
     * @param mixed $key
217
     *
218
     * @phpstan-param TKey $key
219
     */
220
    public function __unset($key)
221
    {
222
        $this->internalRemove($key);
×
223
    }
224

225
    /**
226
     * Get a value by key.
227
     *
228
     * @param mixed $key
229
     *
230
     * @return mixed
231
     *               <p>Get a Value from the current array.</p>
232
     *
233
     * @phpstan-param TKey $key
234
     * @phpstan-return null|self<array-key,T>|T
235
     */
236
    public function &__get($key)
237
    {
238
        $return = $this->get($key, null, null, true);
438 ✔
239

240
        if (\is_array($return) === true) {
438 ✔
241
            $return = static::create(
×
242
                [],
×
243
                $this->iteratorClass,
×
244
                false
×
245
            )->createByReference($return);
×
246
        }
247

248
        return $return;
438 ✔
249
    }
250

251
    /**
252
     * Add new values (optional using dot-notation).
253
     *
254
     * @param mixed           $value
255
     * @param int|string|null $key
256
     *
257
     * @return static
258
     *                <p>(Immutable) Return this Arrayy object, with the appended values.</p>
259
     *
260
     * @phpstan-param T $value
261
     * @phpstan-param TKey $key
262
     * @phpstan-return static<TKey,T>
263
     *
264
     * @psalm-mutation-free
265
     */
266
    public function add($value, $key = null)
267
    {
268
        if ($key !== null) {
42 ✔
269
            $get = $this->get($key);
15 ✔
270
            if ($get !== null) {
15 ✔
271
                $value = \array_merge_recursive(
3 ✔
272
                    !$get instanceof self ? [$get] : $get->getArray(),
3 ✔
273
                    !\is_array($value) ? [$value] : $value
3 ✔
274
                );
3 ✔
275
            }
276

277
            $this->internalSet($key, $value);
15 ✔
278

279
            return $this;
12 ✔
280
        }
281

282
        return $this->append($value);
27 ✔
283
    }
284

285
    /**
286
     * Append a (key) + value to the current array.
287
     *
288
     * EXAMPLE: <code>
289
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->append('foo'); // Arrayy['fΓ²Γ΄' => 'bΓ Ε™', 0 => 'foo']
290
     * </code>
291
     *
292
     * @param mixed $value
293
     * @param mixed $key
294
     *
295
     * @return $this
296
     *               <p>(Mutable) Return this Arrayy object, with the appended values.</p>
297
     *
298
     * @phpstan-param T $value
299
     * @phpstan-param TKey|null $key
300
     * @phpstan-return static<TKey,T>
301
     */
302
    #[\ReturnTypeWillChange]
303
    public function append($value, $key = null): self
304
    {
305
        $this->generatorToArray();
63 ✔
306

307
        if ($this->properties !== []) {
63 ✔
308
            $this->checkType($key, $value);
21 ✔
309
        }
310

311
        if ($key !== null) {
60 ✔
312
            if (
313
                isset($this->array[$key])
6 ✔
314
                &&
315
                \is_array($this->array[$key])
6 ✔
316
            ) {
NEW
317
                $this->array[$key][] = $value; // @phpstan-ignore-line
×
318
            } else {
319
                $this->array[$key] = $value;
6 ✔
320
            }
321
        } else {
322
            $this->array[] = $value;
54 ✔
323
        }
324

325
        return $this;
60 ✔
326
    }
327

328
    /**
329
     * Append a (key) + value to the current array.
330
     *
331
     * EXAMPLE: <code>
332
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->appendImmutable('foo')->getArray(); // ['fΓ²Γ΄' => 'bΓ Ε™', 0 => 'foo']
333
     * </code>
334
     *
335
     * @param mixed $value
336
     * @param mixed $key
337
     *
338
     * @return $this
339
     *               <p>(Immutable) Return this Arrayy object, with the appended values.</p>
340
     *
341
     * @phpstan-param T $value
342
     * @phpstan-param TKey $key
343
     * @phpstan-return static<TKey,T>
344
     * @psalm-mutation-free
345
     */
346
    public function appendImmutable($value, $key = null): self
347
    {
348
        /**
349
         * @phpstan-return \Generator<TKey,T> $generator
350
         */
351
        $generator = function () use ($key, $value): \Generator {
3 ✔
352
            if ($this->properties !== []) {
3 ✔
353
                $this->checkType($key, $value);
×
354
            }
355

356
            foreach ($this->getGenerator() as $keyOld => $itemOld) {
3 ✔
357
                yield $keyOld => $itemOld;
3 ✔
358
            }
359

360
            if ($key !== null) {
3 ✔
361
                yield $key => $value;
×
362
            } else {
363
                yield $value;
3 ✔
364
            }
365
        };
3 ✔
366

367
        return static::create(
3 ✔
368
            $generator,
3 ✔
369
            $this->iteratorClass,
3 ✔
370
            false
3 ✔
371
        );
3 ✔
372
    }
373

374
    /**
375
     * Sort the entries by value.
376
     *
377
     * @param int $sort_flags [optional] <p>
378
     *                        You may modify the behavior of the sort using the optional
379
     *                        parameter sort_flags, for details
380
     *                        see sort.
381
     *                        </p>
382
     *
383
     * @return $this
384
     *               <p>(Mutable) Return this Arrayy object.</p>
385
     *
386
     * @phpstan-return static<TKey,T>
387
     */
388
    #[\ReturnTypeWillChange]
389
    public function asort(int $sort_flags = 0): self
390
    {
391
        $this->generatorToArray();
12 ✔
392

393
        \asort($this->array, $sort_flags);
12 ✔
394

395
        return $this;
12 ✔
396
    }
397

398
    /**
399
     * Sort the entries by value.
400
     *
401
     * @param int $sort_flags [optional] <p>
402
     *                        You may modify the behavior of the sort using the optional
403
     *                        parameter sort_flags, for details
404
     *                        see sort.
405
     *                        </p>
406
     *
407
     * @return $this
408
     *               <p>(Immutable) Return this Arrayy object.</p>
409
     *
410
     * @phpstan-return static<TKey,T>
411
     * @psalm-mutation-free
412
     */
413
    public function asortImmutable(int $sort_flags = 0): self
414
    {
415
        $that = clone $this;
12 ✔
416

417
        /**
418
         * @psalm-suppress ImpureMethodCall - object is already cloned
419
         */
420
        $that->asort($sort_flags);
12 ✔
421

422
        return $that;
12 ✔
423
    }
424

425
    /**
426
     * Counts all elements in an array, or something in an object.
427
     *
428
     * EXAMPLE: <code>
429
     * a([-9, -8, -7, 1.32])->count(); // 4
430
     * </code>
431
     *
432
     * <p>
433
     * For objects, if you have SPL installed, you can hook into count() by implementing interface {@see Countable}.
434
     * The interface has exactly one method, {@see Countable::count()}, which returns the return value for the count()
435
     * function. Please see the {@see Array} section of the manual for a detailed explanation of how arrays are
436
     * implemented and used in PHP.
437
     * </p>
438
     *
439
     * @see http://php.net/manual/en/function.count.php
440
     *
441
     * @param int $mode [optional] If the optional mode parameter is set to
442
     *                  COUNT_RECURSIVE (or 1), count
443
     *                  will recursively count the array. This is particularly useful for
444
     *                  counting all the elements of a multidimensional array. count does not detect infinite recursion.
445
     *
446
     * @return int
447
     *             <p>
448
     *             The number of elements in var, which is
449
     *             typically an array, since anything else will have one
450
     *             element.
451
     *             </p>
452
     *             <p>
453
     *             If var is not an array or an object with
454
     *             implemented Countable interface,
455
     *             1 will be returned.
456
     *             There is one exception, if var is &null;,
457
     *             0 will be returned.
458
     *             </p>
459
     *             <p>
460
     *             Caution: count may return 0 for a variable that isn't set,
461
     *             but it may also return 0 for a variable that has been initialized with an
462
     *             empty array. Use isset to test if a variable is set.
463
     *             </p>
464
     * @psalm-mutation-free
465
     */
466
    public function count(int $mode = \COUNT_NORMAL): int
467
    {
468
        if (
469
            $this->generator
444 ✔
470
            &&
471
            $mode === \COUNT_NORMAL
444 ✔
472
        ) {
473
            return \iterator_count($this->generator);
12 ✔
474
        }
475

476
        return \count($this->toArray(), $mode);
432 ✔
477
    }
478

479
    /**
480
     * Exchange the array for another one.
481
     *
482
     * @param array|mixed|static $data
483
     *
484
     * 1. use the current array, if it's a array
485
     * 2. fallback to empty array, if there is nothing
486
     * 3. call "getArray()" on object, if there is a "Arrayy"-object
487
     * 4. call "createFromObject()" on object, if there is a "\Traversable"-object
488
     * 5. call "__toArray()" on object, if the method exists
489
     * 6. cast a string or object with "__toString()" into an array
490
     * 7. throw a "InvalidArgumentException"-Exception
491
     *
492
     * @return array
493
     *
494
     * @phpstan-param  T|array<TKey,T>|self<TKey,T> $data
495
     * @phpstan-return array<TKey,T>
496
     */
497
    public function exchangeArray($data): array
498
    {
499
        /** @phpstan-var array<TKey,T> array */
500
        $array = $this->fallbackForArray($data);
3 ✔
501

502
        $this->array = $array;
3 ✔
503
        $this->generator = null;
3 ✔
504

505
        return $this->array;
3 ✔
506
    }
507

508
    /**
509
     * Creates a copy of the ArrayyObject.
510
     *
511
     * @return array
512
     *
513
     * @phpstan-return array<int|string|TKey,T>
514
     */
515
    public function getArrayCopy(): array
516
    {
517
        $this->generatorToArray();
18 ✔
518

519
        return $this->array;
18 ✔
520
    }
521

522
    /**
523
     * Returns a new iterator, thus implementing the \Iterator interface.
524
     *
525
     * EXAMPLE: <code>
526
     * a(['foo', 'bar'])->getIterator(); // ArrayyIterator['foo', 'bar']
527
     * </code>
528
     *
529
     * @return \Iterator<mixed, mixed>
530
     *                          <p>An iterator for the values in the array.</p>
531
     * @phpstan-return \Iterator<TKey, T>
532
     */
533
    public function getIterator(): \Iterator
534
    {
535
        if ($this->generator instanceof ArrayyRewindableGenerator) {
102 ✔
536
            $generator = clone $this->generator;
6 ✔
537

538
            /** @phpstan-var \Arrayy\ArrayyRewindableGenerator<TKey,T> */
539
            $generatorTmp = new ArrayyRewindableExtendedGenerator(
6 ✔
540
                static function () use ($generator): \Generator {
6 ✔
541
                    yield from $generator;
6 ✔
542
                },
6 ✔
543
                null,
6 ✔
544
                static::class
6 ✔
545
            );
6 ✔
546

547
            $this->generator = $generatorTmp;
6 ✔
548

549
            return $this->generator;
6 ✔
550
        }
551

552
        $iterator = $this->getIteratorClass();
99 ✔
553

554
        if ($iterator === ArrayyIterator::class) {
99 ✔
555
            return new $iterator($this->toArray(), 0, static::class);
99 ✔
556
        }
557

558
        $return = new $iterator($this->toArray());
×
559
        \assert($return instanceof \Iterator);
560

561
        return $return;
×
562
    }
563

564
    /**
565
     * Gets the iterator classname for the ArrayObject.
566
     *
567
     * @return string
568
     *
569
     * @phpstan-return class-string
570
     */
571
    public function getIteratorClass(): string
572
    {
573
        return $this->iteratorClass;
99 ✔
574
    }
575

576
    /**
577
     * Sort the entries by key.
578
     *
579
     * @param int $sort_flags [optional] <p>
580
     *                        You may modify the behavior of the sort using the optional
581
     *                        parameter sort_flags, for details
582
     *                        see sort.
583
     *                        </p>
584
     *
585
     * @return $this
586
     *               <p>(Mutable) Return this Arrayy object.</p>
587
     *
588
     * @phpstan-return static<TKey,T>
589
     */
590
    #[\ReturnTypeWillChange]
591
    public function ksort(int $sort_flags = 0): self
592
    {
593
        $this->generatorToArray();
12 ✔
594

595
        \ksort($this->array, $sort_flags);
12 ✔
596

597
        return $this;
12 ✔
598
    }
599

600
    /**
601
     * Sort the entries by key.
602
     *
603
     * @param int $sort_flags [optional] <p>
604
     *                        You may modify the behavior of the sort using the optional
605
     *                        parameter sort_flags, for details
606
     *                        see sort.
607
     *                        </p>
608
     *
609
     * @return $this
610
     *               <p>(Immutable) Return this Arrayy object.</p>
611
     *
612
     * @phpstan-return static<TKey,T>
613
     */
614
    public function ksortImmutable(int $sort_flags = 0): self
615
    {
616
        $that = clone $this;
12 ✔
617

618
        /**
619
         * @psalm-suppress ImpureMethodCall - object is already cloned
620
         */
621
        $that->ksort($sort_flags);
12 ✔
622

623
        return $that;
12 ✔
624
    }
625

626
    /**
627
     * Sort an array using a case insensitive "natural order" algorithm.
628
     *
629
     * @return $this
630
     *               <p>(Mutable) Return this Arrayy object.</p>
631
     *
632
     * @phpstan-return static<TKey,T>
633
     */
634
    #[\ReturnTypeWillChange]
635
    public function natcasesort(): self
636
    {
637
        $this->generatorToArray();
24 ✔
638

639
        \natcasesort($this->array);
24 ✔
640

641
        return $this;
24 ✔
642
    }
643

644
    /**
645
     * Sort an array using a case insensitive "natural order" algorithm.
646
     *
647
     * @return $this
648
     *               <p>(Immutable) Return this Arrayy object.</p>
649
     *
650
     * @phpstan-return static<TKey,T>
651
     * @psalm-mutation-free
652
     */
653
    public function natcasesortImmutable(): self
654
    {
655
        $that = clone $this;
12 ✔
656

657
        /**
658
         * @psalm-suppress ImpureMethodCall - object is already cloned
659
         */
660
        $that->natcasesort();
12 ✔
661

662
        return $that;
12 ✔
663
    }
664

665
    /**
666
     * Sort entries using a "natural order" algorithm.
667
     *
668
     * @return $this
669
     *               <p>(Mutable) Return this Arrayy object.</p>
670
     *
671
     * @phpstan-return static<TKey,T>
672
     */
673
    #[\ReturnTypeWillChange]
674
    public function natsort(): self
675
    {
676
        $this->generatorToArray();
30 ✔
677

678
        \natsort($this->array);
30 ✔
679

680
        return $this;
30 ✔
681
    }
682

683
    /**
684
     * Sort entries using a "natural order" algorithm.
685
     *
686
     * @return $this
687
     *               <p>(Immutable) Return this Arrayy object.</p>
688
     *
689
     * @phpstan-return static<TKey,T>
690
     * @psalm-mutation-free
691
     */
692
    public function natsortImmutable(): self
693
    {
694
        $that = clone $this;
12 ✔
695

696
        /**
697
         * @psalm-suppress ImpureMethodCall - object is already cloned
698
         */
699
        $that->natsort();
12 ✔
700

701
        return $that;
12 ✔
702
    }
703

704
    /**
705
     * Whether or not an offset exists.
706
     *
707
     * @param bool|int|string $offset
708
     *
709
     * @return bool
710
     *
711
     * @psalm-mutation-free
712
     */
713
    #[\ReturnTypeWillChange]
714
    public function offsetExists($offset): bool
715
    {
716
        // php cast "bool"-index into "int"-index
717
        if ((bool) $offset === $offset) {
528 ✔
718
            $offset = (int) $offset;
3 ✔
719
        }
720
        \assert(\is_int($offset) || \is_string($offset));
721

722
        $offsetExists = $this->keyExists($offset);
528 ✔
723
        if ($offsetExists === true) {
528 ✔
724
            return true;
465 ✔
725
        }
726

727
        /**
728
         * https://github.com/vimeo/psalm/issues/2536
729
         *
730
         * @psalm-suppress PossiblyInvalidArgument
731
         * @psalm-suppress InvalidScalarArgument
732
         */
733
        if (
734
            $this->pathSeparator
408 ✔
735
            &&
736
            (string) $offset === $offset
408 ✔
737
            &&
738
            \strpos($offset, $this->pathSeparator) !== false
408 ✔
739
        ) {
740
            $explodedPath = \explode($this->pathSeparator, (string) $offset);
12 ✔
741
            if ($explodedPath !== false) {
12 ✔
742
                /** @var string $lastOffset - helper for phpstan */
743
                $lastOffset = \array_pop($explodedPath);
12 ✔
744
                $containerPath = \implode($this->pathSeparator, $explodedPath);
12 ✔
745

746
                /**
747
                 * @psalm-suppress MissingClosureReturnType
748
                 * @psalm-suppress MissingClosureParamType
749
                 */
750
                $this->callAtPath(
12 ✔
751
                    $containerPath,
12 ✔
752
                    static function ($container) use ($lastOffset, &$offsetExists) {
12 ✔
753
                        $offsetExists = \array_key_exists($lastOffset, $container);
12 ✔
754
                    }
12 ✔
755
                );
12 ✔
756
            }
757
        }
758

759
        return $offsetExists;
408 ✔
760
    }
761

762
    /**
763
     * Returns the value at specified offset.
764
     *
765
     * @param int|string $offset
766
     *
767
     * @return mixed
768
     *               <p>Will return null if the offset did not exists.</p>
769
     *
770
     * @phpstan-param TKey $offset
771
     */
772
    #[\ReturnTypeWillChange]
773
    public function &offsetGet($offset)
774
    {
775
        // init
776
        $value = null;
435 ✔
777

778
        if ($this->offsetExists($offset)) {
435 ✔
779
            $value = &$this->__get($offset);
429 ✔
780
        }
781

782
        return $value;
435 ✔
783
    }
784

785
    /**
786
     * Assigns a value to the specified offset + check the type.
787
     *
788
     * @param int|string|null $offset
789
     * @param mixed           $value
790
     *
791
     * @return void
792
     */
793
    #[\ReturnTypeWillChange]
794
    public function offsetSet($offset, $value)
795
    {
796
        $this->generatorToArray();
90 ✔
797

798
        if ($offset === null) {
90 ✔
799
            if ($this->properties !== []) {
24 ✔
800
                $this->checkType(null, $value);
9 ✔
801
            }
802

803
            $this->array[] = $value;
21 ✔
804
        } else {
805
            $this->internalSet(
69 ✔
806
                $offset,
69 ✔
807
                $value,
69 ✔
808
                true
69 ✔
809
            );
69 ✔
810
        }
811
    }
812

813
    /**
814
     * Unset an offset.
815
     *
816
     * @param int|string $offset
817
     *
818
     * @return void
819
     *              <p>(Mutable) Return nothing.</p>
820
     */
821
    #[\ReturnTypeWillChange]
822
    public function offsetUnset($offset)
823
    {
824
        $this->generatorToArray();
78 ✔
825

826
        if ($this->array === []) {
78 ✔
827
            return;
18 ✔
828
        }
829

830
        if ($this->keyExists($offset)) {
63 ✔
831
            unset($this->array[$offset]);
42 ✔
832

833
            return;
42 ✔
834
        }
835

836
        /**
837
         * https://github.com/vimeo/psalm/issues/2536
838
         *
839
         * @psalm-suppress PossiblyInvalidArgument
840
         * @psalm-suppress InvalidScalarArgument
841
         */
842
        if (
843
            $this->pathSeparator
30 ✔
844
            &&
845
            (string) $offset === $offset
30 ✔
846
            &&
847
            \strpos($offset, $this->pathSeparator) !== false
30 ✔
848
        ) {
849
            $path = \explode($this->pathSeparator, (string) $offset);
21 ✔
850

851
            if ($path !== false) {
21 ✔
852
                $pathToUnset = \array_pop($path);
21 ✔
853

854
                /**
855
                 * @psalm-suppress MissingClosureReturnType
856
                 * @psalm-suppress MissingClosureParamType
857
                 */
858
                $this->callAtPath(
21 ✔
859
                    \implode($this->pathSeparator, $path),
21 ✔
860
                    static function (&$offset) use ($pathToUnset) {
21 ✔
861
                        if (\is_array($offset)) {
18 ✔
862
                            unset($offset[$pathToUnset]);
15 ✔
863
                        } else {
864
                            $offset = null;
3 ✔
865
                        }
866
                    }
21 ✔
867
                );
21 ✔
868
            }
869
        }
870

871
        unset($this->array[$offset]);
30 ✔
872
    }
873

874
    /**
875
     * Serialize the current "Arrayy"-object.
876
     *
877
     * EXAMPLE: <code>
878
     * a([1, 4, 7])->serialize();
879
     * </code>
880
     *
881
     * @return string
882
     */
883
    public function serialize(): string
884
    {
885
        $this->generatorToArray();
3 ✔
886

887
        if (\PHP_VERSION_ID < 70400) {
3 ✔
888
            return parent::serialize();
×
889
        }
890

891
        return \serialize($this);
3 ✔
892
    }
893

894
    /**
895
     * Sets the iterator classname for the current "Arrayy"-object.
896
     *
897
     * @param string $iteratorClass
898
     *
899
     * @throws \InvalidArgumentException
900
     *
901
     * @return void
902
     *
903
     * @phpstan-param class-string<\Arrayy\ArrayyIterator<TKey,T>> $iteratorClass
904
     */
905
    #[\ReturnTypeWillChange]
906
    public function setIteratorClass($iteratorClass)
907
    {
908
        if (\class_exists($iteratorClass)) {
3,732 ✔
909
            $this->iteratorClass = $iteratorClass;
3,732 ✔
910

911
            return;
3,732 ✔
912
        }
913

914
        if (\strpos($iteratorClass, '\\') === 0) {
×
915
            /** @var class-string<\Arrayy\ArrayyIterator<TKey,T>> $iteratorClass */
916
            $iteratorClass = '\\' . $iteratorClass;
×
917
            if (\class_exists($iteratorClass)) {
×
918
                /**
919
                 * @psalm-suppress PropertyTypeCoercion
920
                 */
921
                $this->iteratorClass = $iteratorClass;
×
922

923
                return;
×
924
            }
925
        }
926

927
        throw new \InvalidArgumentException('The iterator class does not exist: ' . $iteratorClass);
×
928
    }
929

930
    /**
931
     * Sort the entries with a user-defined comparison function and maintain key association.
932
     *
933
     * @param callable $callable
934
     *
935
     *@throws \InvalidArgumentException
936
     *
937
     * @return $this
938
     *               <p>(Mutable) Return this Arrayy object.</p>
939
     *
940
     * @phpstan-param  callable(T,T):int $callable
941
     * @phpstan-return static<TKey,T>
942
     */
943
    #[\ReturnTypeWillChange]
944
    public function uasort($callable): self
945
    {
946
        if (!\is_callable($callable)) {
24 ✔
947
            throw new \InvalidArgumentException('Passed function must be callable');
×
948
        }
949

950
        $this->generatorToArray();
24 ✔
951

952
        \uasort($this->array, $callable);
24 ✔
953

954
        return $this;
24 ✔
955
    }
956

957
    /**
958
     * Sort the entries with a user-defined comparison function and maintain key association.
959
     *
960
     * @param callable $callable
961
     *
962
     *@throws \InvalidArgumentException
963
     *
964
     * @return $this
965
     *               <p>(Immutable) Return this Arrayy object.</p>
966
     *
967
     * @phpstan-param  callable(T,T):int $callable
968
     * @phpstan-return static<TKey,T>
969
     * @psalm-mutation-free
970
     */
971
    public function uasortImmutable($callable): self
972
    {
973
        $that = clone $this;
12 ✔
974

975
        /**
976
         * @psalm-suppress ImpureMethodCall - object is already cloned
977
         */
978
        $that->uasort($callable);
12 ✔
979

980
        return $that;
12 ✔
981
    }
982

983
    /**
984
     * Sort the entries by keys using a user-defined comparison function.
985
     *
986
     * @param callable $callable
987
     *
988
     * @throws \InvalidArgumentException
989
     *
990
     * @return static
991
     *                <p>(Mutable) Return this Arrayy object.</p>
992
     *
993
     * @phpstan-param  callable(TKey,TKey):int $callable
994
     * @phpstan-return static<TKey,T>
995
     */
996
    #[\ReturnTypeWillChange]
997
    public function uksort($callable): self
998
    {
999
        return $this->customSortKeys($callable);
15 ✔
1000
    }
1001

1002
    /**
1003
     * Sort the entries by keys using a user-defined comparison function.
1004
     *
1005
     * @param callable $callable
1006
     *
1007
     * @throws \InvalidArgumentException
1008
     *
1009
     * @return static
1010
     *                <p>(Immutable) Return this Arrayy object.</p>
1011
     *
1012
     * @phpstan-param  callable(TKey,TKey):int $callable
1013
     * @phpstan-return static<TKey,T>
1014
     * @psalm-mutation-free
1015
     */
1016
    public function uksortImmutable($callable): self
1017
    {
1018
        return $this->customSortKeysImmutable($callable);
3 ✔
1019
    }
1020

1021
    /**
1022
     * Unserialize an string and return the instance of the "Arrayy"-class.
1023
     *
1024
     * EXAMPLE: <code>
1025
     * $serialized = a([1, 4, 7])->serialize();
1026
     * a()->unserialize($serialized);
1027
     * </code>
1028
     *
1029
     * @param string $string
1030
     *
1031
     * @return $this
1032
     *
1033
     * @phpstan-return static<TKey,T>
1034
     */
1035
    #[\ReturnTypeWillChange]
1036
    public function unserialize($string): self
1037
    {
1038
        if (\PHP_VERSION_ID < 70400) {
3 ✔
1039
            parent::unserialize($string);
×
1040

1041
            return $this;
×
1042
        }
1043

1044
        return \unserialize($string, ['allowed_classes' => [__CLASS__, TypeCheckPhpDoc::class]]);
3 ✔
1045
    }
1046

1047
    /**
1048
     * Append a (key) + values to the current array.
1049
     *
1050
     * EXAMPLE: <code>
1051
     * a(['fΓ²Γ΄' => ['bΓ Ε™']])->appendArrayValues(['foo1', 'foo2'], 'fΓ²Γ΄'); // Arrayy['fΓ²Γ΄' => ['bΓ Ε™', 'foo1', 'foo2']]
1052
     * </code>
1053
     *
1054
     * @param array $values
1055
     * @param mixed $key
1056
     *
1057
     * @return $this
1058
     *               <p>(Mutable) Return this Arrayy object, with the appended values.</p>
1059
     *
1060
     * @phpstan-param  array<T> $values
1061
     * @phpstan-param  TKey|null $key
1062
     * @phpstan-return static<TKey,T>
1063
     */
1064
    public function appendArrayValues(array $values, $key = null)
1065
    {
1066
        $this->generatorToArray();
3 ✔
1067

1068
        if ($key !== null) {
3 ✔
1069
            if (
1070
                isset($this->array[$key])
3 ✔
1071
                &&
1072
                \is_array($this->array[$key])
3 ✔
1073
            ) {
1074
                foreach ($values as $value) {
3 ✔
1075
                    $this->array[$key][] = $value;
3 ✔
1076
                }
1077
            } else {
1078
                foreach ($values as $value) {
3 ✔
1079
                    $this->array[$key] = $value;
×
1080
                }
1081
            }
1082
        } else {
1083
            foreach ($values as $value) {
×
1084
                $this->array[] = $value;
×
1085
            }
1086
        }
1087

1088
        return $this;
3 ✔
1089
    }
1090

1091
    /**
1092
     * Add a suffix to each key.
1093
     *
1094
     * @param int|string $prefix
1095
     *
1096
     * @return static
1097
     *                <p>(Immutable) Return an Arrayy object, with the prefixed keys.</p>
1098
     *
1099
     * @phpstan-return static<TKey,T>
1100
     * @psalm-mutation-free
1101
     */
1102
    public function appendToEachKey($prefix): self
1103
    {
1104
        // init
1105
        $result = [];
30 ✔
1106

1107
        foreach ($this->getGenerator() as $key => $item) {
30 ✔
1108
            if ($item instanceof self) {
27 ✔
1109
                $result[$prefix . $key] = $item->appendToEachKey($prefix);
×
1110
            } elseif (\is_array($item)) {
27 ✔
1111
                $result[$prefix . $key] = self::create($item, $this->iteratorClass, false)
×
1112
                    ->appendToEachKey($prefix)
×
1113
                    ->toArray();
×
1114
            } else {
1115
                $result[$prefix . $key] = $item;
27 ✔
1116
            }
1117
        }
1118

1119
        return self::create(
30 ✔
1120
            $result,
30 ✔
1121
            $this->iteratorClass,
30 ✔
1122
            false
30 ✔
1123
        );
30 ✔
1124
    }
1125

1126
    /**
1127
     * Add a prefix to each value.
1128
     *
1129
     * @param float|int|string $prefix
1130
     *
1131
     * @return static
1132
     *                <p>(Immutable) Return an Arrayy object, with the prefixed values.</p>
1133
     *
1134
     * @phpstan-return static<TKey,T>
1135
     * @psalm-mutation-free
1136
     */
1137
    public function appendToEachValue($prefix): self
1138
    {
1139
        // init
1140
        $result = [];
30 ✔
1141

1142
        foreach ($this->getGenerator() as $key => $item) {
30 ✔
1143
            if ($item instanceof self) {
27 ✔
1144
                $result[$key] = $item->appendToEachValue($prefix);
×
1145
            } elseif (\is_array($item)) {
27 ✔
1146
                $result[$key] = self::create($item, $this->iteratorClass, false)->appendToEachValue($prefix)->toArray();
×
1147
            } elseif (\is_object($item) === true) {
27 ✔
1148
                $result[$key] = $item;
3 ✔
1149
            } else {
1150
                $result[$key] = $prefix . $item;
24 ✔
1151
            }
1152
        }
1153

1154
        return self::create($result, $this->iteratorClass, false);
30 ✔
1155
    }
1156

1157
    /**
1158
     * Sort an array in reverse order and maintain index association.
1159
     *
1160
     * @return $this
1161
     *               <p>(Mutable) Return this Arrayy object.</p>
1162
     *
1163
     * @phpstan-return static<TKey,T>
1164
     */
1165
    public function arsort(): self
1166
    {
1167
        $this->generatorToArray();
12 ✔
1168

1169
        \arsort($this->array);
12 ✔
1170

1171
        return $this;
12 ✔
1172
    }
1173

1174
    /**
1175
     * Sort an array in reverse order and maintain index association.
1176
     *
1177
     * @return $this
1178
     *               <p>(Immutable) Return this Arrayy object.</p>
1179
     *
1180
     * @phpstan-return static<TKey,T>
1181
     * @psalm-mutation-free
1182
     */
1183
    public function arsortImmutable(): self
1184
    {
1185
        $that = clone $this;
30 ✔
1186

1187
        $that->generatorToArray();
30 ✔
1188

1189
        \arsort($that->array);
30 ✔
1190

1191
        return $that;
30 ✔
1192
    }
1193

1194
    /**
1195
     * Iterate over the current array and execute a callback for each loop.
1196
     *
1197
     * EXAMPLE: <code>
1198
     * $result = A::create();
1199
     * $closure = function ($value, $key) use ($result) {
1200
     *     $result[$key] = ':' . $value . ':';
1201
     * };
1202
     * a(['foo', 'bar' => 'bis'])->at($closure); // Arrayy[':foo:', 'bar' => ':bis:']
1203
     * </code>
1204
     *
1205
     * @param \Closure $closure
1206
     *
1207
     * @return static
1208
     *                <p>(Immutable)</p>
1209
     *
1210
     * @phpstan-param \Closure(T,TKey):mixed $closure <p>INFO: \Closure result is not used, but void is not supported in PHP 7.0</p>
1211
     * @phpstan-return static<TKey,T>
1212
     * @psalm-mutation-free
1213
     */
1214
    public function at(\Closure $closure): self
1215
    {
1216
        $that = clone $this;
9 ✔
1217

1218
        foreach ($that->getGenerator() as $key => $value) {
9 ✔
1219
            $closure($value, $key);
9 ✔
1220
        }
1221

1222
        return static::create(
9 ✔
1223
            $that->toArray(),
9 ✔
1224
            $this->iteratorClass,
9 ✔
1225
            false
9 ✔
1226
        );
9 ✔
1227
    }
1228

1229
    /**
1230
     * Returns the average value of the current array.
1231
     *
1232
     * EXAMPLE: <code>
1233
     * a([-9, -8, -7, 1.32])->average(2); // -5.67
1234
     * </code>
1235
     *
1236
     * @param int $decimals <p>The number of decimal-numbers to return.</p>
1237
     *
1238
     * @return float|int
1239
     *                   <p>The average value.</p>
1240
     * @psalm-mutation-free
1241
     */
1242
    public function average($decimals = 0)
1243
    {
1244
        $count = \count($this->toArray(), \COUNT_NORMAL);
30 ✔
1245

1246
        if (!$count) {
30 ✔
1247
            return 0;
6 ✔
1248
        }
1249

1250
        if ((int) $decimals !== $decimals) {
24 ✔
1251
            $decimals = 0;
9 ✔
1252
        }
1253

1254
        return \round(\array_sum($this->toArray()) / $count, $decimals);
24 ✔
1255
    }
1256

1257
    /**
1258
     * Changes all keys in an array.
1259
     *
1260
     * @param int $case [optional] <p> Either <strong>CASE_UPPER</strong><br />
1261
     *                  or <strong>CASE_LOWER</strong> (default)</p>
1262
     *
1263
     * @return static
1264
     *                <p>(Immutable)</p>
1265
     *
1266
     * @phpstan-return static<TKey,T>
1267
     * @psalm-mutation-free
1268
     */
1269
    public function changeKeyCase(int $case = \CASE_LOWER): self
1270
    {
1271
        if (
1272
            $case !== \CASE_LOWER
3 ✔
1273
            &&
1274
            $case !== \CASE_UPPER
3 ✔
1275
        ) {
1276
            $case = \CASE_LOWER;
×
1277
        }
1278

1279
        $return = [];
3 ✔
1280
        foreach ($this->getGenerator() as $key => $value) {
3 ✔
1281
            if ($case === \CASE_LOWER) {
3 ✔
1282
                $key = \mb_strtolower((string) $key);
3 ✔
1283
            } else {
1284
                $key = \mb_strtoupper((string) $key);
3 ✔
1285
            }
1286

1287
            $return[$key] = $value;
3 ✔
1288
        }
1289

1290
        return static::create(
3 ✔
1291
            $return,
3 ✔
1292
            $this->iteratorClass,
3 ✔
1293
            false
3 ✔
1294
        );
3 ✔
1295
    }
1296

1297
    /**
1298
     * Change the path separator of the array wrapper.
1299
     *
1300
     * By default, the separator is: "."
1301
     *
1302
     * @param non-empty-string $separator <p>Separator to set.</p>
1303
     *
1304
     * @return $this
1305
     *               <p>(Mutable) Return this Arrayy object.</p>
1306
     *
1307
     * @phpstan-return static<TKey,T>
1308
     */
1309
    public function changeSeparator($separator): self
1310
    {
1311
        $this->pathSeparator = $separator;
33 ✔
1312

1313
        return $this;
33 ✔
1314
    }
1315

1316
    /**
1317
     * Create a chunked version of the current array.
1318
     *
1319
     * EXAMPLE: <code>
1320
     * a([-9, -8, -7, 1.32])->chunk(2); // Arrayy[[-9, -8], [-7, 1.32]]
1321
     * </code>
1322
     *
1323
     * @param int  $size         <p>Size of each chunk.</p>
1324
     * @param bool $preserveKeys <p>Whether array keys are preserved or no.</p>
1325
     *
1326
     * @return static|static[]
1327
     *                <p>(Immutable) A new array of chunks from the original array.</p>
1328
     *
1329
     * @phpstan-return static<int, static<array-key,T>>
1330
     * @psalm-mutation-free
1331
     */
1332
    public function chunk($size, $preserveKeys = false): self
1333
    {
1334
        if ($preserveKeys) {
18 ✔
1335
            $generator = function () use ($size) {
×
1336
                $values = [];
×
1337
                $tmpCounter = 0;
×
1338
                foreach ($this->getGenerator() as $key => $value) {
×
1339
                    ++$tmpCounter;
×
1340

1341
                    $values[$key] = $value;
×
1342
                    if ($tmpCounter === $size) {
×
1343
                        yield $values;
×
1344

1345
                        $values = [];
×
1346
                        $tmpCounter = 0;
×
1347
                    }
1348
                }
1349

1350
                if ($values !== []) {
×
1351
                    yield $values;
×
1352
                }
1353
            };
×
1354
        } else {
1355
            $generator = function () use ($size) {
18 ✔
1356
                $values = [];
18 ✔
1357
                $tmpCounter = 0;
18 ✔
1358
                foreach ($this->getGenerator() as $value) {
18 ✔
1359
                    ++$tmpCounter;
18 ✔
1360

1361
                    $values[] = $value;
18 ✔
1362
                    if ($tmpCounter === $size) {
18 ✔
1363
                        yield $values;
18 ✔
1364

1365
                        $values = [];
18 ✔
1366
                        $tmpCounter = 0;
18 ✔
1367
                    }
1368
                }
1369

1370
                if ($values !== []) {
18 ✔
1371
                    yield $values;
15 ✔
1372
                }
1373
            };
18 ✔
1374
        }
1375

1376
        return static::create(
18 ✔
1377
            $generator,
18 ✔
1378
            $this->iteratorClass,
18 ✔
1379
            false
18 ✔
1380
        );
18 ✔
1381
    }
1382

1383
    /**
1384
     * Clean all falsy values from the current array.
1385
     *
1386
     * EXAMPLE: <code>
1387
     * a([-8 => -9, 1, 2 => false])->clean(); // Arrayy[-8 => -9, 1]
1388
     * </code>
1389
     *
1390
     * @return static
1391
     *                <p>(Immutable)</p>
1392
     *
1393
     * @phpstan-return static<TKey,T>
1394
     * @psalm-mutation-free
1395
     */
1396
    public function clean(): self
1397
    {
1398
        return $this->filter(
24 ✔
1399
            static function ($value) {
24 ✔
1400
                return (bool) $value;
21 ✔
1401
            }
24 ✔
1402
        );
24 ✔
1403
    }
1404

1405
    /**
1406
     * WARNING!!! -> Clear the current full array or a $key of it.
1407
     *
1408
     * EXAMPLE: <code>
1409
     * a([-8 => -9, 1, 2 => false])->clear(); // Arrayy[]
1410
     * </code>
1411
     *
1412
     * @param int|int[]|string|string[]|null $key
1413
     *
1414
     * @return $this
1415
     *               <p>(Mutable) Return this Arrayy object, with an empty array.</p>
1416
     *
1417
     * @phpstan-return static<TKey,T>
1418
     */
1419
    public function clear($key = null): self
1420
    {
1421
        if ($key !== null) {
30 ✔
1422
            if (\is_array($key)) {
9 ✔
1423
                foreach ($key as $keyTmp) {
3 ✔
1424
                    $this->offsetUnset($keyTmp);
3 ✔
1425
                }
1426
            } else {
1427
                $this->offsetUnset($key);
6 ✔
1428
            }
1429

1430
            return $this;
9 ✔
1431
        }
1432

1433
        $this->array = [];
21 ✔
1434
        $this->generator = null;
21 ✔
1435

1436
        return $this;
21 ✔
1437
    }
1438

1439
    /**
1440
     * Check if an item is in the current array.
1441
     *
1442
     * EXAMPLE: <code>
1443
     * a([1, true])->containsOnly(true); // false
1444
     * </code>
1445
     *
1446
     * @param float|int|string $value
1447
     * @param bool             $recursive
1448
     * @param bool             $strict
1449
     *
1450
     * @return bool
1451
     * @psalm-mutation-free
1452
     */
1453
    public function containsOnly($value, bool $recursive = false, bool $strict = true): bool
1454
    {
1455
        if ($recursive === true) {
30 ✔
1456
            return $this->in_array_recursive($value, $this->toArray(), $strict);
×
1457
        }
1458

1459
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1460
        $tmpCount = 0;
30 ✔
1461
        foreach ($this->getGeneratorByReference() as &$valueFromArray) {
30 ✔
1462
            $tmpCount++;
24 ✔
1463

1464
            if ($strict) {
24 ✔
1465
                if ($value !== $valueFromArray) {
24 ✔
1466
                    return false;
24 ✔
1467
                }
1468
            } else {
1469
                /** @noinspection NestedPositiveIfStatementsInspection */
1470
                if ($value != $valueFromArray) {
×
1471
                    return false;
×
1472
                }
1473
            }
1474
        }
1475

1476
        return $tmpCount !== 0;
21 ✔
1477
    }
1478

1479
    /**
1480
     * Check if an item is in the current array.
1481
     *
1482
     * EXAMPLE: <code>
1483
     * a([1, true])->contains(true); // true
1484
     * </code>
1485
     *
1486
     * @param float|int|string $value
1487
     * @param bool             $recursive
1488
     * @param bool             $strict
1489
     *
1490
     * @return bool
1491
     * @psalm-mutation-free
1492
     */
1493
    public function contains($value, bool $recursive = false, bool $strict = true): bool
1494
    {
1495
        if ($recursive === true) {
69 ✔
1496
            return $this->in_array_recursive($value, $this->toArray(), $strict);
54 ✔
1497
        }
1498

1499
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1500
        foreach ($this->getGeneratorByReference() as &$valueFromArray) {
42 ✔
1501
            if ($strict) {
33 ✔
1502
                if ($value === $valueFromArray) {
33 ✔
1503
                    return true;
33 ✔
1504
                }
1505
            } else {
1506
                /** @noinspection NestedPositiveIfStatementsInspection */
1507
                if ($value == $valueFromArray) {
×
1508
                    return true;
×
1509
                }
1510
            }
1511
        }
1512

1513
        return false;
21 ✔
1514
    }
1515

1516
    /**
1517
     * Check if an (case-insensitive) string is in the current array.
1518
     *
1519
     * EXAMPLE: <code>
1520
     * a(['E', 'Γ©'])->containsCaseInsensitive('Γ‰'); // true
1521
     * </code>
1522
     *
1523
     * @param mixed $value
1524
     * @param bool  $recursive
1525
     *
1526
     * @return bool
1527
     * @psalm-mutation-free
1528
     *
1529
     * @psalm-suppress InvalidCast - hack for int|float|bool support
1530
     */
1531
    public function containsCaseInsensitive($value, $recursive = false): bool
1532
    {
1533
        if ($value === null) {
78 ✔
1534
            return false;
6 ✔
1535
        }
1536

1537
        if ($recursive === true) {
72 ✔
1538
            /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1539
            foreach ($this->getGeneratorByReference() as &$valueTmp) {
72 ✔
1540
                if (\is_array($valueTmp)) {
66 ✔
1541
                    $return = (new self($valueTmp))->containsCaseInsensitive($value, $recursive);
15 ✔
1542
                    if ($return === true) {
15 ✔
1543
                        return $return;
15 ✔
1544
                    }
1545
                } elseif (\mb_strtoupper((string) $valueTmp) === \mb_strtoupper((string) $value)) {
66 ✔
1546
                    return true;
48 ✔
1547
                }
1548
            }
1549

1550
            return false;
24 ✔
1551
        }
1552

1553
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1554
        foreach ($this->getGeneratorByReference() as &$valueTmp) {
36 ✔
1555
            if (\mb_strtoupper((string) $valueTmp) === \mb_strtoupper((string) $value)) {
33 ✔
1556
                return true;
24 ✔
1557
            }
1558
        }
1559

1560
        return false;
12 ✔
1561
    }
1562

1563
    /**
1564
     * Check if the given key/index exists in the array.
1565
     *
1566
     * EXAMPLE: <code>
1567
     * a([1 => true])->containsKey(1); // true
1568
     * </code>
1569
     *
1570
     * @param int|string $key <p>key/index to search for</p>
1571
     *
1572
     * @return bool
1573
     *              <p>Returns true if the given key/index exists in the array, false otherwise.</p>
1574
     *
1575
     * @psalm-mutation-free
1576
     */
1577
    public function containsKey($key): bool
1578
    {
1579
        return $this->offsetExists($key);
12 ✔
1580
    }
1581

1582
    /**
1583
     * Check if all given needles are present in the array as key/index.
1584
     *
1585
     * EXAMPLE: <code>
1586
     * a([1 => true])->containsKeys(array(1 => 0)); // true
1587
     * </code>
1588
     *
1589
     * @param array $needles   <p>The keys you are searching for.</p>
1590
     * @param bool  $recursive
1591
     *
1592
     * @return bool
1593
     *              <p>Returns true if all the given keys/indexes exists in the array, false otherwise.</p>
1594
     *
1595
     * @phpstan-param array<TKey> $needles
1596
     * @psalm-mutation-free
1597
     */
1598
    public function containsKeys(array $needles, bool $recursive = false): bool
1599
    {
1600
        if ($recursive === true) {
6 ✔
1601
            return
6 ✔
1602
                \count(
6 ✔
1603
                    \array_intersect(
6 ✔
1604
                        $needles,
6 ✔
1605
                        $this->keys(true)->toArray()
6 ✔
1606
                    ),
6 ✔
1607
                    \COUNT_RECURSIVE
6 ✔
1608
                )
6 ✔
1609
                ===
6 ✔
1610
                \count(
6 ✔
1611
                    $needles,
6 ✔
1612
                    \COUNT_RECURSIVE
6 ✔
1613
                );
6 ✔
1614
        }
1615

1616
        return \count(
3 ✔
1617
            \array_intersect($needles, $this->keys()->toArray()),
3 ✔
1618
            \COUNT_NORMAL
3 ✔
1619
        )
3 ✔
1620
                ===
3 ✔
1621
                \count(
3 ✔
1622
                    $needles,
3 ✔
1623
                    \COUNT_NORMAL
3 ✔
1624
                );
3 ✔
1625
    }
1626

1627
    /**
1628
     * Check if all given needles are present in the array as key/index.
1629
     *
1630
     * @param array $needles <p>The keys you are searching for.</p>
1631
     *
1632
     * @return bool
1633
     *              <p>Returns true if all the given keys/indexes exists in the array, false otherwise.</p>
1634
     *
1635
     * @phpstan-param array<TKey> $needles
1636
     * @psalm-mutation-free
1637
     */
1638
    public function containsKeysRecursive(array $needles): bool
1639
    {
1640
        return $this->containsKeys($needles, true);
3 ✔
1641
    }
1642

1643
    /**
1644
     * alias: for "Arrayy->contains()"
1645
     *
1646
     * @param float|int|string $value
1647
     *
1648
     * @return bool
1649
     *
1650
     * @see Arrayy::contains()
1651
     * @psalm-mutation-free
1652
     */
1653
    public function containsValue($value): bool
1654
    {
1655
        return $this->contains($value);
27 ✔
1656
    }
1657

1658
    /**
1659
     * alias: for "Arrayy->contains($value, true)"
1660
     *
1661
     * @param float|int|string $value
1662
     *
1663
     * @return bool
1664
     *
1665
     * @see Arrayy::contains()
1666
     * @psalm-mutation-free
1667
     */
1668
    public function containsValueRecursive($value): bool
1669
    {
1670
        return $this->contains($value, true);
54 ✔
1671
    }
1672

1673
    /**
1674
     * Check if all given needles are present in the array.
1675
     *
1676
     * EXAMPLE: <code>
1677
     * a([1, true])->containsValues(array(1, true)); // true
1678
     * </code>
1679
     *
1680
     * @param array $needles
1681
     *
1682
     * @return bool
1683
     *              <p>Returns true if all the given values exists in the array, false otherwise.</p>
1684
     *
1685
     * @phpstan-param array<T> $needles
1686
     * @psalm-mutation-free
1687
     */
1688
    public function containsValues(array $needles): bool
1689
    {
1690
        return \count(
3 ✔
1691
            \array_intersect(
3 ✔
1692
                $needles,
3 ✔
1693
                $this->toArray()
3 ✔
1694
            ),
3 ✔
1695
            \COUNT_NORMAL
3 ✔
1696
        )
3 ✔
1697
               ===
3 ✔
1698
               \count(
3 ✔
1699
                   $needles,
3 ✔
1700
                   \COUNT_NORMAL
3 ✔
1701
               );
3 ✔
1702
    }
1703

1704
    /**
1705
     * Counts all the values of an array
1706
     *
1707
     * @see          http://php.net/manual/en/function.array-count-values.php
1708
     *
1709
     * @return static
1710
     *                <p>
1711
     *                (Immutable)
1712
     *                An associative Arrayy-object of values from input as
1713
     *                keys and their count as value.
1714
     *                </p>
1715
     *
1716
     * @phpstan-return static<array-key,int>
1717
     * @psalm-mutation-free
1718
     */
1719
    public function countValues(): self
1720
    {
1721
        /** @phpstan-var static<array-key,int> $return - help for phpstan */
1722
        $return = self::create(\array_count_values($this->toArray()), $this->iteratorClass);
21 ✔
1723

1724
        return $return;
21 ✔
1725
    }
1726

1727
    /**
1728
     * Creates an Arrayy object.
1729
     *
1730
     * @param mixed  $data
1731
     * @param string $iteratorClass
1732
     * @param bool   $checkPropertiesInConstructor
1733
     *
1734
     * @return static
1735
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1736
     *
1737
     * @phpstan-param  class-string<\Arrayy\ArrayyIterator<TKey,T>> $iteratorClass
1738
     * @phpstan-return static<TKey,T>
1739
     * @psalm-mutation-free
1740
     */
1741
    public static function create(
1742
        $data = [],
1743
        string $iteratorClass = ArrayyIterator::class,
1744
        bool $checkPropertiesInConstructor = true
1745
    ) {
1746
        // @phpstan-ignore-next-line
1747
        return new static(
2,308 ✔
1748
            $data,
2,308 ✔
1749
            $iteratorClass,
2,308 ✔
1750
            $checkPropertiesInConstructor
2,308 ✔
1751
        );
2,308 ✔
1752
    }
1753

1754
    /**
1755
     * Flatten an array with the given character as a key delimiter.
1756
     *
1757
     * EXAMPLE: <code>
1758
     * $dot = a(['foo' => ['abc' => 'xyz', 'bar' => ['baz']]]);
1759
     * $flatten = $dot->flatten();
1760
     * $flatten['foo.abc']; // 'xyz'
1761
     * $flatten['foo.bar.0']; // 'baz'
1762
     * </code>
1763
     *
1764
     * @param string     $delimiter
1765
     * @param string     $prepend
1766
     * @param array|null $items
1767
     *
1768
     * @return array
1769
     */
1770
    public function flatten($delimiter = '.', $prepend = '', $items = null)
1771
    {
1772
        // init
1773
        $flatten = [];
6 ✔
1774

1775
        if ($items === null) {
6 ✔
1776
            $items = $this->getArray();
6 ✔
1777
        }
1778

1779
        foreach ($items as $key => $value) {
6 ✔
1780
            if (\is_array($value) && $value !== []) {
6 ✔
1781
                $flatten[] = $this->flatten($delimiter, $prepend . $key . $delimiter, $value);
6 ✔
1782
            } else {
1783
                $flatten[] = [$prepend . $key => $value];
6 ✔
1784
            }
1785
        }
1786

1787
        if (\count($flatten) === 0) {
6 ✔
UNCOV
1788
            return [];
×
1789
        }
1790

1791
        return \array_merge_recursive([], ...$flatten);
6 ✔
1792
    }
1793

1794
    /**
1795
     * WARNING: Creates an Arrayy object by reference.
1796
     *
1797
     * @param array $array
1798
     *
1799
     * @return $this
1800
     *               <p>(Mutable) Return this Arrayy object.</p>
1801
     *
1802
     * @phpstan-param  array<TKey,T> $array
1803
     * @phpstan-return $this<TKey,T>
1804
     *
1805
     * @internal this will not check any types because it's set directly as reference
1806
     */
1807
    public function createByReference(array &$array = []): self
1808
    {
1809
        $this->array = &$array;
78 ✔
1810
        $this->generator = null;
78 ✔
1811

1812
        return $this;
78 ✔
1813
    }
1814

1815
    /**
1816
     * Create an new instance from a callable function which will return an Generator.
1817
     *
1818
     * @param callable $generatorFunction
1819
     *
1820
     * @return static
1821
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1822
     *
1823
     * @phpstan-param callable():\Generator<TKey,T> $generatorFunction
1824
     * @phpstan-return static<TKey,T>
1825
     * @psalm-mutation-free
1826
     */
1827
    public static function createFromGeneratorFunction(callable $generatorFunction): self
1828
    {
1829
        return self::create($generatorFunction);
24 ✔
1830
    }
1831

1832
    /**
1833
     * Create an new instance filled with a copy of values from a "Generator"-object.
1834
     *
1835
     * @param \Generator $generator
1836
     *
1837
     * @return static
1838
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1839
     *
1840
     * @phpstan-param \Generator<TKey,T> $generator
1841
     * @phpstan-return static<TKey,T>
1842
     * @psalm-mutation-free
1843
     */
1844
    public static function createFromGeneratorImmutable(\Generator $generator): self
1845
    {
1846
        return self::create(\iterator_to_array($generator, true));
12 ✔
1847
    }
1848

1849
    /**
1850
     * Create an new Arrayy object via JSON.
1851
     *
1852
     * @param string $json
1853
     *
1854
     * @return static
1855
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1856
     *
1857
     * @phpstan-return static<int|string,mixed>
1858
     * @psalm-mutation-free
1859
     */
1860
    public static function createFromJson(string $json): self
1861
    {
1862
        return static::create(\json_decode($json, true));
18 ✔
1863
    }
1864

1865
    /**
1866
     * Create an new Arrayy object via JSON.
1867
     *
1868
     * @param array $array
1869
     *
1870
     * @return static
1871
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1872
     *
1873
     * @phpstan-param array<TKey,T> $array
1874
     * @phpstan-return static<TKey,T>
1875
     * @psalm-mutation-free
1876
     */
1877
    public static function createFromArray(array $array): self
1878
    {
1879
        return static::create($array);
3 ✔
1880
    }
1881

1882
    /**
1883
     * Create an new instance filled with values from an object that is iterable.
1884
     *
1885
     * @param \Traversable $object <p>iterable object</p>
1886
     *
1887
     * @return static
1888
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1889
     *
1890
     * @phpstan-param \Traversable<array-key,T> $object
1891
     * @phpstan-return static<array-key,T>
1892
     * @psalm-mutation-free
1893
     */
1894
    public static function createFromObject(\Traversable $object): self
1895
    {
1896
        // init
1897
        $arrayy = static::create();
12 ✔
1898

1899
        if ($object instanceof self) {
12 ✔
1900
            $objectArray = $object->getGenerator();
12 ✔
1901
        } else {
UNCOV
1902
            $objectArray = $object;
×
1903
        }
1904

1905
        foreach ($objectArray as $key => $value) {
12 ✔
1906
            /**
1907
             * @psalm-suppress ImpureMethodCall - object is already re-created
1908
             */
1909
            $arrayy->internalSet($key, $value);
9 ✔
1910
        }
1911

1912
        return $arrayy;
12 ✔
1913
    }
1914

1915
    /**
1916
     * Create an new instance filled with values from an object.
1917
     *
1918
     * @param object $object
1919
     *
1920
     * @return static
1921
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1922
     *
1923
     * @phpstan-return static<array-key,mixed>
1924
     * @psalm-mutation-free
1925
     */
1926
    public static function createFromObjectVars($object): self
1927
    {
1928
        return self::create(self::objectToArray($object));
15 ✔
1929
    }
1930

1931
    /**
1932
     * Create an new Arrayy object via string.
1933
     *
1934
     * @param string                $str       <p>The input string.</p>
1935
     * @param non-empty-string|null $delimiter <p>The boundary string.</p>
1936
     * @param string|null           $regEx     <p>Use the $delimiter or the $regEx, so if $pattern is null, $delimiter will be
1937
     *                                         used.</p>
1938
     *
1939
     * @return static
1940
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1941
     *
1942
     * @phpstan-return static<int,string>
1943
     * @psalm-mutation-free
1944
     */
1945
    public static function createFromString(string $str, ?string $delimiter = null, ?string $regEx = null): self
1946
    {
1947
        if ($regEx) {
30 ✔
1948
            \preg_match_all($regEx, $str, $array);
3 ✔
1949

1950
            if (!empty($array)) {
3 ✔
1951
                $array = $array[0];
3 ✔
1952
            }
1953
        } else {
1954
            /** @noinspection NestedPositiveIfStatementsInspection */
1955
            if ($delimiter !== null) {
27 ✔
1956
                $array = \explode($delimiter, $str);
21 ✔
1957
            } else {
1958
                $array = [$str];
6 ✔
1959
            }
1960
        }
1961

1962
        // trim all string in the array
1963
        /**
1964
         * @psalm-suppress MissingClosureParamType
1965
         */
1966
        \array_walk(
30 ✔
1967
            $array,
30 ✔
1968
            static function (&$val) {
30 ✔
1969
                if ((string) $val === $val) {
30 ✔
1970
                    $val = \trim($val);
30 ✔
1971
                }
1972
            }
30 ✔
1973
        );
30 ✔
1974

1975
        /** @var static<int,string> $return - help for phpstan */
1976
        $return = static::create($array);
30 ✔
1977

1978
        return $return;
30 ✔
1979
    }
1980

1981
    /**
1982
     * Create an new instance filled with a copy of values from a "Traversable"-object.
1983
     *
1984
     * @param \Traversable $traversable
1985
     * @param bool         $use_keys    [optional] <p>
1986
     *                                  Whether to use the iterator element keys as index.
1987
     *                                  </p>
1988
     *
1989
     * @return static
1990
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1991
     *
1992
     * @phpstan-param \Traversable<array-key|TKey,T> $traversable
1993
     * @phpstan-return static<int|TKey,T>
1994
     * @psalm-mutation-free
1995
     */
1996
    public static function createFromTraversableImmutable(\Traversable $traversable, bool $use_keys = true): self
1997
    {
1998
        return self::create(\iterator_to_array($traversable, $use_keys));
3 ✔
1999
    }
2000

2001
    /**
2002
     * Create an new instance containing a range of elements.
2003
     *
2004
     * @param float|int|string $low  <p>First value of the sequence.</p>
2005
     * @param float|int|string $high <p>The sequence is ended upon reaching the end value.</p>
2006
     * @param float|int        $step <p>Used as the increment between elements in the sequence.</p>
2007
     *
2008
     * @return static
2009
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
2010
     *
2011
     * @phpstan-return static<int,int|string>
2012
     * @psalm-mutation-free
2013
     */
2014
    public static function createWithRange($low, $high, $step = 1): self
2015
    {
2016
        /** @phpstan-var static<int,int|string> $return - help for phpstan */
2017
        $return = static::create(\range($low, $high, $step));
6 ✔
2018

2019
        return $return;
6 ✔
2020
    }
2021

2022
    /**
2023
     * Gets the element of the array at the current internal iterator position.
2024
     *
2025
     * @return false|mixed
2026
     *
2027
     * @phpstan-return false|T
2028
     */
2029
    public function current()
2030
    {
2031
        if ($this->generator) {
×
UNCOV
2032
            return $this->generator->current();
×
2033
        }
2034

UNCOV
2035
        return \current($this->array);
×
2036
    }
2037

2038
    /**
2039
     * Custom sort by index via "uksort".
2040
     *
2041
     * EXAMPLE: <code>
2042
     * $callable = function ($a, $b) {
2043
     *     if ($a == $b) {
2044
     *         return 0;
2045
     *     }
2046
     *     return ($a > $b) ? 1 : -1;
2047
     * };
2048
     * $arrayy = a(['three' => 3, 'one' => 1, 'two' => 2]);
2049
     * $resultArrayy = $arrayy->customSortKeys($callable); // Arrayy['one' => 1, 'three' => 3, 'two' => 2]
2050
     * </code>
2051
     *
2052
     * @see          http://php.net/manual/en/function.uksort.php
2053
     *
2054
     * @param callable $callable
2055
     *
2056
     * @throws \InvalidArgumentException
2057
     *
2058
     * @return $this
2059
     *               <p>(Mutable) Return this Arrayy object.</p>
2060
     *
2061
     * @phpstan-param  callable(TKey,TKey):int $callable
2062
     * @phpstan-return static<TKey,T>
2063
     */
2064
    public function customSortKeys(callable $callable): self
2065
    {
2066
        $this->generatorToArray();
15 ✔
2067

2068
        \uksort($this->array, $callable);
15 ✔
2069

2070
        return $this;
15 ✔
2071
    }
2072

2073
    /**
2074
     * Custom sort by index via "uksort".
2075
     *
2076
     * @see          http://php.net/manual/en/function.uksort.php
2077
     *
2078
     * @param callable $callable
2079
     *
2080
     * @throws \InvalidArgumentException
2081
     *
2082
     * @return $this
2083
     *               <p>(Immutable) Return this Arrayy object.</p>
2084
     *
2085
     * @phpstan-param  callable(TKey,TKey):int $callable
2086
     * @phpstan-return static<TKey,T>
2087
     * @psalm-mutation-free
2088
     */
2089
    public function customSortKeysImmutable(callable $callable): self
2090
    {
2091
        $that = clone $this;
3 ✔
2092

2093
        $that->generatorToArray();
3 ✔
2094

2095
        /**
2096
         * @psalm-suppress ImpureFunctionCall - object is already cloned
2097
         */
2098
        \uksort($that->array, $callable);
3 ✔
2099

2100
        return $that;
3 ✔
2101
    }
2102

2103
    /**
2104
     * Custom sort by value via "usort".
2105
     *
2106
     * EXAMPLE: <code>
2107
     * $callable = function ($a, $b) {
2108
     *     if ($a == $b) {
2109
     *         return 0;
2110
     *     }
2111
     *     return ($a > $b) ? 1 : -1;
2112
     * };
2113
     * $arrayy = a(['three' => 3, 'one' => 1, 'two' => 2]);
2114
     * $resultArrayy = $arrayy->customSortValues($callable); // Arrayy[1, 2, 3]
2115
     * </code>
2116
     *
2117
     * @see          http://php.net/manual/en/function.usort.php
2118
     *
2119
     * @param callable $callable
2120
     *
2121
     * @return $this
2122
     *               <p>(Mutable) Return this Arrayy object.</p>
2123
     *
2124
     * @phpstan-param  callable(T,T):int $callable
2125
     * @phpstan-return static<int,T>
2126
     */
2127
    public function customSortValues(callable $callable): self
2128
    {
2129
        $this->generatorToArray();
33 ✔
2130

2131
        \usort($this->array, $callable);
33 ✔
2132

2133
        return $this;
33 ✔
2134
    }
2135

2136
    /**
2137
     * Custom sort by value via "usort".
2138
     *
2139
     * @see          http://php.net/manual/en/function.usort.php
2140
     *
2141
     * @param callable $callable
2142
     *
2143
     * @throws \InvalidArgumentException
2144
     *
2145
     * @return $this
2146
     *               <p>(Immutable) Return this Arrayy object.</p>
2147
     *
2148
     * @phpstan-param  callable(T,T):int $callable
2149
     * @phpstan-return static<int,T>
2150
     * @psalm-mutation-free
2151
     */
2152
    public function customSortValuesImmutable($callable): self
2153
    {
2154
        $that = clone $this;
15 ✔
2155

2156
        /**
2157
         * @psalm-suppress ImpureMethodCall - object is already cloned
2158
         */
2159
        $that->customSortValues($callable);
15 ✔
2160

2161
        return $that;
15 ✔
2162
    }
2163

2164
    /**
2165
     * Delete the given key or keys.
2166
     *
2167
     * @param int|int[]|string|string[] $keyOrKeys
2168
     *
2169
     * @return void
2170
     */
2171
    public function delete($keyOrKeys)
2172
    {
2173
        $keyOrKeys = (array) $keyOrKeys;
27 ✔
2174

2175
        foreach ($keyOrKeys as $key) {
27 ✔
2176
            $this->offsetUnset($key);
27 ✔
2177
        }
2178
    }
2179

2180
    /**
2181
     * Return elements where the values that are only in the current array.
2182
     *
2183
     * EXAMPLE: <code>
2184
     * a([1 => 1, 2 => 2])->diff([1 => 1]); // Arrayy[2 => 2]
2185
     * </code>
2186
     *
2187
     * @param array ...$array
2188
     *
2189
     * @return static
2190
     *                <p>(Immutable)</p>
2191
     *
2192
     * @phpstan-param  array<TKey,T> ...$array
2193
     * @phpstan-return static<TKey,T>
2194
     * @psalm-mutation-free
2195
     */
2196
    public function diff(array ...$array): self
2197
    {
2198
        if (\count($array) > 1) {
39 ✔
2199
            $array = \array_merge([], ...$array);
3 ✔
2200
        } else {
2201
            $array = $array[0];
39 ✔
2202
        }
2203

2204
        $generator = function () use ($array): \Generator {
39 ✔
2205
            foreach ($this->getGenerator() as $key => $value) {
39 ✔
2206
                if (\in_array($value, $array, true) === false) {
33 ✔
2207
                    yield $key => $value;
15 ✔
2208
                }
2209
            }
2210
        };
39 ✔
2211

2212
        return static::create(
39 ✔
2213
            $generator,
39 ✔
2214
            $this->iteratorClass,
39 ✔
2215
            false
39 ✔
2216
        );
39 ✔
2217
    }
2218

2219
    /**
2220
     * Return elements where the keys are only in the current array.
2221
     *
2222
     * @param array ...$array
2223
     *
2224
     * @return static
2225
     *                <p>(Immutable)</p>
2226
     *
2227
     * @phpstan-param  array<TKey,T> ...$array
2228
     * @phpstan-return static<TKey,T>
2229
     * @psalm-mutation-free
2230
     */
2231
    public function diffKey(array ...$array): self
2232
    {
2233
        if (\count($array) > 1) {
27 ✔
2234
            $array = \array_replace([], ...$array);
3 ✔
2235
        } else {
2236
            $array = $array[0];
24 ✔
2237
        }
2238

2239
        $generator = function () use ($array): \Generator {
27 ✔
2240
            foreach ($this->getGenerator() as $key => $value) {
27 ✔
2241
                if (\array_key_exists($key, $array) === false) {
24 ✔
2242
                    yield $key => $value;
6 ✔
2243
                }
2244
            }
2245
        };
27 ✔
2246

2247
        return static::create(
27 ✔
2248
            $generator,
27 ✔
2249
            $this->iteratorClass,
27 ✔
2250
            false
27 ✔
2251
        );
27 ✔
2252
    }
2253

2254
    /**
2255
     * Return elements where the values and keys are only in the current array.
2256
     *
2257
     * @param array ...$array
2258
     *
2259
     * @return static
2260
     *                <p>(Immutable)</p>
2261
     *
2262
     * @phpstan-param  array<TKey,T> $array
2263
     * @phpstan-return static<TKey,T>
2264
     * @psalm-mutation-free
2265
     */
2266
    public function diffKeyAndValue(array ...$array): self
2267
    {
2268
        if (\count($array) > 1) {
27 ✔
2269
            $array = \array_merge([], ...$array);
3 ✔
2270
        } else {
2271
            $array = $array[0];
24 ✔
2272
        }
2273

2274
        $generator = function () use ($array): \Generator {
27 ✔
2275
            foreach ($this->getGenerator() as $key => $value) {
27 ✔
2276
                $isset = isset($array[$key]);
24 ✔
2277

2278
                if (
2279
                    !$isset
24 ✔
2280
                    ||
2281
                    $array[$key] !== $value
24 ✔
2282
                ) {
2283
                    yield $key => $value;
12 ✔
2284
                }
2285
            }
2286
        };
27 ✔
2287

2288
        return static::create(
27 ✔
2289
            $generator,
27 ✔
2290
            $this->iteratorClass,
27 ✔
2291
            false
27 ✔
2292
        );
27 ✔
2293
    }
2294

2295
    /**
2296
     * Return elements where the values are only in the current multi-dimensional array.
2297
     *
2298
     * EXAMPLE: <code>
2299
     * a([1 => [1 => 1], 2 => [2 => 2]])->diffRecursive([1 => [1 => 1]]); // Arrayy[2 => [2 => 2]]
2300
     * </code>
2301
     *
2302
     * @param array                 $array
2303
     * @param array|\Generator|null $helperVariableForRecursion <p>(only for internal usage)</p>
2304
     *
2305
     * @return static
2306
     *                <p>(Immutable)</p>
2307
     *
2308
     * @phpstan-param  array<TKey,T> $array
2309
     * @phpstan-param  null|array<TKey,T>|\Generator<TKey,T> $helperVariableForRecursion
2310
     * @phpstan-return static<TKey,T>
2311
     * @psalm-mutation-free
2312
     */
2313
    public function diffRecursive(array $array = [], $helperVariableForRecursion = null): self
2314
    {
2315
        // init
2316
        $result = [];
3 ✔
2317

2318
        if (
2319
            $helperVariableForRecursion !== null
3 ✔
2320
            &&
2321
            \is_array($helperVariableForRecursion)
3 ✔
2322
        ) {
UNCOV
2323
            $arrayForTheLoop = $helperVariableForRecursion;
×
2324
        } else {
2325
            $arrayForTheLoop = $this->getGenerator();
3 ✔
2326
        }
2327

2328
        foreach ($arrayForTheLoop as $key => $value) {
3 ✔
2329
            if ($value instanceof self) {
3 ✔
2330
                $value = $value->toArray();
3 ✔
2331
            }
2332

2333
            if (\array_key_exists($key, $array)) {
3 ✔
2334
                if ($value !== $array[$key]) {
3 ✔
2335
                    $result[$key] = $value;
3 ✔
2336
                }
2337
            } else {
2338
                $result[$key] = $value;
3 ✔
2339
            }
2340
        }
2341

2342
        return static::create(
3 ✔
2343
            $result,
3 ✔
2344
            $this->iteratorClass,
3 ✔
2345
            false
3 ✔
2346
        );
3 ✔
2347
    }
2348

2349
    /**
2350
     * Return elements where the values that are only in the new $array.
2351
     *
2352
     * EXAMPLE: <code>
2353
     * a([1 => 1])->diffReverse([1 => 1, 2 => 2]); // Arrayy[2 => 2]
2354
     * </code>
2355
     *
2356
     * @param array $array
2357
     *
2358
     * @return static
2359
     *                <p>(Immutable)</p>
2360
     *
2361
     * @phpstan-param  array<TKey,T> $array
2362
     * @phpstan-return static<TKey,T>
2363
     * @psalm-mutation-free
2364
     */
2365
    public function diffReverse(array $array = []): self
2366
    {
2367
        return static::create(
24 ✔
2368
            \array_diff($array, $this->toArray()),
24 ✔
2369
            $this->iteratorClass,
24 ✔
2370
            false
24 ✔
2371
        );
24 ✔
2372
    }
2373

2374
    /**
2375
     * Divide an array into two arrays. One with keys and the other with values.
2376
     *
2377
     * EXAMPLE: <code>
2378
     * a(['a' => 1, 'b' => ''])->divide(); // Arrayy[Arrayy['a', 'b'], Arrayy[1, '']]
2379
     * </code>
2380
     *
2381
     * @return static
2382
     *                <p>(Immutable)</p>
2383
     *
2384
     * @phpstan-return static<TKey,T>
2385
     * @psalm-mutation-free
2386
     */
2387
    public function divide(): self
2388
    {
2389
        return static::create(
3 ✔
2390
            [
3 ✔
2391
                $this->keys(),
3 ✔
2392
                $this->values(),
3 ✔
2393
            ],
3 ✔
2394
            $this->iteratorClass,
3 ✔
2395
            false
3 ✔
2396
        );
3 ✔
2397
    }
2398

2399
    /**
2400
     * Iterate over the current array and modify the array's value.
2401
     *
2402
     * EXAMPLE: <code>
2403
     * $result = A::create();
2404
     * $closure = function ($value) {
2405
     *     return ':' . $value . ':';
2406
     * };
2407
     * a(['foo', 'bar' => 'bis'])->each($closure); // Arrayy[':foo:', 'bar' => ':bis:']
2408
     * </code>
2409
     *
2410
     * @param \Closure $closure
2411
     *
2412
     * @return static
2413
     *                <p>(Immutable)</p>
2414
     *
2415
     * @phpstan-param \Closure(T,?TKey):T $closure
2416
     * @phpstan-return static<TKey,T>
2417
     * @psalm-mutation-free
2418
     */
2419
    public function each(\Closure $closure): self
2420
    {
2421
        // init
2422
        $array = [];
18 ✔
2423

2424
        foreach ($this->getGenerator() as $key => $value) {
18 ✔
2425
            $array[$key] = $closure($value, $key);
18 ✔
2426
        }
2427

2428
        return static::create(
18 ✔
2429
            $array,
18 ✔
2430
            $this->iteratorClass,
18 ✔
2431
            false
18 ✔
2432
        );
18 ✔
2433
    }
2434

2435
    /**
2436
     * Sets the internal iterator to the last element in the array and returns this element.
2437
     *
2438
     * @return false|mixed
2439
     *
2440
     * @phpstan-return T|false
2441
     */
2442
    public function end()
2443
    {
2444
        if ($this->generator) {
×
2445
            $count = $this->count();
×
2446
            if ($count === 0) {
×
UNCOV
2447
                return false;
×
2448
            }
2449

UNCOV
2450
            $counter = 0;
×
2451
            /** @noinspection PhpUnusedLocalVariableInspection */
2452
            foreach ($this->getIterator() as $item) {
×
2453
                if (++$counter === $count - 1) {
×
UNCOV
2454
                    break;
×
2455
                }
2456
            }
2457
        }
2458

UNCOV
2459
        return \end($this->array);
×
2460
    }
2461

2462
    /**
2463
     * Check if a value is in the current array using a closure.
2464
     *
2465
     * EXAMPLE: <code>
2466
     * $callable = function ($value, $key) {
2467
     *     return 2 === $key and 'two' === $value;
2468
     * };
2469
     * a(['foo', 2 => 'two'])->exists($callable); // true
2470
     * </code>
2471
     *
2472
     * @param \Closure $closure
2473
     *
2474
     * @return bool
2475
     *              <p>Returns true if the given value is found, false otherwise.</p>
2476
     *
2477
     * @phpstan-param \Closure(T,TKey):bool $closure
2478
     */
2479
    public function exists(\Closure $closure): bool
2480
    {
2481
        // init
2482
        $isExists = false;
12 ✔
2483

2484
        foreach ($this->getGenerator() as $key => $value) {
12 ✔
2485
            if ($closure($value, $key)) {
9 ✔
2486
                $isExists = true;
3 ✔
2487

2488
                break;
3 ✔
2489
            }
2490
        }
2491

2492
        return $isExists;
12 ✔
2493
    }
2494

2495
    /**
2496
     * Fill the array until "$num" with "$default" values.
2497
     *
2498
     * EXAMPLE: <code>
2499
     * a(['bar'])->fillWithDefaults(3, 'foo'); // Arrayy['bar', 'foo', 'foo']
2500
     * </code>
2501
     *
2502
     * @param int   $num
2503
     * @param mixed $default
2504
     *
2505
     * @return static
2506
     *                <p>(Immutable)</p>
2507
     *
2508
     * @phpstan-param T $default
2509
     * @phpstan-return static<TKey,T>
2510
     * @psalm-mutation-free
2511
     */
2512
    public function fillWithDefaults(int $num, $default = null): self
2513
    {
2514
        if ($num < 0) {
24 ✔
2515
            throw new \InvalidArgumentException('The $num parameter can only contain non-negative values.');
3 ✔
2516
        }
2517

2518
        $this->generatorToArray();
21 ✔
2519

2520
        $tmpArray = $this->array;
21 ✔
2521

2522
        $count = \count($tmpArray);
21 ✔
2523

2524
        while ($count < $num) {
21 ✔
2525
            $tmpArray[] = $default;
12 ✔
2526
            ++$count;
12 ✔
2527
        }
2528

2529
        return static::create(
21 ✔
2530
            $tmpArray,
21 ✔
2531
            $this->iteratorClass,
21 ✔
2532
            false
21 ✔
2533
        );
21 ✔
2534
    }
2535

2536
    /**
2537
     * Find all items in an array that pass the truth test.
2538
     *
2539
     * EXAMPLE: <code>
2540
     * $closure = function ($value) {
2541
     *     return $value % 2 !== 0;
2542
     * }
2543
     * a([1, 2, 3, 4])->filter($closure); // Arrayy[0 => 1, 2 => 3]
2544
     * </code>
2545
     *
2546
     * @param \Closure|null $closure [optional] <p>
2547
     *                               The callback function to use
2548
     *                               </p>
2549
     *                               <p>
2550
     *                               If no callback is supplied, all entries of
2551
     *                               input equal to false (see
2552
     *                               converting to
2553
     *                               boolean) will be removed.
2554
     *                               </p>
2555
     * @param int           $flag    [optional] <p>
2556
     *                               Flag determining what arguments are sent to <i>callback</i>:
2557
     *                               </p>
2558
     *                               <ul>
2559
     *                               <li>
2560
     *                               <b>ARRAY_FILTER_USE_KEY</b> (1) - pass key as the only argument
2561
     *                               to <i>callback</i> instead of the value
2562
     *                               </li>
2563
     *                               <li>
2564
     *                               <b>ARRAY_FILTER_USE_BOTH</b> (2) - pass both value and key as
2565
     *                               arguments to <i>callback</i> instead of the value
2566
     *                               </li>
2567
     *                               </ul>
2568
     *
2569
     * @return static
2570
     *                <p>(Immutable)</p>
2571
     *
2572
     * @phpstan-param null|(\Closure(T,TKey=):bool)|(\Closure(T):bool)|(\Closure(TKey):bool) $closure
2573
     * @phpstan-return static<TKey,T>
2574
     * @psalm-mutation-free
2575
     */
2576
    public function filter($closure = null, int $flag = \ARRAY_FILTER_USE_BOTH)
2577
    {
2578
        if (!$closure) {
39 ✔
2579
            return $this->clean();
3 ✔
2580
        }
2581

2582
        if ($flag === \ARRAY_FILTER_USE_KEY) {
39 ✔
2583
            $generator = function () use ($closure) {
3 ✔
2584
                foreach ($this->getGenerator() as $key => $value) {
3 ✔
2585
                    if ($closure($key) === true) {
3 ✔
2586
                        yield $key => $value;
3 ✔
2587
                    }
2588
                }
2589
            };
3 ✔
2590
        } elseif ($flag === \ARRAY_FILTER_USE_BOTH) {
39 ✔
2591
            /** @noinspection PhpSillyAssignmentInspection - hack for phpstan - https://github.com/phpstan/phpstan/issues/4192 */
2592
            /** @phpstan-var \Closure(T,TKey):bool $closure */
2593
            $closure = $closure;
39 ✔
2594

2595
            $generator = function () use ($closure) {
39 ✔
2596
                foreach ($this->getGenerator() as $key => $value) {
36 ✔
2597
                    if ($closure($value, $key) === true) {
33 ✔
2598
                        yield $key => $value;
30 ✔
2599
                    }
2600
                }
2601
            };
39 ✔
2602
        } else {
2603
            $generator = function () use ($closure) {
3 ✔
2604
                foreach ($this->getGenerator() as $key => $value) {
3 ✔
2605
                    if ($closure($value) === true) {
3 ✔
2606
                        yield $key => $value;
3 ✔
2607
                    }
2608
                }
2609
            };
3 ✔
2610
        }
2611

2612
        return static::create(
39 ✔
2613
            $generator,
39 ✔
2614
            $this->iteratorClass,
39 ✔
2615
            false
39 ✔
2616
        );
39 ✔
2617
    }
2618

2619
    /**
2620
     * Filters an array of objects (or a numeric array of associative arrays) based on the value of a particular
2621
     * property within that.
2622
     *
2623
     * @param string      $property
2624
     * @param mixed       $value
2625
     * @param string|null $comparisonOp
2626
     *                                  <p>
2627
     *                                  'eq' (equals),<br />
2628
     *                                  'gt' (greater),<br />
2629
     *                                  'gte' || 'ge' (greater or equals),<br />
2630
     *                                  'lt' (less),<br />
2631
     *                                  'lte' || 'le' (less or equals),<br />
2632
     *                                  'ne' (not equals),<br />
2633
     *                                  'contains',<br />
2634
     *                                  'notContains',<br />
2635
     *                                  'newer' (via strtotime),<br />
2636
     *                                  'older' (via strtotime),<br />
2637
     *                                  </p>
2638
     *
2639
     * @return static
2640
     *                <p>(Immutable)</p>
2641
     *
2642
     * @phpstan-param array|T $value
2643
     * @phpstan-return static<TKey,T>
2644
     * @psalm-mutation-free
2645
     *
2646
     * @psalm-suppress MissingClosureReturnType
2647
     * @psalm-suppress MissingClosureParamType
2648
     */
2649
    public function filterBy(
2650
        string $property,
2651
        $value,
2652
        ?string $comparisonOp = null
2653
    ): self {
2654
        if (!$comparisonOp) {
3 ✔
2655
            $comparisonOp = \is_array($value) ? 'contains' : 'eq';
3 ✔
2656
        }
2657

2658
        $ops = [
3 ✔
2659
            'eq' => static function ($item, $prop, $value): bool {
3 ✔
2660
                return $item[$prop] === $value;
3 ✔
2661
            },
3 ✔
2662
            'gt' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2663
                return $item[$prop] > $value;
×
2664
            },
3 ✔
2665
            'ge' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2666
                return $item[$prop] >= $value;
×
2667
            },
3 ✔
2668
            'gte' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2669
                return $item[$prop] >= $value;
×
2670
            },
3 ✔
2671
            'lt' => static function ($item, $prop, $value): bool {
3 ✔
2672
                return $item[$prop] < $value;
3 ✔
2673
            },
3 ✔
2674
            'le' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2675
                return $item[$prop] <= $value;
×
2676
            },
3 ✔
2677
            'lte' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2678
                return $item[$prop] <= $value;
×
2679
            },
3 ✔
2680
            'ne' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2681
                return $item[$prop] !== $value;
×
2682
            },
3 ✔
2683
            'contains' => static function ($item, $prop, $value): bool {
3 ✔
2684
                return \in_array($item[$prop], (array) $value, true);
3 ✔
2685
            },
3 ✔
2686
            'notContains' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2687
                return !\in_array($item[$prop], (array) $value, true);
×
2688
            },
3 ✔
2689
            'newer' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2690
                return \strtotime($item[$prop]) > \strtotime($value);
×
2691
            },
3 ✔
2692
            'older' => static function ($item, $prop, $value): bool {
3 ✔
UNCOV
2693
                return \strtotime($item[$prop]) < \strtotime($value);
×
2694
            },
3 ✔
2695
        ];
3 ✔
2696

2697
        $result = \array_values(
3 ✔
2698
            \array_filter(
3 ✔
2699
                $this->toArray(false, true),
3 ✔
2700
                static function ($item) use (
3 ✔
2701
                    $property,
3 ✔
2702
                    $value,
3 ✔
2703
                    $ops,
3 ✔
2704
                    $comparisonOp
3 ✔
2705
                ) {
3 ✔
2706
                    $item = (array) $item;
3 ✔
2707
                    $itemArrayy = static::create($item);
3 ✔
2708
                    $item[$property] = $itemArrayy->get($property, []);
3 ✔
2709

2710
                    return $ops[$comparisonOp]($item, $property, $value);
3 ✔
2711
                }
3 ✔
2712
            )
3 ✔
2713
        );
3 ✔
2714

2715
        return static::create(
3 ✔
2716
            $result,
3 ✔
2717
            $this->iteratorClass,
3 ✔
2718
            false
3 ✔
2719
        );
3 ✔
2720
    }
2721

2722
    /**
2723
     * Find the first item in an array that passes the truth test, otherwise return false.
2724
     *
2725
     * EXAMPLE: <code>
2726
     * $search = 'foo';
2727
     * $closure = function ($value, $key) use ($search) {
2728
     *     return $value === $search;
2729
     * };
2730
     * a(['foo', 'bar', 'lall'])->find($closure); // 'foo'
2731
     * </code>
2732
     *
2733
     * @param \Closure $closure
2734
     *
2735
     * @return false|mixed
2736
     *                     <p>Return false if we did not find the value.</p>
2737
     *
2738
     * @phpstan-param \Closure(T,TKey):bool $closure
2739
     * @phpstan-return T|false
2740
     */
2741
    public function find(\Closure $closure)
2742
    {
2743
        foreach ($this->getGenerator() as $key => $value) {
27 ✔
2744
            if ($closure($value, $key)) {
21 ✔
2745
                return $value;
18 ✔
2746
            }
2747
        }
2748

2749
        return false;
9 ✔
2750
    }
2751

2752
    /**
2753
     * Find the key of the first item in an array that passes the truth test, otherwise return false.
2754
     *
2755
     * EXAMPLE: <code>
2756
     * $search = 'foo';
2757
     * $closure = function ($value, $key) use ($search) {
2758
     *     return $value === $search;
2759
     * };
2760
     * a(['foo', 'bar', 'lall'])->findKey($closure); // 0
2761
     * </code>
2762
     *
2763
     * @param \Closure $closure
2764
     *
2765
     * @return false|int|string
2766
     *                          <p>Return false if we did not find the key.</p>
2767
     *
2768
     * @phpstan-param \Closure(T,TKey):bool $closure
2769
     * @phpstan-return TKey|false
2770
     */
2771
    public function findKey(\Closure $closure)
2772
    {
2773
        foreach ($this->getGenerator() as $key => $value) {
39 ✔
2774
            if ($closure($value, $key)) {
36 ✔
2775
                return $key;
30 ✔
2776
            }
2777
        }
2778

2779
        return false;
12 ✔
2780
    }
2781

2782
    /**
2783
     * find by ...
2784
     *
2785
     * EXAMPLE: <code>
2786
     * $array = [
2787
     *     0 => ['id' => 123, 'name' => 'foo', 'group' => 'primary', 'value' => 123456, 'when' => '2014-01-01'],
2788
     *     1 => ['id' => 456, 'name' => 'bar', 'group' => 'primary', 'value' => 1468, 'when' => '2014-07-15'],
2789
     * ];
2790
     * a($array)->filterBy('name', 'foo'); // Arrayy[0 => ['id' => 123, 'name' => 'foo', 'group' => 'primary', 'value' => 123456, 'when' => '2014-01-01']]
2791
     * </code>
2792
     *
2793
     * @param string $property
2794
     * @param mixed  $value
2795
     * @param string $comparisonOp
2796
     *
2797
     * @return static
2798
     *                <p>(Immutable)</p>
2799
     *
2800
     * @phpstan-param array|T $value
2801
     * @phpstan-return static<TKey,T>
2802
     * @psalm-mutation-free
2803
     */
2804
    public function findBy(string $property, $value, string $comparisonOp = 'eq'): self
2805
    {
2806
        return $this->filterBy($property, $value, $comparisonOp);
3 ✔
2807
    }
2808

2809
    /**
2810
     * Get the first value from the current array.
2811
     *
2812
     * EXAMPLE: <code>
2813
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->first(); // 'foo'
2814
     * </code>
2815
     *
2816
     * @return mixed|null
2817
     *                    <p>Return null if there wasn't a element.</p>
2818
     *
2819
     * @phpstan-return T|null
2820
     * @psalm-mutation-free
2821
     */
2822
    public function first()
2823
    {
2824
        $key_first = $this->firstKey();
66 ✔
2825
        if ($key_first === null) {
66 ✔
2826
            return null;
9 ✔
2827
        }
2828

2829
        return $this->get($key_first);
57 ✔
2830
    }
2831

2832
    /**
2833
     * Get the first key from the current array.
2834
     *
2835
     * @return mixed|null
2836
     *                    <p>Return null if there wasn't a element.</p>
2837
     *
2838
     * @phpstan-return TKey|null
2839
     *
2840
     * @psalm-mutation-free
2841
     */
2842
    public function firstKey()
2843
    {
2844
        $this->generatorToArray();
87 ✔
2845

2846
        /** @phpstan-var TKey|null $return - help for phpstan */
2847
        $return = \array_key_first($this->array);
87 ✔
2848

2849
        return $return;
87 ✔
2850
    }
2851

2852
    /**
2853
     * Get the first value(s) from the current array.
2854
     * And will return an empty array if there was no first entry.
2855
     *
2856
     * EXAMPLE: <code>
2857
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->firstsImmutable(2); // Arrayy[0 => 'foo', 1 => 'bar']
2858
     * </code>
2859
     *
2860
     * @param int|null $number <p>How many values you will take?</p>
2861
     *
2862
     * @return static
2863
     *                <p>(Immutable)</p>
2864
     *
2865
     * @phpstan-return static<TKey,T>
2866
     * @psalm-mutation-free
2867
     */
2868
    public function firstsImmutable(?int $number = null): self
2869
    {
2870
        $arrayTmp = $this->toArray();
111 ✔
2871

2872
        if ($number === null) {
111 ✔
2873
            $array = (array) \array_shift($arrayTmp);
42 ✔
2874
        } else {
2875
            $array = \array_splice($arrayTmp, 0, $number);
69 ✔
2876
        }
2877

2878
        return static::create(
111 ✔
2879
            $array,
111 ✔
2880
            $this->iteratorClass,
111 ✔
2881
            false
111 ✔
2882
        );
111 ✔
2883
    }
2884

2885
    /**
2886
     * Get the first value(s) from the current array.
2887
     * And will return an empty array if there was no first entry.
2888
     *
2889
     * @param int|null $number <p>How many values you will take?</p>
2890
     *
2891
     * @return static
2892
     *                <p>(Immutable)</p>
2893
     *
2894
     * @phpstan-return static<array-key,TKey>
2895
     * @psalm-mutation-free
2896
     */
2897
    public function firstsKeys(?int $number = null): self
2898
    {
2899
        $arrayTmp = $this->keys()->toArray();
9 ✔
2900

2901
        if ($number === null) {
9 ✔
UNCOV
2902
            $array = (array) \array_shift($arrayTmp);
×
2903
        } else {
2904
            $array = \array_splice($arrayTmp, 0, $number);
9 ✔
2905
        }
2906

2907
        return static::create(
9 ✔
2908
            $array,
9 ✔
2909
            $this->iteratorClass,
9 ✔
2910
            false
9 ✔
2911
        );
9 ✔
2912
    }
2913

2914
    /**
2915
     * Get and remove the first value(s) from the current array.
2916
     * And will return an empty array if there was no first entry.
2917
     *
2918
     * EXAMPLE: <code>
2919
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->firstsMutable(); // 'foo'
2920
     * </code>
2921
     *
2922
     * @param int|null $number <p>How many values you will take?</p>
2923
     *
2924
     * @return $this
2925
     *               <p>(Mutable)</p>
2926
     *
2927
     * @phpstan-return ($number is null ? static<int,T> : static<TKey,T>)
2928
     */
2929
    public function firstsMutable(?int $number = null): self
2930
    {
2931
        $this->generatorToArray();
102 ✔
2932

2933
        if ($number === null) {
102 ✔
2934
            $shift = \array_shift($this->array);
57 ✔
2935
            /* @phpstan-ignore-next-line | I am not sure if "array<int, T of mixed>" is an error here? */
2936
            $this->array = $shift !== null ? [$shift] : [];
57 ✔
2937
        } else {
2938
            $splice = \array_splice($this->array, 0, $number);
45 ✔
2939
            $this->array = $splice;
45 ✔
2940
        }
2941

2942
        return $this;
102 ✔
2943
    }
2944

2945
    /**
2946
     * Exchanges all keys with their associated values in an array.
2947
     *
2948
     * EXAMPLE: <code>
2949
     * a([0 => 'foo', 1 => 'bar'])->flip(); // Arrayy['foo' => 0, 'bar' => 1]
2950
     * </code>
2951
     *
2952
     * @return static
2953
     *                <p>(Immutable)</p>
2954
     *
2955
     * @phpstan-return static<array-key,TKey>
2956
     * @psalm-mutation-free
2957
     */
2958
    public function flip(): self
2959
    {
2960
        $generator = function (): \Generator {
3 ✔
2961
            foreach ($this->getGenerator() as $key => $value) {
3 ✔
2962
                yield (string) $value => $key;
3 ✔
2963
            }
2964
        };
3 ✔
2965

2966
        return static::create(
3 ✔
2967
            $generator,
3 ✔
2968
            $this->iteratorClass,
3 ✔
2969
            false
3 ✔
2970
        );
3 ✔
2971
    }
2972

2973
    /**
2974
     * Get a value from an array (optional using dot-notation).
2975
     *
2976
     * EXAMPLE: <code>
2977
     * $arrayy = a(['user' => ['lastname' => 'Moelleken']]);
2978
     * $arrayy->get('user.lastname'); // 'Moelleken'
2979
     * // ---
2980
     * $arrayy = new A();
2981
     * $arrayy['user'] = ['lastname' => 'Moelleken'];
2982
     * $arrayy['user.firstname'] = 'Lars';
2983
     * $arrayy['user']['lastname']; // Moelleken
2984
     * $arrayy['user.lastname']; // Moelleken
2985
     * $arrayy['user.firstname']; // Lars
2986
     * </code>
2987
     *
2988
     * @param int|string $key
2989
     *                                   <p>The key to look for.</p>
2990
     * @param mixed      $fallback
2991
     *                                   <p>Value to fallback to.</p>
2992
     * @param array|null $array
2993
     *                                   <p>The array to get from, if it's set to "null" we use the current array from the
2994
     *                                   class.</p>
2995
     * @param bool       $useByReference
2996
     *
2997
     * @return mixed|static
2998
     *
2999
     * @phpstan-param TKey $key
3000
     * @phpstan-param array<array-key,mixed>|array<TKey,T> $array
3001
     * @psalm-mutation-free
3002
     */
3003
    public function get(
3004
        $key = null,
3005
        $fallback = null,
3006
        ?array $array = null,
3007
        bool $useByReference = false
3008
    ) {
3009
        if ($array === null && $key === null) {
783 ✔
3010
            if ($useByReference) {
3 ✔
UNCOV
3011
                return $this;
×
3012
            }
3013

3014
            return clone $this;
3 ✔
3015
        }
3016

3017
        if ($array !== null) {
783 ✔
3018
            if ($useByReference) {
12 ✔
UNCOV
3019
                $usedArray = &$array;
×
3020
            } else {
3021
                $usedArray = $array;
12 ✔
3022
            }
3023
        } else {
3024
            $this->generatorToArray();
774 ✔
3025

3026
            if ($useByReference) {
774 ✔
3027
                $usedArray = &$this->array;
438 ✔
3028
            } else {
3029
                $usedArray = $this->array;
390 ✔
3030
            }
3031
        }
3032

3033
        if ($key === null) {
783 ✔
3034
            return static::create(
3 ✔
3035
                [],
3 ✔
3036
                $this->iteratorClass,
3 ✔
3037
                false
3 ✔
3038
            )->createByReference($usedArray);
3 ✔
3039
        }
3040

3041
        // php cast "bool"-index into "int"-index
3042
        /* @phpstan-ignore-next-line | this is only a fallback */
3043
        if ((bool) $key === $key) {
783 ✔
UNCOV
3044
            $key = (int) $key;
×
3045
        }
3046

3047
        if (\array_key_exists($key, $usedArray) === true) {
783 ✔
3048
            if (\is_array($usedArray[$key])) {
669 ✔
3049
                return static::create(
54 ✔
3050
                    [],
54 ✔
3051
                    $this->iteratorClass,
54 ✔
3052
                    false
54 ✔
3053
                )->createByReference($usedArray[$key]);
54 ✔
3054
            }
3055

3056
            return $usedArray[$key];
627 ✔
3057
        }
3058

3059
        // crawl through array, get key according to object or not
3060
        $usePath = false;
183 ✔
3061
        if (
3062
            $this->pathSeparator
183 ✔
3063
            &&
3064
            (string) $key === $key
183 ✔
3065
            &&
3066
            \strpos($key, $this->pathSeparator) !== false
183 ✔
3067
        ) {
3068
            $segments = \explode($this->pathSeparator, (string) $key);
93 ✔
3069
            if ($segments !== false) {
93 ✔
3070
                $usePath = true;
93 ✔
3071
                $usedArrayTmp = $usedArray; // do not use the reference for dot-annotations
93 ✔
3072

3073
                foreach ($segments as $segment) {
93 ✔
3074
                    if (
3075
                        (
3076
                            \is_array($usedArrayTmp)
93 ✔
3077
                            ||
93 ✔
3078
                            $usedArrayTmp instanceof \ArrayAccess
93 ✔
3079
                        )
3080
                        &&
3081
                        isset($usedArrayTmp[$segment])
93 ✔
3082
                    ) {
3083
                        $usedArrayTmp = $usedArrayTmp[$segment];
90 ✔
3084

3085
                        continue;
90 ✔
3086
                    }
3087

3088
                    if (
3089
                        \is_object($usedArrayTmp) === true
42 ✔
3090
                        &&
3091
                        \property_exists($usedArrayTmp, $segment)
42 ✔
3092
                    ) {
3093
                        $usedArrayTmp = $usedArrayTmp->{$segment};
3 ✔
3094

3095
                        continue;
3 ✔
3096
                    }
3097

3098
                    if (isset($segments[0]) && $segments[0] === '*') {
39 ✔
3099
                        $segmentsTmp = $segments;
3 ✔
3100
                        unset($segmentsTmp[0]);
3 ✔
3101
                        $keyTmp = \implode('.', $segmentsTmp);
3 ✔
3102
                        $returnTmp = static::create(
3 ✔
3103
                            [],
3 ✔
3104
                            $this->iteratorClass,
3 ✔
3105
                            false
3 ✔
3106
                        );
3 ✔
3107
                        foreach ($this->getAll() as $dataTmp) {
3 ✔
3108
                            if ($dataTmp instanceof self) {
3 ✔
UNCOV
3109
                                $returnTmp->add($dataTmp->get($keyTmp));
×
3110

UNCOV
3111
                                continue;
×
3112
                            }
3113

3114
                            if (
3115
                                (
3116
                                    \is_array($dataTmp)
3 ✔
3117
                                    ||
3 ✔
3118
                                    $dataTmp instanceof \ArrayAccess
3 ✔
3119
                                )
3120
                                &&
3121
                                isset($dataTmp[$keyTmp])
3 ✔
3122
                            ) {
UNCOV
3123
                                $returnTmp->add($dataTmp[$keyTmp]);
×
3124

UNCOV
3125
                                continue;
×
3126
                            }
3127

3128
                            if (
3129
                                \is_object($dataTmp) === true
3 ✔
3130
                                &&
3131
                                \property_exists($dataTmp, $keyTmp)
3 ✔
3132
                            ) {
3133
                                $returnTmp->add($dataTmp->{$keyTmp});
3 ✔
3134

3135
                                continue;
3 ✔
3136
                            }
3137
                        }
3138

3139
                        if ($returnTmp->count() > 0) {
3 ✔
3140
                            return $returnTmp;
3 ✔
3141
                        }
3142
                    }
3143

3144
                    return $fallback instanceof \Closure ? $fallback() : $fallback;
36 ✔
3145
                }
3146
            }
3147
        }
3148

3149
        if (isset($usedArrayTmp)) {
174 ✔
3150
            if (!$usePath && !isset($usedArrayTmp[$key])) {
84 ✔
UNCOV
3151
                return $fallback instanceof \Closure ? $fallback() : $fallback;
×
3152
            }
3153

3154
            if (\is_array($usedArrayTmp)) {
84 ✔
3155
                return static::create(
18 ✔
3156
                    [],
18 ✔
3157
                    $this->iteratorClass,
18 ✔
3158
                    false
18 ✔
3159
                )->createByReference($usedArrayTmp);
18 ✔
3160
            }
3161

3162
            return $usedArrayTmp;
84 ✔
3163
        }
3164

3165
        if (!$usePath && !isset($usedArray[$key])) {
90 ✔
3166
            return $fallback instanceof \Closure ? $fallback() : $fallback;
90 ✔
3167
        }
3168

3169
        return static::create(
×
3170
            [],
×
3171
            $this->iteratorClass,
×
3172
            false
×
UNCOV
3173
        )->createByReference($usedArray);
×
3174
    }
3175

3176
    /**
3177
     * alias: for "Arrayy->toArray()"
3178
     *
3179
     * @return array
3180
     *
3181
     * @see          Arrayy::getArray()
3182
     *
3183
     * @phpstan-return array<TKey,T>
3184
     */
3185
    public function getAll(): array
3186
    {
3187
        /** @var array<TKey,T> $return */
3188
        $return = $this->toArray();
45 ✔
3189

3190
        return $return;
45 ✔
3191
    }
3192

3193
    /**
3194
     * Get the current array from the "Arrayy"-object.
3195
     *
3196
     * alias for "toArray()"
3197
     *
3198
     * @param bool $convertAllArrayyElements <p>
3199
     *                                       Convert all Child-"Arrayy" objects also to arrays.
3200
     *                                       </p>
3201
     * @param bool $preserveKeys             <p>
3202
     *                                       e.g.: A generator maybe return the same key more than once,
3203
     *                                       so maybe you will ignore the keys.
3204
     *                                       </p>
3205
     *
3206
     * @return array
3207
     *
3208
     * @phpstan-return array<array-key,T>|array<TKey,T>
3209
     * @psalm-mutation-free
3210
     *
3211
     * @see Arrayy::toArray()
3212
     */
3213
    public function getArray(
3214
        bool $convertAllArrayyElements = false,
3215
        bool $preserveKeys = true
3216
    ): array {
3217
        return $this->toArray(
1,554 ✔
3218
            $convertAllArrayyElements,
1,554 ✔
3219
            $preserveKeys
1,554 ✔
3220
        );
1,554 ✔
3221
    }
3222

3223
    /**
3224
     * @param string $json
3225
     *
3226
     * @return static
3227
     *                <p>(Immutable)</p>
3228
     */
3229
    public static function createFromJsonMapper(string $json)
3230
    {
3231
        // init
3232
        $class = static::create();
12 ✔
3233

3234
        $jsonObject = \json_decode($json, false);
12 ✔
3235

3236
        $mapper = new \Arrayy\Mapper\Json();
12 ✔
3237
        $mapper->undefinedPropertyHandler = static function ($object, $key, $jsonValue) use ($class) {
12 ✔
3238
            if ($class->checkPropertiesMismatchInConstructor) {
×
UNCOV
3239
                throw new \TypeError('Property mismatch - input: ' . \print_r(['key' => $key, 'jsonValue' => $jsonValue], true) . ' for object: ' . \get_class($object));
×
3240
            }
3241
        };
12 ✔
3242

3243
        /** @var static $return - hack for phpstan */
3244
        $return = $mapper->map($jsonObject, $class);
12 ✔
3245

3246
        return $return;
12 ✔
3247
    }
3248

3249
    /**
3250
     * @return array<array-key,TypeCheckInterface>|TypeCheckArray<array-key,TypeCheckInterface>
3251
     *
3252
     * @internal
3253
     */
3254
    public function getPhpDocPropertiesFromClass()
3255
    {
3256
        if ($this->properties === []) {
24 ✔
3257
            $this->properties = $this->getPropertiesFromPhpDoc();
6 ✔
3258
        }
3259

3260
        return $this->properties;
24 ✔
3261
    }
3262

3263
    /**
3264
     * Get the current array from the "Arrayy"-object as list.
3265
     *
3266
     * alias for "toList()"
3267
     *
3268
     * @param bool $convertAllArrayyElements <p>
3269
     *                                       Convert all Child-"Arrayy" objects also to arrays.
3270
     *                                       </p>
3271
     *
3272
     * @return array
3273
     *
3274
     * @phpstan-return list<T>
3275
     * @psalm-mutation-free
3276
     *
3277
     * @see Arrayy::toList()
3278
     */
3279
    public function getList(bool $convertAllArrayyElements = false): array
3280
    {
3281
        return $this->toList($convertAllArrayyElements);
3 ✔
3282
    }
3283

3284
    /**
3285
     * Returns the values from a single column of the input array, identified by
3286
     * the $columnKey, can be used to extract data-columns from multi-arrays.
3287
     *
3288
     * EXAMPLE: <code>
3289
     * a([['foo' => 'bar', 'id' => 1], ['foo => 'lall', 'id' => 2]])->getColumn('foo', 'id'); // Arrayy[1 => 'bar', 2 => 'lall']
3290
     * </code>
3291
     *
3292
     * INFO: Optionally, you may provide an $indexKey to index the values in the returned
3293
     *       array by the values from the $indexKey column in the input array.
3294
     *
3295
     * @param int|string|null $columnKey
3296
     * @param int|string|null $indexKey
3297
     *
3298
     * @return static
3299
     *                <p>(Immutable)</p>
3300
     *
3301
     * @phpstan-return static<TKey,T>
3302
     * @psalm-mutation-free
3303
     */
3304
    public function getColumn($columnKey = null, $indexKey = null): self
3305
    {
3306
        if ($columnKey === null && $indexKey === null) {
3 ✔
3307
            $generator = function () {
3 ✔
3308
                foreach ($this->getGenerator() as $value) {
3 ✔
3309
                    yield $value;
3 ✔
3310
                }
3311
            };
3 ✔
3312
        } else {
3313
            $generator = function () use ($columnKey, $indexKey) {
3 ✔
3314
                foreach ($this->getGenerator() as $value) {
3 ✔
3315
                    // reset
3316
                    $newKey = null;
3 ✔
3317
                    $newValue = null;
3 ✔
3318
                    $newValueFound = false;
3 ✔
3319

3320
                    if ($indexKey !== null) {
3 ✔
3321
                        foreach ($value as $keyInner => $valueInner) {
3 ✔
3322
                            if ($indexKey === $keyInner) {
3 ✔
3323
                                $newKey = $valueInner;
3 ✔
3324
                            }
3325

3326
                            if ($columnKey === $keyInner) {
3 ✔
3327
                                $newValue = $valueInner;
3 ✔
3328
                                $newValueFound = true;
3 ✔
3329
                            }
3330
                        }
3331
                    } else {
3332
                        foreach ($value as $keyInner => $valueInner) {
3 ✔
3333
                            if ($columnKey === $keyInner) {
3 ✔
3334
                                $newValue = $valueInner;
3 ✔
3335
                                $newValueFound = true;
3 ✔
3336
                            }
3337
                        }
3338
                    }
3339

3340
                    if ($newValueFound === false) {
3 ✔
3341
                        if ($newKey !== null) {
3 ✔
3342
                            yield $newKey => $value;
3 ✔
3343
                        } else {
3344
                            yield $value;
3 ✔
3345
                        }
3346
                    } else {
3347
                        /** @noinspection NestedPositiveIfStatementsInspection */
3348
                        if ($newKey !== null) {
3 ✔
3349
                            yield $newKey => $newValue;
3 ✔
3350
                        } else {
3351
                            yield $newValue;
3 ✔
3352
                        }
3353
                    }
3354
                }
3355
            };
3 ✔
3356
        }
3357

3358
        return static::create(
3 ✔
3359
            $generator,
3 ✔
3360
            $this->iteratorClass,
3 ✔
3361
            false
3 ✔
3362
        );
3 ✔
3363
    }
3364

3365
    /**
3366
     * Get the current array from the "Arrayy"-object as generator by reference.
3367
     *
3368
     * @return \Generator
3369
     *
3370
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3371
     */
3372
    public function &getGeneratorByReference(): \Generator
3373
    {
3374
        if ($this->generator instanceof ArrayyRewindableGenerator) {
258 ✔
3375
            foreach ($this->generator as $key => $value) {
51 ✔
3376
                yield $key => $value;
51 ✔
3377
            }
3378

3379
            return;
15 ✔
3380
        }
3381

3382
        // -> false-positive -> see "&$value"
3383
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3384
        foreach ($this->array as $key => &$value) {
210 ✔
3385
            yield $key => $value;
189 ✔
3386
        }
3387
    }
3388

3389
    /**
3390
     * Get the current array from the "Arrayy"-object as generator.
3391
     *
3392
     * @return \Generator
3393
     *
3394
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3395
     * @psalm-mutation-free
3396
     */
3397
    public function getGenerator(): \Generator
3398
    {
3399
        if ($this->generator instanceof ArrayyRewindableGenerator) {
3,312 ✔
3400
            yield from $this->generator;
234 ✔
3401

3402
            return;
234 ✔
3403
        }
3404

3405
        yield from $this->array;
3,306 ✔
3406
    }
3407

3408
    /**
3409
     * Get the current array from the "Arrayy"-object as generator.
3410
     *
3411
     * @return \Generator
3412
     *
3413
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3414
     * @psalm-mutation-free
3415
     */
3416
    public function getBackwardsGenerator(): \Generator
3417
    {
3418
        yield from $this->reverseKeepIndex();
12 ✔
3419
    }
3420

3421
    /**
3422
     * alias: for "Arrayy->keys()"
3423
     *
3424
     * @return static
3425
     *                <p>(Immutable)</p>
3426
     *
3427
     * @see          Arrayy::keys()
3428
     *
3429
     * @phpstan-return static<int,TKey>
3430
     * @psalm-mutation-free
3431
     */
3432
    public function getKeys()
3433
    {
3434
        return $this->keys();
6 ✔
3435
    }
3436

3437
    /**
3438
     * Get the current array from the "Arrayy"-object as object.
3439
     *
3440
     * @return \stdClass
3441
     */
3442
    public function getObject(): \stdClass
3443
    {
3444
        return self::arrayToObject($this->toArray());
12 ✔
3445
    }
3446

3447
    /**
3448
     * alias: for "Arrayy->randomImmutable()"
3449
     *
3450
     * @return static
3451
     *                <p>(Immutable)</p>
3452
     *
3453
     * @see          Arrayy::randomImmutable()
3454
     *
3455
     * @phpstan-return static<array-key,T>
3456
     */
3457
    public function getRandom(): self
3458
    {
3459
        return $this->randomImmutable();
12 ✔
3460
    }
3461

3462
    /**
3463
     * alias: for "Arrayy->randomKey()"
3464
     *
3465
     * @return mixed|null
3466
     *                    <p>Get a key/index or null if there wasn't a key/index.</p>
3467
     *
3468
     * @phpstan-return null|TKey
3469
     *
3470
     * @see Arrayy::randomKey()
3471
     */
3472
    public function getRandomKey()
3473
    {
3474
        return $this->randomKey();
9 ✔
3475
    }
3476

3477
    /**
3478
     * alias: for "Arrayy->randomKeys()"
3479
     *
3480
     * @param int $number
3481
     *
3482
     * @return static
3483
     *                <p>(Immutable)</p>
3484
     *
3485
     * @see          Arrayy::randomKeys()
3486
     *
3487
     * @phpstan-return static<TKey,T>
3488
     */
3489
    public function getRandomKeys(int $number): self
3490
    {
3491
        return $this->randomKeys($number);
24 ✔
3492
    }
3493

3494
    /**
3495
     * alias: for "Arrayy->randomValue()"
3496
     *
3497
     * @return mixed|null
3498
     *                    <p>Get a random value or null if there wasn't a value.</p>
3499
     *
3500
     * @phpstan-return null|T
3501
     *
3502
     * @see Arrayy::randomValue()
3503
     */
3504
    public function getRandomValue()
3505
    {
3506
        return $this->randomValue();
9 ✔
3507
    }
3508

3509
    /**
3510
     * alias: for "Arrayy->randomValues()"
3511
     *
3512
     * @param int $number
3513
     *
3514
     * @return static
3515
     *                <p>(Immutable)</p>
3516
     *
3517
     * @see          Arrayy::randomValues()
3518
     *
3519
     * @phpstan-return static<TKey,T>
3520
     */
3521
    public function getRandomValues(int $number): self
3522
    {
3523
        return $this->randomValues($number);
18 ✔
3524
    }
3525

3526
    /**
3527
     * Gets all values.
3528
     *
3529
     * @return static
3530
     *                <p>The values of all elements in this array, in the order they
3531
     *                appear in the array.</p>
3532
     *
3533
     * @phpstan-return static<TKey,T>
3534
     */
3535
    public function getValues()
3536
    {
3537
        $this->generatorToArray(false);
12 ✔
3538

3539
        return static::create(
12 ✔
3540
            \array_values($this->array),
12 ✔
3541
            $this->iteratorClass,
12 ✔
3542
            false
12 ✔
3543
        );
12 ✔
3544
    }
3545

3546
    /**
3547
     * Gets all values via Generator.
3548
     *
3549
     * @return \Generator
3550
     *                    <p>The values of all elements in this array, in the order they
3551
     *                    appear in the array as Generator.</p>
3552
     *
3553
     * @phpstan-return \Generator<TKey,T>
3554
     */
3555
    public function getValuesYield(): \Generator
3556
    {
3557
        yield from $this->getGenerator();
12 ✔
3558
    }
3559

3560
    /**
3561
     * Group values from a array according to the results of a closure.
3562
     *
3563
     * @param callable|int|string $grouper  <p>A callable function name.</p>
3564
     * @param bool                $saveKeys
3565
     *
3566
     * @return static
3567
     *                <p>(Immutable)</p>
3568
     *
3569
     * @phpstan-param \Closure(T,TKey):TKey|TKey $grouper
3570
     * @phpstan-return static<TKey,T>
3571
     * @psalm-mutation-free
3572
     */
3573
    public function group($grouper, bool $saveKeys = false): self
3574
    {
3575
        // init
3576
        $result = [];
12 ✔
3577

3578
        // Iterate over values, group by property/results from closure.
3579
        foreach ($this->getGenerator() as $key => $value) {
12 ✔
3580
            if (\is_callable($grouper) === true) {
12 ✔
3581
                $groupKey = $grouper($value, $key);
9 ✔
3582
            } else {
3583
                $groupKey = $this->get($grouper);
3 ✔
3584
            }
3585

3586
            $newValue = $this->get($groupKey, null, $result);
12 ✔
3587

3588
            if ($groupKey instanceof self) {
12 ✔
UNCOV
3589
                $groupKey = $groupKey->toArray();
×
3590
            }
3591

3592
            if ($newValue instanceof self) {
12 ✔
3593
                $newValue = $newValue->toArray();
12 ✔
3594
            }
3595

3596
            // Add to result.
3597
            if ($groupKey !== null) {
12 ✔
3598
                $result[$groupKey] = $newValue;
9 ✔
3599

3600
                if ($saveKeys) {
9 ✔
3601
                    $result[$groupKey][$key] = $value;
6 ✔
3602
                } else {
3603
                    $result[$groupKey][] = $value;
3 ✔
3604
                }
3605
            }
3606
        }
3607

3608
        return static::create(
12 ✔
3609
            $result,
12 ✔
3610
            $this->iteratorClass,
12 ✔
3611
            false
12 ✔
3612
        );
12 ✔
3613
    }
3614

3615
    /**
3616
     * Check if an array has a given key.
3617
     *
3618
     * @param mixed $key
3619
     *
3620
     * @return bool
3621
     *
3622
     * @phpstan-param null|TKey|TKey[] $key
3623
     */
3624
    public function has($key): bool
3625
    {
3626
        static $UN_FOUND = null;
90 ✔
3627

3628
        if ($UN_FOUND === null) {
90 ✔
3629
            // Generate unique string to use as marker.
3630
            $UN_FOUND = 'arrayy--' . \uniqid('arrayy', true);
3 ✔
3631
        }
3632

3633
        if (\is_array($key)) {
90 ✔
3634
            if ($key === []) {
3 ✔
UNCOV
3635
                return false;
×
3636
            }
3637

3638
            foreach ($key as $keyTmp) {
3 ✔
3639
                $found = ($this->get($keyTmp, $UN_FOUND) !== $UN_FOUND);
3 ✔
3640
                if ($found === false) {
3 ✔
3641
                    return false;
3 ✔
3642
                }
3643
            }
3644

3645
            return true;
3 ✔
3646
        }
3647

3648
        return $this->get($key, $UN_FOUND) !== $UN_FOUND;
87 ✔
3649
    }
3650

3651
    /**
3652
     * Check if an array has a given value.
3653
     *
3654
     * INFO: If you need to search recursive please use ```contains($value, true)```.
3655
     *
3656
     * @param mixed $value
3657
     *
3658
     * @return bool
3659
     *
3660
     * @phpstan-param T $value
3661
     */
3662
    public function hasValue($value): bool
3663
    {
3664
        return $this->contains($value);
3 ✔
3665
    }
3666

3667
    /**
3668
     * Implodes the values of this array.
3669
     *
3670
     * EXAMPLE: <code>
3671
     * a([0 => -9, 1, 2])->implode('|'); // '-9|1|2'
3672
     * </code>
3673
     *
3674
     * @param string $glue
3675
     * @param string $prefix
3676
     *
3677
     * @return string
3678
     * @psalm-mutation-free
3679
     */
3680
    public function implode(string $glue = '', string $prefix = ''): string
3681
    {
3682
        return $prefix . $this->implode_recursive($glue, $this->toArray(), false);
87 ✔
3683
    }
3684

3685
    /**
3686
     * Implodes the keys of this array.
3687
     *
3688
     * @param string $glue
3689
     *
3690
     * @return string
3691
     * @psalm-mutation-free
3692
     */
3693
    public function implodeKeys(string $glue = ''): string
3694
    {
3695
        return $this->implode_recursive($glue, $this->toArray(), true);
24 ✔
3696
    }
3697

3698
    /**
3699
     * Given a list and an iterate-function that returns
3700
     * a key for each element in the list (or a property name),
3701
     * returns an object with an index of each item.
3702
     *
3703
     * @param int|string $key
3704
     *
3705
     * @return static
3706
     *                <p>(Immutable)</p>
3707
     *
3708
     * @phpstan-param array-key $key
3709
     * @phpstan-return static<TKey,T>
3710
     * @psalm-mutation-free
3711
     */
3712
    public function indexBy($key): self
3713
    {
3714
        // init
3715
        $results = [];
12 ✔
3716

3717
        foreach ($this->getGenerator() as $a) {
12 ✔
3718
            if (\array_key_exists($key, $a) === true) {
12 ✔
3719
                $results[$a[$key]] = $a;
9 ✔
3720
            }
3721
        }
3722

3723
        return static::create(
12 ✔
3724
            $results,
12 ✔
3725
            $this->iteratorClass,
12 ✔
3726
            false
12 ✔
3727
        );
12 ✔
3728
    }
3729

3730
    /**
3731
     * alias: for "Arrayy->searchIndex()"
3732
     *
3733
     * @param mixed $value
3734
     *                     <p>The value to search for.</p>
3735
     *
3736
     * @return false|int|string
3737
     *
3738
     * @phpstan-param T $value
3739
     * @phpstan-return false|TKey
3740
     *
3741
     * @see Arrayy::searchIndex()
3742
     */
3743
    public function indexOf($value)
3744
    {
3745
        return $this->searchIndex($value);
12 ✔
3746
    }
3747

3748
    /**
3749
     * Get everything but the last..$to items.
3750
     *
3751
     * EXAMPLE: <code>
3752
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->initial(2); // Arrayy[0 => 'foo']
3753
     * </code>
3754
     *
3755
     * @param int $to
3756
     *
3757
     * @return static
3758
     *                <p>(Immutable)</p>
3759
     *
3760
     * @phpstan-return static<TKey,T>
3761
     * @psalm-mutation-free
3762
     */
3763
    public function initial(int $to = 1): self
3764
    {
3765
        return $this->firstsImmutable(\count($this->toArray(), \COUNT_NORMAL) - $to);
36 ✔
3766
    }
3767

3768
    /**
3769
     * Return an array with all elements found in input array.
3770
     *
3771
     * EXAMPLE: <code>
3772
     * a(['foo', 'bar'])->intersection(['bar', 'baz']); // Arrayy['bar']
3773
     * </code>
3774
     *
3775
     * @param array $search
3776
     * @param bool  $keepKeys
3777
     *
3778
     * @return static
3779
     *                <p>(Immutable)</p>
3780
     *
3781
     * @phpstan-param  array<TKey,T> $search
3782
     * @phpstan-return static<TKey,T>
3783
     * @psalm-mutation-free
3784
     */
3785
    public function intersection(array $search, bool $keepKeys = false): self
3786
    {
3787
        if ($keepKeys) {
12 ✔
3788
            /**
3789
             * @psalm-suppress MissingClosureReturnType
3790
             * @psalm-suppress MissingClosureParamType
3791
             */
3792
            return static::create(
3 ✔
3793
                \array_uintersect(
3 ✔
3794
                    $this->toArray(),
3 ✔
3795
                    $search,
3 ✔
3796
                    static function ($a, $b) {
3 ✔
3797
                        return $a === $b ? 0 : -1;
3 ✔
3798
                    }
3 ✔
3799
                ),
3 ✔
3800
                $this->iteratorClass,
3 ✔
3801
                false
3 ✔
3802
            );
3 ✔
3803
        }
3804

3805
        return static::create(
9 ✔
3806
            \array_values(\array_intersect($this->toArray(), $search)),
9 ✔
3807
            $this->iteratorClass,
9 ✔
3808
            false
9 ✔
3809
        );
9 ✔
3810
    }
3811

3812
    /**
3813
     * Return an array with all elements found in input array.
3814
     *
3815
     * @param array ...$array
3816
     *
3817
     * @return static
3818
     *                <p>(Immutable)</p>
3819
     *
3820
     * @phpstan-param  array<array<TKey,T>> ...$array
3821
     * @phpstan-return static<TKey,T>
3822
     * @psalm-mutation-free
3823
     */
3824
    public function intersectionMulti(...$array): self
3825
    {
3826
        return static::create(
3 ✔
3827
            \array_values(\array_intersect($this->toArray(), ...$array)),
3 ✔
3828
            $this->iteratorClass,
3 ✔
3829
            false
3 ✔
3830
        );
3 ✔
3831
    }
3832

3833
    /**
3834
     * Return a boolean flag which indicates whether the two input arrays have any common elements.
3835
     *
3836
     * EXAMPLE: <code>
3837
     * a(['foo', 'bar'])->intersects(['fΓΆΓΆ', 'bΓ€r']); // false
3838
     * </code>
3839
     *
3840
     * @param array $search
3841
     *
3842
     * @return bool
3843
     *
3844
     * @phpstan-param array<TKey,T> $search
3845
     */
3846
    public function intersects(array $search): bool
3847
    {
3848
        return $this->intersection($search)->count() > 0;
3 ✔
3849
    }
3850

3851
    /**
3852
     * Invoke a function on all of an array's values.
3853
     *
3854
     * @param callable $callable
3855
     * @param mixed    $arguments
3856
     *
3857
     * @return static
3858
     *                <p>(Immutable)</p>
3859
     *
3860
     * @phpstan-param  callable(T,mixed=):mixed $callable
3861
     * @phpstan-return static<int, T>|static<TKey, T>
3862
     * @psalm-mutation-free
3863
     */
3864
    public function invoke($callable, $arguments = []): self
3865
    {
3866
        // If one argument given for each iteration, create an array for it.
3867
        if (!\is_array($arguments)) {
3 ✔
3868
            $arguments = \array_fill(
3 ✔
3869
                0,
3 ✔
3870
                $this->count(),
3 ✔
3871
                $arguments
3 ✔
3872
            );
3 ✔
3873
        }
3874

3875
        // If the callable has arguments, pass them.
3876
        if ($arguments) {
3 ✔
3877
            $array = \array_map($callable, $this->toArray(), $arguments);
3 ✔
3878
        } else {
3879
            $array = $this->map($callable);
3 ✔
3880
        }
3881

3882
        return static::create(
3 ✔
3883
            $array,
3 ✔
3884
            $this->iteratorClass,
3 ✔
3885
            false
3 ✔
3886
        );
3 ✔
3887
    }
3888

3889
    /**
3890
     * Check whether array is associative or not.
3891
     *
3892
     * EXAMPLE: <code>
3893
     * a(['foo' => 'bar', 2, 3])->isAssoc(); // true
3894
     * </code>
3895
     *
3896
     * @param bool $recursive
3897
     *
3898
     * @return bool
3899
     *              <p>Returns true if associative, false otherwise.</p>
3900
     */
3901
    public function isAssoc(bool $recursive = false): bool
3902
    {
3903
        if ($this->isEmpty()) {
45 ✔
3904
            return false;
9 ✔
3905
        }
3906

3907
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3908
        foreach ($this->keys($recursive)->getGeneratorByReference() as &$key) {
39 ✔
3909
            if ((string) $key !== $key) {
39 ✔
3910
                return false;
33 ✔
3911
            }
3912
        }
3913

3914
        return true;
9 ✔
3915
    }
3916

3917
    /**
3918
     * Check if a given key or keys are empty.
3919
     *
3920
     * @param int|int[]|string|string[]|null $keys
3921
     *
3922
     * @return bool
3923
     *              <p>Returns true if empty, false otherwise.</p>
3924
     * @psalm-mutation-free
3925
     */
3926
    public function isEmpty($keys = null): bool
3927
    {
3928
        if ($this->generator) {
135 ✔
UNCOV
3929
            return $this->toArray() === [];
×
3930
        }
3931

3932
        if ($keys === null) {
135 ✔
3933
            return $this->array === [];
129 ✔
3934
        }
3935

3936
        foreach ((array) $keys as $key) {
6 ✔
3937
            if (!empty($this->get($key))) {
6 ✔
3938
                return false;
6 ✔
3939
            }
3940
        }
3941

3942
        return true;
6 ✔
3943
    }
3944

3945
    /**
3946
     * Check if the current array is equal to the given "$array" or not.
3947
     *
3948
     * EXAMPLE: <code>
3949
     * a(['πŸ’©'])->isEqual(['πŸ’©']); // true
3950
     * </code>
3951
     *
3952
     * @param array $array
3953
     *
3954
     * @return bool
3955
     *
3956
     * @phpstan-param array<TKey,T> $array
3957
     */
3958
    public function isEqual(array $array): bool
3959
    {
3960
        return $this->toArray() === $array;
3 ✔
3961
    }
3962

3963
    /**
3964
     * Check if the current array is a multi-array.
3965
     *
3966
     * EXAMPLE: <code>
3967
     * a(['foo' => [1, 2 , 3]])->isMultiArray(); // true
3968
     * </code>
3969
     *
3970
     * @return bool
3971
     */
3972
    public function isMultiArray(): bool
3973
    {
3974
        foreach ($this->getGenerator() as $value) {
66 ✔
3975
            if (\is_array($value)) {
60 ✔
3976
                return true;
15 ✔
3977
            }
3978
        }
3979

3980
        return false;
54 ✔
3981
    }
3982

3983
    /**
3984
     * Check whether array is numeric or not.
3985
     *
3986
     * @return bool
3987
     *              <p>Returns true if numeric, false otherwise.</p>
3988
     */
3989
    public function isNumeric(): bool
3990
    {
3991
        if ($this->isEmpty()) {
15 ✔
3992
            return false;
6 ✔
3993
        }
3994

3995
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3996
        foreach ($this->keys()->getGeneratorByReference() as &$key) {
12 ✔
3997
            if ((int) $key !== $key) {
12 ✔
3998
                return false;
6 ✔
3999
            }
4000
        }
4001

4002
        return true;
6 ✔
4003
    }
4004

4005
    /**
4006
     * Check if the current array is sequential [0, 1, 2, 3, 4, 5 ...] or not.
4007
     *
4008
     * EXAMPLE: <code>
4009
     * a([0 => 'foo', 1 => 'lall', 2 => 'foobar'])->isSequential(); // true
4010
     * </code>
4011
     *
4012
     * INFO: If the array is empty we count it as non-sequential.
4013
     *
4014
     * @param bool $recursive
4015
     *
4016
     * @return bool
4017
     * @psalm-mutation-free
4018
     */
4019
    public function isSequential(bool $recursive = false): bool
4020
    {
4021
        $i = 0;
30 ✔
4022
        foreach ($this->getGenerator() as $key => $value) {
30 ✔
4023
            if (
4024
                $recursive
27 ✔
4025
                &&
4026
                (\is_array($value) || $value instanceof \Traversable)
27 ✔
4027
                &&
4028
                self::create($value)->isSequential() === false
27 ✔
4029
            ) {
4030
                return false;
3 ✔
4031
            }
4032

4033
            if ($key !== $i) {
27 ✔
4034
                return false;
9 ✔
4035
            }
4036

4037
            ++$i;
24 ✔
4038
        }
4039

4040
        return !($i === 0);
27 ✔
4041
    }
4042

4043
    /**
4044
     * @return array
4045
     *
4046
     * @phpstan-return array<TKey,T>
4047
     */
4048
    public function jsonSerialize(): array
4049
    {
4050
        /** @var array<TKey,T> $return */
4051
        $return = $this->toArray();
6 ✔
4052

4053
        return $return;
6 ✔
4054
    }
4055

4056
    /**
4057
     * Gets the key/index of the element at the current internal iterator position.
4058
     *
4059
     * @return int|string|null
4060
     * @phpstan-return array-key|null
4061
     */
4062
    public function key()
4063
    {
4064
        if ($this->generator) {
×
UNCOV
4065
            return $this->generator->key();
×
4066
        }
4067

UNCOV
4068
        return \key($this->array);
×
4069
    }
4070

4071
    /**
4072
     * Checks if the given key exists in the provided array.
4073
     *
4074
     * INFO: This method only use "array_key_exists()" if you want to use "dot"-notation,
4075
     *       then you need to use "Arrayy->offsetExists()".
4076
     *
4077
     * @param int|string $key the key to look for
4078
     *
4079
     * @return bool
4080
     * @psalm-mutation-free
4081
     */
4082
    public function keyExists($key): bool
4083
    {
4084
        foreach ($this->getGenerator() as $keyTmp => $value) {
558 ✔
4085
            if ($key === $keyTmp) {
543 ✔
4086
                return true;
498 ✔
4087
            }
4088
        }
4089

4090
        return false;
429 ✔
4091
    }
4092

4093
    /**
4094
     * Get all keys from the current array.
4095
     *
4096
     * EXAMPLE: <code>
4097
     * a([1 => 'foo', 2 => 'foo2', 3 => 'bar'])->keys(); // Arrayy[1, 2, 3]
4098
     * </code>
4099
     *
4100
     * @param bool       $recursive
4101
     *                                  [optional] <p>
4102
     *                                  Get all keys, also from all sub-arrays from an multi-dimensional array.
4103
     *                                  </p>
4104
     * @param mixed|null $search_values
4105
     *                                  [optional] <p>
4106
     *                                  If specified, then only keys containing these values are returned.
4107
     *                                  </p>
4108
     * @param bool       $strict
4109
     *                                  [optional] <p>
4110
     *                                  Determines if strict comparison (===) should be used during the search.
4111
     *                                  </p>
4112
     *
4113
     * @return static
4114
     *                <p>(Immutable) An array of all the keys in input.</p>
4115
     *
4116
     * @phpstan-param null|T|T[] $search_values
4117
     * @phpstan-return static<int,TKey>
4118
     *
4119
     * @psalm-mutation-free
4120
     */
4121
    public function keys(
4122
        bool $recursive = false,
4123
        $search_values = null,
4124
        bool $strict = true
4125
    ): self {
4126
        // recursive
4127

4128
        if ($recursive === true) {
87 ✔
4129
            $array = $this->array_keys_recursive(
12 ✔
4130
                null,
12 ✔
4131
                $search_values,
12 ✔
4132
                $strict
12 ✔
4133
            );
12 ✔
4134

4135
            return static::create(
12 ✔
4136
                $array,
12 ✔
4137
                $this->iteratorClass,
12 ✔
4138
                false
12 ✔
4139
            );
12 ✔
4140
        }
4141

4142
        // non recursive
4143

4144
        if ($search_values === null) {
84 ✔
4145
            $arrayFunction = function (): \Generator {
84 ✔
4146
                foreach ($this->getGenerator() as $key => $value) {
84 ✔
4147
                    yield $key;
78 ✔
4148
                }
4149
            };
84 ✔
4150
        } else {
4151
            $arrayFunction = function () use ($search_values, $strict): \Generator {
3 ✔
4152
                $is_array_tmp = \is_array($search_values);
3 ✔
4153

4154
                /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4155
                foreach ($this->getGeneratorByReference() as $key => &$value) {
3 ✔
4156
                    if (
4157
                        (
4158
                            $is_array_tmp === false
3 ✔
4159
                            &&
3 ✔
4160
                            $strict === true
3 ✔
4161
                            &&
3 ✔
4162
                            $search_values === $value
3 ✔
4163
                        )
4164
                        ||
4165
                        (
4166
                            $is_array_tmp === false
3 ✔
4167
                            &&
3 ✔
4168
                            $strict === false
3 ✔
4169
                            &&
3 ✔
4170
                            $search_values == $value
3 ✔
4171
                        )
4172
                        ||
4173
                        (
4174
                            $is_array_tmp === true
3 ✔
4175
                            &&
3 ✔
4176
                            \in_array($value, $search_values, $strict)
3 ✔
4177
                        )
4178
                    ) {
4179
                        yield $key;
3 ✔
4180
                    }
4181
                }
4182
            };
3 ✔
4183
        }
4184

4185
        return static::create(
84 ✔
4186
            $arrayFunction,
84 ✔
4187
            $this->iteratorClass,
84 ✔
4188
            false
84 ✔
4189
        );
84 ✔
4190
    }
4191

4192
    /**
4193
     * Sort an array by key in reverse order.
4194
     *
4195
     * @param int $sort_flags [optional] <p>
4196
     *                        You may modify the behavior of the sort using the optional
4197
     *                        parameter sort_flags, for details
4198
     *                        see sort.
4199
     *                        </p>
4200
     *
4201
     * @return $this
4202
     *               <p>(Mutable) Return this Arrayy object.</p>
4203
     *
4204
     * @phpstan-return static<TKey,T>
4205
     */
4206
    public function krsort(int $sort_flags = 0): self
4207
    {
4208
        $this->generatorToArray();
12 ✔
4209

4210
        \krsort($this->array, $sort_flags);
12 ✔
4211

4212
        return $this;
12 ✔
4213
    }
4214

4215
    /**
4216
     * Sort an array by key in reverse order.
4217
     *
4218
     * @param int $sort_flags [optional] <p>
4219
     *                        You may modify the behavior of the sort using the optional
4220
     *                        parameter sort_flags, for details
4221
     *                        see sort.
4222
     *                        </p>
4223
     *
4224
     * @return $this
4225
     *               <p>(Immutable)</p>
4226
     *
4227
     * @phpstan-return static<TKey,T>
4228
     * @psalm-mutation-free
4229
     */
4230
    public function krsortImmutable(int $sort_flags = 0): self
4231
    {
4232
        $that = clone $this;
12 ✔
4233

4234
        /**
4235
         * @psalm-suppress ImpureMethodCall - object is already cloned
4236
         */
4237
        $that->krsort($sort_flags);
12 ✔
4238

4239
        return $that;
12 ✔
4240
    }
4241

4242
    /**
4243
     * Get the last value from the current array.
4244
     *
4245
     * EXAMPLE: <code>
4246
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->last(); // 'lall'
4247
     * </code>
4248
     *
4249
     * @return mixed|null
4250
     *                    <p>Return null if there wasn't a element.</p>
4251
     *
4252
     * @phpstan-return T|null
4253
     * @psalm-mutation-free
4254
     */
4255
    public function last()
4256
    {
4257
        $key_last = $this->lastKey();
51 ✔
4258
        if ($key_last === null) {
51 ✔
4259
            return null;
6 ✔
4260
        }
4261

4262
        /** @var T $value_last */
4263
        $value_last = $this->get($key_last);
45 ✔
4264

4265
        return $value_last;
45 ✔
4266
    }
4267

4268
    /**
4269
     * Get the last key from the current array.
4270
     *
4271
     * @return mixed|null
4272
     *                    <p>Return null if there wasn't a element.</p>
4273
     *
4274
     * @phpstan-return null|TKey
4275
     * @psalm-mutation-free
4276
     */
4277
    public function lastKey()
4278
    {
4279
        $this->generatorToArray();
63 ✔
4280

4281
        return \array_key_last($this->array);
63 ✔
4282
    }
4283

4284
    /**
4285
     * Get the last value(s) from the current array.
4286
     *
4287
     * EXAMPLE: <code>
4288
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->lasts(2); // Arrayy[0 => 'bar', 1 => 'lall']
4289
     * </code>
4290
     *
4291
     * @param int|null $number
4292
     *
4293
     * @return static
4294
     *                <p>(Immutable)</p>
4295
     *
4296
     * @phpstan-return static<TKey,T>
4297
     * @psalm-mutation-free
4298
     */
4299
    public function lastsImmutable(?int $number = null): self
4300
    {
4301
        if ($this->isEmpty()) {
39 ✔
4302
            return static::create(
3 ✔
4303
                [],
3 ✔
4304
                $this->iteratorClass,
3 ✔
4305
                false
3 ✔
4306
            );
3 ✔
4307
        }
4308

4309
        if ($number === null) {
36 ✔
4310
            $poppedValue = $this->last();
24 ✔
4311

4312
            if ($poppedValue === null) {
24 ✔
4313
                $poppedValue = [$poppedValue];
3 ✔
4314
            } else {
4315
                $poppedValue = (array) $poppedValue;
21 ✔
4316
            }
4317

4318
            $arrayy = static::create(
24 ✔
4319
                $poppedValue,
24 ✔
4320
                $this->iteratorClass,
24 ✔
4321
                false
24 ✔
4322
            );
24 ✔
4323
        } else {
4324
            $arrayy = $this->rest(-$number);
12 ✔
4325
        }
4326

4327
        return $arrayy;
36 ✔
4328
    }
4329

4330
    /**
4331
     * Get the last value(s) from the current array.
4332
     *
4333
     * EXAMPLE: <code>
4334
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->lasts(2); // Arrayy[0 => 'bar', 1 => 'lall']
4335
     * </code>
4336
     *
4337
     * @param int|null $number
4338
     *
4339
     * @return $this
4340
     *               <p>(Mutable)</p>
4341
     *
4342
     * @phpstan-return static<TKey,T>
4343
     */
4344
    public function lastsMutable(?int $number = null): self
4345
    {
4346
        if ($this->isEmpty()) {
39 ✔
4347
            return $this;
3 ✔
4348
        }
4349

4350
        $this->array = $this->lastsImmutable($number)->toArray();
36 ✔
4351
        $this->generator = null;
36 ✔
4352

4353
        return $this;
36 ✔
4354
    }
4355

4356
    /**
4357
     * Count the values from the current array.
4358
     *
4359
     * alias: for "Arrayy->count()"
4360
     *
4361
     * @param int $mode
4362
     *
4363
     * @return int
4364
     *
4365
     * @see Arrayy::count()
4366
     */
4367
    public function length(int $mode = \COUNT_NORMAL): int
4368
    {
4369
        return $this->count($mode);
60 ✔
4370
    }
4371

4372
    /**
4373
     * Apply the given function to the every element of the array,
4374
     * collecting the results.
4375
     *
4376
     * EXAMPLE: <code>
4377
     * a(['foo', 'Foo'])->map('mb_strtoupper'); // Arrayy['FOO', 'FOO']
4378
     * </code>
4379
     *
4380
     * @param callable $callable
4381
     * @param bool     $useKeyAsSecondParameter
4382
     * @param mixed    ...$arguments
4383
     *
4384
     * @return static
4385
     *                <p>(Immutable) Arrayy object with modified elements.</p>
4386
     *
4387
     * @template T2
4388
     *              <p>The output value type.</p>
4389
     *
4390
     * @phpstan-param callable(T,TKey=,mixed=):T2 $callable
4391
     * @phpstan-return static<TKey,T2>
4392
     * @psalm-mutation-free
4393
     */
4394
    public function map(
4395
        callable $callable,
4396
        bool $useKeyAsSecondParameter = false,
4397
        ...$arguments
4398
    ) {
4399
        /**
4400
         * @psalm-suppress ImpureFunctionCall - func_num_args is only used to detect the number of args
4401
         */
4402
        $useArguments = \func_num_args() > 2;
21 ✔
4403

4404
        return static::create(
21 ✔
4405
            function () use ($useArguments, $callable, $useKeyAsSecondParameter, $arguments) {
21 ✔
4406
                foreach ($this->getGenerator() as $key => $value) {
21 ✔
4407
                    if ($useArguments) {
18 ✔
4408
                        if ($useKeyAsSecondParameter) {
9 ✔
UNCOV
4409
                            yield $key => $callable($value, $key, ...$arguments);
×
4410
                        } else {
4411
                            yield $key => $callable($value, ...$arguments);
9 ✔
4412
                        }
4413
                    } else {
4414
                        /** @noinspection NestedPositiveIfStatementsInspection */
4415
                        if ($useKeyAsSecondParameter) {
18 ✔
UNCOV
4416
                            yield $key => $callable($value, $key);
×
4417
                        } else {
4418
                            yield $key => $callable($value);
18 ✔
4419
                        }
4420
                    }
4421
                }
4422
            },
21 ✔
4423
            $this->iteratorClass,
21 ✔
4424
            false
21 ✔
4425
        );
21 ✔
4426
    }
4427

4428
    /**
4429
     * Check if all items in current array match a truth test.
4430
     *
4431
     * EXAMPLE: <code>
4432
     * $closure = function ($value, $key) {
4433
     *     return ($value % 2 === 0);
4434
     * };
4435
     * a([2, 4, 8])->matches($closure); // true
4436
     * </code>
4437
     *
4438
     * @param \Closure $closure
4439
     *
4440
     * @return bool
4441
     *
4442
     * @phpstan-param \Closure(T,TKey):bool $closure
4443
     */
4444
    public function matches(\Closure $closure): bool
4445
    {
4446
        if ($this->count() === 0) {
45 ✔
4447
            return false;
6 ✔
4448
        }
4449

4450
        foreach ($this->getGenerator() as $key => $value) {
39 ✔
4451
            $value = $closure($value, $key);
39 ✔
4452

4453
            if ($value === false) {
39 ✔
4454
                return false;
21 ✔
4455
            }
4456
        }
4457

4458
        return true;
21 ✔
4459
    }
4460

4461
    /**
4462
     * Check if any item in the current array matches a truth test.
4463
     *
4464
     * EXAMPLE: <code>
4465
     * $closure = function ($value, $key) {
4466
     *     return ($value % 2 === 0);
4467
     * };
4468
     * a([1, 4, 7])->matches($closure); // true
4469
     * </code>
4470
     *
4471
     * @param \Closure $closure
4472
     *
4473
     * @return bool
4474
     *
4475
     * @phpstan-param \Closure(T,TKey):bool $closure
4476
     */
4477
    public function matchesAny(\Closure $closure): bool
4478
    {
4479
        if ($this->count() === 0) {
42 ✔
4480
            return false;
6 ✔
4481
        }
4482

4483
        foreach ($this->getGenerator() as $key => $value) {
36 ✔
4484
            $value = $closure($value, $key);
36 ✔
4485

4486
            if ($value === true) {
36 ✔
4487
                return true;
27 ✔
4488
            }
4489
        }
4490

4491
        return false;
12 ✔
4492
    }
4493

4494
    /**
4495
     * Get the max value from an array.
4496
     *
4497
     * EXAMPLE: <code>
4498
     * a([-9, -8, -7, 1.32])->max(); // 1.32
4499
     * </code>
4500
     *
4501
     * @return false|float|int|string
4502
     *                                <p>Will return false if there are no values.</p>
4503
     */
4504
    public function max()
4505
    {
4506
        if ($this->count() === 0) {
33 ✔
4507
            return false;
3 ✔
4508
        }
4509

4510
        $max = false;
30 ✔
4511
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4512
        foreach ($this->getGeneratorByReference() as &$value) {
30 ✔
4513
            if (
4514
                $max === false
30 ✔
4515
                ||
4516
                $value > $max
30 ✔
4517
            ) {
4518
                $max = $value;
30 ✔
4519
            }
4520
        }
4521

4522
        return $max;
30 ✔
4523
    }
4524

4525
    /**
4526
     * Merge the new $array into the current array.
4527
     *
4528
     * - keep key,value from the current array, also if the index is in the new $array
4529
     *
4530
     * EXAMPLE: <code>
4531
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4532
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4533
     * a($array1)->mergeAppendKeepIndex($array2); // Arrayy[1 => 'one', 'foo' => 'bar2', 3 => 'three']
4534
     * // ---
4535
     * $array1 = [0 => 'one', 1 => 'foo'];
4536
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4537
     * a($array1)->mergeAppendKeepIndex($array2); // Arrayy[0 => 'foo', 1 => 'bar2']
4538
     * </code>
4539
     *
4540
     * @param array $array
4541
     * @param bool  $recursive
4542
     *
4543
     * @return static
4544
     *                <p>(Immutable)</p>
4545
     *
4546
     * @phpstan-param  array<int|TKey,T> $array
4547
     * @phpstan-return static<int|TKey,T>
4548
     * @psalm-mutation-free
4549
     */
4550
    public function mergeAppendKeepIndex(array $array = [], bool $recursive = false): self
4551
    {
4552
        if ($recursive === true) {
99 ✔
4553
            $array = $this->getArrayRecursiveHelperArrayy($array);
27 ✔
4554
            $result = \array_replace_recursive($this->toArray(), $array);
27 ✔
4555
        } else {
4556
            $result = \array_replace($this->toArray(), $array);
72 ✔
4557
        }
4558

4559
        return static::create(
99 ✔
4560
            $result,
99 ✔
4561
            $this->iteratorClass,
99 ✔
4562
            false
99 ✔
4563
        );
99 ✔
4564
    }
4565

4566
    /**
4567
     * Merge the new $array into the current array.
4568
     *
4569
     * - replace duplicate assoc-keys from the current array with the key,values from the new $array
4570
     * - create new indexes
4571
     *
4572
     * EXAMPLE: <code>
4573
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4574
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4575
     * a($array1)->mergeAppendNewIndex($array2); // Arrayy[0 => 'one', 'foo' => 'bar2', 1 => 'three']
4576
     * // ---
4577
     * $array1 = [0 => 'one', 1 => 'foo'];
4578
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4579
     * a($array1)->mergeAppendNewIndex($array2); // Arrayy[0 => 'one', 1 => 'foo', 2 => 'foo', 3 => 'bar2']
4580
     * </code>
4581
     *
4582
     * @param array $array
4583
     * @param bool  $recursive
4584
     *
4585
     * @return static
4586
     *                <p>(Immutable)</p>
4587
     *
4588
     * @phpstan-param  array<TKey,T> $array
4589
     * @phpstan-return static<int,T>
4590
     * @psalm-mutation-free
4591
     */
4592
    public function mergeAppendNewIndex(array $array = [], bool $recursive = false): self
4593
    {
4594
        if ($recursive === true) {
60 ✔
4595
            $array = $this->getArrayRecursiveHelperArrayy($array);
15 ✔
4596
            $result = \array_merge_recursive($this->toArray(), $array);
15 ✔
4597
        } else {
4598
            $result = \array_merge($this->toArray(), $array);
45 ✔
4599
        }
4600

4601
        return static::create(
60 ✔
4602
            $result,
60 ✔
4603
            $this->iteratorClass,
60 ✔
4604
            false
60 ✔
4605
        );
60 ✔
4606
    }
4607

4608
    /**
4609
     * Merge the the current array into the $array.
4610
     *
4611
     * - use key,value from the new $array, also if the index is in the current array
4612
     *
4613
     * EXAMPLE: <code>
4614
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4615
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4616
     * a($array1)->mergePrependKeepIndex($array2); // Arrayy['foo' => 'bar1', 3 => 'three', 1 => 'one']
4617
     * // ---
4618
     * $array1 = [0 => 'one', 1 => 'foo'];
4619
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4620
     * a($array1)->mergePrependKeepIndex($array2); // Arrayy[0 => 'one', 1 => 'foo']
4621
     * </code>
4622
     *
4623
     * @param array $array
4624
     * @param bool  $recursive
4625
     *
4626
     * @return static
4627
     *                <p>(Immutable)</p>
4628
     *
4629
     * @phpstan-param  array<TKey,T> $array
4630
     * @phpstan-return static<TKey,T>
4631
     * @psalm-mutation-free
4632
     */
4633
    public function mergePrependKeepIndex(array $array = [], bool $recursive = false): self
4634
    {
4635
        if ($recursive === true) {
51 ✔
4636
            $array = $this->getArrayRecursiveHelperArrayy($array);
12 ✔
4637
            $result = \array_replace_recursive($array, $this->toArray());
12 ✔
4638
        } else {
4639
            $result = \array_replace($array, $this->toArray());
39 ✔
4640
        }
4641

4642
        return static::create(
51 ✔
4643
            $result,
51 ✔
4644
            $this->iteratorClass,
51 ✔
4645
            false
51 ✔
4646
        );
51 ✔
4647
    }
4648

4649
    /**
4650
     * Merge the current array into the new $array.
4651
     *
4652
     * - replace duplicate assoc-keys from new $array with the key,values from the current array
4653
     * - create new indexes
4654
     *
4655
     * EXAMPLE: <code>
4656
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4657
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4658
     * a($array1)->mergePrependNewIndex($array2); // Arrayy['foo' => 'bar1', 0 => 'three', 1 => 'one']
4659
     * // ---
4660
     * $array1 = [0 => 'one', 1 => 'foo'];
4661
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4662
     * a($array1)->mergePrependNewIndex($array2); // Arrayy[0 => 'foo', 1 => 'bar2', 2 => 'one', 3 => 'foo']
4663
     * </code>
4664
     *
4665
     * @param array $array
4666
     * @param bool  $recursive
4667
     *
4668
     * @return static
4669
     *                <p>(Immutable)</p>
4670
     *
4671
     * @phpstan-param  array<TKey,T> $array
4672
     * @phpstan-return static<int,T>
4673
     * @psalm-mutation-free
4674
     */
4675
    public function mergePrependNewIndex(array $array = [], bool $recursive = false): self
4676
    {
4677
        if ($recursive === true) {
63 ✔
4678
            $array = $this->getArrayRecursiveHelperArrayy($array);
21 ✔
4679
            $result = \array_merge_recursive($array, $this->toArray());
21 ✔
4680
        } else {
4681
            $result = \array_merge($array, $this->toArray());
42 ✔
4682
        }
4683

4684
        return static::create(
63 ✔
4685
            $result,
63 ✔
4686
            $this->iteratorClass,
63 ✔
4687
            false
63 ✔
4688
        );
63 ✔
4689
    }
4690

4691
    /**
4692
     * @return ArrayyMeta|mixed|static
4693
     */
4694
    public static function meta()
4695
    {
4696
        return (new ArrayyMeta())->getMetaObject(static::class);
57 ✔
4697
    }
4698

4699
    /**
4700
     * Get the min value from an array.
4701
     *
4702
     * EXAMPLE: <code>
4703
     * a([-9, -8, -7, 1.32])->min(); // -9
4704
     * </code>
4705
     *
4706
     * @return false|mixed
4707
     *                     <p>Will return false if there are no values.</p>
4708
     *
4709
     * @phpstan-return false|T
4710
     */
4711
    public function min()
4712
    {
4713
        if ($this->count() === 0) {
33 ✔
4714
            return false;
3 ✔
4715
        }
4716

4717
        $min = false;
30 ✔
4718
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4719
        foreach ($this->getGeneratorByReference() as &$value) {
30 ✔
4720
            if (
4721
                $min === false
30 ✔
4722
                ||
4723
                $value < $min
30 ✔
4724
            ) {
4725
                $min = $value;
30 ✔
4726
            }
4727
        }
4728

4729
        return $min;
30 ✔
4730
    }
4731

4732
    /**
4733
     * Get the most used value from the array.
4734
     *
4735
     * @return mixed|null
4736
     *                    <p>(Immutable) Return null if there wasn't an element.</p>
4737
     *
4738
     * @phpstan-return T|null
4739
     * @psalm-mutation-free
4740
     */
4741
    public function mostUsedValue()
4742
    {
4743
        /* @phpstan-ignore-next-line | false-positive? maybe because we switch key-value via "countValues"? */
4744
        return $this->countValues()->arsortImmutable()->firstKey();
9 ✔
4745
    }
4746

4747
    /**
4748
     * Get the most used value from the array.
4749
     *
4750
     * @param int|null $number <p>How many values you will take?</p>
4751
     *
4752
     * @return static
4753
     *                <p>(Immutable)</p>
4754
     *
4755
     * @phpstan-return static<array-key,T>
4756
     * @psalm-mutation-free
4757
     */
4758
    public function mostUsedValues(?int $number = null): self
4759
    {
4760
        return $this->countValues()->arsortImmutable()->firstsKeys($number);
9 ✔
4761
    }
4762

4763
    /**
4764
     * Move an array element to a new index.
4765
     *
4766
     * EXAMPLE: <code>
4767
     * $arr2 = new A(['A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e']);
4768
     * $newArr2 = $arr2->moveElement('D', 1); // Arrayy['A' => 'a', 'D' => 'd', 'B' => 'b', 'C' => 'c', 'E' => 'e']
4769
     * </code>
4770
     *
4771
     * @param int|string $from
4772
     * @param int        $to
4773
     *
4774
     * @return static
4775
     *                <p>(Immutable)</p>
4776
     *
4777
     * @phpstan-return static<TKey,T>
4778
     * @psalm-mutation-free
4779
     */
4780
    public function moveElement($from, $to): self
4781
    {
4782
        $array = $this->toArray();
3 ✔
4783

4784
        if ((int) $from === $from) {
3 ✔
4785
            $tmp = \array_splice($array, $from, 1);
3 ✔
4786
            \array_splice($array, (int) $to, 0, $tmp);
3 ✔
4787
            $output = $array;
3 ✔
4788
        } elseif ((string) $from === $from) {
3 ✔
4789
            $indexToMove = \array_search($from, \array_keys($array), true);
3 ✔
4790
            $itemToMove = $array[$from];
3 ✔
4791
            if ($indexToMove !== false) {
3 ✔
4792
                \array_splice($array, $indexToMove, 1);
3 ✔
4793
            }
4794
            $i = 0;
3 ✔
4795
            $output = [];
3 ✔
4796
            foreach ($array as $key => $item) {
3 ✔
4797
                if ($i === $to) {
3 ✔
4798
                    $output[$from] = $itemToMove;
3 ✔
4799
                }
4800
                $output[$key] = $item;
3 ✔
4801
                ++$i;
3 ✔
4802
            }
4803
        } else {
UNCOV
4804
            $output = [];
×
4805
        }
4806

4807
        return static::create(
3 ✔
4808
            $output,
3 ✔
4809
            $this->iteratorClass,
3 ✔
4810
            false
3 ✔
4811
        );
3 ✔
4812
    }
4813

4814
    /**
4815
     * Move an array element to the first place.
4816
     *
4817
     * INFO: Instead of "Arrayy->moveElement()" this method will NOT
4818
     *       loss the keys of an indexed array.
4819
     *
4820
     * @param int|string $key
4821
     *
4822
     * @return static
4823
     *                <p>(Immutable)</p>
4824
     *
4825
     * @phpstan-return static<TKey,T>
4826
     * @psalm-mutation-free
4827
     */
4828
    public function moveElementToFirstPlace($key): self
4829
    {
4830
        $array = $this->toArray();
3 ✔
4831

4832
        if ($this->offsetExists($key)) {
3 ✔
4833
            $tmpValue = $this->get($key);
3 ✔
4834
            unset($array[$key]);
3 ✔
4835
            $array = [$key => $tmpValue] + $array;
3 ✔
4836
        }
4837

4838
        return static::create(
3 ✔
4839
            $array,
3 ✔
4840
            $this->iteratorClass,
3 ✔
4841
            false
3 ✔
4842
        );
3 ✔
4843
    }
4844

4845
    /**
4846
     * Move an array element to the last place.
4847
     *
4848
     * INFO: Instead of "Arrayy->moveElement()" this method will NOT
4849
     *       loss the keys of an indexed array.
4850
     *
4851
     * @param int|string $key
4852
     *
4853
     * @return static
4854
     *                <p>(Immutable)</p>
4855
     *
4856
     * @phpstan-return static<TKey,T>
4857
     * @psalm-mutation-free
4858
     */
4859
    public function moveElementToLastPlace($key): self
4860
    {
4861
        $array = $this->toArray();
3 ✔
4862

4863
        if ($this->offsetExists($key)) {
3 ✔
4864
            $tmpValue = $this->get($key);
3 ✔
4865
            unset($array[$key]);
3 ✔
4866
            $array += [$key => $tmpValue];
3 ✔
4867
        }
4868

4869
        return static::create(
3 ✔
4870
            $array,
3 ✔
4871
            $this->iteratorClass,
3 ✔
4872
            false
3 ✔
4873
        );
3 ✔
4874
    }
4875

4876
    /**
4877
     * Moves the internal iterator position to the next element and returns this element.
4878
     *
4879
     * @return false|mixed
4880
     *                     <p>(Mutable) Will return false if there are no values.</p>
4881
     *
4882
     * @phpstan-return false|T
4883
     */
4884
    public function next()
4885
    {
4886
        if ($this->generator) {
×
UNCOV
4887
            $this->generator->next();
×
4888

UNCOV
4889
            return $this->generator->current() ?? false;
×
4890
        }
4891

UNCOV
4892
        return \next($this->array);
×
4893
    }
4894

4895
    /**
4896
     * Get the next nth keys and values from the array.
4897
     *
4898
     * @param int $step
4899
     * @param int $offset
4900
     *
4901
     * @return static
4902
     *                <p>(Immutable)</p>
4903
     *
4904
     * @phpstan-return static<TKey,T>
4905
     * @psalm-mutation-free
4906
     */
4907
    public function nth(int $step, int $offset = 0): self
4908
    {
4909
        $arrayFunction = function () use ($step, $offset): \Generator {
3 ✔
4910
            $position = 0;
3 ✔
4911
            foreach ($this->getGenerator() as $key => $value) {
3 ✔
4912
                if ($position++ % $step !== $offset) {
3 ✔
4913
                    continue;
3 ✔
4914
                }
4915

4916
                yield $key => $value;
3 ✔
4917
            }
4918
        };
3 ✔
4919

4920
        return static::create(
3 ✔
4921
            $arrayFunction,
3 ✔
4922
            $this->iteratorClass,
3 ✔
4923
            false
3 ✔
4924
        );
3 ✔
4925
    }
4926

4927
    /**
4928
     * Get a subset of the items from the given array.
4929
     *
4930
     * @param int[]|string[] $keys
4931
     *
4932
     * @return static
4933
     *                <p>(Immutable)</p>
4934
     *
4935
     * @phpstan-param array-key[] $keys
4936
     * @phpstan-return static<TKey,T>
4937
     * @psalm-mutation-free
4938
     */
4939
    public function only(array $keys): self
4940
    {
4941
        $keys = \array_flip($keys);
3 ✔
4942

4943
        $generator = function () use ($keys): \Generator {
3 ✔
4944
            foreach ($this->getGenerator() as $key => $value) {
3 ✔
4945
                if (isset($keys[$key])) {
3 ✔
4946
                    yield $key => $value;
3 ✔
4947
                }
4948
            }
4949
        };
3 ✔
4950

4951
        return static::create(
3 ✔
4952
            $generator,
3 ✔
4953
            $this->iteratorClass,
3 ✔
4954
            false
3 ✔
4955
        );
3 ✔
4956
    }
4957

4958
    /**
4959
     * Pad array to the specified size with a given value.
4960
     *
4961
     * @param int   $size  <p>Size of the result array.</p>
4962
     * @param mixed $value <p>Empty value by default.</p>
4963
     *
4964
     * @return static
4965
     *                <p>(Immutable) Arrayy object padded to $size with $value.</p>
4966
     *
4967
     * @phpstan-return static<TKey,T>
4968
     * @psalm-mutation-free
4969
     */
4970
    public function pad(int $size, $value): self
4971
    {
4972
        return static::create(
15 ✔
4973
            \array_pad($this->toArray(), $size, $value),
15 ✔
4974
            $this->iteratorClass,
15 ✔
4975
            false
15 ✔
4976
        );
15 ✔
4977
    }
4978

4979
    /**
4980
     * Partitions this array in two array according to a predicate.
4981
     * Keys are preserved in the resulting array.
4982
     *
4983
     * @param \Closure $closure
4984
     *                          <p>The predicate on which to partition.</p>
4985
     *
4986
     * @return array<int, static>
4987
     *                    <p>An array with two elements. The first element contains the array
4988
     *                    of elements where the predicate returned TRUE, the second element
4989
     *                    contains the array of elements where the predicate returned FALSE.</p>
4990
     *
4991
     * @phpstan-param \Closure(T,TKey):bool $closure
4992
     * @phpstan-return array<int, static<TKey,T>>
4993
     */
4994
    public function partition(\Closure $closure): array
4995
    {
4996
        // init
4997
        $matches = [];
3 ✔
4998
        $noMatches = [];
3 ✔
4999

5000
        foreach ($this->getGenerator() as $key => $value) {
3 ✔
5001
            if ($closure($value, $key)) {
3 ✔
5002
                $matches[$key] = $value;
3 ✔
5003
            } else {
5004
                $noMatches[$key] = $value;
3 ✔
5005
            }
5006
        }
5007

5008
        return [self::create($matches), self::create($noMatches)];
3 ✔
5009
    }
5010

5011
    /**
5012
     * Pop a specified value off the end of the current array.
5013
     *
5014
     * @return mixed|null
5015
     *                    <p>(Mutable) The popped element from the current array or null if the array is e.g. empty.</p>
5016
     *
5017
     * @phpstan-return T|null
5018
     */
5019
    public function pop()
5020
    {
5021
        $this->generatorToArray();
15 ✔
5022

5023
        return \array_pop($this->array);
15 ✔
5024
    }
5025

5026
    /**
5027
     * Prepend a (key) + value to the current array.
5028
     *
5029
     * EXAMPLE: <code>
5030
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->prepend('foo'); // Arrayy[0 => 'foo', 'fΓ²Γ΄' => 'bΓ Ε™']
5031
     * </code>
5032
     *
5033
     * @param mixed $value
5034
     * @param mixed $key
5035
     *
5036
     * @return $this
5037
     *               <p>(Mutable) Return this Arrayy object, with the prepended value.</p>
5038
     *
5039
     * @phpstan-param T $value
5040
     * @phpstan-param TKey|null $key
5041
     * @phpstan-return static<TKey,T>
5042
     */
5043
    public function prepend($value, $key = null)
5044
    {
5045
        $this->generatorToArray();
33 ✔
5046

5047
        if ($this->properties !== []) {
33 ✔
5048
            $this->checkType($key, $value);
9 ✔
5049
        }
5050

5051
        if ($key === null) {
27 ✔
5052
            \array_unshift($this->array, $value);
24 ✔
5053
        } else {
5054
            $this->array = [$key => $value] + $this->array; // @phpstan-ignore-line
6 ✔
5055
        }
5056

5057
        return $this;
27 ✔
5058
    }
5059

5060
    /**
5061
     * Prepend a (key) + value to the current array.
5062
     *
5063
     * EXAMPLE: <code>
5064
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->prependImmutable('foo')->getArray(); // [0 => 'foo', 'fΓ²Γ΄' => 'bΓ Ε™']
5065
     * </code>
5066
     *
5067
     * @param mixed $value
5068
     * @param mixed $key
5069
     *
5070
     * @return $this
5071
     *               <p>(Immutable) Return this Arrayy object, with the prepended value.</p>
5072
     *
5073
     * @phpstan-param T $value
5074
     * @phpstan-param TKey $key
5075
     * @phpstan-return static<TKey,T>
5076
     * @psalm-mutation-free
5077
     */
5078
    public function prependImmutable($value, $key = null)
5079
    {
5080
        $generator = function () use ($key, $value): \Generator {
3 ✔
5081
            if ($this->properties !== []) {
3 ✔
UNCOV
5082
                $this->checkType($key, $value);
×
5083
            }
5084

5085
            if ($key !== null) {
3 ✔
UNCOV
5086
                yield $key => $value;
×
5087
            } else {
5088
                yield $value;
3 ✔
5089
            }
5090

5091
            foreach ($this->getGenerator() as $keyOld => $itemOld) {
3 ✔
5092
                yield $keyOld => $itemOld;
3 ✔
5093
            }
5094
        };
3 ✔
5095

5096
        return static::create(
3 ✔
5097
            $generator,
3 ✔
5098
            $this->iteratorClass,
3 ✔
5099
            false
3 ✔
5100
        );
3 ✔
5101
    }
5102

5103
    /**
5104
     * Add a suffix to each key.
5105
     *
5106
     * @param float|int|string $suffix
5107
     *
5108
     * @return static
5109
     *                <p>(Immutable) Return an Arrayy object, with the prepended keys.</p>
5110
     *
5111
     * @phpstan-return static<TKey,T>
5112
     * @psalm-mutation-free
5113
     */
5114
    public function prependToEachKey($suffix): self
5115
    {
5116
        // init
5117
        $result = [];
30 ✔
5118

5119
        foreach ($this->getGenerator() as $key => $item) {
30 ✔
5120
            if ($item instanceof self) {
27 ✔
UNCOV
5121
                $result[$key] = $item->prependToEachKey($suffix);
×
5122
            } elseif (\is_array($item)) {
27 ✔
5123
                $result[$key] = self::create(
×
5124
                    $item,
×
5125
                    $this->iteratorClass,
×
5126
                    false
×
5127
                )->prependToEachKey($suffix)
×
UNCOV
5128
                    ->toArray();
×
5129
            } else {
5130
                $result[$key . $suffix] = $item;
27 ✔
5131
            }
5132
        }
5133

5134
        return self::create(
30 ✔
5135
            $result,
30 ✔
5136
            $this->iteratorClass,
30 ✔
5137
            false
30 ✔
5138
        );
30 ✔
5139
    }
5140

5141
    /**
5142
     * Add a suffix to each value.
5143
     *
5144
     * @param float|int|string $suffix
5145
     *
5146
     * @return static
5147
     *                <p>(Immutable) Return an Arrayy object, with the prepended values.</p>
5148
     *
5149
     * @phpstan-return static<TKey,T>
5150
     * @psalm-mutation-free
5151
     */
5152
    public function prependToEachValue($suffix): self
5153
    {
5154
        // init
5155
        $result = [];
30 ✔
5156

5157
        foreach ($this->getGenerator() as $key => $item) {
30 ✔
5158
            if ($item instanceof self) {
27 ✔
UNCOV
5159
                $result[$key] = $item->prependToEachValue($suffix);
×
5160
            } elseif (\is_array($item)) {
27 ✔
5161
                $result[$key] = self::create(
×
5162
                    $item,
×
5163
                    $this->iteratorClass,
×
5164
                    false
×
5165
                )->prependToEachValue($suffix)
×
UNCOV
5166
                    ->toArray();
×
5167
            } elseif (\is_object($item) === true) {
27 ✔
5168
                $result[$key] = $item;
3 ✔
5169
            } else {
5170
                $result[$key] = $item . $suffix;
24 ✔
5171
            }
5172
        }
5173

5174
        return self::create(
30 ✔
5175
            $result,
30 ✔
5176
            $this->iteratorClass,
30 ✔
5177
            false
30 ✔
5178
        );
30 ✔
5179
    }
5180

5181
    /**
5182
     * Return the value of a given key and
5183
     * delete the key.
5184
     *
5185
     * @param int|int[]|string|string[]|null $keyOrKeys
5186
     * @param mixed                          $fallback
5187
     *
5188
     * @return mixed
5189
     *
5190
     * @template TFallback $fallback
5191
     * @phpstan-param TFallback $fallback
5192
     * @phpstan-return TFallback|T|T[]
5193
     */
5194
    public function pull($keyOrKeys = null, $fallback = null)
5195
    {
5196
        if ($keyOrKeys === null) {
18 ✔
5197
            $array = $this->toArray();
3 ✔
5198
            $this->clear();
3 ✔
5199

5200
            return $array;
3 ✔
5201
        }
5202

5203
        if (\is_array($keyOrKeys)) {
15 ✔
5204
            $valueOrValues = [];
3 ✔
5205
            foreach ($keyOrKeys as $key) {
3 ✔
5206
                $valueOrValues[] = $this->get($key, $fallback);
3 ✔
5207
                $this->offsetUnset($key);
3 ✔
5208
            }
5209
        } else {
5210
            $valueOrValues = $this->get($keyOrKeys, $fallback);
15 ✔
5211
            $this->offsetUnset($keyOrKeys);
15 ✔
5212
        }
5213

5214
        /** @var T|T[]|TFallback $valueOrValues */
5215
        return $valueOrValues;
15 ✔
5216
    }
5217

5218
    /**
5219
     * Push one or more values onto the end of array at once.
5220
     *
5221
     * @param mixed ...$args
5222
     *
5223
     * @return $this
5224
     *               <p>(Mutable) Return this Arrayy object, with pushed elements to the end of array.</p>
5225
     *
5226
     * @noinspection ReturnTypeCanBeDeclaredInspection
5227
     *
5228
     * @phpstan-param  array<TKey,T> ...$args
5229
     * @phpstan-return static<TKey,T>
5230
     */
5231
    public function push(...$args)
5232
    {
5233
        $this->generatorToArray();
27 ✔
5234

5235
        if (
5236
            $this->checkPropertyTypes
27 ✔
5237
            &&
5238
            $this->properties !== []
27 ✔
5239
        ) {
5240
            foreach ($args as $key => $value) {
9 ✔
5241
                $this->checkType($key, $value);
9 ✔
5242
            }
5243
        }
5244

5245
        \array_push($this->array, ...$args); // @phpstan-ignore-line
24 ✔
5246

5247
        return $this;
24 ✔
5248
    }
5249

5250
    /**
5251
     * Get a random value from the current array.
5252
     *
5253
     * EXAMPLE: <code>
5254
     * a([1, 2, 3, 4])->randomImmutable(2); // e.g.: Arrayy[1, 4]
5255
     * </code>
5256
     *
5257
     * @param int|null $number <p>How many values you will take?</p>
5258
     *
5259
     * @return static
5260
     *                <p>(Immutable)</p>
5261
     *
5262
     * @phpstan-return static<array-key,T>
5263
     */
5264
    public function randomImmutable(?int $number = null): self
5265
    {
5266
        $this->generatorToArray();
57 ✔
5267

5268
        if ($this->count() === 0) {
57 ✔
5269
            return static::create(
3 ✔
5270
                [],
3 ✔
5271
                $this->iteratorClass,
3 ✔
5272
                false
3 ✔
5273
            );
3 ✔
5274
        }
5275

5276
        if ($number === null) {
54 ✔
5277
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
39 ✔
5278

5279
            return static::create(
39 ✔
5280
                $arrayRandValue,
39 ✔
5281
                $this->iteratorClass,
39 ✔
5282
                false
39 ✔
5283
            );
39 ✔
5284
        }
5285

5286
        $arrayTmp = $this->array;
18 ✔
5287
        \shuffle($arrayTmp);
18 ✔
5288

5289
        return static::create(
18 ✔
5290
            $arrayTmp,
18 ✔
5291
            $this->iteratorClass,
18 ✔
5292
            false
18 ✔
5293
        )->firstsImmutable($number);
18 ✔
5294
    }
5295

5296
    /**
5297
     * Pick a random key/index from the keys of this array.
5298
     *
5299
     * EXAMPLE: <code>
5300
     * $arrayy = A::create([1 => 'one', 2 => 'two']);
5301
     * $arrayy->randomKey(); // e.g. 2
5302
     * </code>
5303
     *
5304
     * @throws \RangeException If array is empty
5305
     *
5306
     * @return mixed|null
5307
     *                    <p>Get a key/index or null if there wasn't a key/index.</p>
5308
     *
5309
     * @phpstan-return null|TKey
5310
     */
5311
    public function randomKey()
5312
    {
5313
        $result = $this->randomKeys(1);
12 ✔
5314

5315
        if (!isset($result[0])) {
12 ✔
UNCOV
5316
            $result[0] = null;
×
5317
        }
5318

5319
        return $result[0];
12 ✔
5320
    }
5321

5322
    /**
5323
     * Pick a given number of random keys/indexes out of this array.
5324
     *
5325
     * EXAMPLE: <code>
5326
     * a([1 => 'one', 2 => 'two'])->randomKeys(); // e.g. Arrayy[1, 2]
5327
     * </code>
5328
     *
5329
     * @param int $number <p>The number of keys/indexes (should be <= \count($this->array))</p>
5330
     *
5331
     * @throws \RangeException If array is empty
5332
     *
5333
     * @return static
5334
     *                <p>(Immutable)</p>
5335
     *
5336
     * @phpstan-return static<TKey,T>
5337
     */
5338
    public function randomKeys(int $number): self
5339
    {
5340
        $this->generatorToArray();
39 ✔
5341

5342
        $count = $this->count();
39 ✔
5343

5344
        if (
5345
            $number === 0
39 ✔
5346
            ||
5347
            $number > $count
39 ✔
5348
        ) {
5349
            throw new \RangeException(
6 ✔
5350
                \sprintf(
6 ✔
5351
                    'Number of requested keys (%s) must be equal or lower than number of elements in this array (%s)',
6 ✔
5352
                    $number,
6 ✔
5353
                    $count
6 ✔
5354
                )
6 ✔
5355
            );
6 ✔
5356
        }
5357

5358
        $result = (array) \array_rand($this->array, $number);
33 ✔
5359

5360
        return static::create(
33 ✔
5361
            $result,
33 ✔
5362
            $this->iteratorClass,
33 ✔
5363
            false
33 ✔
5364
        );
33 ✔
5365
    }
5366

5367
    /**
5368
     * Get a random value from the current array.
5369
     *
5370
     * EXAMPLE: <code>
5371
     * a([1, 2, 3, 4])->randomMutable(2); // e.g.: Arrayy[1, 4]
5372
     * </code>
5373
     *
5374
     * @param int|null $number <p>How many values you will take?</p>
5375
     *
5376
     * @return $this
5377
     *               <p>(Mutable) Return this Arrayy object.</p>
5378
     *
5379
     * @phpstan-return static<TKey,T>
5380
     */
5381
    public function randomMutable(?int $number = null): self
5382
    {
5383
        $this->generatorToArray();
51 ✔
5384

5385
        if ($this->count() === 0) {
51 ✔
5386
            return static::create(
×
5387
                [],
×
5388
                $this->iteratorClass,
×
5389
                false
×
UNCOV
5390
            );
×
5391
        }
5392

5393
        if ($number === null) {
51 ✔
5394
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
21 ✔
5395
            $this->array = $arrayRandValue; // @phpstan-ignore-line
21 ✔
5396

5397
            return $this;
21 ✔
5398
        }
5399

5400
        \shuffle($this->array);
33 ✔
5401

5402
        return $this->firstsMutable($number);
33 ✔
5403
    }
5404

5405
    /**
5406
     * Pick a random value from the values of this array.
5407
     *
5408
     * EXAMPLE: <code>
5409
     * a([1 => 'one', 2 => 'two'])->randomValue(); // e.g. 'one'
5410
     * </code>
5411
     *
5412
     * @return mixed
5413
     *               <p>Get a random value or null if there wasn't a value.</p>
5414
     *
5415
     * @phpstan-return T|null
5416
     */
5417
    public function randomValue()
5418
    {
5419
        $result = $this->randomImmutable();
12 ✔
5420

5421
        if (!isset($result[0])) {
12 ✔
UNCOV
5422
            $result[0] = null;
×
5423
        }
5424

5425
        return $result[0];
12 ✔
5426
    }
5427

5428
    /**
5429
     * Pick a given number of random values out of this array.
5430
     *
5431
     * EXAMPLE: <code>
5432
     * a([1 => 'one', 2 => 'two'])->randomValues(); // e.g. Arrayy['one', 'two']
5433
     * </code>
5434
     *
5435
     * @param int $number
5436
     *
5437
     * @return static
5438
     *                <p>(Mutable)</p>
5439
     *
5440
     * @phpstan-return static<TKey,T>
5441
     */
5442
    public function randomValues(int $number): self
5443
    {
5444
        return $this->randomMutable($number);
21 ✔
5445
    }
5446

5447
    /**
5448
     * Get a random value from an array, with the ability to skew the results.
5449
     *
5450
     * EXAMPLE: <code>
5451
     * a([0 => 3, 1 => 4])->randomWeighted([1 => 4]); // e.g.: Arrayy[4] (has a 66% chance of returning 4)
5452
     * </code>
5453
     *
5454
     * @param array    $array
5455
     * @param int|null $number <p>How many values you will take?</p>
5456
     *
5457
     * @return static<int,mixed>
5458
     *                           <p>(Immutable)</p>
5459
     *
5460
     * @phpstan-param  array<(int&T)|(string&T),int> $array
5461
     * @phpstan-return static<array-key,T>
5462
     */
5463
    public function randomWeighted(array $array, ?int $number = null): self
5464
    {
5465
        // init
5466
        $options = [];
27 ✔
5467

5468
        foreach ($array as $option => $weight) {
27 ✔
5469
            /** @phpstan-var T $option - hack: we protect this method via (int&T)|(string&T) */
5470
            if ($this->searchIndex($option) !== false) {
27 ✔
5471
                for ($i = 0; $i < $weight; ++$i) {
6 ✔
5472
                    $options[] = $option;
3 ✔
5473
                }
5474
            }
5475
        }
5476

5477
        return $this->mergeAppendKeepIndex($options)->randomImmutable($number);
27 ✔
5478
    }
5479

5480
    /**
5481
     * Reduce the current array via callable e.g. anonymous-function and return the end result.
5482
     *
5483
     * EXAMPLE: <code>
5484
     * a([1, 2, 3, 4])->reduce(
5485
     *     function ($carry, $item) {
5486
     *         return $carry * $item;
5487
     *     },
5488
     *     1
5489
     * ); // Arrayy[24]
5490
     * </code>
5491
     *
5492
     * @param callable $callable
5493
     * @param mixed    $initial
5494
     *
5495
     * @return static
5496
     *                <p>(Immutable)</p>
5497
     *
5498
     * @template T2
5499
     *              <p>The output value type.</p>
5500
     *
5501
     * @phpstan-param callable(T2, T, TKey): T2 $callable
5502
     * @phpstan-param T2                        $initial
5503
     *
5504
     * @phpstan-return static<TKey,T2>
5505
     * @psalm-mutation-free
5506
     */
5507
    public function reduce($callable, $initial = []): self
5508
    {
5509
        foreach ($this->getGenerator() as $key => $value) {
54 ✔
5510
            $initial = $callable($initial, $value, $key);
51 ✔
5511
        }
5512

5513
        /** @var static<TKey,T2> $return - help for phpstan */
5514
        $return = static::create(
54 ✔
5515
            $initial,
54 ✔
5516
            $this->iteratorClass,
54 ✔
5517
            false
54 ✔
5518
        );
54 ✔
5519

5520
        return $return;
54 ✔
5521
    }
5522

5523
    /**
5524
     * @param bool $unique
5525
     *
5526
     * @return static
5527
     *                <p>(Immutable)</p>
5528
     *
5529
     * @phpstan-return static<int,mixed>
5530
     * @psalm-mutation-free
5531
     */
5532
    public function reduce_dimension(bool $unique = true): self
5533
    {
5534
        // init
5535
        $result = [];
42 ✔
5536

5537
        foreach ($this->getGenerator() as $val) {
42 ✔
5538
            if (\is_array($val)) {
36 ✔
5539
                $result[] = static::create($val)->reduce_dimension($unique)->toArray();
15 ✔
5540
            } else {
5541
                $result[] = [$val];
36 ✔
5542
            }
5543
        }
5544

5545
        $result = $result === [] ? [] : \array_merge(...$result);
42 ✔
5546

5547
        $resultArrayy = static::create($result);
42 ✔
5548

5549
        /**
5550
         * @psalm-suppress ImpureMethodCall - object is already re-created
5551
         * @psalm-suppress InvalidReturnStatement - why?
5552
         */
5553
        return $unique ? $resultArrayy->unique() : $resultArrayy;
42 ✔
5554
    }
5555

5556
    /**
5557
     * Create a numerically re-indexed Arrayy object.
5558
     *
5559
     * EXAMPLE: <code>
5560
     * a([2 => 1, 3 => 2])->reindex(); // Arrayy[0 => 1, 1 => 2]
5561
     * </code>
5562
     *
5563
     * @return $this
5564
     *               <p>(Mutable) Return this Arrayy object, with re-indexed array-elements.</p>
5565
     *
5566
     * @phpstan-return static<TKey,T>
5567
     */
5568
    public function reindex(): self
5569
    {
5570
        $this->generatorToArray(false);
27 ✔
5571

5572
        $this->array = \array_values($this->array);
27 ✔
5573

5574
        return $this;
27 ✔
5575
    }
5576

5577
    /**
5578
     * Return all items that fail the truth test.
5579
     *
5580
     * EXAMPLE: <code>
5581
     * $closure = function ($value) {
5582
     *     return $value % 2 !== 0;
5583
     * }
5584
     * a([1, 2, 3, 4])->reject($closure); // Arrayy[1 => 2, 3 => 4]
5585
     * </code>
5586
     *
5587
     * @param \Closure $closure
5588
     *
5589
     * @return static
5590
     *                <p>(Immutable)</p>
5591
     *
5592
     * @phpstan-param \Closure(T,TKey):bool  $closure
5593
     * @phpstan-return static<TKey,T>
5594
     * @psalm-mutation-free
5595
     */
5596
    public function reject(\Closure $closure): self
5597
    {
5598
        // init
5599
        $filtered = [];
3 ✔
5600

5601
        foreach ($this->getGenerator() as $key => $value) {
3 ✔
5602
            if (!$closure($value, $key)) {
3 ✔
5603
                $filtered[$key] = $value;
3 ✔
5604
            }
5605
        }
5606

5607
        return static::create(
3 ✔
5608
            $filtered,
3 ✔
5609
            $this->iteratorClass,
3 ✔
5610
            false
3 ✔
5611
        );
3 ✔
5612
    }
5613

5614
    /**
5615
     * Remove a value from the current array (optional using dot-notation).
5616
     *
5617
     * EXAMPLE: <code>
5618
     * a([1 => 'bar', 'foo' => 'foo'])->remove(1); // Arrayy['foo' => 'foo']
5619
     * </code>
5620
     *
5621
     * @param mixed $key
5622
     *
5623
     * @return static
5624
     *                <p>(Mutable)</p>
5625
     *
5626
     * @phpstan-param  TKey|TKey[] $key
5627
     * @phpstan-return static<TKey,T>
5628
     */
5629
    public function remove($key)
5630
    {
5631
        // recursive call
5632
        if (\is_array($key)) {
66 ✔
5633
            foreach ($key as $k) {
3 ✔
5634
                $this->internalRemove($k);
3 ✔
5635
            }
5636

5637
            return static::create(
3 ✔
5638
                $this->toArray(),
3 ✔
5639
                $this->iteratorClass,
3 ✔
5640
                false
3 ✔
5641
            );
3 ✔
5642
        }
5643

5644
        $this->internalRemove($key);
63 ✔
5645

5646
        return static::create(
63 ✔
5647
            $this->toArray(),
63 ✔
5648
            $this->iteratorClass,
63 ✔
5649
            false
63 ✔
5650
        );
63 ✔
5651
    }
5652

5653
    /**
5654
     * alias: for "Arrayy->removeValue()"
5655
     *
5656
     * @param mixed $element
5657
     *
5658
     * @return static
5659
     *                <p>(Immutable)</p>
5660
     *
5661
     * @phpstan-param  T $element
5662
     * @phpstan-return static<TKey,T>
5663
     * @psalm-mutation-free
5664
     */
5665
    public function removeElement($element)
5666
    {
5667
        return $this->removeValue($element);
24 ✔
5668
    }
5669

5670
    /**
5671
     * Remove the first value from the current array.
5672
     *
5673
     * EXAMPLE: <code>
5674
     * a([1 => 'bar', 'foo' => 'foo'])->removeFirst(); // Arrayy['foo' => 'foo']
5675
     * </code>
5676
     *
5677
     * @return static
5678
     *                <p>(Immutable)</p>
5679
     *
5680
     * @phpstan-return static<TKey,T>
5681
     * @psalm-mutation-free
5682
     */
5683
    public function removeFirst(): self
5684
    {
5685
        $tmpArray = $this->toArray();
21 ✔
5686

5687
        \array_shift($tmpArray);
21 ✔
5688

5689
        return static::create(
21 ✔
5690
            $tmpArray,
21 ✔
5691
            $this->iteratorClass,
21 ✔
5692
            false
21 ✔
5693
        );
21 ✔
5694
    }
5695

5696
    /**
5697
     * Remove the last value from the current array.
5698
     *
5699
     * EXAMPLE: <code>
5700
     * a([1 => 'bar', 'foo' => 'foo'])->removeLast(); // Arrayy[1 => 'bar']
5701
     * </code>
5702
     *
5703
     * @return static
5704
     *                <p>(Immutable)</p>
5705
     *
5706
     * @phpstan-return static<TKey,T>
5707
     * @psalm-mutation-free
5708
     */
5709
    public function removeLast(): self
5710
    {
5711
        $tmpArray = $this->toArray();
21 ✔
5712

5713
        \array_pop($tmpArray);
21 ✔
5714

5715
        return static::create(
21 ✔
5716
            $tmpArray,
21 ✔
5717
            $this->iteratorClass,
21 ✔
5718
            false
21 ✔
5719
        );
21 ✔
5720
    }
5721

5722
    /**
5723
     * Removes a particular value from an array (numeric or associative).
5724
     *
5725
     * EXAMPLE: <code>
5726
     * a([1 => 'bar', 'foo' => 'foo'])->removeValue('foo'); // Arrayy[1 => 'bar']
5727
     * </code>
5728
     *
5729
     * @param mixed $value
5730
     *
5731
     * @return static
5732
     *                <p>(Immutable)</p>
5733
     *
5734
     * @phpstan-param  T $value
5735
     * @phpstan-return static<TKey,T>
5736
     * @psalm-mutation-free
5737
     */
5738
    public function removeValue($value): self
5739
    {
5740
        $this->generatorToArray();
24 ✔
5741

5742
        // init
5743
        $isSequentialArray = $this->isSequential();
24 ✔
5744

5745
        foreach ($this->array as $key => $item) {
24 ✔
5746
            if ($item === $value) {
21 ✔
5747
                unset($this->array[$key]);
21 ✔
5748
            }
5749
        }
5750

5751
        if ($isSequentialArray) {
24 ✔
5752
            $this->array = \array_values($this->array);
18 ✔
5753
        }
5754

5755
        return static::create(
24 ✔
5756
            $this->array,
24 ✔
5757
            $this->iteratorClass,
24 ✔
5758
            false
24 ✔
5759
        );
24 ✔
5760
    }
5761

5762
    /**
5763
     * Generate array of repeated arrays.
5764
     *
5765
     * @param int $times <p>How many times has to be repeated.</p>
5766
     *
5767
     * @return static
5768
     *                <p>(Immutable)</p>
5769
     *
5770
     * @phpstan-return static<TKey,T>
5771
     * @psalm-mutation-free
5772
     */
5773
    public function repeat($times): self
5774
    {
5775
        if ($times === 0) {
3 ✔
5776
            return static::create([], $this->iteratorClass);
3 ✔
5777
        }
5778

5779
        return static::create(
3 ✔
5780
            \array_fill(0, (int) $times, $this->toArray()),
3 ✔
5781
            $this->iteratorClass,
3 ✔
5782
            false
3 ✔
5783
        );
3 ✔
5784
    }
5785

5786
    /**
5787
     * Replace a key with a new key/value pair.
5788
     *
5789
     * EXAMPLE: <code>
5790
     * $arrayy = a([1 => 'foo', 2 => 'foo2', 3 => 'bar']);
5791
     * $arrayy->replace(2, 'notfoo', 'notbar'); // Arrayy[1 => 'foo', 'notfoo' => 'notbar', 3 => 'bar']
5792
     * </code>
5793
     *
5794
     * @param mixed $oldKey
5795
     * @param mixed $newKey
5796
     * @param mixed $newValue
5797
     *
5798
     * @return static
5799
     *                <p>(Immutable)</p>
5800
     *
5801
     * @phpstan-param TKey $oldKey
5802
     * @phpstan-param TKey $newKey
5803
     * @phpstan-param T $newValue
5804
     * @phpstan-return static<TKey,T>
5805
     * @psalm-mutation-free
5806
     */
5807
    public function replace($oldKey, $newKey, $newValue): self
5808
    {
5809
        $that = clone $this;
15 ✔
5810

5811
        /**
5812
         * @psalm-suppress ImpureMethodCall - object is already cloned
5813
         */
5814
        return $that->remove($oldKey)
15 ✔
5815
            ->set($newKey, $newValue);
15 ✔
5816
    }
5817

5818
    /**
5819
     * Create an array using the current array as values and the other array as keys.
5820
     *
5821
     * EXAMPLE: <code>
5822
     * $firstArray = [
5823
     *     1 => 'one',
5824
     *     2 => 'two',
5825
     *     3 => 'three',
5826
     * ];
5827
     * $secondArray = [
5828
     *     'one' => 1,
5829
     *     1     => 'one',
5830
     *     2     => 2,
5831
     * ];
5832
     * $arrayy = a($firstArray);
5833
     * $arrayy->replaceAllKeys($secondArray); // Arrayy[1 => "one", 'one' => "two", 2 => "three"]
5834
     * </code>
5835
     *
5836
     * @param int[]|string[] $keys <p>An array of keys.</p>
5837
     *
5838
     * @return static
5839
     *                <p>(Immutable) Arrayy object with keys from the other array, empty Arrayy object if the number of elements
5840
     *                for each array isn't equal or if the arrays are empty.
5841
     *                </p>
5842
     *
5843
     * @phpstan-param  array<TKey> $keys
5844
     * @phpstan-return static<TKey,T>
5845
     * @psalm-mutation-free
5846
     */
5847
    public function replaceAllKeys(array $keys): self
5848
    {
5849
        $data = \array_combine($keys, $this->toArray());
6 ✔
5850
        /* @phpstan-ignore-next-line | change from PHP >= 8, but we still support old versions */
5851
        if ($data === false) {
6 ✔
UNCOV
5852
            $data = [];
×
5853
        }
5854

5855
        return static::create(
6 ✔
5856
            $data,
6 ✔
5857
            $this->iteratorClass,
6 ✔
5858
            false
6 ✔
5859
        );
6 ✔
5860
    }
5861

5862
    /**
5863
     * Create an array using the current array as keys and the other array as values.
5864
     *
5865
     * EXAMPLE: <code>
5866
     * $firstArray = [
5867
     *     1 => 'one',
5868
     *     2 => 'two',
5869
     *     3 => 'three',
5870
     * ];
5871
     * $secondArray = [
5872
     *     'one' => 1,
5873
     *     1     => 'one',
5874
     *     2     => 2,
5875
     * ];
5876
     * $arrayy = a($firstArray);
5877
     * $arrayy->replaceAllValues($secondArray); // Arrayy['one' => 1, 'two' => 'one', 'three' => 2]
5878
     * </code>
5879
     *
5880
     * @param array $array <p>An array of values.</p>
5881
     *
5882
     * @return static
5883
     *                <p>(Immutable) Arrayy object with values from the other array, empty Arrayy object if the number of elements
5884
     *                for each array isn't equal or if the arrays are empty.
5885
     *                </p>
5886
     *
5887
     * @phpstan-param  array<T> $array
5888
     * @phpstan-return static<TKey,T>
5889
     * @psalm-mutation-free
5890
     */
5891
    public function replaceAllValues(array $array): self
5892
    {
5893
        $data = \array_combine($this->toArray(), $array);
6 ✔
5894
        /* @phpstan-ignore-next-line | change from PHP >= 8, but we still support old versions */
5895
        if ($data === false) {
6 ✔
UNCOV
5896
            $data = [];
×
5897
        }
5898

5899
        return static::create(
6 ✔
5900
            $data,
6 ✔
5901
            $this->iteratorClass,
6 ✔
5902
            false
6 ✔
5903
        );
6 ✔
5904
    }
5905

5906
    /**
5907
     * Replace the keys in an array with another set.
5908
     *
5909
     * EXAMPLE: <code>
5910
     * a([1 => 'bar', 'foo' => 'foo'])->replaceKeys([1 => 2, 'foo' => 'replaced']); // Arrayy[2 => 'bar', 'replaced' => 'foo']
5911
     * </code>
5912
     *
5913
     * @param array $keys <p>An array of keys matching the array's size.</p>
5914
     *
5915
     * @return static
5916
     *                <p>(Immutable)</p>
5917
     *
5918
     * @phpstan-param  array<TKey> $keys
5919
     * @phpstan-return static<TKey,T>
5920
     * @psalm-mutation-free
5921
     */
5922
    public function replaceKeys(array $keys): self
5923
    {
5924
        $values = \array_values($this->toArray());
3 ✔
5925
        $result = \array_combine($keys, $values);
3 ✔
5926
        /* @phpstan-ignore-next-line | change from PHP >= 8, but we still support old versions */
5927
        if ($result === false) {
3 ✔
UNCOV
5928
            $result = [];
×
5929
        }
5930

5931
        return static::create(
3 ✔
5932
            $result,
3 ✔
5933
            $this->iteratorClass,
3 ✔
5934
            false
3 ✔
5935
        );
3 ✔
5936
    }
5937

5938
    /**
5939
     * Replace the first matched value in an array.
5940
     *
5941
     * EXAMPLE: <code>
5942
     * $testArray = ['bar', 'foo' => 'foo', 'foobar' => 'foobar'];
5943
     * a($testArray)->replaceOneValue('foo', 'replaced'); // Arrayy['bar', 'foo' => 'replaced', 'foobar' => 'foobar']
5944
     * </code>
5945
     *
5946
     * @param mixed $search      <p>The value to replace.</p>
5947
     * @param mixed $replacement <p>The value to replace.</p>
5948
     *
5949
     * @return static
5950
     *                <p>(Immutable)</p>
5951
     *
5952
     * @phpstan-param T $search
5953
     * @phpstan-param T $replacement
5954
     * @phpstan-return static<TKey,T>
5955
     * @psalm-mutation-free
5956
     */
5957
    public function replaceOneValue($search, $replacement = ''): self
5958
    {
5959
        $array = $this->toArray();
9 ✔
5960
        $key = \array_search($search, $array, true);
9 ✔
5961

5962
        if ($key !== false) {
9 ✔
5963
            $array[$key] = $replacement;
9 ✔
5964
        }
5965

5966
        return static::create(
9 ✔
5967
            $array,
9 ✔
5968
            $this->iteratorClass,
9 ✔
5969
            false
9 ✔
5970
        );
9 ✔
5971
    }
5972

5973
    /**
5974
     * Replace values in the current array.
5975
     *
5976
     * EXAMPLE: <code>
5977
     * $testArray = ['bar', 'foo' => 'foo', 'foobar' => 'foobar'];
5978
     * a($testArray)->replaceValues('foo', 'replaced'); // Arrayy['bar', 'foo' => 'replaced', 'foobar' => 'replacedbar']
5979
     * </code>
5980
     *
5981
     * @param string $search      <p>The value to replace.</p>
5982
     * @param string $replacement <p>What to replace it with.</p>
5983
     *
5984
     * @return static
5985
     *                <p>(Immutable)</p>
5986
     *
5987
     * @phpstan-return static<TKey,T>
5988
     * @psalm-mutation-free
5989
     */
5990
    public function replaceValues($search, $replacement = ''): self
5991
    {
5992
        $callable = static function ($value) use ($search, $replacement) {
3 ✔
5993
            return \str_replace($search, $replacement, $value);
3 ✔
5994
        };
3 ✔
5995

5996
        /* @phpstan-ignore-next-line | ignore Closure with one or two parameters, is this a bug in phpstan? */
5997
        return $this->each($callable);
3 ✔
5998
    }
5999

6000
    /**
6001
     * Get the last elements from index $from until the end of this array.
6002
     *
6003
     * EXAMPLE: <code>
6004
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->rest(2); // Arrayy[0 => 'lall']
6005
     * </code>
6006
     *
6007
     * @param int $from
6008
     *
6009
     * @return static
6010
     *                <p>(Immutable)</p>
6011
     *
6012
     * @phpstan-return static<TKey,T>
6013
     * @psalm-mutation-free
6014
     */
6015
    public function rest(int $from = 1): self
6016
    {
6017
        $tmpArray = $this->toArray();
45 ✔
6018

6019
        return static::create(
45 ✔
6020
            \array_splice($tmpArray, $from),
45 ✔
6021
            $this->iteratorClass,
45 ✔
6022
            false
45 ✔
6023
        );
45 ✔
6024
    }
6025

6026
    /**
6027
     * Return the array in the reverse order.
6028
     *
6029
     * EXAMPLE: <code>
6030
     * a([1 => 1, 2 => 2, 3 => 3])->reverse(); // self[3, 2, 1]
6031
     * </code>
6032
     *
6033
     * @return $this
6034
     *               <p>(Mutable) Return this Arrayy object.</p>
6035
     *
6036
     * @phpstan-return static<TKey,T>
6037
     */
6038
    public function reverse(): self
6039
    {
6040
        $this->generatorToArray();
27 ✔
6041

6042
        $this->array = \array_reverse($this->array);
27 ✔
6043

6044
        return $this;
27 ✔
6045
    }
6046

6047
    /**
6048
     * Return the array with keys in the reverse order.
6049
     *
6050
     * EXAMPLE: <code>
6051
     * a([1 => 1, 2 => 2, 3 => 3])->reverse(); // self[3 => 3, 2 => 2, 1 => 1]
6052
     * </code>
6053
     *
6054
     * @return $this
6055
     *               <p>(Mutable) Return this Arrayy object.</p>
6056
     *
6057
     * @phpstan-return static<TKey,T>
6058
     */
6059
    public function reverseKeepIndex(): self
6060
    {
6061
        $this->generatorToArray();
15 ✔
6062

6063
        $this->array = \array_reverse($this->array, true);
15 ✔
6064

6065
        return $this;
15 ✔
6066
    }
6067

6068
    /**
6069
     * Sort an array in reverse order.
6070
     *
6071
     * @param int $sort_flags [optional] <p>
6072
     *                        You may modify the behavior of the sort using the optional
6073
     *                        parameter sort_flags, for details
6074
     *                        see sort.
6075
     *                        </p>
6076
     *
6077
     * @return $this
6078
     *               <p>(Mutable) Return this Arrayy object.</p>
6079
     *
6080
     * @phpstan-return static<TKey,T>
6081
     */
6082
    public function rsort(int $sort_flags = 0): self
6083
    {
6084
        $this->generatorToArray();
12 ✔
6085

6086
        \rsort($this->array, $sort_flags);
12 ✔
6087

6088
        return $this;
12 ✔
6089
    }
6090

6091
    /**
6092
     * Sort an array in reverse order.
6093
     *
6094
     * @param int $sort_flags [optional] <p>
6095
     *                        You may modify the behavior of the sort using the optional
6096
     *                        parameter sort_flags, for details
6097
     *                        see sort.
6098
     *                        </p>
6099
     *
6100
     * @return $this
6101
     *               <p>(Immutable) Return this Arrayy object.</p>
6102
     *
6103
     * @phpstan-return static<TKey,T>
6104
     * @psalm-mutation-free
6105
     */
6106
    public function rsortImmutable(int $sort_flags = 0): self
6107
    {
6108
        $that = clone $this;
12 ✔
6109

6110
        /**
6111
         * @psalm-suppress ImpureMethodCall - object is already cloned
6112
         */
6113
        $that->rsort($sort_flags);
12 ✔
6114

6115
        return $that;
12 ✔
6116
    }
6117

6118
    /**
6119
     * Search for the first index of the current array via $value.
6120
     *
6121
     * EXAMPLE: <code>
6122
     * a(['fΓ²Γ΄' => 'bΓ Ε™', 'lall' => 'bΓ Ε™'])->searchIndex('bΓ Ε™'); // Arrayy[0 => 'fΓ²Γ΄']
6123
     * </code>
6124
     *
6125
     * @param mixed $value
6126
     *
6127
     * @return false|int|string
6128
     *                          <p>Will return <b>FALSE</b> if the value can't be found.</p>
6129
     *
6130
     * @phpstan-param T $value
6131
     * @phpstan-return false|TKey
6132
     *
6133
     * @psalm-mutation-free
6134
     */
6135
    public function searchIndex($value)
6136
    {
6137
        foreach ($this->getGenerator() as $keyFromArray => $valueFromArray) {
63 ✔
6138
            if ($value === $valueFromArray) {
60 ✔
6139
                return $keyFromArray;
30 ✔
6140
            }
6141
        }
6142

6143
        return false;
33 ✔
6144
    }
6145

6146
    /**
6147
     * Search for the value of the current array via $index.
6148
     *
6149
     * EXAMPLE: <code>
6150
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->searchValue('fΓ²Γ΄'); // Arrayy[0 => 'bΓ Ε™']
6151
     * </code>
6152
     *
6153
     * @param mixed $index
6154
     *
6155
     * @return static
6156
     *                <p>(Immutable) Will return a empty Arrayy if the value wasn't found.</p>
6157
     *
6158
     * @phpstan-param TKey $index
6159
     * @phpstan-return static<TKey,T>
6160
     * @psalm-mutation-free
6161
     */
6162
    public function searchValue($index): self
6163
    {
6164
        $this->generatorToArray();
27 ✔
6165

6166
        // init
6167
        $return = [];
27 ✔
6168

6169
        if ($this->array === []) {
27 ✔
6170
            return static::create(
×
6171
                [],
×
6172
                $this->iteratorClass,
×
6173
                false
×
UNCOV
6174
            );
×
6175
        }
6176

6177
        // php cast "bool"-index into "int"-index
6178
        /* @phpstan-ignore-next-line | array-key helper */
6179
        if ((bool) $index === $index) {
27 ✔
6180
            $index = (int) $index;
3 ✔
6181
        }
6182

6183
        if ($this->offsetExists($index)) {
27 ✔
6184
            $return = [$this->array[$index]];
21 ✔
6185
        }
6186

6187
        return static::create(
27 ✔
6188
            $return,
27 ✔
6189
            $this->iteratorClass,
27 ✔
6190
            false
27 ✔
6191
        );
27 ✔
6192
    }
6193

6194
    /**
6195
     * Set a value for the current array (optional using dot-notation).
6196
     *
6197
     * EXAMPLE: <code>
6198
     * $arrayy = a(['Lars' => ['lastname' => 'Moelleken']]);
6199
     * $arrayy->set('Lars.lastname', 'MΓΌller'); // Arrayy['Lars', ['lastname' => 'MΓΌller']]]
6200
     * </code>
6201
     *
6202
     * @param string $key   <p>The key to set.</p>
6203
     * @param mixed  $value <p>Its value.</p>
6204
     *
6205
     * @return $this
6206
     *               <p>(Mutable) Return this Arrayy object.</p>
6207
     *
6208
     * @phpstan-param  TKey $key
6209
     * @phpstan-param  T $value
6210
     * @phpstan-return static<TKey,T>
6211
     */
6212
    public function set($key, $value): self
6213
    {
6214
        $this->internalSet($key, $value);
84 ✔
6215

6216
        return $this;
81 ✔
6217
    }
6218

6219
    /**
6220
     * Get a value from a array and set it if it was not.
6221
     *
6222
     * WARNING: this method only set the value, if the $key is not already set
6223
     *
6224
     * EXAMPLE: <code>
6225
     * $arrayy = a([1 => 1, 2 => 2, 3 => 3]);
6226
     * $arrayy->setAndGet(1, 4); // 1
6227
     * $arrayy->setAndGet(0, 4); // 4
6228
     * </code>
6229
     *
6230
     * @param mixed $key      <p>The key</p>
6231
     * @param mixed $fallback <p>The default value to set if it isn't.</p>
6232
     *
6233
     * @return mixed
6234
     *               <p>(Mutable)</p>
6235
     *
6236
     * @phpstan-param TKey $key
6237
     * @phpstan-param T $fallback
6238
     */
6239
    public function setAndGet($key, $fallback = null)
6240
    {
6241
        $this->generatorToArray();
33 ✔
6242

6243
        // If the key doesn't exist, set it.
6244
        if (!$this->has($key)) {
33 ✔
6245
            $this->array = $this->set($key, $fallback)->toArray();
12 ✔
6246
        }
6247

6248
        return $this->get($key);
33 ✔
6249
    }
6250

6251
    /**
6252
     * Shifts a specified value off the beginning of array.
6253
     *
6254
     * @return mixed|null
6255
     *                    <p>(Mutable) A shifted element from the current array.</p>
6256
     *
6257
     * @phpstan-return T|null
6258
     */
6259
    public function shift()
6260
    {
6261
        $this->generatorToArray();
15 ✔
6262

6263
        return \array_shift($this->array);
15 ✔
6264
    }
6265

6266
    /**
6267
     * Shuffle the current array.
6268
     *
6269
     * EXAMPLE: <code>
6270
     * a([1 => 'bar', 'foo' => 'foo'])->shuffle(); // e.g.: Arrayy[['foo' => 'foo', 1 => 'bar']]
6271
     * </code>
6272
     *
6273
     * @param bool       $secure <p>using a CSPRNG | @see https://paragonie.com/b/JvICXzh_jhLyt4y3</p>
6274
     * @param array|null $array  [optional]
6275
     *
6276
     * @return static
6277
     *                <p>(Immutable)</p>
6278
     *
6279
     * @phpstan-param  array<TKey,T> $array
6280
     * @phpstan-return static<TKey,T>
6281
     */
6282
    public function shuffle(bool $secure = false, ?array $array = null): self
6283
    {
6284
        if ($array === null) {
6 ✔
6285
            $array = $this->toArray(false);
6 ✔
6286
        }
6287

6288
        if ($secure !== true) {
6 ✔
6289
            \shuffle($array);
6 ✔
6290
        } else {
6291
            $size = \count($array, \COUNT_NORMAL);
3 ✔
6292
            $keys = \array_keys($array);
3 ✔
6293
            for ($i = $size - 1; $i > 0; --$i) {
3 ✔
6294
                try {
6295
                    $r = \random_int(0, $i);
3 ✔
UNCOV
6296
                } catch (\Exception $e) {
×
6297
                    /** @noinspection RandomApiMigrationInspection - "random_int" is already in use */
UNCOV
6298
                    $r = \mt_rand(0, $i);
×
6299
                }
6300
                if ($r !== $i) {
3 ✔
6301
                    $temp = $array[$keys[$r]];
2 ✔
6302
                    $array[$keys[$r]] = $array[$keys[$i]];
2 ✔
6303
                    $array[$keys[$i]] = $temp;
2 ✔
6304
                }
6305
            }
6306
        }
6307

6308
        foreach ($array as $key => $value) {
6 ✔
6309
            // check if recursive is needed
6310
            if (\is_array($value)) {
6 ✔
6311
                /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
6312
                /** @phpstan-var array<TKey,T> $value */
UNCOV
6313
                $value = $value;
×
6314

UNCOV
6315
                $array[$key] = $this->shuffle($secure, $value);
×
6316
            }
6317
        }
6318

6319
        return static::create(
6 ✔
6320
            $array,
6 ✔
6321
            $this->iteratorClass,
6 ✔
6322
            false
6 ✔
6323
        );
6 ✔
6324
    }
6325

6326
    /**
6327
     * Count the values from the current array.
6328
     *
6329
     * alias: for "Arrayy->count()"
6330
     *
6331
     * @param int $mode
6332
     *
6333
     * @return int
6334
     */
6335
    public function size(int $mode = \COUNT_NORMAL): int
6336
    {
6337
        return $this->count($mode);
60 ✔
6338
    }
6339

6340
    /**
6341
     * Checks whether array has exactly $size items.
6342
     *
6343
     * @param int $size
6344
     *
6345
     * @return bool
6346
     */
6347
    public function sizeIs(int $size): bool
6348
    {
6349
        // init
6350
        $itemsTempCount = 0;
3 ✔
6351

6352
        /** @noinspection PhpUnusedLocalVariableInspection */
6353
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
6354
        foreach ($this->getGeneratorByReference() as &$value) {
3 ✔
6355
            ++$itemsTempCount;
3 ✔
6356
            if ($itemsTempCount > $size) {
3 ✔
6357
                return false;
3 ✔
6358
            }
6359
        }
6360

6361
        return $itemsTempCount === $size;
3 ✔
6362
    }
6363

6364
    /**
6365
     * Checks whether array has between $fromSize to $toSize items. $toSize can be
6366
     * smaller than $fromSize.
6367
     *
6368
     * @param int $fromSize
6369
     * @param int $toSize
6370
     *
6371
     * @return bool
6372
     */
6373
    public function sizeIsBetween(int $fromSize, int $toSize): bool
6374
    {
6375
        if ($fromSize > $toSize) {
3 ✔
6376
            $tmp = $toSize;
3 ✔
6377
            $toSize = $fromSize;
3 ✔
6378
            $fromSize = $tmp;
3 ✔
6379
        }
6380

6381
        // init
6382
        $itemsTempCount = 0;
3 ✔
6383

6384
        /** @noinspection PhpUnusedLocalVariableInspection */
6385
        foreach ($this->getGenerator() as $value) {
3 ✔
6386
            ++$itemsTempCount;
3 ✔
6387
            if ($itemsTempCount > $toSize) {
3 ✔
6388
                return false;
3 ✔
6389
            }
6390
        }
6391

6392
        return $fromSize < $itemsTempCount && $itemsTempCount < $toSize;
3 ✔
6393
    }
6394

6395
    /**
6396
     * Checks whether array has more than $size items.
6397
     *
6398
     * @param int $size
6399
     *
6400
     * @return bool
6401
     */
6402
    public function sizeIsGreaterThan(int $size): bool
6403
    {
6404
        // init
6405
        $itemsTempCount = 0;
3 ✔
6406

6407
        /** @noinspection PhpUnusedLocalVariableInspection */
6408
        foreach ($this->getGenerator() as $value) {
3 ✔
6409
            ++$itemsTempCount;
3 ✔
6410
            if ($itemsTempCount > $size) {
3 ✔
6411
                return true;
3 ✔
6412
            }
6413
        }
6414

6415
        return $itemsTempCount > $size;
3 ✔
6416
    }
6417

6418
    /**
6419
     * Checks whether array has less than $size items.
6420
     *
6421
     * @param int $size
6422
     *
6423
     * @return bool
6424
     */
6425
    public function sizeIsLessThan(int $size): bool
6426
    {
6427
        // init
6428
        $itemsTempCount = 0;
3 ✔
6429

6430
        /** @noinspection PhpUnusedLocalVariableInspection */
6431
        foreach ($this->getGenerator() as $value) {
3 ✔
6432
            ++$itemsTempCount;
3 ✔
6433
            if ($itemsTempCount > $size) {
3 ✔
6434
                return false;
3 ✔
6435
            }
6436
        }
6437

6438
        return $itemsTempCount < $size;
3 ✔
6439
    }
6440

6441
    /**
6442
     * Counts all elements in an array, or something in an object.
6443
     *
6444
     * <p>
6445
     * For objects, if you have SPL installed, you can hook into count() by implementing interface {@see Countable}.
6446
     * The interface has exactly one method, {@see Countable::count()}, which returns the return value for the count()
6447
     * function. Please see the {@see Array} section of the manual for a detailed explanation of how arrays are
6448
     * implemented and used in PHP.
6449
     * </p>
6450
     *
6451
     * @return int
6452
     *             <p>
6453
     *             The number of elements in var, which is
6454
     *             typically an array, since anything else will have one
6455
     *             element.
6456
     *             </p>
6457
     *             <p>
6458
     *             If var is not an array or an object with
6459
     *             implemented Countable interface,
6460
     *             1 will be returned.
6461
     *             There is one exception, if var is &null;,
6462
     *             0 will be returned.
6463
     *             </p>
6464
     *             <p>
6465
     *             Caution: count may return 0 for a variable that isn't set,
6466
     *             but it may also return 0 for a variable that has been initialized with an
6467
     *             empty array. Use isset to test if a variable is set.
6468
     *             </p>
6469
     */
6470
    public function sizeRecursive(): int
6471
    {
6472
        return \count($this->toArray(), \COUNT_RECURSIVE);
30 ✔
6473
    }
6474

6475
    /**
6476
     * Extract a slice of the array.
6477
     *
6478
     * @param int      $offset       <p>Slice begin index.</p>
6479
     * @param int|null $length       <p>Length of the slice.</p>
6480
     * @param bool     $preserveKeys <p>Whether array keys are preserved or no.</p>
6481
     *
6482
     * @return static
6483
     *                <p>(Immutable) A slice of the original array with length $length.</p>
6484
     *
6485
     * @phpstan-return static<array-key,T>
6486
     * @psalm-mutation-free
6487
     */
6488
    public function slice(int $offset, ?int $length = null, bool $preserveKeys = false)
6489
    {
6490
        return static::create(
15 ✔
6491
            \array_slice(
15 ✔
6492
                $this->toArray(),
15 ✔
6493
                $offset,
15 ✔
6494
                $length,
15 ✔
6495
                $preserveKeys
15 ✔
6496
            ),
15 ✔
6497
            $this->iteratorClass,
15 ✔
6498
            false
15 ✔
6499
        );
15 ✔
6500
    }
6501

6502
    /**
6503
     * Sort the current array and optional you can keep the keys.
6504
     *
6505
     * EXAMPLE: <code>
6506
     * a(3 => 'd', 2 => 'f', 0 => 'a')->sort(SORT_ASC, SORT_NATURAL, false); // Arrayy[0 => 'a', 1 => 'd', 2 => 'f']
6507
     * </code>
6508
     *
6509
     * @param int|string $direction
6510
     *                              <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6511
     * @param int        $strategy
6512
     *                              <p>sort_flags => use e.g.: <strong>SORT_REGULAR</strong> (default) or
6513
     *                              <strong>SORT_NATURAL</strong></p>
6514
     * @param bool       $keepKeys
6515
     *
6516
     * @return static
6517
     *                <p>(Mutable) Return this Arrayy object.</p>
6518
     *
6519
     * @phpstan-return static<int|TKey,T>
6520
     */
6521
    public function sort(
6522
        $direction = \SORT_ASC,
6523
        int $strategy = \SORT_REGULAR,
6524
        bool $keepKeys = false
6525
    ): self {
6526
        $this->generatorToArray();
60 ✔
6527

6528
        return $this->sorting(
60 ✔
6529
            $this->array,
60 ✔
6530
            $direction,
60 ✔
6531
            $strategy,
60 ✔
6532
            $keepKeys
60 ✔
6533
        );
60 ✔
6534
    }
6535

6536
    /**
6537
     * Sort the current array and optional you can keep the keys.
6538
     *
6539
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6540
     * @param int        $strategy  <p>sort_flags => use e.g.: <strong>SORT_REGULAR</strong> (default) or
6541
     *                              <strong>SORT_NATURAL</strong></p>
6542
     * @param bool       $keepKeys
6543
     *
6544
     * @return static
6545
     *                <p>(Immutable) Return this Arrayy object.</p>
6546
     *
6547
     * @phpstan-return static<int|TKey,T>
6548
     */
6549
    public function sortImmutable(
6550
        $direction = \SORT_ASC,
6551
        int $strategy = \SORT_REGULAR,
6552
        bool $keepKeys = false
6553
    ): self {
6554
        $that = clone $this;
36 ✔
6555

6556
        $that->generatorToArray();
36 ✔
6557

6558
        return $that->sorting(
36 ✔
6559
            $that->array,
36 ✔
6560
            $direction,
36 ✔
6561
            $strategy,
36 ✔
6562
            $keepKeys
36 ✔
6563
        );
36 ✔
6564
    }
6565

6566
    /**
6567
     * Sort the current array by key.
6568
     *
6569
     * EXAMPLE: <code>
6570
     * a([1 => 2, 0 => 1])->sortKeys(\SORT_ASC); // Arrayy[0 => 1, 1 => 2]
6571
     * </code>
6572
     *
6573
     * @see http://php.net/manual/en/function.ksort.php
6574
     * @see http://php.net/manual/en/function.krsort.php
6575
     *
6576
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6577
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6578
     *                              <strong>SORT_NATURAL</strong></p>
6579
     *
6580
     * @return $this
6581
     *               <p>(Mutable) Return this Arrayy object.</p>
6582
     *
6583
     * @phpstan-return static<TKey,T>
6584
     */
6585
    public function sortKeys(
6586
        $direction = \SORT_ASC,
6587
        int $strategy = \SORT_REGULAR
6588
    ): self {
6589
        $this->generatorToArray();
54 ✔
6590

6591
        $this->sorterKeys($this->array, $direction, $strategy);
54 ✔
6592

6593
        return $this;
54 ✔
6594
    }
6595

6596
    /**
6597
     * Sort the current array by key.
6598
     *
6599
     * @see          http://php.net/manual/en/function.ksort.php
6600
     * @see          http://php.net/manual/en/function.krsort.php
6601
     *
6602
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6603
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6604
     *                              <strong>SORT_NATURAL</strong></p>
6605
     *
6606
     * @return $this
6607
     *               <p>(Immutable) Return this Arrayy object.</p>
6608
     *
6609
     * @phpstan-return static<TKey,T>
6610
     * @psalm-mutation-free
6611
     */
6612
    public function sortKeysImmutable(
6613
        $direction = \SORT_ASC,
6614
        int $strategy = \SORT_REGULAR
6615
    ): self {
6616
        $that = clone $this;
24 ✔
6617

6618
        /**
6619
         * @psalm-suppress ImpureMethodCall - object is already cloned
6620
         */
6621
        $that->sortKeys($direction, $strategy);
24 ✔
6622

6623
        return $that;
24 ✔
6624
    }
6625

6626
    /**
6627
     * Sort the current array by value.
6628
     *
6629
     * EXAMPLE: <code>
6630
     * a(3 => 'd', 2 => 'f', 0 => 'a')->sortValueKeepIndex(SORT_ASC, SORT_REGULAR); // Arrayy[0 => 'a', 3 => 'd', 2 => 'f']
6631
     * </code>
6632
     *
6633
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6634
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6635
     *                              <strong>SORT_NATURAL</strong></p>
6636
     *
6637
     * @return static
6638
     *                <p>(Mutable)</p>
6639
     *
6640
     * @phpstan-return static<int|TKey,T>
6641
     */
6642
    public function sortValueKeepIndex(
6643
        $direction = \SORT_ASC,
6644
        int $strategy = \SORT_REGULAR
6645
    ): self {
6646
        return $this->sort($direction, $strategy, true);
3 ✔
6647
    }
6648

6649
    /**
6650
     * Sort the current array by value.
6651
     *
6652
     * EXAMPLE: <code>
6653
     * a(3 => 'd', 2 => 'f', 0 => 'a')->sortValueNewIndex(SORT_ASC, SORT_NATURAL); // Arrayy[0 => 'a', 1 => 'd', 2 => 'f']
6654
     * </code>
6655
     *
6656
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6657
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6658
     *                              <strong>SORT_NATURAL</strong></p>
6659
     *
6660
     * @return static
6661
     *                <p>(Mutable)</p>
6662
     *
6663
     * @phpstan-return static<int|TKey,T>
6664
     */
6665
    public function sortValueNewIndex($direction = \SORT_ASC, int $strategy = \SORT_REGULAR): self
6666
    {
6667
        return $this->sort($direction, $strategy, false);
3 ✔
6668
    }
6669

6670
    /**
6671
     * Sort a array by value or by a closure.
6672
     *
6673
     * - If the sorter is null, the array is sorted naturally.
6674
     * - Associative (string) keys will be maintained, but numeric keys will be re-indexed.
6675
     *
6676
     * EXAMPLE: <code>
6677
     * $testArray = range(1, 5);
6678
     * $under = a($testArray)->sorter(
6679
     *     function ($value) {
6680
     *         return $value % 2 === 0;
6681
     *     }
6682
     * );
6683
     * var_dump($under); // Arrayy[1, 3, 5, 2, 4]
6684
     * </code>
6685
     *
6686
     * @param callable|mixed|null $sorter
6687
     * @param int|string          $direction <p>use <strong>SORT_ASC</strong> (default) or
6688
     *                                       <strong>SORT_DESC</strong></p>
6689
     * @param int                 $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6690
     *                                       <strong>SORT_NATURAL</strong></p>
6691
     *
6692
     * @return static
6693
     *                <p>(Immutable)</p>
6694
     *
6695
     * @pslam-param callable|T|null $sorter
6696
     * @phpstan-return static<TKey,T>
6697
     * @psalm-mutation-free
6698
     */
6699
    public function sorter($sorter = null, $direction = \SORT_ASC, int $strategy = \SORT_REGULAR): self
6700
    {
6701
        $array = $this->toArray();
3 ✔
6702
        $direction = $this->getDirection($direction);
3 ✔
6703

6704
        // Transform all values into their results.
6705
        if ($sorter) {
3 ✔
6706
            $arrayy = static::create(
3 ✔
6707
                $array,
3 ✔
6708
                $this->iteratorClass,
3 ✔
6709
                false
3 ✔
6710
            );
3 ✔
6711

6712
            /**
6713
             * @psalm-suppress MissingClosureReturnType
6714
             * @psalm-suppress MissingClosureParamType
6715
             */
6716
            $results = $arrayy->each(
3 ✔
6717
                static function ($value) use ($sorter) {
3 ✔
6718
                    if (\is_callable($sorter) === true) {
3 ✔
6719
                        return $sorter($value);
3 ✔
6720
                    }
6721

6722
                    return $sorter === $value;
3 ✔
6723
                }
3 ✔
6724
            );
3 ✔
6725

6726
            $results = $results->toArray();
3 ✔
6727
        } else {
6728
            $results = $array;
3 ✔
6729
        }
6730

6731
        // Sort by the results and replace by original values
6732
        \array_multisort($results, $direction, $strategy, $array);
3 ✔
6733

6734
        return static::create(
3 ✔
6735
            $array,
3 ✔
6736
            $this->iteratorClass,
3 ✔
6737
            false
3 ✔
6738
        );
3 ✔
6739
    }
6740

6741
    /**
6742
     * @param int      $offset
6743
     * @param int|null $length
6744
     * @param array    $replacement
6745
     *
6746
     * @return static
6747
     *                <p>(Immutable)</p>
6748
     *
6749
     * @phpstan-param  array<T> $replacement
6750
     * @phpstan-return static<TKey,T>
6751
     * @psalm-mutation-free
6752
     */
6753
    public function splice(int $offset, ?int $length = null, $replacement = []): self
6754
    {
6755
        $tmpArray = $this->toArray();
3 ✔
6756

6757
        \array_splice(
3 ✔
6758
            $tmpArray,
3 ✔
6759
            $offset,
3 ✔
6760
            $length ?? $this->count(),
3 ✔
6761
            $replacement
3 ✔
6762
        );
3 ✔
6763

6764
        return static::create(
3 ✔
6765
            $tmpArray,
3 ✔
6766
            $this->iteratorClass,
3 ✔
6767
            false
3 ✔
6768
        );
3 ✔
6769
    }
6770

6771
    /**
6772
     * Split an array in the given amount of pieces.
6773
     *
6774
     * EXAMPLE: <code>
6775
     * a(['a' => 1, 'b' => 2])->split(2, true); // Arrayy[['a' => 1], ['b' => 2]]
6776
     * </code>
6777
     *
6778
     * @param int  $numberOfPieces
6779
     * @param bool $keepKeys
6780
     *
6781
     * @return static
6782
     *                <p>(Immutable)</p>
6783
     *
6784
     * @phpstan-return static<TKey,T>
6785
     * @psalm-mutation-free
6786
     */
6787
    public function split(int $numberOfPieces = 2, bool $keepKeys = false): self
6788
    {
6789
        if ($keepKeys) {
3 ✔
6790
            $generator = function () use ($numberOfPieces) {
3 ✔
6791
                $carry = [];
3 ✔
6792
                $i = 1;
3 ✔
6793
                foreach ($this->getGenerator() as $key => $value) {
3 ✔
6794
                    $carry[$key] = $value;
3 ✔
6795

6796
                    if ($i % $numberOfPieces !== 0) {
3 ✔
6797
                        ++$i;
3 ✔
6798

6799
                        continue;
3 ✔
6800
                    }
6801

6802
                    yield $carry;
3 ✔
6803

6804
                    $carry = [];
3 ✔
6805
                    $i = 1;
3 ✔
6806
                }
6807

6808
                if ($carry !== []) {
3 ✔
6809
                    yield $carry;
3 ✔
6810
                }
6811
            };
3 ✔
6812
        } else {
6813
            $generator = function () use ($numberOfPieces) {
3 ✔
6814
                $carry = [];
3 ✔
6815
                $i = 1;
3 ✔
6816
                foreach ($this->getGenerator() as $value) {
3 ✔
6817
                    $carry[] = $value;
3 ✔
6818

6819
                    if ($i % $numberOfPieces !== 0) {
3 ✔
6820
                        ++$i;
3 ✔
6821

6822
                        continue;
3 ✔
6823
                    }
6824

6825
                    yield $carry;
3 ✔
6826

6827
                    $carry = [];
3 ✔
6828
                    $i = 1;
3 ✔
6829
                }
6830

6831
                if ($carry !== []) {
3 ✔
6832
                    yield $carry;
3 ✔
6833
                }
6834
            };
3 ✔
6835
        }
6836

6837
        return static::create(
3 ✔
6838
            $generator,
3 ✔
6839
            $this->iteratorClass,
3 ✔
6840
            false
3 ✔
6841
        );
3 ✔
6842
    }
6843

6844
    /**
6845
     * Strip all empty items from the current array.
6846
     *
6847
     * EXAMPLE: <code>
6848
     * a(['a' => 1, 'b' => ''])->stripEmpty(); // Arrayy[['a' => 1]]
6849
     * </code>
6850
     *
6851
     * @return static
6852
     *                <p>(Immutable)</p>
6853
     *
6854
     * @phpstan-return static<TKey,T>
6855
     * @psalm-mutation-free
6856
     */
6857
    public function stripEmpty(): self
6858
    {
6859
        return $this->filter(
3 ✔
6860
            static function ($item) {
3 ✔
6861
                if ($item === null) {
3 ✔
6862
                    return false;
3 ✔
6863
                }
6864

6865
                return (bool) \trim((string) $item);
3 ✔
6866
            }
3 ✔
6867
        );
3 ✔
6868
    }
6869

6870
    /**
6871
     * Swap two values between positions by key.
6872
     *
6873
     * EXAMPLE: <code>
6874
     * a(['a' => 1, 'b' => ''])->swap('a', 'b'); // Arrayy[['a' => '', 'b' => 1]]
6875
     * </code>
6876
     *
6877
     * @param int|string $swapA <p>a key in the array</p>
6878
     * @param int|string $swapB <p>a key in the array</p>
6879
     *
6880
     * @return static
6881
     *                <p>(Immutable)</p>
6882
     *
6883
     * @phpstan-return static<TKey,T>
6884
     * @psalm-mutation-free
6885
     */
6886
    public function swap($swapA, $swapB): self
6887
    {
6888
        $array = $this->toArray();
3 ✔
6889

6890
        list($array[$swapA], $array[$swapB]) = [$array[$swapB], $array[$swapA]];
3 ✔
6891

6892
        return static::create(
3 ✔
6893
            $array,
3 ✔
6894
            $this->iteratorClass,
3 ✔
6895
            false
3 ✔
6896
        );
3 ✔
6897
    }
6898

6899
    /**
6900
     * Get the current array from the "Arrayy"-object.
6901
     * alias for "getArray()"
6902
     *
6903
     * @param bool $convertAllArrayyElements <p>
6904
     *                                       Convert all Child-"Arrayy" objects also to arrays.
6905
     *                                       </p>
6906
     * @param bool $preserveKeys             <p>
6907
     *                                       e.g.: A generator maybe return the same key more than once,
6908
     *                                       so maybe you will ignore the keys.
6909
     *                                       </p>
6910
     *
6911
     * @return array
6912
     *
6913
     * @phpstan-return ($preserveKeys is true ? array<TKey,T> : T[])
6914
     * @psalm-mutation-free
6915
     */
6916
    public function toArray(
6917
        bool $convertAllArrayyElements = false,
6918
        bool $preserveKeys = true
6919
    ): array {
6920
        if ($convertAllArrayyElements) {
2,871 ✔
6921
            // init
6922
            $array = [];
9 ✔
6923

6924
            foreach ($this->getGenerator() as $key => $value) {
9 ✔
6925
                if ($value instanceof self) {
9 ✔
6926
                    $value = $value->toArray(
6 ✔
6927
                        $convertAllArrayyElements,
6 ✔
6928
                        $preserveKeys
6 ✔
6929
                    );
6 ✔
6930
                }
6931

6932
                if ($preserveKeys) {
9 ✔
6933
                    $array[$key] = $value;
6 ✔
6934
                } else {
6935
                    $array[] = $value;
3 ✔
6936
                }
6937
            }
6938

6939
            /* @phpstan-ignore-next-line - depends on the $convertAllArrayyElements parameter :/ */
6940
            return $array;
9 ✔
6941
        }
6942

6943
        return \iterator_to_array($this->getGenerator(), $preserveKeys);
2,868 ✔
6944
    }
6945

6946
    /**
6947
     * Get the current array from the "Arrayy"-object as list.
6948
     *
6949
     * @param bool $convertAllArrayyElements <p>
6950
     *                                       Convert all Child-"Arrayy" objects also to arrays.
6951
     *                                       </p>
6952
     *
6953
     * @return array
6954
     *
6955
     * @phpstan-return list<T>
6956
     * @psalm-mutation-free
6957
     */
6958
    public function toList(bool $convertAllArrayyElements = false): array
6959
    {
6960
        /** @var list<T> - currently phpstan can't return different types depending on the phpdocs params */
6961
        return $this->toArray(
3 ✔
6962
            $convertAllArrayyElements,
3 ✔
6963
            false
3 ✔
6964
        );
3 ✔
6965
    }
6966

6967
    /**
6968
     * Convert the current array to JSON.
6969
     *
6970
     * EXAMPLE: <code>
6971
     * a(['bar', ['foo']])->toJson(); // '["bar",{"1":"foo"}]'
6972
     * </code>
6973
     *
6974
     * @param int $options [optional] <p>e.g. JSON_PRETTY_PRINT</p>
6975
     * @param int $depth   [optional] <p>Set the maximum depth. Must be greater than zero.</p>
6976
     *
6977
     * @return string
6978
     */
6979
    public function toJson(int $options = 0, int $depth = 512): string
6980
    {
6981
        if ($depth < 1) {
39 ✔
UNCOV
6982
            $depth = 1;
×
6983
        }
6984

6985
        $return = \json_encode($this->toArray(), $options, $depth);
39 ✔
6986
        if ($return === false) {
39 ✔
UNCOV
6987
            return '';
×
6988
        }
6989

6990
        return $return;
39 ✔
6991
    }
6992

6993
    /**
6994
     * @param string[]|null $items  [optional]
6995
     * @param string[]      $helper [optional]
6996
     *
6997
     * @return static|static[]
6998
     *
6999
     * @phpstan-return static<int, static<TKey,T>>
7000
     */
7001
    public function toPermutation(?array $items = null, array $helper = []): self
7002
    {
7003
        // init
7004
        $return = [];
3 ✔
7005

7006
        if ($items === null) {
3 ✔
7007
            $items = $this->toArray();
3 ✔
7008
        }
7009

7010
        if (empty($items)) {
3 ✔
7011
            $return[] = $helper;
3 ✔
7012
        } else {
7013
            for ($i = \count($items) - 1; $i >= 0; --$i) {
3 ✔
7014
                $new_items = $items;
3 ✔
7015
                $new_helper = $helper;
3 ✔
7016
                list($tmp_helper) = \array_splice($new_items, $i, 1);
3 ✔
7017
                /** @noinspection PhpSillyAssignmentInspection */
7018
                /** @var string[] $new_items */
7019
                $new_items = $new_items;
3 ✔
7020
                \array_unshift($new_helper, $tmp_helper);
3 ✔
7021
                $return = \array_merge(
3 ✔
7022
                    $return,
3 ✔
7023
                    $this->toPermutation($new_items, $new_helper)->toArray()
3 ✔
7024
                );
3 ✔
7025
            }
7026
        }
7027

7028
        /** @var static<int, static<TKey,T>> $return  - help for phpstan */
7029
        $return = static::create(
3 ✔
7030
            $return,
3 ✔
7031
            $this->iteratorClass,
3 ✔
7032
            false
3 ✔
7033
        );
3 ✔
7034

7035
        return $return;
3 ✔
7036
    }
7037

7038
    /**
7039
     * Implodes array to a string with specified separator.
7040
     *
7041
     * @param string $separator [optional] <p>The element's separator.</p>
7042
     *
7043
     * @return string
7044
     *                <p>The string representation of array, separated by ",".</p>
7045
     */
7046
    public function toString(string $separator = ','): string
7047
    {
7048
        return $this->implode($separator);
57 ✔
7049
    }
7050

7051
    /**
7052
     * Return a duplicate free copy of the current array.
7053
     *
7054
     * EXAMPLE: <code>
7055
     * a([2 => 1, 3 => 2, 4 => 2])->uniqueNewIndex(); // Arrayy[1, 2]
7056
     * </code>
7057
     *
7058
     * @return $this
7059
     *               <p>(Mutable)</p>
7060
     *
7061
     * @phpstan-return static<int,T>
7062
     */
7063
    public function uniqueNewIndex(): self
7064
    {
7065
        // INFO: \array_unique() can't handle e.g. "stdClass"-values in an array
7066

7067
        $this->array = $this->reduce(
39 ✔
7068
            static function ($resultArray, $value, $key) {
39 ✔
7069
                if (!\in_array($value, $resultArray, true)) {
36 ✔
7070
                    $resultArray[] = $value;
36 ✔
7071
                }
7072

7073
                return $resultArray;
36 ✔
7074
            },
39 ✔
7075
            []
39 ✔
7076
        )->toArray();
39 ✔
7077
        $this->generator = null;
39 ✔
7078

7079
        return $this;
39 ✔
7080
    }
7081

7082
    /**
7083
     * Return a duplicate free copy of the current array. (with the old keys)
7084
     *
7085
     * EXAMPLE: <code>
7086
     * a([2 => 1, 3 => 2, 4 => 2])->uniqueNewIndex(); // Arrayy[2 => 1, 3 => 2]
7087
     * </code>
7088
     *
7089
     * @return $this
7090
     *               <p>(Mutable)</p>
7091
     *
7092
     * @phpstan-return static<TKey,T>
7093
     */
7094
    public function uniqueKeepIndex(): self
7095
    {
7096
        // INFO: \array_unique() can't handle e.g. "stdClass"-values in an array
7097

7098
        // init
7099
        $array = $this->toArray();
33 ✔
7100

7101
        /**
7102
         * @psalm-suppress MissingClosureReturnType
7103
         * @psalm-suppress MissingClosureParamType
7104
         */
7105
        $this->array = \array_reduce(
33 ✔
7106
            \array_keys($array),
33 ✔
7107
            static function ($resultArray, $key) use ($array) {
33 ✔
7108
                if (!\in_array($array[$key], $resultArray, true)) {
30 ✔
7109
                    $resultArray[$key] = $array[$key];
30 ✔
7110
                }
7111

7112
                return $resultArray;
30 ✔
7113
            },
33 ✔
7114
            []
33 ✔
7115
        );
33 ✔
7116
        $this->generator = null;
33 ✔
7117

7118
        return $this;
33 ✔
7119
    }
7120

7121
    /**
7122
     * alias: for "Arrayy->uniqueNewIndex()"
7123
     *
7124
     * @return static
7125
     *                <p>(Mutable) Return this Arrayy object, with the appended values.</p>
7126
     *
7127
     * @see          Arrayy::unique()
7128
     *
7129
     * @phpstan-return static<int,T>
7130
     */
7131
    public function unique(): self
7132
    {
7133
        return $this->uniqueNewIndex();
39 ✔
7134
    }
7135

7136
    /**
7137
     * Prepends one or more values to the beginning of array at once.
7138
     *
7139
     * @param mixed ...$args
7140
     *
7141
     * @return $this
7142
     *               <p>(Mutable) Return this Arrayy object, with prepended elements to the beginning of array.</p>
7143
     *
7144
     * @phpstan-param  array<TKey,T> ...$args
7145
     * @phpstan-return static<TKey,T>
7146
     */
7147
    public function unshift(...$args): self
7148
    {
7149
        $this->generatorToArray();
18 ✔
7150

7151
        if (
7152
            $this->checkPropertyTypes
18 ✔
7153
            &&
7154
            $this->properties !== []
18 ✔
7155
        ) {
7156
            foreach ($args as $key => $value) {
6 ✔
7157
                $this->checkType($key, $value);
6 ✔
7158
            }
7159
        }
7160

7161
        \array_unshift($this->array, ...$args); // @phpstan-ignore-line
15 ✔
7162

7163
        return $this;
15 ✔
7164
    }
7165

7166
    /**
7167
     * Tests whether the given closure return something valid for all elements of this array.
7168
     *
7169
     * @param \Closure $closure the predicate
7170
     *
7171
     * @return bool
7172
     *              <p>TRUE, if the predicate yields TRUE for all elements, FALSE otherwise.</p>
7173
     *
7174
     * @phpstan-param \Closure(T,TKey):bool $closure
7175
     */
7176
    public function validate(\Closure $closure): bool
7177
    {
7178
        foreach ($this->getGenerator() as $key => $value) {
3 ✔
7179
            if (!$closure($value, $key)) {
3 ✔
7180
                return false;
3 ✔
7181
            }
7182
        }
7183

7184
        return true;
3 ✔
7185
    }
7186

7187
    /**
7188
     * Get all values from a array.
7189
     *
7190
     * EXAMPLE: <code>
7191
     * $arrayy = a([1 => 'foo', 2 => 'foo2', 3 => 'bar']);
7192
     * $arrayyTmp->values(); // Arrayy[0 => 'foo', 1 => 'foo2', 2 => 'bar']
7193
     * </code>
7194
     *
7195
     * @return static
7196
     *                <p>(Immutable)</p>
7197
     *
7198
     * @phpstan-return static<int,T>
7199
     * @psalm-mutation-free
7200
     */
7201
    public function values(): self
7202
    {
7203
        return static::create(
6 ✔
7204
            function () {
6 ✔
7205
                foreach ($this->getGenerator() as $value) {
6 ✔
7206
                    yield $value;
6 ✔
7207
                }
7208
            },
6 ✔
7209
            $this->iteratorClass,
6 ✔
7210
            false
6 ✔
7211
        );
6 ✔
7212
    }
7213

7214
    /**
7215
     * Apply the given function to every element in the array, discarding the results.
7216
     *
7217
     * EXAMPLE: <code>
7218
     * $callable = function (&$value, $key) {
7219
     *     $value = $key;
7220
     * };
7221
     * $arrayy = a([1, 2, 3]);
7222
     * $arrayy->walk($callable); // Arrayy[0, 1, 2]
7223
     * </code>
7224
     *
7225
     * @param callable $callable
7226
     * @param bool     $recursive
7227
     *                            [optional] <p>Whether array will be walked recursively or no</p>
7228
     * @param mixed    $userData
7229
     *                            [optional] <p>
7230
     *                            If the optional $userData parameter is supplied,
7231
     *                            it will be passed as the third parameter to the $callable.
7232
     *                            </p>
7233
     *
7234
     * @return $this
7235
     *               <p>(Mutable) Return this Arrayy object, with modified elements.</p>
7236
     *
7237
     * @template TExtra
7238
     *              <p>The extra input value type.</p>
7239
     *
7240
     * @phostan-param TExtra $userData
7241
     * @phpstan-param  callable(T,TKey,?TExtra):void $callable
7242
     * @phpstan-return static<TKey,T>
7243
     */
7244
    public function walk(
7245
        $callable,
7246
        bool $recursive = false,
7247
        $userData = self::ARRAYY_HELPER_WALK
7248
    ): self {
7249
        $this->generatorToArray();
36 ✔
7250

7251
        if ($this->array !== []) {
36 ✔
7252
            if ($recursive === true) {
30 ✔
7253
                if ($userData !== self::ARRAYY_HELPER_WALK) {
15 ✔
UNCOV
7254
                    \array_walk_recursive($this->array, $callable, $userData);
×
7255
                } else {
7256
                    \array_walk_recursive($this->array, $callable);
15 ✔
7257
                }
7258
            } else {
7259
                if ($userData !== self::ARRAYY_HELPER_WALK) {
15 ✔
UNCOV
7260
                    \array_walk($this->array, $callable, $userData);
×
7261
                } else {
7262
                    /* @phpstan-ignore-next-line | callback with no arguments is ok here */
7263
                    \array_walk($this->array, $callable);
15 ✔
7264
                }
7265
            }
7266
        }
7267

7268
        return $this;
36 ✔
7269
    }
7270

7271
    /**
7272
     * Returns a collection of matching items.
7273
     *
7274
     * @param string $keyOrPropertyOrMethod
7275
     *                                      <p>The property or method to evaluate.</p>
7276
     * @param mixed  $value
7277
     *                                      <p>The value to match.</p>
7278
     *
7279
     * @throws \InvalidArgumentException if property or method is not defined
7280
     *
7281
     * @return static
7282
     *
7283
     * @phpstan-return static<TKey,T>
7284
     */
7285
    public function where(string $keyOrPropertyOrMethod, $value): self
7286
    {
7287
        return $this->filter(
3 ✔
7288
            function ($item) use ($keyOrPropertyOrMethod, $value) {
3 ✔
7289
                $accessorValue = $this->extractValue(
×
7290
                    $item,
×
7291
                    $keyOrPropertyOrMethod
×
UNCOV
7292
                );
×
7293

UNCOV
7294
                return $accessorValue === $value;
×
7295
            }
3 ✔
7296
        );
3 ✔
7297
    }
7298

7299
    /**
7300
     * Convert an array into an object.
7301
     *
7302
     * @param array $array
7303
     *
7304
     * @return \stdClass
7305
     *
7306
     * @phpstan-param array<int|string,mixed> $array
7307
     */
7308
    final protected static function arrayToObject(array $array = []): \stdClass
7309
    {
7310
        // init
7311
        $object = new \stdClass();
12 ✔
7312

7313
        if (\count($array, \COUNT_NORMAL) <= 0) {
12 ✔
7314
            return $object;
3 ✔
7315
        }
7316

7317
        foreach ($array as $name => $value) {
9 ✔
7318
            if (\is_array($value)) {
9 ✔
7319
                $object->{$name} = static::arrayToObject($value);
3 ✔
7320
            } else {
7321
                $object->{$name} = $value;
9 ✔
7322
            }
7323
        }
7324

7325
        return $object;
9 ✔
7326
    }
7327

7328
    /**
7329
     * @param array|\Generator|null $input         <p>
7330
     *                                             An array containing keys to return.
7331
     *                                             </p>
7332
     * @param mixed|null            $search_values [optional] <p>
7333
     *                                             If specified, then only keys containing these values are returned.
7334
     *                                             </p>
7335
     * @param bool                  $strict        [optional] <p>
7336
     *                                             Determines if strict comparison (===) should be used during the
7337
     *                                             search.
7338
     *                                             </p>
7339
     *
7340
     * @return array
7341
     *               <p>An array of all the keys in input.</p>
7342
     *
7343
     * @template TInput
7344
     *
7345
     * @phpstan-param  array<array-key,TInput>|\Generator<array-key,TInput>|null $input
7346
     * @phpstan-param T|T[]|null $search_values
7347
     * @phpstan-return array<int, TKey>
7348
     *
7349
     * @psalm-mutation-free
7350
     */
7351
    protected function array_keys_recursive(
7352
        $input = null,
7353
        $search_values = null,
7354
        bool $strict = true
7355
    ): array {
7356
        // init
7357
        $keys = [];
33 ✔
7358
        $keysTmp = [];
33 ✔
7359

7360
        if ($input === null) {
33 ✔
7361
            $input = $this->getGenerator();
12 ✔
7362
        }
7363

7364
        if ($search_values === null) {
33 ✔
7365
            foreach ($input as $key => $value) {
33 ✔
7366
                $keys[] = $key;
33 ✔
7367

7368
                // check if recursive is needed
7369
                if (\is_array($value)) {
33 ✔
7370
                    $keysTmp[] = $this->array_keys_recursive($value);
12 ✔
7371
                }
7372
            }
7373
        } else {
7374
            $is_array_tmp = \is_array($search_values);
3 ✔
7375

7376
            foreach ($input as $key => $value) {
3 ✔
7377
                if (
7378
                    (
7379
                        $is_array_tmp === false
3 ✔
7380
                        &&
3 ✔
7381
                        $strict === true
3 ✔
7382
                        &&
3 ✔
7383
                        $search_values === $value
3 ✔
7384
                    )
7385
                    ||
7386
                    (
7387
                        $is_array_tmp === false
3 ✔
7388
                        &&
3 ✔
7389
                        $strict === false
3 ✔
7390
                        &&
3 ✔
7391
                        $search_values == $value
3 ✔
7392
                    )
7393
                    ||
7394
                    (
7395
                        $is_array_tmp === true
3 ✔
7396
                        &&
3 ✔
7397
                        \in_array($value, $search_values, $strict)
3 ✔
7398
                    )
7399
                ) {
7400
                    $keys[] = $key;
3 ✔
7401
                }
7402

7403
                // check if recursive is needed
7404
                if (\is_array($value)) {
3 ✔
7405
                    $keysTmp[] = $this->array_keys_recursive($value);
3 ✔
7406
                }
7407
            }
7408
        }
7409

7410
        return $keysTmp === [] ? $keys : \array_merge($keys, ...$keysTmp);
33 ✔
7411
    }
7412

7413
    /**
7414
     * @param string     $path
7415
     * @param callable   $callable
7416
     * @param array|null $currentOffset
7417
     *
7418
     * @return void
7419
     *
7420
     * @phpstan-param array<TKey,T>|null $currentOffset
7421
     * @psalm-mutation-free
7422
     */
7423
    protected function callAtPath($path, $callable, &$currentOffset = null)
7424
    {
7425
        $this->generatorToArray();
30 ✔
7426

7427
        if ($currentOffset === null) {
30 ✔
7428
            $currentOffset = &$this->array;
30 ✔
7429
        }
7430

7431
        $explodedPath = \explode($this->pathSeparator, $path);
30 ✔
7432
        /* @phpstan-ignore-next-line | change from PHP >= 8, but we still support old versions */
7433
        if ($explodedPath === false) {
30 ✔
UNCOV
7434
            return;
×
7435
        }
7436

7437
        $nextPath = \array_shift($explodedPath);
30 ✔
7438
        if (!isset($currentOffset[$nextPath])) {
30 ✔
7439
            return;
3 ✔
7440
        }
7441

7442
        if ($explodedPath !== []) {
27 ✔
7443
            $this->callAtPath(
3 ✔
7444
                \implode($this->pathSeparator, $explodedPath),
3 ✔
7445
                $callable,
3 ✔
7446
                $currentOffset[$nextPath]
3 ✔
7447
            );
3 ✔
7448
        } else {
7449
            $callable($currentOffset[$nextPath]);
27 ✔
7450
        }
7451
    }
7452

7453
    /**
7454
     * Extracts the value of the given property or method from the object.
7455
     *
7456
     * @param static<T> $object
7457
     *                                         <p>The object to extract the value from.</p>
7458
     * @param string    $keyOrPropertyOrMethod
7459
     *                                         <p>The property or method for which the
7460
     *                                         value should be extracted.</p>
7461
     *
7462
     * @throws \InvalidArgumentException if the method or property is not defined
7463
     *
7464
     * @return mixed
7465
     *               <p>The value extracted from the specified property or method.</p>
7466
     *
7467
     * @phpstan-param self<TKey,T> $object
7468
     */
7469
    final protected function extractValue(self $object, string $keyOrPropertyOrMethod)
7470
    {
7471
        if (isset($object[$keyOrPropertyOrMethod])) {
3 ✔
7472
            $return = $object->get($keyOrPropertyOrMethod);
3 ✔
7473

7474
            if ($return instanceof self) {
3 ✔
UNCOV
7475
                return $return->toArray();
×
7476
            }
7477

7478
            return $return;
3 ✔
7479
        }
7480

7481
        if (\property_exists($object, $keyOrPropertyOrMethod)) {
×
UNCOV
7482
            return $object->{$keyOrPropertyOrMethod};
×
7483
        }
7484

7485
        if (\method_exists($object, $keyOrPropertyOrMethod)) {
×
UNCOV
7486
            return $object->{$keyOrPropertyOrMethod}();
×
7487
        }
7488

UNCOV
7489
        throw new \InvalidArgumentException(\sprintf('array-key & property & method "%s" not defined in %s', $keyOrPropertyOrMethod, \gettype($object)));
×
7490
    }
7491

7492
    /**
7493
     * create a fallback for array
7494
     *
7495
     * 1. use the current array, if it's a array
7496
     * 2. fallback to empty array, if there is nothing
7497
     * 3. call "getArray()" on object, if there is a "Arrayy"-object
7498
     * 4. call "createFromObject()" on object, if there is a "\Traversable"-object
7499
     * 5. call "__toArray()" on object, if the method exists
7500
     * 6. cast a string or object with "__toString()" into an array
7501
     * 7. throw a "InvalidArgumentException"-Exception
7502
     *
7503
     * @param mixed $data
7504
     *
7505
     * @throws \InvalidArgumentException
7506
     *
7507
     * @return array
7508
     *
7509
     * @phpstan-return array<mixed>|array<TKey,T>
7510
     */
7511
    protected function fallbackForArray(&$data): array
7512
    {
7513
        $data = $this->internalGetArray($data);
3,762 ✔
7514

7515
        if ($data === null) {
3,762 ✔
7516
            throw new \InvalidArgumentException('Passed value should be a array');
6 ✔
7517
        }
7518

7519
        return $data;
3,756 ✔
7520
    }
7521

7522
    /**
7523
     * @param bool $preserveKeys <p>
7524
     *                           e.g.: A generator maybe return the same key more than once,
7525
     *                           so maybe you will ignore the keys.
7526
     *                           </p>
7527
     *
7528
     * @return bool
7529
     *
7530
     * @noinspection ReturnTypeCanBeDeclaredInspection
7531
     * @psalm-mutation-free :/
7532
     */
7533
    protected function generatorToArray(bool $preserveKeys = true)
7534
    {
7535
        if ($this->generator) {
3,480 ✔
7536
            $this->array = $this->toArray(false, $preserveKeys);
9 ✔
7537
            $this->generator = null;
9 ✔
7538

7539
            return true;
9 ✔
7540
        }
7541

7542
        return false;
3,480 ✔
7543
    }
7544

7545
    /**
7546
     * Get correct PHP constant for direction.
7547
     *
7548
     * @param int|string $direction
7549
     *
7550
     * @return int
7551
     * @psalm-mutation-free
7552
     */
7553
    protected function getDirection($direction): int
7554
    {
7555
        if ((string) $direction === $direction) {
129 ✔
7556
            $direction = \strtolower($direction);
30 ✔
7557

7558
            if ($direction === 'desc') {
30 ✔
7559
                $direction = \SORT_DESC;
6 ✔
7560
            } else {
7561
                $direction = \SORT_ASC;
27 ✔
7562
            }
7563
        }
7564

7565
        if (
7566
            $direction !== \SORT_DESC
129 ✔
7567
            &&
7568
            $direction !== \SORT_ASC
129 ✔
7569
        ) {
UNCOV
7570
            $direction = \SORT_ASC;
×
7571
        }
7572

7573
        return $direction;
129 ✔
7574
    }
7575

7576
    /**
7577
     * @return TypeCheckInterface[]
7578
     *
7579
     * @noinspection ReturnTypeCanBeDeclaredInspection
7580
     */
7581
    protected function getPropertiesFromPhpDoc()
7582
    {
7583
        static $PROPERTY_CACHE = [];
81 ✔
7584
        $cacheKey = 'Class::' . static::class;
81 ✔
7585

7586
        if (isset($PROPERTY_CACHE[$cacheKey])) {
81 ✔
7587
            return $PROPERTY_CACHE[$cacheKey];
72 ✔
7588
        }
7589

7590
        // init
7591
        $properties = [];
15 ✔
7592

7593
        $reflector = new \ReflectionClass($this);
15 ✔
7594
        $factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
15 ✔
7595
        $docComment = $reflector->getDocComment();
15 ✔
7596
        if ($docComment) {
15 ✔
7597
            $docblock = $factory->create($docComment);
15 ✔
7598
            /** @var \phpDocumentor\Reflection\DocBlock\Tags\Property $tag */
7599
            foreach ($docblock->getTagsByName('property') as $tag) {
15 ✔
7600
                $typeName = $tag->getVariableName();
12 ✔
7601
                /** @var string|null $typeName */
7602
                if ($typeName !== null) {
12 ✔
7603
                    $typeCheckPhpDoc = TypeCheckPhpDoc::fromPhpDocumentorProperty($tag, $typeName);
12 ✔
7604
                    if ($typeCheckPhpDoc !== null) {
12 ✔
7605
                        $properties[$typeName] = $typeCheckPhpDoc;
12 ✔
7606
                    }
7607
                }
7608
            }
7609
        }
7610

7611
        /** @noinspection PhpAssignmentInConditionInspection */
7612
        while ($reflector = $reflector->getParentClass()) {
15 ✔
7613
            $docComment = $reflector->getDocComment();
15 ✔
7614
            if ($docComment) {
15 ✔
7615
                $docblock = $factory->create($docComment);
15 ✔
7616
                /** @var \phpDocumentor\Reflection\DocBlock\Tags\Property $tag */
7617
                foreach ($docblock->getTagsByName('property') as $tag) {
15 ✔
7618
                    $typeName = $tag->getVariableName();
3 ✔
7619
                    /** @var string|null $typeName */
7620
                    if ($typeName !== null) {
3 ✔
7621
                        if (isset($properties[$typeName])) {
3 ✔
7622
                            continue;
3 ✔
7623
                        }
7624

7625
                        $typeCheckPhpDoc = TypeCheckPhpDoc::fromPhpDocumentorProperty($tag, $typeName);
3 ✔
7626
                        if ($typeCheckPhpDoc !== null) {
3 ✔
7627
                            $properties[$typeName] = $typeCheckPhpDoc;
3 ✔
7628
                        }
7629
                    }
7630
                }
7631
            }
7632
        }
7633

7634
        return $PROPERTY_CACHE[$cacheKey] = $properties;
15 ✔
7635
    }
7636

7637
    /**
7638
     * @param string $glue
7639
     * @param mixed  $pieces
7640
     * @param bool   $useKeys
7641
     *
7642
     * @return string
7643
     *
7644
     * @phpstan-param scalar|object|self<TKey|T>|array<TKey,T>|array<T> $pieces
7645
     * @psalm-mutation-free
7646
     */
7647
    protected function implode_recursive(
7648
        $glue = '',
7649
        $pieces = [],
7650
        bool $useKeys = false
7651
    ): string {
7652
        if ($pieces instanceof self) {
111 ✔
7653
            $pieces = $pieces->toArray();
3 ✔
7654
        }
7655

7656
        if (\is_array($pieces)) {
111 ✔
7657
            /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
7658
            /** @phpstan-var array<TKey,T> $pieces */
7659
            $pieces = $pieces;
111 ✔
7660

7661
            $pieces_count = \count($pieces, \COUNT_NORMAL);
111 ✔
7662
            $pieces_count_not_zero = $pieces_count > 0;
111 ✔
7663

7664
            return \implode(
111 ✔
7665
                $glue,
111 ✔
7666
                \array_map(
111 ✔
7667
                    [$this, 'implode_recursive'],
111 ✔
7668
                    \array_fill(0, ($pieces_count_not_zero ? $pieces_count : 1), $glue),
111 ✔
7669
                    ($useKeys === true && $pieces_count_not_zero ? $this->array_keys_recursive($pieces) : $pieces)
111 ✔
7670
                )
111 ✔
7671
            );
111 ✔
7672
        }
7673

7674
        if (
7675
            \is_scalar($pieces) === true
111 ✔
7676
            ||
7677
            (\is_object($pieces) && \method_exists($pieces, '__toString'))
111 ✔
7678
        ) {
7679
            return (string) $pieces;
99 ✔
7680
        }
7681

7682
        return '';
24 ✔
7683
    }
7684

7685
    /**
7686
     * @param mixed                 $needle   <p>
7687
     *                                        The searched value.
7688
     *                                        </p>
7689
     *                                        <p>
7690
     *                                        If needle is a string, the comparison is done
7691
     *                                        in a case-sensitive manner.
7692
     *                                        </p>
7693
     * @param array|\Generator|null $haystack <p>
7694
     *                                        The array.
7695
     *                                        </p>
7696
     * @param bool                  $strict   [optional] <p>
7697
     *                                        If the third parameter strict is set to true
7698
     *                                        then the in_array function will also check the
7699
     *                                        types of the
7700
     *                                        needle in the haystack.
7701
     *                                        </p>
7702
     *
7703
     * @return bool
7704
     *              <p>true if needle is found in the array, false otherwise</p>
7705
     *
7706
     * @phpstan-param (array&T)|array<TKey,T>|\Generator<TKey,T>|null $haystack
7707
     *
7708
     * @psalm-mutation-free
7709
     */
7710
    protected function in_array_recursive($needle, $haystack = null, $strict = true): bool
7711
    {
7712
        if ($haystack === null) {
54 ✔
UNCOV
7713
            $haystack = $this->getGenerator();
×
7714
        }
7715

7716
        foreach ($haystack as $item) {
54 ✔
7717
            if (\is_array($item)) {
42 ✔
7718
                $returnTmp = $this->in_array_recursive($needle, $item, $strict);
9 ✔
7719
            } else {
7720
                /** @noinspection NestedPositiveIfStatementsInspection */
7721
                if ($strict === true) {
42 ✔
7722
                    $returnTmp = $item === $needle;
42 ✔
7723
                } else {
UNCOV
7724
                    $returnTmp = $item == $needle;
×
7725
                }
7726
            }
7727

7728
            if ($returnTmp === true) {
42 ✔
7729
                return true;
30 ✔
7730
            }
7731
        }
7732

7733
        return false;
24 ✔
7734
    }
7735

7736
    /**
7737
     * @param mixed $data
7738
     *
7739
     * @return array<mixed>|null
7740
     */
7741
    protected function internalGetArray(&$data)
7742
    {
7743
        if (\is_array($data)) {
3,762 ✔
7744
            return $data;
3,744 ✔
7745
        }
7746

7747
        if (!$data) {
336 ✔
7748
            return [];
21 ✔
7749
        }
7750

7751
        if (\is_object($data) === true) {
333 ✔
7752
            if ($data instanceof \ArrayObject) {
312 ✔
7753
                return $data->getArrayCopy();
15 ✔
7754
            }
7755

7756
            if ($data instanceof \Generator) {
300 ✔
UNCOV
7757
                return static::createFromGeneratorImmutable($data)->toArray();
×
7758
            }
7759

7760
            if ($data instanceof \Traversable) {
300 ✔
UNCOV
7761
                return static::createFromObject($data)->toArray();
×
7762
            }
7763

7764
            if ($data instanceof \JsonSerializable) {
300 ✔
UNCOV
7765
                return (array) $data->jsonSerialize();
×
7766
            }
7767

7768
            if (\method_exists($data, '__toArray')) {
300 ✔
UNCOV
7769
                return (array) $data->__toArray();
×
7770
            }
7771

7772
            if (\method_exists($data, '__toString')) {
300 ✔
UNCOV
7773
                return [(string) $data];
×
7774
            }
7775
        }
7776

7777
        if (\is_callable($data)) {
321 ✔
7778
            /**
7779
             * @psalm-suppress InvalidPropertyAssignmentValue - why?
7780
             */
7781
            $this->generator = new ArrayyRewindableGenerator($data);
294 ✔
7782

7783
            return [];
294 ✔
7784
        }
7785

7786
        if (\is_scalar($data)) {
33 ✔
7787
            return [$data];
27 ✔
7788
        }
7789

7790
        return null;
6 ✔
7791
    }
7792

7793
    /**
7794
     * Internal mechanics of remove method.
7795
     *
7796
     * @param float|int|string $key
7797
     *
7798
     * @return bool
7799
     */
7800
    protected function internalRemove($key): bool
7801
    {
7802
        $this->generatorToArray();
66 ✔
7803

7804
        if (
7805
            $this->pathSeparator
66 ✔
7806
            &&
7807
            (string) $key === $key
66 ✔
7808
            &&
7809
            \strpos($key, $this->pathSeparator) !== false
66 ✔
7810
        ) {
UNCOV
7811
            $path = \explode($this->pathSeparator, (string) $key);
×
7812

UNCOV
7813
            if ($path !== false) {
×
7814
                // crawl though the keys
7815
                while (\count($path, \COUNT_NORMAL) > 1) {
×
UNCOV
7816
                    $key = \array_shift($path);
×
7817

7818
                    if (!$this->has($key)) {
×
UNCOV
7819
                        return false;
×
7820
                    }
7821

UNCOV
7822
                    $this->array = &$this->array[$key];
×
7823
                }
7824

UNCOV
7825
                $key = \array_shift($path);
×
7826
            }
7827
        }
7828

7829
        unset($this->array[$key]);
66 ✔
7830

7831
        return true;
66 ✔
7832
    }
7833

7834
    /**
7835
     * Internal mechanic of set method.
7836
     *
7837
     * @param int|string|null $key
7838
     * @param mixed           $value
7839
     * @param bool            $checkProperties
7840
     *
7841
     * @return bool
7842
     *
7843
     * @phpstan-param TKey|null $key
7844
     * @phpstan-param T $value
7845
     */
7846
    protected function internalSet(
7847
        $key,
7848
        &$value,
7849
        bool $checkProperties = true
7850
    ): bool {
7851
        if (
7852
            $checkProperties === true
3,300 ✔
7853
            &&
7854
            $this->properties !== []
3,300 ✔
7855
        ) {
7856
            $this->checkType($key, $value);
390 ✔
7857
        }
7858

7859
        if ($key === null) {
3,294 ✔
UNCOV
7860
            return false;
×
7861
        }
7862

7863
        $this->generatorToArray();
3,294 ✔
7864

7865
        $array = &$this->array;
3,294 ✔
7866

7867
        /**
7868
         * https://github.com/vimeo/psalm/issues/2536
7869
         *
7870
         * @psalm-suppress PossiblyInvalidArgument
7871
         * @psalm-suppress InvalidScalarArgument
7872
         */
7873
        if (
7874
            $this->pathSeparator
3,294 ✔
7875
            &&
7876
            (string) $key === $key
3,294 ✔
7877
            &&
7878
            \strpos($key, $this->pathSeparator) !== false
3,294 ✔
7879
        ) {
7880
            $path = \explode($this->pathSeparator, (string) $key);
27 ✔
7881

7882
            if ($path !== false) {
27 ✔
7883
                // crawl through the keys
7884
                while (\count($path, \COUNT_NORMAL) > 1) {
27 ✔
7885
                    $key = \array_shift($path);
27 ✔
7886

7887
                    $array = &$array[$key];
27 ✔
7888
                }
7889

7890
                $key = \array_shift($path);
27 ✔
7891
            }
7892
        }
7893

7894
        if ($array === null) {
3,294 ✔
7895
            $array = [];
12 ✔
7896
        } elseif (!\is_array($array)) {
3,285 ✔
7897
            throw new \RuntimeException('Can not set value at this path "' . $key . '" because (' . \gettype($array) . ')"' . \print_r($array, true) . '" is not an array.');
3 ✔
7898
        }
7899

7900
        $array[$key] = $value;
3,294 ✔
7901

7902
        return true;
3,294 ✔
7903
    }
7904

7905
    /**
7906
     * Convert a object into an array.
7907
     *
7908
     * @param mixed|object $object
7909
     *
7910
     * @return array|mixed
7911
     *
7912
     * @psalm-mutation-free
7913
     */
7914
    protected static function objectToArray($object)
7915
    {
7916
        if (!\is_object($object)) {
15 ✔
7917
            return $object;
12 ✔
7918
        }
7919

7920
        $object = \get_object_vars($object);
15 ✔
7921

7922
        /**
7923
         * @psalm-suppress PossiblyInvalidArgument - the parameter is always some kind of array - false-positive from psalm?
7924
         */
7925
        return \array_map([static::class, 'objectToArray'], $object);
15 ✔
7926
    }
7927

7928
    /**
7929
     * @param array $data
7930
     * @param bool  $checkPropertiesInConstructor
7931
     *
7932
     * @return void
7933
     *
7934
     * @phpstan-param array<mixed,T> $data
7935
     */
7936
    protected function setInitialValuesAndProperties(array &$data, bool $checkPropertiesInConstructor)
7937
    {
7938
        $checkPropertiesInConstructor = $this->checkForMissingPropertiesInConstructor === true
3,756 ✔
7939
                                        &&
3,756 ✔
7940
                                        $checkPropertiesInConstructor === true;
3,756 ✔
7941

7942
        if ($this->properties === []) {
3,756 ✔
7943
            if (
7944
                $this->checkPropertyTypes === true
3,471 ✔
7945
                ||
7946
                $checkPropertiesInConstructor === true
3,471 ✔
7947
            ) {
7948
                $this->properties = $this->getPropertiesFromPhpDoc();
75 ✔
7949
            }
7950

7951
            /** @var TypeCheckInterface[] $properties */
7952
            $properties = $this->properties;
3,471 ✔
7953

7954
            if (
7955
                $this->checkPropertiesMismatchInConstructor === true
3,471 ✔
7956
                &&
7957
                \count($data) !== 0
3,471 ✔
7958
                &&
7959
                \count(\array_diff_key($properties, $data)) > 0
3,471 ✔
7960
            ) {
7961
                throw new \TypeError('Property mismatch - input: ' . \print_r(\array_keys($data), true) . ' | expected: ' . \print_r(\array_keys($properties), true));
3 ✔
7962
            }
7963
        }
7964

7965
        foreach ($data as $key => &$valueInner) {
3,753 ✔
7966
            $this->internalSet(
3,261 ✔
7967
                $key,
3,261 ✔
7968
                $valueInner,
3,261 ✔
7969
                $checkPropertiesInConstructor
3,261 ✔
7970
            );
3,261 ✔
7971
        }
7972
    }
7973

7974
    /**
7975
     * sorting keys
7976
     *
7977
     * @param array      $elements
7978
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
7979
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
7980
     *                              <strong>SORT_NATURAL</strong></p>
7981
     *
7982
     * @return $this
7983
     *               <p>(Mutable) Return this Arrayy object.</p>
7984
     *
7985
     * @phpstan-param  array<mixed|TKey,T> $elements
7986
     * @phpstan-return static<TKey,T>
7987
     */
7988
    protected function sorterKeys(
7989
        array &$elements,
7990
        $direction = \SORT_ASC,
7991
        int $strategy = \SORT_REGULAR
7992
    ): self {
7993
        $direction = $this->getDirection($direction);
54 ✔
7994

7995
        switch ($direction) {
7996
            case 'desc':
54 ✔
7997
            case \SORT_DESC:
7998
                \krsort($elements, $strategy);
18 ✔
7999

8000
                break;
18 ✔
8001
            case 'asc':
39 ✔
8002
            case \SORT_ASC:
39 ✔
8003
            default:
8004
                \ksort($elements, $strategy);
39 ✔
8005
        }
8006

8007
        return $this;
54 ✔
8008
    }
8009

8010
    /**
8011
     * @param array      $elements  <p>Warning: used as reference</p>
8012
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
8013
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
8014
     *                              <strong>SORT_NATURAL</strong></p>
8015
     * @param bool       $keepKeys
8016
     *
8017
     * @return $this
8018
     *               <p>(Mutable) Return this Arrayy object.</p>
8019
     *
8020
     * @phpstan-param array<mixed|TKey,T> $elements
8021
     * @phpstan-return static<int|TKey,T>
8022
     */
8023
    protected function sorting(
8024
        array &$elements,
8025
        $direction = \SORT_ASC,
8026
        int $strategy = \SORT_REGULAR,
8027
        bool $keepKeys = false
8028
    ): self {
8029
        $direction = $this->getDirection($direction);
72 ✔
8030

8031
        if (!$strategy) {
72 ✔
8032
            $strategy = \SORT_REGULAR;
72 ✔
8033
        }
8034

8035
        switch ($direction) {
8036
            case 'desc':
72 ✔
8037
            case \SORT_DESC:
8038
                if ($keepKeys) {
39 ✔
8039
                    \arsort($elements, $strategy);
27 ✔
8040
                } else {
8041
                    \rsort($elements, $strategy);
12 ✔
8042
                }
8043

8044
                break;
39 ✔
8045
            case 'asc':
33 ✔
8046
            case \SORT_ASC:
33 ✔
8047
            default:
8048
                if ($keepKeys) {
33 ✔
8049
                    \asort($elements, $strategy);
12 ✔
8050
                } else {
8051
                    \sort($elements, $strategy);
21 ✔
8052
                }
8053
        }
8054

8055
        return $this;
72 ✔
8056
    }
8057

8058
    /**
8059
     * @param array $array
8060
     *
8061
     * @return array
8062
     *
8063
     * @psalm-mutation-free
8064
     */
8065
    private function getArrayRecursiveHelperArrayy(array $array)
8066
    {
8067
        if ($array === []) {
75 ✔
UNCOV
8068
            return [];
×
8069
        }
8070

8071
        \array_walk_recursive(
75 ✔
8072
            $array,
75 ✔
8073
            /**
8074
             * @param array|self $item
8075
             *
8076
             * @return void
8077
             */
8078
            static function (&$item) {
75 ✔
8079
                if ($item instanceof self) {
75 ✔
8080
                    $item = $item->getArray();
3 ✔
8081
                }
8082
            }
75 ✔
8083
        );
75 ✔
8084

8085
        return $array;
75 ✔
8086
    }
8087

8088
    /**
8089
     * @param int|string|null $key
8090
     * @param mixed           $value
8091
     *
8092
     * @return void
8093
     */
8094
    private function checkType($key, $value)
8095
    {
8096
        if (
8097
            $key !== null
390 ✔
8098
            &&
8099
            isset($this->properties[$key]) === false
390 ✔
8100
            &&
8101
            $this->checkPropertiesMismatch === true
390 ✔
8102
        ) {
UNCOV
8103
            throw new \TypeError('The key "' . $key . '" does not exists as "@property" phpdoc. (' . \get_class($this) . ').');
×
8104
        }
8105

8106
        if (isset($this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES])) {
390 ✔
8107
            $this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES]->checkType($value);
345 ✔
8108
        } elseif ($key !== null && isset($this->properties[$key])) {
78 ✔
8109
            $this->properties[$key]->checkType($value);
78 ✔
8110
        }
8111
    }
8112
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc