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

voku / Arrayy / 24917960344

25 Apr 2026 12:27AM UTC coverage: 89.25% (-0.09%) from 89.336%
24917960344

push

github

web-flow
Merge pull request #159 from voku/copilot/add-native-properties-type-checking

Fix PHP 8.0 intersection-type CI failure, strengthen type-check coverage, and refresh PHP 8.0+ docs/CI matrix

143 of 164 new or added lines in 6 files covered. (87.2%)

12 existing lines in 1 file now uncovered.

2607 of 2921 relevant lines covered (89.25%)

238.01 hits per line

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

91.73
/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);
8,965 ✔
122

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

129
        $this->setInitialValuesAndProperties($data, $checkPropertiesInConstructor);
8,951 ✔
130

131
        $this->setIteratorClass($iteratorClass);
8,804 ✔
132
    }
133

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

143
        if ($this->generator !== null) {
371 ✔
144
            $this->generator = clone $this->generator;
7 ✔
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) {
7 ✔
161
            $this->generatorToArray();
7 ✔
162

163
            return $this->array[$key] ?? false;
7 ✔
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);
7 ✔
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);
21 ✔
201
    }
202

203
    /**
204
     * magic to string
205
     *
206
     * @return string
207
     */
208
    public function __toString(): string
209
    {
210
        return $this->toString();
105 ✔
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);
1,083 ✔
239

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

248
        return $return;
1,083 ✔
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) {
98 ✔
269
            $get = $this->get($key);
35 ✔
270
            if ($get !== null) {
35 ✔
271
                $value = \array_merge_recursive(
7 ✔
272
                    !$get instanceof self ? [$get] : $get->getArray(),
7 ✔
273
                    !\is_array($value) ? [$value] : $value
7 ✔
274
                );
7 ✔
275
            }
276

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

279
            return $this;
28 ✔
280
        }
281

282
        return $this->append($value);
63 ✔
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();
147 ✔
306

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

311
        if ($key !== null) {
140 ✔
312
            if (
313
                isset($this->array[$key])
14 ✔
314
                &&
315
                \is_array($this->array[$key])
14 ✔
316
            ) {
317
                $this->array[$key][] = $value; // @phpstan-ignore assign.propertyType
×
318
            } else {
319
                $this->array[$key] = $value;
14 ✔
320
            }
321
        } else {
322
            $this->array[] = $value;
126 ✔
323
        }
324

325
        return $this;
140 ✔
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 {
7 ✔
352
            if ($this->properties !== []) {
7 ✔
353
                $this->checkType($key, $value);
×
354
            }
355

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

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

367
        return static::create(
7 ✔
368
            $generator,
7 ✔
369
            $this->iteratorClass,
7 ✔
370
            false
7 ✔
371
        );
7 ✔
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();
28 ✔
392

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

395
        return $this;
28 ✔
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;
28 ✔
416

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

422
        return $that;
28 ✔
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
1,050 ✔
470
            &&
471
            $mode === \COUNT_NORMAL
1,050 ✔
472
        ) {
473
            return \iterator_count($this->generator);
28 ✔
474
        }
475

476
        return \count($this->toArray(), $mode);
1,022 ✔
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);
7 ✔
501

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

505
        return $this->array;
7 ✔
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();
42 ✔
518

519
        return $this->array;
42 ✔
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) {
238 ✔
536
            $generator = clone $this->generator;
14 ✔
537

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

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

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

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

554
        if ($iterator === ArrayyIterator::class) {
231 ✔
555
            return new $iterator($this->toArray(), 0, static::class);
231 ✔
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;
231 ✔
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();
28 ✔
594

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

597
        return $this;
28 ✔
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;
28 ✔
617

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

623
        return $that;
28 ✔
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();
56 ✔
638

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

641
        return $this;
56 ✔
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;
28 ✔
656

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

662
        return $that;
28 ✔
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();
70 ✔
677

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

680
        return $this;
70 ✔
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;
28 ✔
695

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

701
        return $that;
28 ✔
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) {
1,293 ✔
718
            $offset = (int) $offset;
7 ✔
719
        }
720
        \assert(\is_int($offset) || \is_string($offset));
721

722
        $offsetExists = $this->keyExists($offset);
1,293 ✔
723
        if ($offsetExists === true) {
1,293 ✔
724
            return true;
1,146 ✔
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
952 ✔
735
            &&
736
            (string) $offset === $offset
952 ✔
737
            &&
738
            \strpos($offset, $this->pathSeparator) !== false
952 ✔
739
        ) {
740
            $explodedPath = \explode($this->pathSeparator, (string) $offset);
28 ✔
741
            if ($explodedPath !== false) {
28 ✔
742
                /** @var string $lastOffset - helper for phpstan */
743
                $lastOffset = \array_pop($explodedPath);
28 ✔
744
                $containerPath = \implode($this->pathSeparator, $explodedPath);
28 ✔
745

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

759
        return $offsetExists;
952 ✔
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;
1,076 ✔
777

778
        if ($this->offsetExists($offset)) {
1,076 ✔
779
            $value = &$this->__get($offset);
1,062 ✔
780
        }
781

782
        return $value;
1,076 ✔
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();
252 ✔
797

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

803
            $this->array[] = $value;
49 ✔
804
        } else {
805
            $this->internalSet(
203 ✔
806
                $offset,
203 ✔
807
                $value,
203 ✔
808
                true
203 ✔
809
            );
203 ✔
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();
182 ✔
825

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

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

833
            return;
98 ✔
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
70 ✔
844
            &&
845
            (string) $offset === $offset
70 ✔
846
            &&
847
            \strpos($offset, $this->pathSeparator) !== false
70 ✔
848
        ) {
849
            $path = \explode($this->pathSeparator, (string) $offset);
49 ✔
850

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

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

871
        unset($this->array[$offset]);
70 ✔
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();
7 ✔
886

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

891
        return \serialize($this);
7 ✔
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)) {
8,804 ✔
909
            $this->iteratorClass = $iteratorClass;
8,804 ✔
910

911
            return;
8,804 ✔
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)) {
56 ✔
947
            throw new \InvalidArgumentException('Passed function must be callable');
×
948
        }
949

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

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

954
        return $this;
56 ✔
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;
28 ✔
974

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

980
        return $that;
28 ✔
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);
35 ✔
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);
7 ✔
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) {
7 ✔
1039
            parent::unserialize($string);
×
1040

1041
            return $this;
×
1042
        }
1043

1044
        return \unserialize($string, ['allowed_classes' => [__CLASS__, TypeCheckPhpDoc::class]]);
7 ✔
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();
7 ✔
1067

1068
        if ($key !== null) {
7 ✔
1069
            if (
1070
                isset($this->array[$key])
7 ✔
1071
                &&
1072
                \is_array($this->array[$key])
7 ✔
1073
            ) {
1074
                foreach ($values as $value) {
7 ✔
1075
                    $this->array[$key][] = $value;
7 ✔
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;
7 ✔
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 = [];
70 ✔
1106

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

1119
        return self::create(
70 ✔
1120
            $result,
70 ✔
1121
            $this->iteratorClass,
70 ✔
1122
            false
70 ✔
1123
        );
70 ✔
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 = [];
70 ✔
1141

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

1154
        return self::create($result, $this->iteratorClass, false);
70 ✔
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();
28 ✔
1168

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

1171
        return $this;
28 ✔
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;
70 ✔
1186

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

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

1191
        return $that;
70 ✔
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;
21 ✔
1217

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

1222
        return static::create(
21 ✔
1223
            $that->toArray(),
21 ✔
1224
            $this->iteratorClass,
21 ✔
1225
            false
21 ✔
1226
        );
21 ✔
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
        $array = $this->toArray();
70 ✔
1245
        $count = \count($array, \COUNT_NORMAL);
70 ✔
1246

1247
        if (!$count) {
70 ✔
1248
            return 0;
14 ✔
1249
        }
1250

1251
        if ((int) $decimals !== $decimals) {
56 ✔
1252
            $decimals = 0;
21 ✔
1253
        }
1254

1255
        $sum = 0;
56 ✔
1256
        foreach ($array as $value) {
56 ✔
1257
            if (
1258
                \is_int($value)
56 ✔
1259
                ||
1260
                \is_float($value)
49 ✔
1261
                ||
1262
                \is_bool($value)
56 ✔
1263
            ) {
1264
                $sum += $value;
42 ✔
1265
            } elseif (\is_string($value) && \is_numeric($value)) {
14 ✔
NEW
1266
                $sum += (float) $value;
×
1267
            }
1268
        }
1269

1270
        return \round($sum / $count, $decimals);
56 ✔
1271
    }
1272

1273
    /**
1274
     * Changes all keys in an array.
1275
     *
1276
     * @param int $case [optional] <p> Either <strong>CASE_UPPER</strong><br />
1277
     *                  or <strong>CASE_LOWER</strong> (default)</p>
1278
     *
1279
     * @return static
1280
     *                <p>(Immutable)</p>
1281
     *
1282
     * @phpstan-return static<TKey,T>
1283
     * @psalm-mutation-free
1284
     */
1285
    public function changeKeyCase(int $case = \CASE_LOWER): self
1286
    {
1287
        if (
1288
            $case !== \CASE_LOWER
7 ✔
1289
            &&
1290
            $case !== \CASE_UPPER
7 ✔
1291
        ) {
1292
            $case = \CASE_LOWER;
×
1293
        }
1294

1295
        $return = [];
7 ✔
1296
        foreach ($this->getGenerator() as $key => $value) {
7 ✔
1297
            if ($case === \CASE_LOWER) {
7 ✔
1298
                $key = \mb_convert_case(
7 ✔
1299
                    (string) $key,
7 ✔
1300
                    \defined('MB_CASE_LOWER_SIMPLE') ? \MB_CASE_LOWER_SIMPLE : \MB_CASE_LOWER,
7 ✔
1301
                    'UTF-8'
7 ✔
1302
                );
7 ✔
1303
            } else {
1304
                $key = \mb_convert_case(
7 ✔
1305
                    (string) $key,
7 ✔
1306
                    \defined('MB_CASE_UPPER_SIMPLE') ? \MB_CASE_UPPER_SIMPLE : \MB_CASE_UPPER,
7 ✔
1307
                    'UTF-8'
7 ✔
1308
                );
7 ✔
1309
            }
1310

1311
            $return[$key] = $value;
7 ✔
1312
        }
1313

1314
        return static::create(
7 ✔
1315
            $return,
7 ✔
1316
            $this->iteratorClass,
7 ✔
1317
            false
7 ✔
1318
        );
7 ✔
1319
    }
1320

1321
    /**
1322
     * Change the path separator of the array wrapper.
1323
     *
1324
     * By default, the separator is: "."
1325
     *
1326
     * @param non-empty-string $separator <p>Separator to set.</p>
1327
     *
1328
     * @return $this
1329
     *               <p>(Mutable) Return this Arrayy object.</p>
1330
     *
1331
     * @phpstan-return static<TKey,T>
1332
     */
1333
    public function changeSeparator($separator): self
1334
    {
1335
        $this->pathSeparator = $separator;
77 ✔
1336

1337
        return $this;
77 ✔
1338
    }
1339

1340
    /**
1341
     * Create a chunked version of the current array.
1342
     *
1343
     * EXAMPLE: <code>
1344
     * a([-9, -8, -7, 1.32])->chunk(2); // Arrayy[[-9, -8], [-7, 1.32]]
1345
     * </code>
1346
     *
1347
     * @param int  $size         <p>Size of each chunk.</p>
1348
     * @param bool $preserveKeys <p>Whether array keys are preserved or no.</p>
1349
     *
1350
     * @return static|static[]
1351
     *                <p>(Immutable) A new array of chunks from the original array.</p>
1352
     *
1353
     * @phpstan-return static<int, static<array-key,T>>
1354
     * @psalm-mutation-free
1355
     */
1356
    public function chunk($size, $preserveKeys = false): self
1357
    {
1358
        if ($preserveKeys) {
42 ✔
1359
            $generator = function () use ($size) {
×
1360
                $values = [];
×
1361
                $tmpCounter = 0;
×
1362
                foreach ($this->getGenerator() as $key => $value) {
×
1363
                    ++$tmpCounter;
×
1364

1365
                    $values[$key] = $value;
×
1366
                    if ($tmpCounter === $size) {
×
1367
                        yield $values;
×
1368

1369
                        $values = [];
×
1370
                        $tmpCounter = 0;
×
1371
                    }
1372
                }
1373

1374
                if ($values !== []) {
×
1375
                    yield $values;
×
1376
                }
1377
            };
×
1378
        } else {
1379
            $generator = function () use ($size) {
42 ✔
1380
                $values = [];
42 ✔
1381
                $tmpCounter = 0;
42 ✔
1382
                foreach ($this->getGenerator() as $value) {
42 ✔
1383
                    ++$tmpCounter;
42 ✔
1384

1385
                    $values[] = $value;
42 ✔
1386
                    if ($tmpCounter === $size) {
42 ✔
1387
                        yield $values;
42 ✔
1388

1389
                        $values = [];
42 ✔
1390
                        $tmpCounter = 0;
42 ✔
1391
                    }
1392
                }
1393

1394
                if ($values !== []) {
42 ✔
1395
                    yield $values;
35 ✔
1396
                }
1397
            };
42 ✔
1398
        }
1399

1400
        return static::create(
42 ✔
1401
            $generator,
42 ✔
1402
            $this->iteratorClass,
42 ✔
1403
            false
42 ✔
1404
        );
42 ✔
1405
    }
1406

1407
    /**
1408
     * Clean all falsy values from the current array.
1409
     *
1410
     * EXAMPLE: <code>
1411
     * a([-8 => -9, 1, 2 => false])->clean(); // Arrayy[-8 => -9, 1]
1412
     * </code>
1413
     *
1414
     * @return static
1415
     *                <p>(Immutable)</p>
1416
     *
1417
     * @phpstan-return static<TKey,T>
1418
     * @psalm-mutation-free
1419
     */
1420
    public function clean(): self
1421
    {
1422
        return $this->filter(
56 ✔
1423
            static function ($value) {
56 ✔
1424
                return (bool) $value;
49 ✔
1425
            }
56 ✔
1426
        );
56 ✔
1427
    }
1428

1429
    /**
1430
     * WARNING!!! -> Clear the current full array or a $key of it.
1431
     *
1432
     * EXAMPLE: <code>
1433
     * a([-8 => -9, 1, 2 => false])->clear(); // Arrayy[]
1434
     * </code>
1435
     *
1436
     * @param int|int[]|string|string[]|null $key
1437
     *
1438
     * @return $this
1439
     *               <p>(Mutable) Return this Arrayy object, with an empty array.</p>
1440
     *
1441
     * @phpstan-return static<TKey,T>
1442
     */
1443
    public function clear($key = null): self
1444
    {
1445
        if ($key !== null) {
70 ✔
1446
            if (\is_array($key)) {
21 ✔
1447
                foreach ($key as $keyTmp) {
7 ✔
1448
                    $this->offsetUnset($keyTmp);
7 ✔
1449
                }
1450
            } else {
1451
                $this->offsetUnset($key);
14 ✔
1452
            }
1453

1454
            return $this;
21 ✔
1455
        }
1456

1457
        $this->array = [];
49 ✔
1458
        $this->generator = null;
49 ✔
1459

1460
        return $this;
49 ✔
1461
    }
1462

1463
    /**
1464
     * Check if an item is in the current array.
1465
     *
1466
     * EXAMPLE: <code>
1467
     * a([1, true])->containsOnly(true); // false
1468
     * </code>
1469
     *
1470
     * @param float|int|string $value
1471
     * @param bool             $recursive
1472
     * @param bool             $strict
1473
     *
1474
     * @return bool
1475
     * @psalm-mutation-free
1476
     */
1477
    public function containsOnly($value, bool $recursive = false, bool $strict = true): bool
1478
    {
1479
        if ($recursive === true) {
70 ✔
1480
            return $this->in_array_recursive($value, $this->toArray(), $strict);
×
1481
        }
1482

1483
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1484
        $tmpCount = 0;
70 ✔
1485
        foreach ($this->getGeneratorByReference() as &$valueFromArray) {
70 ✔
1486
            $tmpCount++;
56 ✔
1487

1488
            if ($strict) {
56 ✔
1489
                if ($value !== $valueFromArray) {
56 ✔
1490
                    return false;
36 ✔
1491
                }
1492
            } else {
1493
                /** @noinspection NestedPositiveIfStatementsInspection */
1494
                if ($value != $valueFromArray) {
×
1495
                    return false;
×
1496
                }
1497
            }
1498
        }
1499

1500
        return $tmpCount !== 0;
49 ✔
1501
    }
1502

1503
    /**
1504
     * Check if an item is in the current array.
1505
     *
1506
     * EXAMPLE: <code>
1507
     * a([1, true])->contains(true); // true
1508
     * </code>
1509
     *
1510
     * @param float|int|string $value
1511
     * @param bool             $recursive
1512
     * @param bool             $strict
1513
     *
1514
     * @return bool
1515
     * @psalm-mutation-free
1516
     */
1517
    public function contains($value, bool $recursive = false, bool $strict = true): bool
1518
    {
1519
        if ($recursive === true) {
163 ✔
1520
            return $this->in_array_recursive($value, $this->toArray(), $strict);
128 ✔
1521
        }
1522

1523
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1524
        foreach ($this->getGeneratorByReference() as &$valueFromArray) {
98 ✔
1525
            if ($strict) {
77 ✔
1526
                if ($value === $valueFromArray) {
77 ✔
1527
                    return true;
65 ✔
1528
                }
1529
            } else {
1530
                /** @noinspection NestedPositiveIfStatementsInspection */
1531
                if ($value == $valueFromArray) {
×
1532
                    return true;
×
1533
                }
1534
            }
1535
        }
1536

1537
        return false;
49 ✔
1538
    }
1539

1540
    /**
1541
     * Check if an (case-insensitive) string is in the current array.
1542
     *
1543
     * EXAMPLE: <code>
1544
     * a(['E', 'Γ©'])->containsCaseInsensitive('Γ‰'); // true
1545
     * </code>
1546
     *
1547
     * @param mixed $value
1548
     * @param bool  $recursive
1549
     *
1550
     * @return bool
1551
     * @psalm-mutation-free
1552
     *
1553
     * @psalm-suppress InvalidCast - hack for int|float|bool support
1554
     */
1555
    public function containsCaseInsensitive($value, $recursive = false): bool
1556
    {
1557
        if ($value === null) {
182 ✔
1558
            return false;
14 ✔
1559
        }
1560

1561
        if ($recursive === true) {
168 ✔
1562
            /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1563
            foreach ($this->getGeneratorByReference() as &$valueTmp) {
168 ✔
1564
                if (\is_array($valueTmp)) {
154 ✔
1565
                    $return = (new self($valueTmp))->containsCaseInsensitive($value, $recursive);
35 ✔
1566
                    if ($return === true) {
35 ✔
1567
                        return $return;
27 ✔
1568
                    }
1569
                } elseif (\mb_strtoupper((string) $valueTmp) === \mb_strtoupper((string) $value)) {
154 ✔
1570
                    return true;
112 ✔
1571
                }
1572
            }
1573

1574
            return false;
56 ✔
1575
        }
1576

1577
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1578
        foreach ($this->getGeneratorByReference() as &$valueTmp) {
84 ✔
1579
            if (\mb_strtoupper((string) $valueTmp) === \mb_strtoupper((string) $value)) {
77 ✔
1580
                return true;
56 ✔
1581
            }
1582
        }
1583

1584
        return false;
28 ✔
1585
    }
1586

1587
    /**
1588
     * Check if the given key/index exists in the array.
1589
     *
1590
     * EXAMPLE: <code>
1591
     * a([1 => true])->containsKey(1); // true
1592
     * </code>
1593
     *
1594
     * @param int|string $key <p>key/index to search for</p>
1595
     *
1596
     * @return bool
1597
     *              <p>Returns true if the given key/index exists in the array, false otherwise.</p>
1598
     *
1599
     * @psalm-mutation-free
1600
     */
1601
    public function containsKey($key): bool
1602
    {
1603
        return $this->offsetExists($key);
28 ✔
1604
    }
1605

1606
    /**
1607
     * Check if all given needles are present in the array as key/index.
1608
     *
1609
     * EXAMPLE: <code>
1610
     * a([1 => true])->containsKeys(array(1 => 0)); // true
1611
     * </code>
1612
     *
1613
     * @param array $needles   <p>The keys you are searching for.</p>
1614
     * @param bool  $recursive
1615
     *
1616
     * @return bool
1617
     *              <p>Returns true if all the given keys/indexes exists in the array, false otherwise.</p>
1618
     *
1619
     * @phpstan-param array<TKey> $needles
1620
     * @psalm-mutation-free
1621
     */
1622
    public function containsKeys(array $needles, bool $recursive = false): bool
1623
    {
1624
        if ($recursive === true) {
14 ✔
1625
            return
14 ✔
1626
                \count(
14 ✔
1627
                    \array_intersect(
14 ✔
1628
                        $needles,
14 ✔
1629
                        $this->keys(true)->toArray()
14 ✔
1630
                    ),
14 ✔
1631
                    \COUNT_RECURSIVE
14 ✔
1632
                )
14 ✔
1633
                ===
14 ✔
1634
                \count(
14 ✔
1635
                    $needles,
14 ✔
1636
                    \COUNT_RECURSIVE
14 ✔
1637
                );
14 ✔
1638
        }
1639

1640
        return \count(
7 ✔
1641
            \array_intersect($needles, $this->keys()->toArray()),
7 ✔
1642
            \COUNT_NORMAL
7 ✔
1643
        )
7 ✔
1644
                ===
7 ✔
1645
                \count(
7 ✔
1646
                    $needles,
7 ✔
1647
                    \COUNT_NORMAL
7 ✔
1648
                );
7 ✔
1649
    }
1650

1651
    /**
1652
     * Check if all given needles are present in the array as key/index.
1653
     *
1654
     * @param array $needles <p>The keys you are searching for.</p>
1655
     *
1656
     * @return bool
1657
     *              <p>Returns true if all the given keys/indexes exists in the array, false otherwise.</p>
1658
     *
1659
     * @phpstan-param array<TKey> $needles
1660
     * @psalm-mutation-free
1661
     */
1662
    public function containsKeysRecursive(array $needles): bool
1663
    {
1664
        return $this->containsKeys($needles, true);
7 ✔
1665
    }
1666

1667
    /**
1668
     * alias: for "Arrayy->contains()"
1669
     *
1670
     * @param float|int|string $value
1671
     *
1672
     * @return bool
1673
     *
1674
     * @see Arrayy::contains()
1675
     * @psalm-mutation-free
1676
     */
1677
    public function containsValue($value): bool
1678
    {
1679
        return $this->contains($value);
63 ✔
1680
    }
1681

1682
    /**
1683
     * alias: for "Arrayy->contains($value, true)"
1684
     *
1685
     * @param float|int|string $value
1686
     *
1687
     * @return bool
1688
     *
1689
     * @see Arrayy::contains()
1690
     * @psalm-mutation-free
1691
     */
1692
    public function containsValueRecursive($value): bool
1693
    {
1694
        return $this->contains($value, true);
126 ✔
1695
    }
1696

1697
    /**
1698
     * Check if all given needles are present in the array.
1699
     *
1700
     * EXAMPLE: <code>
1701
     * a([1, true])->containsValues(array(1, true)); // true
1702
     * </code>
1703
     *
1704
     * @param array $needles
1705
     *
1706
     * @return bool
1707
     *              <p>Returns true if all the given values exists in the array, false otherwise.</p>
1708
     *
1709
     * @phpstan-param array<T> $needles
1710
     * @psalm-mutation-free
1711
     */
1712
    public function containsValues(array $needles): bool
1713
    {
1714
        return \count(
7 ✔
1715
            \array_intersect(
7 ✔
1716
                $needles,
7 ✔
1717
                $this->toArray()
7 ✔
1718
            ),
7 ✔
1719
            \COUNT_NORMAL
7 ✔
1720
        )
7 ✔
1721
               ===
7 ✔
1722
               \count(
7 ✔
1723
                   $needles,
7 ✔
1724
                   \COUNT_NORMAL
7 ✔
1725
               );
7 ✔
1726
    }
1727

1728
    /**
1729
     * Counts all the values of an array
1730
     *
1731
     * @see          http://php.net/manual/en/function.array-count-values.php
1732
     *
1733
     * @return static
1734
     *                <p>
1735
     *                (Immutable)
1736
     *                An associative Arrayy-object of values from input as
1737
     *                keys and their count as value.
1738
     *                </p>
1739
     *
1740
     * @phpstan-return static<array-key,int>
1741
     * @psalm-mutation-free
1742
     */
1743
    public function countValues(): self
1744
    {
1745
        /** @phpstan-var static<array-key,int> $return - help for phpstan */
1746
        $return = self::create(\array_count_values($this->toArray()), $this->iteratorClass);
49 ✔
1747

1748
        return $return;
49 ✔
1749
    }
1750

1751
    /**
1752
     * Creates an Arrayy object.
1753
     *
1754
     * @param mixed  $data
1755
     * @param string $iteratorClass
1756
     * @param bool   $checkPropertiesInConstructor
1757
     *
1758
     * @return static
1759
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1760
     *
1761
     * @phpstan-param  class-string<\Arrayy\ArrayyIterator<TKey,T>> $iteratorClass
1762
     * @phpstan-return static<TKey,T>
1763
     * @psalm-mutation-free
1764
     */
1765
    public static function create(
1766
        $data = [],
1767
        string $iteratorClass = ArrayyIterator::class,
1768
        bool $checkPropertiesInConstructor = true
1769
    ) {
1770
        return new static( // @phpstan-ignore new.static
5,438 ✔
1771
            $data,
5,438 ✔
1772
            $iteratorClass,
5,438 ✔
1773
            $checkPropertiesInConstructor
5,438 ✔
1774
        );
5,438 ✔
1775
    }
1776

1777
    /**
1778
     * Flatten an array with the given character as a key delimiter.
1779
     *
1780
     * EXAMPLE: <code>
1781
     * $dot = a(['foo' => ['abc' => 'xyz', 'bar' => ['baz']]]);
1782
     * $flatten = $dot->flatten();
1783
     * $flatten['foo.abc']; // 'xyz'
1784
     * $flatten['foo.bar.0']; // 'baz'
1785
     * </code>
1786
     *
1787
     * @param string     $delimiter
1788
     * @param string     $prepend
1789
     * @param array|null $items
1790
     *
1791
     * @return array
1792
     */
1793
    public function flatten($delimiter = '.', $prepend = '', $items = null)
1794
    {
1795
        // init
1796
        $flatten = [];
14 ✔
1797

1798
        if ($items === null) {
14 ✔
1799
            $items = $this->getArray();
14 ✔
1800
        }
1801

1802
        foreach ($items as $key => $value) {
14 ✔
1803
            if (\is_array($value) && $value !== []) {
14 ✔
1804
                $flatten[] = $this->flatten($delimiter, $prepend . $key . $delimiter, $value);
14 ✔
1805
            } else {
1806
                $flatten[] = [$prepend . $key => $value];
14 ✔
1807
            }
1808
        }
1809

1810
        if (\count($flatten) === 0) {
14 ✔
1811
            return [];
×
1812
        }
1813

1814
        return \array_merge_recursive([], ...$flatten);
14 ✔
1815
    }
1816

1817
    /**
1818
     * WARNING: Creates an Arrayy object by reference.
1819
     *
1820
     * @param array $array
1821
     *
1822
     * @return $this
1823
     *               <p>(Mutable) Return this Arrayy object.</p>
1824
     *
1825
     * @phpstan-param  array<TKey,T> $array
1826
     * @phpstan-return $this<TKey,T>
1827
     *
1828
     * @internal this will not check any types because it's set directly as reference
1829
     */
1830
    public function createByReference(array &$array = []): self
1831
    {
1832
        $this->array = &$array;
198 ✔
1833
        $this->generator = null;
198 ✔
1834

1835
        return $this;
198 ✔
1836
    }
1837

1838
    /**
1839
     * Create an new instance from a callable function which will return an Generator.
1840
     *
1841
     * @param callable $generatorFunction
1842
     *
1843
     * @return static
1844
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1845
     *
1846
     * @phpstan-param callable():\Generator<TKey,T> $generatorFunction
1847
     * @phpstan-return static<TKey,T>
1848
     * @psalm-mutation-free
1849
     */
1850
    public static function createFromGeneratorFunction(callable $generatorFunction): self
1851
    {
1852
        return self::create($generatorFunction);
56 ✔
1853
    }
1854

1855
    /**
1856
     * Create an new instance filled with a copy of values from a "Generator"-object.
1857
     *
1858
     * @param \Generator $generator
1859
     *
1860
     * @return static
1861
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1862
     *
1863
     * @phpstan-param \Generator<TKey,T> $generator
1864
     * @phpstan-return static<TKey,T>
1865
     * @psalm-mutation-free
1866
     */
1867
    public static function createFromGeneratorImmutable(\Generator $generator): self
1868
    {
1869
        return self::create(\iterator_to_array($generator, true));
28 ✔
1870
    }
1871

1872
    /**
1873
     * Create an new Arrayy object via JSON.
1874
     *
1875
     * @param string $json
1876
     *
1877
     * @return static
1878
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1879
     *
1880
     * @phpstan-return static<int|string,mixed>
1881
     * @psalm-mutation-free
1882
     */
1883
    public static function createFromJson(string $json): self
1884
    {
1885
        return static::create(\json_decode($json, true));
42 ✔
1886
    }
1887

1888
    /**
1889
     * Create an new Arrayy object via JSON.
1890
     *
1891
     * @param array $array
1892
     *
1893
     * @return static
1894
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1895
     *
1896
     * @phpstan-param array<TKey,T> $array
1897
     * @phpstan-return static<TKey,T>
1898
     * @psalm-mutation-free
1899
     */
1900
    public static function createFromArray(array $array): self
1901
    {
1902
        return static::create($array);
7 ✔
1903
    }
1904

1905
    /**
1906
     * Create an new instance filled with values from an object that is iterable.
1907
     *
1908
     * @param \Traversable $object <p>iterable object</p>
1909
     *
1910
     * @return static
1911
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1912
     *
1913
     * @phpstan-param \Traversable<array-key,T> $object
1914
     * @phpstan-return static<array-key,T>
1915
     * @psalm-mutation-free
1916
     */
1917
    public static function createFromObject(\Traversable $object): self
1918
    {
1919
        // init
1920
        $arrayy = static::create();
28 ✔
1921

1922
        if ($object instanceof self) {
28 ✔
1923
            $objectArray = $object->getGenerator();
28 ✔
1924
        } else {
1925
            $objectArray = $object;
×
1926
        }
1927

1928
        foreach ($objectArray as $key => $value) {
28 ✔
1929
            /**
1930
             * @psalm-suppress ImpureMethodCall - object is already re-created
1931
             */
1932
            $arrayy->internalSet($key, $value);
21 ✔
1933
        }
1934

1935
        return $arrayy;
28 ✔
1936
    }
1937

1938
    /**
1939
     * Create an new instance filled with values from an object.
1940
     *
1941
     * @param object $object
1942
     *
1943
     * @return static
1944
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1945
     *
1946
     * @phpstan-return static<array-key,mixed>
1947
     * @psalm-mutation-free
1948
     */
1949
    public static function createFromObjectVars($object): self
1950
    {
1951
        return self::create(self::objectToArray($object));
35 ✔
1952
    }
1953

1954
    /**
1955
     * Create an new Arrayy object via string.
1956
     *
1957
     * @param string                $str       <p>The input string.</p>
1958
     * @param non-empty-string|null $delimiter <p>The boundary string.</p>
1959
     * @param string|null           $regEx     <p>Use the $delimiter or the $regEx, so if $pattern is null, $delimiter will be
1960
     *                                         used.</p>
1961
     *
1962
     * @return static
1963
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1964
     *
1965
     * @phpstan-return static<int,string>
1966
     * @psalm-mutation-free
1967
     */
1968
    public static function createFromString(string $str, ?string $delimiter = null, ?string $regEx = null): self
1969
    {
1970
        if ($regEx) {
70 ✔
1971
            \preg_match_all($regEx, $str, $array);
7 ✔
1972

1973
            if (!empty($array)) {
7 ✔
1974
                $array = $array[0];
7 ✔
1975
            }
1976
        } else {
1977
            /** @noinspection NestedPositiveIfStatementsInspection */
1978
            if ($delimiter !== null) {
63 ✔
1979
                $array = \explode($delimiter, $str);
49 ✔
1980
            } else {
1981
                $array = [$str];
14 ✔
1982
            }
1983
        }
1984

1985
        // trim all string in the array
1986
        /**
1987
         * @psalm-suppress MissingClosureParamType
1988
         */
1989
        \array_walk(
70 ✔
1990
            $array,
70 ✔
1991
            static function (&$val) {
70 ✔
1992
                if ((string) $val === $val) {
70 ✔
1993
                    $val = \trim($val);
70 ✔
1994
                }
1995
            }
70 ✔
1996
        );
70 ✔
1997

1998
        /** @var static<int,string> $return - help for phpstan */
1999
        $return = static::create($array);
70 ✔
2000

2001
        return $return;
70 ✔
2002
    }
2003

2004
    /**
2005
     * Create an new instance filled with a copy of values from a "Traversable"-object.
2006
     *
2007
     * @param \Traversable $traversable
2008
     * @param bool         $use_keys    [optional] <p>
2009
     *                                  Whether to use the iterator element keys as index.
2010
     *                                  </p>
2011
     *
2012
     * @return static
2013
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
2014
     *
2015
     * @phpstan-param \Traversable<array-key|TKey,T> $traversable
2016
     * @phpstan-return static<int|TKey,T>
2017
     * @psalm-mutation-free
2018
     */
2019
    public static function createFromTraversableImmutable(\Traversable $traversable, bool $use_keys = true): self
2020
    {
2021
        return self::create(\iterator_to_array($traversable, $use_keys));
7 ✔
2022
    }
2023

2024
    /**
2025
     * Create an new instance containing a range of elements.
2026
     *
2027
     * @param float|int|string $low  <p>First value of the sequence.</p>
2028
     * @param float|int|string $high <p>The sequence is ended upon reaching the end value.</p>
2029
     * @param float|int        $step <p>Used as the increment between elements in the sequence.</p>
2030
     *
2031
     * @return static
2032
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
2033
     *
2034
     * @phpstan-return static<int,int|string>
2035
     * @psalm-mutation-free
2036
     */
2037
    public static function createWithRange($low, $high, $step = 1): self
2038
    {
2039
        /** @phpstan-var static<int,int|string> $return - help for phpstan */
2040
        $return = static::create(\range($low, $high, $step));
14 ✔
2041

2042
        return $return;
14 ✔
2043
    }
2044

2045
    /**
2046
     * Gets the element of the array at the current internal iterator position.
2047
     *
2048
     * @return false|mixed
2049
     *
2050
     * @phpstan-return false|T
2051
     */
2052
    public function current()
2053
    {
2054
        if ($this->generator) {
×
2055
            return $this->generator->current();
×
2056
        }
2057

2058
        return \current($this->array);
×
2059
    }
2060

2061
    /**
2062
     * Custom sort by index via "uksort".
2063
     *
2064
     * EXAMPLE: <code>
2065
     * $callable = function ($a, $b) {
2066
     *     if ($a == $b) {
2067
     *         return 0;
2068
     *     }
2069
     *     return ($a > $b) ? 1 : -1;
2070
     * };
2071
     * $arrayy = a(['three' => 3, 'one' => 1, 'two' => 2]);
2072
     * $resultArrayy = $arrayy->customSortKeys($callable); // Arrayy['one' => 1, 'three' => 3, 'two' => 2]
2073
     * </code>
2074
     *
2075
     * @see          http://php.net/manual/en/function.uksort.php
2076
     *
2077
     * @param callable $callable
2078
     *
2079
     * @throws \InvalidArgumentException
2080
     *
2081
     * @return $this
2082
     *               <p>(Mutable) Return this Arrayy object.</p>
2083
     *
2084
     * @phpstan-param  callable(TKey,TKey):int $callable
2085
     * @phpstan-return static<TKey,T>
2086
     */
2087
    public function customSortKeys(callable $callable): self
2088
    {
2089
        $this->generatorToArray();
35 ✔
2090

2091
        \uksort($this->array, $callable);
35 ✔
2092

2093
        return $this;
35 ✔
2094
    }
2095

2096
    /**
2097
     * Custom sort by index via "uksort".
2098
     *
2099
     * @see          http://php.net/manual/en/function.uksort.php
2100
     *
2101
     * @param callable $callable
2102
     *
2103
     * @throws \InvalidArgumentException
2104
     *
2105
     * @return $this
2106
     *               <p>(Immutable) Return this Arrayy object.</p>
2107
     *
2108
     * @phpstan-param  callable(TKey,TKey):int $callable
2109
     * @phpstan-return static<TKey,T>
2110
     * @psalm-mutation-free
2111
     */
2112
    public function customSortKeysImmutable(callable $callable): self
2113
    {
2114
        $that = clone $this;
7 ✔
2115

2116
        $that->generatorToArray();
7 ✔
2117

2118
        /**
2119
         * @psalm-suppress ImpureFunctionCall - object is already cloned
2120
         */
2121
        \uksort($that->array, $callable);
7 ✔
2122

2123
        return $that;
7 ✔
2124
    }
2125

2126
    /**
2127
     * Custom sort by value via "usort".
2128
     *
2129
     * EXAMPLE: <code>
2130
     * $callable = function ($a, $b) {
2131
     *     if ($a == $b) {
2132
     *         return 0;
2133
     *     }
2134
     *     return ($a > $b) ? 1 : -1;
2135
     * };
2136
     * $arrayy = a(['three' => 3, 'one' => 1, 'two' => 2]);
2137
     * $resultArrayy = $arrayy->customSortValues($callable); // Arrayy[1, 2, 3]
2138
     * </code>
2139
     *
2140
     * @see          http://php.net/manual/en/function.usort.php
2141
     *
2142
     * @param callable $callable
2143
     *
2144
     * @return $this
2145
     *               <p>(Mutable) Return this Arrayy object.</p>
2146
     *
2147
     * @phpstan-param  callable(T,T):int $callable
2148
     * @phpstan-return static<int,T>
2149
     */
2150
    public function customSortValues(callable $callable): self
2151
    {
2152
        $this->generatorToArray();
77 ✔
2153

2154
        \usort($this->array, $callable);
77 ✔
2155

2156
        return $this;
77 ✔
2157
    }
2158

2159
    /**
2160
     * Custom sort by value via "usort".
2161
     *
2162
     * @see          http://php.net/manual/en/function.usort.php
2163
     *
2164
     * @param callable $callable
2165
     *
2166
     * @throws \InvalidArgumentException
2167
     *
2168
     * @return $this
2169
     *               <p>(Immutable) Return this Arrayy object.</p>
2170
     *
2171
     * @phpstan-param  callable(T,T):int $callable
2172
     * @phpstan-return static<int,T>
2173
     * @psalm-mutation-free
2174
     */
2175
    public function customSortValuesImmutable($callable): self
2176
    {
2177
        $that = clone $this;
35 ✔
2178

2179
        /**
2180
         * @psalm-suppress ImpureMethodCall - object is already cloned
2181
         */
2182
        $that->customSortValues($callable);
35 ✔
2183

2184
        return $that;
35 ✔
2185
    }
2186

2187
    /**
2188
     * Delete the given key or keys.
2189
     *
2190
     * @param int|int[]|string|string[] $keyOrKeys
2191
     *
2192
     * @return void
2193
     */
2194
    public function delete($keyOrKeys)
2195
    {
2196
        $keyOrKeys = (array) $keyOrKeys;
63 ✔
2197

2198
        foreach ($keyOrKeys as $key) {
63 ✔
2199
            $this->offsetUnset($key);
63 ✔
2200
        }
2201
    }
2202

2203
    /**
2204
     * Return elements where the values that are only in the current array.
2205
     *
2206
     * EXAMPLE: <code>
2207
     * a([1 => 1, 2 => 2])->diff([1 => 1]); // Arrayy[2 => 2]
2208
     * </code>
2209
     *
2210
     * @param array ...$array
2211
     *
2212
     * @return static
2213
     *                <p>(Immutable)</p>
2214
     *
2215
     * @phpstan-param  array<TKey,T> ...$array
2216
     * @phpstan-return static<TKey,T>
2217
     * @psalm-mutation-free
2218
     */
2219
    public function diff(array ...$array): self
2220
    {
2221
        if (\count($array) > 1) {
91 ✔
2222
            $array = \array_merge([], ...$array);
7 ✔
2223
        } else {
2224
            $array = $array[0];
91 ✔
2225
        }
2226

2227
        $generator = function () use ($array): \Generator {
91 ✔
2228
            foreach ($this->getGenerator() as $key => $value) {
91 ✔
2229
                if (\in_array($value, $array, true) === false) {
77 ✔
2230
                    yield $key => $value;
35 ✔
2231
                }
2232
            }
2233
        };
91 ✔
2234

2235
        return static::create(
91 ✔
2236
            $generator,
91 ✔
2237
            $this->iteratorClass,
91 ✔
2238
            false
91 ✔
2239
        );
91 ✔
2240
    }
2241

2242
    /**
2243
     * Return elements where the keys are only in the current array.
2244
     *
2245
     * @param array ...$array
2246
     *
2247
     * @return static
2248
     *                <p>(Immutable)</p>
2249
     *
2250
     * @phpstan-param  array<TKey,T> ...$array
2251
     * @phpstan-return static<TKey,T>
2252
     * @psalm-mutation-free
2253
     */
2254
    public function diffKey(array ...$array): self
2255
    {
2256
        if (\count($array) > 1) {
63 ✔
2257
            $array = \array_replace([], ...$array);
7 ✔
2258
        } else {
2259
            $array = $array[0];
56 ✔
2260
        }
2261

2262
        $generator = function () use ($array): \Generator {
63 ✔
2263
            foreach ($this->getGenerator() as $key => $value) {
63 ✔
2264
                if (\array_key_exists($key, $array) === false) {
56 ✔
2265
                    yield $key => $value;
14 ✔
2266
                }
2267
            }
2268
        };
63 ✔
2269

2270
        return static::create(
63 ✔
2271
            $generator,
63 ✔
2272
            $this->iteratorClass,
63 ✔
2273
            false
63 ✔
2274
        );
63 ✔
2275
    }
2276

2277
    /**
2278
     * Return elements where the values and keys are only in the current array.
2279
     *
2280
     * @param array ...$array
2281
     *
2282
     * @return static
2283
     *                <p>(Immutable)</p>
2284
     *
2285
     * @phpstan-param  array<TKey,T> $array
2286
     * @phpstan-return static<TKey,T>
2287
     * @psalm-mutation-free
2288
     */
2289
    public function diffKeyAndValue(array ...$array): self
2290
    {
2291
        if (\count($array) > 1) {
63 ✔
2292
            $array = \array_merge([], ...$array);
7 ✔
2293
        } else {
2294
            $array = $array[0];
56 ✔
2295
        }
2296

2297
        $generator = function () use ($array): \Generator {
63 ✔
2298
            foreach ($this->getGenerator() as $key => $value) {
63 ✔
2299
                $isset = isset($array[$key]);
56 ✔
2300

2301
                if (
2302
                    !$isset
56 ✔
2303
                    ||
2304
                    $array[$key] !== $value
56 ✔
2305
                ) {
2306
                    yield $key => $value;
28 ✔
2307
                }
2308
            }
2309
        };
63 ✔
2310

2311
        return static::create(
63 ✔
2312
            $generator,
63 ✔
2313
            $this->iteratorClass,
63 ✔
2314
            false
63 ✔
2315
        );
63 ✔
2316
    }
2317

2318
    /**
2319
     * Return elements where the values are only in the current multi-dimensional array.
2320
     *
2321
     * EXAMPLE: <code>
2322
     * a([1 => [1 => 1], 2 => [2 => 2]])->diffRecursive([1 => [1 => 1]]); // Arrayy[2 => [2 => 2]]
2323
     * </code>
2324
     *
2325
     * @param array                 $array
2326
     * @param array|\Generator|null $helperVariableForRecursion <p>(only for internal usage)</p>
2327
     *
2328
     * @return static
2329
     *                <p>(Immutable)</p>
2330
     *
2331
     * @phpstan-param  array<TKey,T> $array
2332
     * @phpstan-param  null|array<TKey,T>|\Generator<TKey,T> $helperVariableForRecursion
2333
     * @phpstan-return static<TKey,T>
2334
     * @psalm-mutation-free
2335
     */
2336
    public function diffRecursive(array $array = [], $helperVariableForRecursion = null): self
2337
    {
2338
        // init
2339
        $result = [];
7 ✔
2340

2341
        if (
2342
            $helperVariableForRecursion !== null
7 ✔
2343
            &&
2344
            \is_array($helperVariableForRecursion)
7 ✔
2345
        ) {
2346
            $arrayForTheLoop = $helperVariableForRecursion;
×
2347
        } else {
2348
            $arrayForTheLoop = $this->getGenerator();
7 ✔
2349
        }
2350

2351
        foreach ($arrayForTheLoop as $key => $value) {
7 ✔
2352
            if ($value instanceof self) {
7 ✔
2353
                $value = $value->toArray();
7 ✔
2354
            }
2355

2356
            if (\array_key_exists($key, $array)) {
7 ✔
2357
                if ($value !== $array[$key]) {
7 ✔
2358
                    $result[$key] = $value;
7 ✔
2359
                }
2360
            } else {
2361
                $result[$key] = $value;
7 ✔
2362
            }
2363
        }
2364

2365
        return static::create(
7 ✔
2366
            $result,
7 ✔
2367
            $this->iteratorClass,
7 ✔
2368
            false
7 ✔
2369
        );
7 ✔
2370
    }
2371

2372
    /**
2373
     * Return elements where the values that are only in the new $array.
2374
     *
2375
     * EXAMPLE: <code>
2376
     * a([1 => 1])->diffReverse([1 => 1, 2 => 2]); // Arrayy[2 => 2]
2377
     * </code>
2378
     *
2379
     * @param array $array
2380
     *
2381
     * @return static
2382
     *                <p>(Immutable)</p>
2383
     *
2384
     * @phpstan-param  array<TKey,T> $array
2385
     * @phpstan-return static<TKey,T>
2386
     * @psalm-mutation-free
2387
     */
2388
    public function diffReverse(array $array = []): self
2389
    {
2390
        return static::create(
56 ✔
2391
            \array_diff($array, $this->toArray()),
56 ✔
2392
            $this->iteratorClass,
56 ✔
2393
            false
56 ✔
2394
        );
56 ✔
2395
    }
2396

2397
    /**
2398
     * Divide an array into two arrays. One with keys and the other with values.
2399
     *
2400
     * EXAMPLE: <code>
2401
     * a(['a' => 1, 'b' => ''])->divide(); // Arrayy[Arrayy['a', 'b'], Arrayy[1, '']]
2402
     * </code>
2403
     *
2404
     * @return static
2405
     *                <p>(Immutable)</p>
2406
     *
2407
     * @phpstan-return static<TKey,T>
2408
     * @psalm-mutation-free
2409
     */
2410
    public function divide(): self
2411
    {
2412
        return static::create(
7 ✔
2413
            [
7 ✔
2414
                $this->keys(),
7 ✔
2415
                $this->values(),
7 ✔
2416
            ],
7 ✔
2417
            $this->iteratorClass,
7 ✔
2418
            false
7 ✔
2419
        );
7 ✔
2420
    }
2421

2422
    /**
2423
     * Iterate over the current array and modify the array's value.
2424
     *
2425
     * EXAMPLE: <code>
2426
     * $result = A::create();
2427
     * $closure = function ($value) {
2428
     *     return ':' . $value . ':';
2429
     * };
2430
     * a(['foo', 'bar' => 'bis'])->each($closure); // Arrayy[':foo:', 'bar' => ':bis:']
2431
     * </code>
2432
     *
2433
     * @param \Closure $closure
2434
     *
2435
     * @return static
2436
     *                <p>(Immutable)</p>
2437
     *
2438
     * @phpstan-param \Closure(T,?TKey):T $closure
2439
     * @phpstan-return static<TKey,T>
2440
     * @psalm-mutation-free
2441
     */
2442
    public function each(\Closure $closure): self
2443
    {
2444
        // init
2445
        $array = [];
42 ✔
2446

2447
        foreach ($this->getGenerator() as $key => $value) {
42 ✔
2448
            $array[$key] = $closure($value, $key);
42 ✔
2449
        }
2450

2451
        return static::create(
42 ✔
2452
            $array,
42 ✔
2453
            $this->iteratorClass,
42 ✔
2454
            false
42 ✔
2455
        );
42 ✔
2456
    }
2457

2458
    /**
2459
     * Sets the internal iterator to the last element in the array and returns this element.
2460
     *
2461
     * @return false|mixed
2462
     *
2463
     * @phpstan-return T|false
2464
     */
2465
    public function end()
2466
    {
2467
        if ($this->generator) {
×
2468
            $count = $this->count();
×
2469
            if ($count === 0) {
×
2470
                return false;
×
2471
            }
2472

2473
            $counter = 0;
×
2474
            /** @noinspection PhpUnusedLocalVariableInspection */
2475
            foreach ($this->getIterator() as $item) {
×
2476
                if (++$counter === $count - 1) {
×
2477
                    break;
×
2478
                }
2479
            }
2480
        }
2481

2482
        return \end($this->array);
×
2483
    }
2484

2485
    /**
2486
     * Check if a value is in the current array using a closure.
2487
     *
2488
     * EXAMPLE: <code>
2489
     * $callable = function ($value, $key) {
2490
     *     return 2 === $key and 'two' === $value;
2491
     * };
2492
     * a(['foo', 2 => 'two'])->exists($callable); // true
2493
     * </code>
2494
     *
2495
     * @param \Closure $closure
2496
     *
2497
     * @return bool
2498
     *              <p>Returns true if the given value is found, false otherwise.</p>
2499
     *
2500
     * @phpstan-param \Closure(T,TKey):bool $closure
2501
     */
2502
    public function exists(\Closure $closure): bool
2503
    {
2504
        // init
2505
        $isExists = false;
28 ✔
2506

2507
        foreach ($this->getGenerator() as $key => $value) {
28 ✔
2508
            if ($closure($value, $key)) {
21 ✔
2509
                $isExists = true;
7 ✔
2510

2511
                break;
7 ✔
2512
            }
2513
        }
2514

2515
        return $isExists;
28 ✔
2516
    }
2517

2518
    /**
2519
     * Fill the array until "$num" with "$default" values.
2520
     *
2521
     * EXAMPLE: <code>
2522
     * a(['bar'])->fillWithDefaults(3, 'foo'); // Arrayy['bar', 'foo', 'foo']
2523
     * </code>
2524
     *
2525
     * @param int   $num
2526
     * @param mixed $default
2527
     *
2528
     * @return static
2529
     *                <p>(Immutable)</p>
2530
     *
2531
     * @phpstan-param T $default
2532
     * @phpstan-return static<TKey,T>
2533
     * @psalm-mutation-free
2534
     */
2535
    public function fillWithDefaults(int $num, $default = null): self
2536
    {
2537
        if ($num < 0) {
56 ✔
2538
            throw new \InvalidArgumentException('The $num parameter can only contain non-negative values.');
7 ✔
2539
        }
2540

2541
        $this->generatorToArray();
49 ✔
2542

2543
        $tmpArray = $this->array;
49 ✔
2544

2545
        $count = \count($tmpArray);
49 ✔
2546

2547
        while ($count < $num) {
49 ✔
2548
            $tmpArray[] = $default;
28 ✔
2549
            ++$count;
28 ✔
2550
        }
2551

2552
        return static::create(
49 ✔
2553
            $tmpArray,
49 ✔
2554
            $this->iteratorClass,
49 ✔
2555
            false
49 ✔
2556
        );
49 ✔
2557
    }
2558

2559
    /**
2560
     * Find all items in an array that pass the truth test.
2561
     *
2562
     * EXAMPLE: <code>
2563
     * $closure = function ($value) {
2564
     *     return $value % 2 !== 0;
2565
     * }
2566
     * a([1, 2, 3, 4])->filter($closure); // Arrayy[0 => 1, 2 => 3]
2567
     * </code>
2568
     *
2569
     * @param \Closure|null $closure [optional] <p>
2570
     *                               The callback function to use
2571
     *                               </p>
2572
     *                               <p>
2573
     *                               If no callback is supplied, all entries of
2574
     *                               input equal to false (see
2575
     *                               converting to
2576
     *                               boolean) will be removed.
2577
     *                               </p>
2578
     * @param int           $flag    [optional] <p>
2579
     *                               Flag determining what arguments are sent to <i>callback</i>:
2580
     *                               </p>
2581
     *                               <ul>
2582
     *                               <li>
2583
     *                               <b>ARRAY_FILTER_USE_KEY</b> (1) - pass key as the only argument
2584
     *                               to <i>callback</i> instead of the value
2585
     *                               </li>
2586
     *                               <li>
2587
     *                               <b>ARRAY_FILTER_USE_BOTH</b> (2) - pass both value and key as
2588
     *                               arguments to <i>callback</i> instead of the value
2589
     *                               </li>
2590
     *                               </ul>
2591
     *
2592
     * @return static
2593
     *                <p>(Immutable)</p>
2594
     *
2595
     * @phpstan-param null|(\Closure(T,TKey=):bool)|(\Closure(T):bool)|(\Closure(TKey):bool) $closure
2596
     * @phpstan-return static<TKey,T>
2597
     * @psalm-mutation-free
2598
     */
2599
    public function filter($closure = null, int $flag = \ARRAY_FILTER_USE_BOTH)
2600
    {
2601
        if (!$closure) {
91 ✔
2602
            return $this->clean();
7 ✔
2603
        }
2604

2605
        if ($flag === \ARRAY_FILTER_USE_KEY) {
91 ✔
2606
            $generator = function () use ($closure) {
7 ✔
2607
                foreach ($this->getGenerator() as $key => $value) {
7 ✔
2608
                    if ($closure($key) === true) {
7 ✔
2609
                        yield $key => $value;
7 ✔
2610
                    }
2611
                }
2612
            };
7 ✔
2613
        } elseif ($flag === \ARRAY_FILTER_USE_BOTH) {
91 ✔
2614
            /** @noinspection PhpSillyAssignmentInspection - hack for phpstan - https://github.com/phpstan/phpstan/issues/4192 */
2615
            /** @phpstan-var \Closure(T,TKey):bool $closure */
2616
            $closure = $closure;
91 ✔
2617

2618
            $generator = function () use ($closure) {
91 ✔
2619
                foreach ($this->getGenerator() as $key => $value) {
84 ✔
2620
                    if ($closure($value, $key) === true) {
77 ✔
2621
                        yield $key => $value;
70 ✔
2622
                    }
2623
                }
2624
            };
91 ✔
2625
        } else {
2626
            $generator = function () use ($closure) {
7 ✔
2627
                foreach ($this->getGenerator() as $key => $value) {
7 ✔
2628
                    if ($closure($value) === true) {
7 ✔
2629
                        yield $key => $value;
7 ✔
2630
                    }
2631
                }
2632
            };
7 ✔
2633
        }
2634

2635
        return static::create(
91 ✔
2636
            $generator,
91 ✔
2637
            $this->iteratorClass,
91 ✔
2638
            false
91 ✔
2639
        );
91 ✔
2640
    }
2641

2642
    /**
2643
     * Filters an array of objects (or a numeric array of associative arrays) based on the value of a particular
2644
     * property within that.
2645
     *
2646
     * @param string      $property
2647
     * @param mixed       $value
2648
     * @param string|null $comparisonOp
2649
     *                                  <p>
2650
     *                                  'eq' (equals),<br />
2651
     *                                  'gt' (greater),<br />
2652
     *                                  'gte' || 'ge' (greater or equals),<br />
2653
     *                                  'lt' (less),<br />
2654
     *                                  'lte' || 'le' (less or equals),<br />
2655
     *                                  'ne' (not equals),<br />
2656
     *                                  'contains',<br />
2657
     *                                  'notContains',<br />
2658
     *                                  'newer' (via strtotime),<br />
2659
     *                                  'older' (via strtotime),<br />
2660
     *                                  </p>
2661
     *
2662
     * @return static
2663
     *                <p>(Immutable)</p>
2664
     *
2665
     * @phpstan-param array|T $value
2666
     * @phpstan-return static<TKey,T>
2667
     * @psalm-mutation-free
2668
     *
2669
     * @psalm-suppress MissingClosureReturnType
2670
     * @psalm-suppress MissingClosureParamType
2671
     */
2672
    public function filterBy(
2673
        string $property,
2674
        $value,
2675
        ?string $comparisonOp = null
2676
    ): self {
2677
        if (!$comparisonOp) {
7 ✔
2678
            $comparisonOp = \is_array($value) ? 'contains' : 'eq';
7 ✔
2679
        }
2680

2681
        $ops = [
7 ✔
2682
            'eq' => static function ($item, $prop, $value): bool {
7 ✔
2683
                return $item[$prop] === $value;
7 ✔
2684
            },
7 ✔
2685
            'gt' => static function ($item, $prop, $value): bool {
7 ✔
2686
                return $item[$prop] > $value;
×
2687
            },
7 ✔
2688
            'ge' => static function ($item, $prop, $value): bool {
7 ✔
2689
                return $item[$prop] >= $value;
×
2690
            },
7 ✔
2691
            'gte' => static function ($item, $prop, $value): bool {
7 ✔
2692
                return $item[$prop] >= $value;
×
2693
            },
7 ✔
2694
            'lt' => static function ($item, $prop, $value): bool {
7 ✔
2695
                return $item[$prop] < $value;
7 ✔
2696
            },
7 ✔
2697
            'le' => static function ($item, $prop, $value): bool {
7 ✔
2698
                return $item[$prop] <= $value;
×
2699
            },
7 ✔
2700
            'lte' => static function ($item, $prop, $value): bool {
7 ✔
2701
                return $item[$prop] <= $value;
×
2702
            },
7 ✔
2703
            'ne' => static function ($item, $prop, $value): bool {
7 ✔
2704
                return $item[$prop] !== $value;
×
2705
            },
7 ✔
2706
            'contains' => static function ($item, $prop, $value): bool {
7 ✔
2707
                return \in_array($item[$prop], (array) $value, true);
7 ✔
2708
            },
7 ✔
2709
            'notContains' => static function ($item, $prop, $value): bool {
7 ✔
2710
                return !\in_array($item[$prop], (array) $value, true);
×
2711
            },
7 ✔
2712
            'newer' => static function ($item, $prop, $value): bool {
7 ✔
2713
                return \strtotime($item[$prop]) > \strtotime($value);
×
2714
            },
7 ✔
2715
            'older' => static function ($item, $prop, $value): bool {
7 ✔
2716
                return \strtotime($item[$prop]) < \strtotime($value);
×
2717
            },
7 ✔
2718
        ];
7 ✔
2719

2720
        $result = \array_values(
7 ✔
2721
            \array_filter(
7 ✔
2722
                $this->toArray(false, true),
7 ✔
2723
                static function ($item) use (
7 ✔
2724
                    $property,
7 ✔
2725
                    $value,
7 ✔
2726
                    $ops,
7 ✔
2727
                    $comparisonOp
7 ✔
2728
                ) {
7 ✔
2729
                    $item = (array) $item;
7 ✔
2730
                    $itemArrayy = static::create($item);
7 ✔
2731
                    $item[$property] = $itemArrayy->get($property, []);
7 ✔
2732

2733
                    return $ops[$comparisonOp]($item, $property, $value);
7 ✔
2734
                }
7 ✔
2735
            )
7 ✔
2736
        );
7 ✔
2737

2738
        return static::create(
7 ✔
2739
            $result,
7 ✔
2740
            $this->iteratorClass,
7 ✔
2741
            false
7 ✔
2742
        );
7 ✔
2743
    }
2744

2745
    /**
2746
     * Find the first item in an array that passes the truth test, otherwise return false.
2747
     *
2748
     * EXAMPLE: <code>
2749
     * $search = 'foo';
2750
     * $closure = function ($value, $key) use ($search) {
2751
     *     return $value === $search;
2752
     * };
2753
     * a(['foo', 'bar', 'lall'])->find($closure); // 'foo'
2754
     * </code>
2755
     *
2756
     * @param \Closure $closure
2757
     *
2758
     * @return false|mixed
2759
     *                     <p>Return false if we did not find the value.</p>
2760
     *
2761
     * @phpstan-param \Closure(T,TKey):bool $closure
2762
     * @phpstan-return T|false
2763
     */
2764
    public function find(\Closure $closure)
2765
    {
2766
        foreach ($this->getGenerator() as $key => $value) {
63 ✔
2767
            if ($closure($value, $key)) {
49 ✔
2768
                return $value;
42 ✔
2769
            }
2770
        }
2771

2772
        return false;
21 ✔
2773
    }
2774

2775
    /**
2776
     * Find the key of the first item in an array that passes the truth test, otherwise return false.
2777
     *
2778
     * EXAMPLE: <code>
2779
     * $search = 'foo';
2780
     * $closure = function ($value, $key) use ($search) {
2781
     *     return $value === $search;
2782
     * };
2783
     * a(['foo', 'bar', 'lall'])->findKey($closure); // 0
2784
     * </code>
2785
     *
2786
     * @param \Closure $closure
2787
     *
2788
     * @return false|int|string
2789
     *                          <p>Return false if we did not find the key.</p>
2790
     *
2791
     * @phpstan-param \Closure(T,TKey):bool $closure
2792
     * @phpstan-return TKey|false
2793
     */
2794
    public function findKey(\Closure $closure)
2795
    {
2796
        foreach ($this->getGenerator() as $key => $value) {
91 ✔
2797
            if ($closure($value, $key)) {
84 ✔
2798
                return $key;
70 ✔
2799
            }
2800
        }
2801

2802
        return false;
28 ✔
2803
    }
2804

2805
    /**
2806
     * find by ...
2807
     *
2808
     * EXAMPLE: <code>
2809
     * $array = [
2810
     *     0 => ['id' => 123, 'name' => 'foo', 'group' => 'primary', 'value' => 123456, 'when' => '2014-01-01'],
2811
     *     1 => ['id' => 456, 'name' => 'bar', 'group' => 'primary', 'value' => 1468, 'when' => '2014-07-15'],
2812
     * ];
2813
     * a($array)->filterBy('name', 'foo'); // Arrayy[0 => ['id' => 123, 'name' => 'foo', 'group' => 'primary', 'value' => 123456, 'when' => '2014-01-01']]
2814
     * </code>
2815
     *
2816
     * @param string $property
2817
     * @param mixed  $value
2818
     * @param string $comparisonOp
2819
     *
2820
     * @return static
2821
     *                <p>(Immutable)</p>
2822
     *
2823
     * @phpstan-param array|T $value
2824
     * @phpstan-return static<TKey,T>
2825
     * @psalm-mutation-free
2826
     */
2827
    public function findBy(string $property, $value, string $comparisonOp = 'eq'): self
2828
    {
2829
        return $this->filterBy($property, $value, $comparisonOp);
7 ✔
2830
    }
2831

2832
    /**
2833
     * Get the first value from the current array.
2834
     *
2835
     * EXAMPLE: <code>
2836
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->first(); // 'foo'
2837
     * </code>
2838
     *
2839
     * @return mixed|null
2840
     *                    <p>Return null if there wasn't a element.</p>
2841
     *
2842
     * @phpstan-return T|null
2843
     * @psalm-mutation-free
2844
     */
2845
    public function first()
2846
    {
2847
        $key_first = $this->firstKey();
156 ✔
2848
        if ($key_first === null) {
156 ✔
2849
            return null;
21 ✔
2850
        }
2851

2852
        return $this->get($key_first);
135 ✔
2853
    }
2854

2855
    /**
2856
     * Get the first key from the current array.
2857
     *
2858
     * @return mixed|null
2859
     *                    <p>Return null if there wasn't a element.</p>
2860
     *
2861
     * @phpstan-return TKey|null
2862
     *
2863
     * @psalm-mutation-free
2864
     */
2865
    public function firstKey()
2866
    {
2867
        $this->generatorToArray();
205 ✔
2868

2869
        /** @phpstan-var TKey|null $return - help for phpstan */
2870
        $return = \array_key_first($this->array);
205 ✔
2871

2872
        return $return;
205 ✔
2873
    }
2874

2875
    /**
2876
     * Get the first value(s) from the current array.
2877
     * And will return an empty array if there was no first entry.
2878
     *
2879
     * EXAMPLE: <code>
2880
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->firstsImmutable(2); // Arrayy[0 => 'foo', 1 => 'bar']
2881
     * </code>
2882
     *
2883
     * @param int|null $number <p>How many values you will take?</p>
2884
     *
2885
     * @return static
2886
     *                <p>(Immutable)</p>
2887
     *
2888
     * @phpstan-return static<TKey,T>
2889
     * @psalm-mutation-free
2890
     */
2891
    public function firstsImmutable(?int $number = null): self
2892
    {
2893
        $arrayTmp = $this->toArray();
259 ✔
2894

2895
        if ($number === null) {
259 ✔
2896
            $array = (array) \array_shift($arrayTmp);
98 ✔
2897
        } else {
2898
            $array = \array_splice($arrayTmp, 0, $number);
161 ✔
2899
        }
2900

2901
        return static::create(
259 ✔
2902
            $array,
259 ✔
2903
            $this->iteratorClass,
259 ✔
2904
            false
259 ✔
2905
        );
259 ✔
2906
    }
2907

2908
    /**
2909
     * Get the first value(s) from the current array.
2910
     * And will return an empty array if there was no first entry.
2911
     *
2912
     * @param int|null $number <p>How many values you will take?</p>
2913
     *
2914
     * @return static
2915
     *                <p>(Immutable)</p>
2916
     *
2917
     * @phpstan-return static<array-key,TKey>
2918
     * @psalm-mutation-free
2919
     */
2920
    public function firstsKeys(?int $number = null): self
2921
    {
2922
        $arrayTmp = $this->keys()->toArray();
21 ✔
2923

2924
        if ($number === null) {
21 ✔
2925
            $array = (array) \array_shift($arrayTmp);
×
2926
        } else {
2927
            $array = \array_splice($arrayTmp, 0, $number);
21 ✔
2928
        }
2929

2930
        return static::create(
21 ✔
2931
            $array,
21 ✔
2932
            $this->iteratorClass,
21 ✔
2933
            false
21 ✔
2934
        );
21 ✔
2935
    }
2936

2937
    /**
2938
     * Get and remove the first value(s) from the current array.
2939
     * And will return an empty array if there was no first entry.
2940
     *
2941
     * EXAMPLE: <code>
2942
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->firstsMutable(); // 'foo'
2943
     * </code>
2944
     *
2945
     * @param int|null $number <p>How many values you will take?</p>
2946
     *
2947
     * @return $this
2948
     *               <p>(Mutable)</p>
2949
     *
2950
     * @phpstan-return ($number is null ? static<int,T> : static<TKey,T>)
2951
     */
2952
    public function firstsMutable(?int $number = null): self
2953
    {
2954
        $this->generatorToArray();
238 ✔
2955

2956
        if ($number === null) {
238 ✔
2957
            $shift = \array_shift($this->array);
133 ✔
2958
            /* @phpstan-ignore-next-line | I am not sure if "array<int, T of mixed>" is an error here? */
2959
            $this->array = $shift !== null ? [$shift] : [];
133 ✔
2960
        } else {
2961
            $splice = \array_splice($this->array, 0, $number);
105 ✔
2962
            $this->array = $splice;
105 ✔
2963
        }
2964

2965
        return $this;
238 ✔
2966
    }
2967

2968
    /**
2969
     * Exchanges all keys with their associated values in an array.
2970
     *
2971
     * EXAMPLE: <code>
2972
     * a([0 => 'foo', 1 => 'bar'])->flip(); // Arrayy['foo' => 0, 'bar' => 1]
2973
     * </code>
2974
     *
2975
     * @return static
2976
     *                <p>(Immutable)</p>
2977
     *
2978
     * @phpstan-return static<array-key,TKey>
2979
     * @psalm-mutation-free
2980
     */
2981
    public function flip(): self
2982
    {
2983
        $generator = function (): \Generator {
7 ✔
2984
            foreach ($this->getGenerator() as $key => $value) {
7 ✔
2985
                yield (string) $value => $key;
7 ✔
2986
            }
2987
        };
7 ✔
2988

2989
        return static::create(
7 ✔
2990
            $generator,
7 ✔
2991
            $this->iteratorClass,
7 ✔
2992
            false
7 ✔
2993
        );
7 ✔
2994
    }
2995

2996
    /**
2997
     * Get a value from an array (optional using dot-notation).
2998
     *
2999
     * EXAMPLE: <code>
3000
     * $arrayy = a(['user' => ['lastname' => 'Moelleken']]);
3001
     * $arrayy->get('user.lastname'); // 'Moelleken'
3002
     * // ---
3003
     * $arrayy = new A();
3004
     * $arrayy['user'] = ['lastname' => 'Moelleken'];
3005
     * $arrayy['user.firstname'] = 'Lars';
3006
     * $arrayy['user']['lastname']; // Moelleken
3007
     * $arrayy['user.lastname']; // Moelleken
3008
     * $arrayy['user.firstname']; // Lars
3009
     * </code>
3010
     *
3011
     * @param int|string $key
3012
     *                                   <p>The key to look for.</p>
3013
     * @param mixed      $fallback
3014
     *                                   <p>Value to fallback to.</p>
3015
     * @param array|null $array
3016
     *                                   <p>The array to get from, if it's set to "null" we use the current array from the
3017
     *                                   class.</p>
3018
     * @param bool       $useByReference
3019
     *
3020
     * @return mixed|static
3021
     *
3022
     * @phpstan-param TKey $key
3023
     * @phpstan-param array<array-key,mixed>|array<TKey,T> $array
3024
     * @psalm-mutation-free
3025
     */
3026
    public function get(
3027
        $key = null,
3028
        $fallback = null,
3029
        ?array $array = null,
3030
        bool $useByReference = false
3031
    ) {
3032
        if ($array === null && $key === null) {
1,888 ✔
3033
            if ($useByReference) {
7 ✔
3034
                return $this;
×
3035
            }
3036

3037
            return clone $this;
7 ✔
3038
        }
3039

3040
        if ($array !== null) {
1,888 ✔
3041
            if ($useByReference) {
28 ✔
3042
                $usedArray = &$array;
×
3043
            } else {
3044
                $usedArray = $array;
28 ✔
3045
            }
3046
        } else {
3047
            $this->generatorToArray();
1,867 ✔
3048

3049
            if ($useByReference) {
1,867 ✔
3050
                $usedArray = &$this->array;
1,083 ✔
3051
            } else {
3052
                $usedArray = $this->array;
912 ✔
3053
            }
3054
        }
3055

3056
        if ($key === null) {
1,888 ✔
3057
            return static::create(
7 ✔
3058
                [],
7 ✔
3059
                $this->iteratorClass,
7 ✔
3060
                false
7 ✔
3061
            )->createByReference($usedArray);
7 ✔
3062
        }
3063

3064
        // php cast "bool"-index into "int"-index
3065
        /* @phpstan-ignore-next-line | this is only a fallback */
3066
        if ((bool) $key === $key) {
1,888 ✔
3067
            $key = (int) $key;
×
3068
        }
3069

3070
        if (\array_key_exists($key, $usedArray) === true) {
1,888 ✔
3071
            if (\is_array($usedArray[$key])) {
1,622 ✔
3072
                return static::create(
142 ✔
3073
                    [],
142 ✔
3074
                    $this->iteratorClass,
142 ✔
3075
                    false
142 ✔
3076
                )->createByReference($usedArray[$key]);
142 ✔
3077
            }
3078

3079
            return $usedArray[$key];
1,510 ✔
3080
        }
3081

3082
        // crawl through array, get key according to object or not
3083
        $usePath = false;
427 ✔
3084
        if (
3085
            $this->pathSeparator
427 ✔
3086
            &&
3087
            (string) $key === $key
427 ✔
3088
            &&
3089
            \strpos($key, $this->pathSeparator) !== false
427 ✔
3090
        ) {
3091
            $segments = \explode($this->pathSeparator, (string) $key);
217 ✔
3092
            if ($segments !== false) {
217 ✔
3093
                $usePath = true;
217 ✔
3094
                $usedArrayTmp = $usedArray; // do not use the reference for dot-annotations
217 ✔
3095

3096
                foreach ($segments as $segment) {
217 ✔
3097
                    if (
3098
                        (
3099
                            \is_array($usedArrayTmp)
217 ✔
3100
                            ||
217 ✔
3101
                            $usedArrayTmp instanceof \ArrayAccess
217 ✔
3102
                        )
3103
                        &&
3104
                        isset($usedArrayTmp[$segment])
217 ✔
3105
                    ) {
3106
                        $usedArrayTmp = $usedArrayTmp[$segment];
210 ✔
3107

3108
                        continue;
210 ✔
3109
                    }
3110

3111
                    if (
3112
                        \is_object($usedArrayTmp) === true
98 ✔
3113
                        &&
3114
                        \property_exists($usedArrayTmp, $segment)
98 ✔
3115
                    ) {
3116
                        $usedArrayTmp = $usedArrayTmp->{$segment};
7 ✔
3117

3118
                        continue;
7 ✔
3119
                    }
3120

3121
                    if (isset($segments[0]) && $segments[0] === '*') {
91 ✔
3122
                        $segmentsTmp = $segments;
7 ✔
3123
                        unset($segmentsTmp[0]);
7 ✔
3124
                        $keyTmp = \implode('.', $segmentsTmp);
7 ✔
3125
                        $returnTmp = static::create(
7 ✔
3126
                            [],
7 ✔
3127
                            $this->iteratorClass,
7 ✔
3128
                            false
7 ✔
3129
                        );
7 ✔
3130
                        foreach ($this->getAll() as $dataTmp) {
7 ✔
3131
                            if ($dataTmp instanceof self) {
7 ✔
3132
                                $returnTmp->add($dataTmp->get($keyTmp));
×
3133

3134
                                continue;
×
3135
                            }
3136

3137
                            if (
3138
                                (
3139
                                    \is_array($dataTmp)
7 ✔
3140
                                    ||
7 ✔
3141
                                    $dataTmp instanceof \ArrayAccess
7 ✔
3142
                                )
3143
                                &&
3144
                                isset($dataTmp[$keyTmp])
7 ✔
3145
                            ) {
3146
                                $returnTmp->add($dataTmp[$keyTmp]);
×
3147

3148
                                continue;
×
3149
                            }
3150

3151
                            if (
3152
                                \is_object($dataTmp) === true
7 ✔
3153
                                &&
3154
                                \property_exists($dataTmp, $keyTmp)
7 ✔
3155
                            ) {
3156
                                $returnTmp->add($dataTmp->{$keyTmp});
7 ✔
3157

3158
                                continue;
7 ✔
3159
                            }
3160
                        }
3161

3162
                        if ($returnTmp->count() > 0) {
7 ✔
3163
                            return $returnTmp;
7 ✔
3164
                        }
3165
                    }
3166

3167
                    return $fallback instanceof \Closure ? $fallback() : $fallback;
84 ✔
3168
                }
3169
            }
3170
        }
3171

3172
        if (isset($usedArrayTmp)) {
406 ✔
3173
            if (!$usePath && !isset($usedArrayTmp[$key])) {
196 ✔
3174
                return $fallback instanceof \Closure ? $fallback() : $fallback;
×
3175
            }
3176

3177
            if (\is_array($usedArrayTmp)) {
196 ✔
3178
                return static::create(
42 ✔
3179
                    [],
42 ✔
3180
                    $this->iteratorClass,
42 ✔
3181
                    false
42 ✔
3182
                )->createByReference($usedArrayTmp);
42 ✔
3183
            }
3184

3185
            return $usedArrayTmp;
196 ✔
3186
        }
3187

3188
        if (!$usePath && !isset($usedArray[$key])) {
210 ✔
3189
            return $fallback instanceof \Closure ? $fallback() : $fallback;
210 ✔
3190
        }
3191

3192
        return static::create(
×
3193
            [],
×
3194
            $this->iteratorClass,
×
3195
            false
×
3196
        )->createByReference($usedArray);
×
3197
    }
3198

3199
    /**
3200
     * alias: for "Arrayy->toArray()"
3201
     *
3202
     * @return array
3203
     *
3204
     * @see          Arrayy::getArray()
3205
     *
3206
     * @phpstan-return array<TKey,T>
3207
     */
3208
    public function getAll(): array
3209
    {
3210
        /** @var array<TKey,T> $return */
3211
        $return = $this->toArray();
105 ✔
3212

3213
        return $return;
105 ✔
3214
    }
3215

3216
    /**
3217
     * Get the current array from the "Arrayy"-object.
3218
     *
3219
     * alias for "toArray()"
3220
     *
3221
     * @param bool $convertAllArrayyElements <p>
3222
     *                                       Convert all Child-"Arrayy" objects also to arrays.
3223
     *                                       </p>
3224
     * @param bool $preserveKeys             <p>
3225
     *                                       e.g.: A generator maybe return the same key more than once,
3226
     *                                       so maybe you will ignore the keys.
3227
     *                                       </p>
3228
     *
3229
     * @return array
3230
     *
3231
     * @phpstan-return array<array-key,T>|array<TKey,T>
3232
     * @psalm-mutation-free
3233
     *
3234
     * @see Arrayy::toArray()
3235
     */
3236
    public function getArray(
3237
        bool $convertAllArrayyElements = false,
3238
        bool $preserveKeys = true
3239
    ): array {
3240
        return $this->toArray(
3,633 ✔
3241
            $convertAllArrayyElements,
3,633 ✔
3242
            $preserveKeys
3,633 ✔
3243
        );
3,633 ✔
3244
    }
3245

3246
    /**
3247
     * Create an instance from JSON using the built-in mapper.
3248
     *
3249
     * For Arrayy models with property checks enabled, both phpdoc `@property`
3250
     * definitions and native declared properties are used for metadata and type checks.
3251
     * Add a property-level `@var` annotation if a native `array` property also needs
3252
     * element-type validation.
3253
     *
3254
     * @param string $json
3255
     *
3256
     * @return static
3257
     *                <p>(Immutable)</p>
3258
     */
3259
    public static function createFromJsonMapper(string $json)
3260
    {
3261
        // init
3262
        $class = static::create();
56 ✔
3263

3264
        $jsonObject = \json_decode($json, false);
56 ✔
3265

3266
        $mapper = new \Arrayy\Mapper\Json();
56 ✔
3267
        $mapper->undefinedPropertyHandler = static function ($object, $key, $jsonValue) use ($class) {
56 ✔
3268
            if ($class->checkPropertiesMismatchInConstructor) {
×
3269
                throw new \TypeError('Property mismatch - input: ' . \print_r(['key' => $key, 'jsonValue' => $jsonValue], true) . ' for object: ' . \get_class($object));
×
3270
            }
3271
        };
56 ✔
3272

3273
        /** @var static $return - hack for phpstan */
3274
        $return = $mapper->map($jsonObject, $class);
56 ✔
3275

3276
        return $return;
35 ✔
3277
    }
3278

3279
    /**
3280
     * @return array<array-key,TypeCheckInterface>|TypeCheckArray<array-key,TypeCheckInterface>
3281
     *
3282
     * @internal
3283
     */
3284
    public function getPhpDocPropertiesFromClass()
3285
    {
3286
        if ($this->properties === []) {
124 ✔
3287
            $this->properties = $this->getPropertiesFromPhpDoc();
54 ✔
3288
        }
3289

3290
        return $this->properties;
124 ✔
3291
    }
3292

3293
    /**
3294
     * Get the current array from the "Arrayy"-object as list.
3295
     *
3296
     * alias for "toList()"
3297
     *
3298
     * @param bool $convertAllArrayyElements <p>
3299
     *                                       Convert all Child-"Arrayy" objects also to arrays.
3300
     *                                       </p>
3301
     *
3302
     * @return array
3303
     *
3304
     * @phpstan-return list<T>
3305
     * @psalm-mutation-free
3306
     *
3307
     * @see Arrayy::toList()
3308
     */
3309
    public function getList(bool $convertAllArrayyElements = false): array
3310
    {
3311
        return $this->toList($convertAllArrayyElements);
7 ✔
3312
    }
3313

3314
    /**
3315
     * Returns the values from a single column of the input array, identified by
3316
     * the $columnKey, can be used to extract data-columns from multi-arrays.
3317
     *
3318
     * EXAMPLE: <code>
3319
     * a([['foo' => 'bar', 'id' => 1], ['foo => 'lall', 'id' => 2]])->getColumn('foo', 'id'); // Arrayy[1 => 'bar', 2 => 'lall']
3320
     * </code>
3321
     *
3322
     * INFO: Optionally, you may provide an $indexKey to index the values in the returned
3323
     *       array by the values from the $indexKey column in the input array.
3324
     *
3325
     * @param int|string|null $columnKey
3326
     * @param int|string|null $indexKey
3327
     *
3328
     * @return static
3329
     *                <p>(Immutable)</p>
3330
     *
3331
     * @phpstan-return static<TKey,T>
3332
     * @psalm-mutation-free
3333
     */
3334
    public function getColumn($columnKey = null, $indexKey = null): self
3335
    {
3336
        if ($columnKey === null && $indexKey === null) {
7 ✔
3337
            $generator = function () {
7 ✔
3338
                foreach ($this->getGenerator() as $value) {
7 ✔
3339
                    yield $value;
7 ✔
3340
                }
3341
            };
7 ✔
3342
        } else {
3343
            $generator = function () use ($columnKey, $indexKey) {
7 ✔
3344
                foreach ($this->getGenerator() as $value) {
7 ✔
3345
                    // reset
3346
                    $newKey = null;
7 ✔
3347
                    $newValue = null;
7 ✔
3348
                    $newValueFound = false;
7 ✔
3349

3350
                    if ($indexKey !== null) {
7 ✔
3351
                        foreach ($value as $keyInner => $valueInner) {
7 ✔
3352
                            if ($indexKey === $keyInner) {
7 ✔
3353
                                $newKey = $valueInner;
7 ✔
3354
                            }
3355

3356
                            if ($columnKey === $keyInner) {
7 ✔
3357
                                $newValue = $valueInner;
7 ✔
3358
                                $newValueFound = true;
7 ✔
3359
                            }
3360
                        }
3361
                    } else {
3362
                        foreach ($value as $keyInner => $valueInner) {
7 ✔
3363
                            if ($columnKey === $keyInner) {
7 ✔
3364
                                $newValue = $valueInner;
7 ✔
3365
                                $newValueFound = true;
7 ✔
3366
                            }
3367
                        }
3368
                    }
3369

3370
                    if ($newValueFound === false) {
7 ✔
3371
                        if ($newKey !== null) {
7 ✔
3372
                            yield $newKey => $value;
7 ✔
3373
                        } else {
3374
                            yield $value;
7 ✔
3375
                        }
3376
                    } else {
3377
                        /** @noinspection NestedPositiveIfStatementsInspection */
3378
                        if ($newKey !== null) {
7 ✔
3379
                            yield $newKey => $newValue;
7 ✔
3380
                        } else {
3381
                            yield $newValue;
7 ✔
3382
                        }
3383
                    }
3384
                }
3385
            };
7 ✔
3386
        }
3387

3388
        return static::create(
7 ✔
3389
            $generator,
7 ✔
3390
            $this->iteratorClass,
7 ✔
3391
            false
7 ✔
3392
        );
7 ✔
3393
    }
3394

3395
    /**
3396
     * Get the current array from the "Arrayy"-object as generator by reference.
3397
     *
3398
     * @return \Generator
3399
     *
3400
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3401
     */
3402
    public function &getGeneratorByReference(): \Generator
3403
    {
3404
        if ($this->generator instanceof ArrayyRewindableGenerator) {
602 ✔
3405
            foreach ($this->generator as $key => $value) {
119 ✔
3406
                yield $key => $value;
119 ✔
3407
            }
3408

3409
            return;
35 ✔
3410
        }
3411

3412
        // -> false-positive -> see "&$value"
3413
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3414
        foreach ($this->array as $key => &$value) {
490 ✔
3415
            yield $key => $value;
441 ✔
3416
        }
3417
    }
3418

3419
    /**
3420
     * Get the current array from the "Arrayy"-object as generator.
3421
     *
3422
     * @return \Generator
3423
     *
3424
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3425
     * @psalm-mutation-free
3426
     */
3427
    public function getGenerator(): \Generator
3428
    {
3429
        if ($this->generator instanceof ArrayyRewindableGenerator) {
7,789 ✔
3430
            yield from $this->generator;
553 ✔
3431

3432
            return;
553 ✔
3433
        }
3434

3435
        yield from $this->array;
7,775 ✔
3436
    }
3437

3438
    /**
3439
     * Get the current array from the "Arrayy"-object as generator.
3440
     *
3441
     * @return \Generator
3442
     *
3443
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3444
     * @psalm-mutation-free
3445
     */
3446
    public function getBackwardsGenerator(): \Generator
3447
    {
3448
        yield from $this->reverseKeepIndex();
28 ✔
3449
    }
3450

3451
    /**
3452
     * alias: for "Arrayy->keys()"
3453
     *
3454
     * @return static
3455
     *                <p>(Immutable)</p>
3456
     *
3457
     * @see          Arrayy::keys()
3458
     *
3459
     * @phpstan-return static<int,TKey>
3460
     * @psalm-mutation-free
3461
     */
3462
    public function getKeys()
3463
    {
3464
        return $this->keys();
14 ✔
3465
    }
3466

3467
    /**
3468
     * Get the current array from the "Arrayy"-object as object.
3469
     *
3470
     * @return \stdClass
3471
     */
3472
    public function getObject(): \stdClass
3473
    {
3474
        return self::arrayToObject($this->toArray());
28 ✔
3475
    }
3476

3477
    /**
3478
     * alias: for "Arrayy->randomImmutable()"
3479
     *
3480
     * @return static
3481
     *                <p>(Immutable)</p>
3482
     *
3483
     * @see          Arrayy::randomImmutable()
3484
     *
3485
     * @phpstan-return static<array-key,T>
3486
     */
3487
    public function getRandom(): self
3488
    {
3489
        return $this->randomImmutable();
28 ✔
3490
    }
3491

3492
    /**
3493
     * alias: for "Arrayy->randomKey()"
3494
     *
3495
     * @return mixed|null
3496
     *                    <p>Get a key/index or null if there wasn't a key/index.</p>
3497
     *
3498
     * @phpstan-return null|TKey
3499
     *
3500
     * @see Arrayy::randomKey()
3501
     */
3502
    public function getRandomKey()
3503
    {
3504
        return $this->randomKey();
21 ✔
3505
    }
3506

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

3524
    /**
3525
     * alias: for "Arrayy->randomValue()"
3526
     *
3527
     * @return mixed|null
3528
     *                    <p>Get a random value or null if there wasn't a value.</p>
3529
     *
3530
     * @phpstan-return null|T
3531
     *
3532
     * @see Arrayy::randomValue()
3533
     */
3534
    public function getRandomValue()
3535
    {
3536
        return $this->randomValue();
21 ✔
3537
    }
3538

3539
    /**
3540
     * alias: for "Arrayy->randomValues()"
3541
     *
3542
     * @param int $number
3543
     *
3544
     * @return static
3545
     *                <p>(Immutable)</p>
3546
     *
3547
     * @see          Arrayy::randomValues()
3548
     *
3549
     * @phpstan-return static<TKey,T>
3550
     */
3551
    public function getRandomValues(int $number): self
3552
    {
3553
        return $this->randomValues($number);
42 ✔
3554
    }
3555

3556
    /**
3557
     * Gets all values.
3558
     *
3559
     * @return static
3560
     *                <p>The values of all elements in this array, in the order they
3561
     *                appear in the array.</p>
3562
     *
3563
     * @phpstan-return static<TKey,T>
3564
     */
3565
    public function getValues()
3566
    {
3567
        $this->generatorToArray(false);
28 ✔
3568

3569
        return static::create(
28 ✔
3570
            \array_values($this->array),
28 ✔
3571
            $this->iteratorClass,
28 ✔
3572
            false
28 ✔
3573
        );
28 ✔
3574
    }
3575

3576
    /**
3577
     * Gets all values via Generator.
3578
     *
3579
     * @return \Generator
3580
     *                    <p>The values of all elements in this array, in the order they
3581
     *                    appear in the array as Generator.</p>
3582
     *
3583
     * @phpstan-return \Generator<TKey,T>
3584
     */
3585
    public function getValuesYield(): \Generator
3586
    {
3587
        yield from $this->getGenerator();
28 ✔
3588
    }
3589

3590
    /**
3591
     * Group values from a array according to the results of a closure.
3592
     *
3593
     * @param callable|int|string $grouper  <p>A callable function name.</p>
3594
     * @param bool                $saveKeys
3595
     *
3596
     * @return static
3597
     *                <p>(Immutable)</p>
3598
     *
3599
     * @phpstan-param \Closure(T,TKey):TKey|TKey $grouper
3600
     * @phpstan-return static<TKey,T>
3601
     * @psalm-mutation-free
3602
     */
3603
    public function group($grouper, bool $saveKeys = false): self
3604
    {
3605
        // init
3606
        $result = [];
28 ✔
3607

3608
        // Iterate over values, group by property/results from closure.
3609
        foreach ($this->getGenerator() as $key => $value) {
28 ✔
3610
            if (\is_callable($grouper) === true) {
28 ✔
3611
                $groupKey = $grouper($value, $key);
21 ✔
3612
            } else {
3613
                $groupKey = $this->get($grouper);
7 ✔
3614
            }
3615

3616
            $newValue = $this->get($groupKey, null, $result);
28 ✔
3617

3618
            if ($groupKey instanceof self) {
28 ✔
3619
                $groupKey = $groupKey->toArray();
×
3620
            }
3621

3622
            if ($newValue instanceof self) {
28 ✔
3623
                $newValue = $newValue->toArray();
28 ✔
3624
            }
3625

3626
            // Add to result.
3627
            if ($groupKey !== null) {
28 ✔
3628
                $result[$groupKey] = $newValue;
21 ✔
3629

3630
                if ($saveKeys) {
21 ✔
3631
                    $result[$groupKey][$key] = $value;
14 ✔
3632
                } else {
3633
                    $result[$groupKey][] = $value;
7 ✔
3634
                }
3635
            }
3636
        }
3637

3638
        return static::create(
28 ✔
3639
            $result,
28 ✔
3640
            $this->iteratorClass,
28 ✔
3641
            false
28 ✔
3642
        );
28 ✔
3643
    }
3644

3645
    /**
3646
     * Check if an array has a given key.
3647
     *
3648
     * @param mixed $key
3649
     *
3650
     * @return bool
3651
     *
3652
     * @phpstan-param null|TKey|TKey[] $key
3653
     */
3654
    public function has($key): bool
3655
    {
3656
        static $UN_FOUND = null;
210 ✔
3657

3658
        if ($UN_FOUND === null) {
210 ✔
3659
            // Generate unique string to use as marker.
3660
            $UN_FOUND = 'arrayy--' . \uniqid('arrayy', true);
7 ✔
3661
        }
3662

3663
        if (\is_array($key)) {
210 ✔
3664
            if ($key === []) {
7 ✔
3665
                return false;
×
3666
            }
3667

3668
            foreach ($key as $keyTmp) {
7 ✔
3669
                $found = ($this->get($keyTmp, $UN_FOUND) !== $UN_FOUND);
7 ✔
3670
                if ($found === false) {
7 ✔
3671
                    return false;
7 ✔
3672
                }
3673
            }
3674

3675
            return true;
7 ✔
3676
        }
3677

3678
        return $this->get($key, $UN_FOUND) !== $UN_FOUND;
203 ✔
3679
    }
3680

3681
    /**
3682
     * Check if an array has a given value.
3683
     *
3684
     * INFO: If you need to search recursive please use ```contains($value, true)```.
3685
     *
3686
     * @param mixed $value
3687
     *
3688
     * @return bool
3689
     *
3690
     * @phpstan-param T $value
3691
     */
3692
    public function hasValue($value): bool
3693
    {
3694
        return $this->contains($value);
7 ✔
3695
    }
3696

3697
    /**
3698
     * Implodes the values of this array.
3699
     *
3700
     * EXAMPLE: <code>
3701
     * a([0 => -9, 1, 2])->implode('|'); // '-9|1|2'
3702
     * </code>
3703
     *
3704
     * @param string $glue
3705
     * @param string $prefix
3706
     *
3707
     * @return string
3708
     * @psalm-mutation-free
3709
     */
3710
    public function implode(string $glue = '', string $prefix = ''): string
3711
    {
3712
        return $prefix . $this->implode_recursive($glue, $this->toArray(), false);
203 ✔
3713
    }
3714

3715
    /**
3716
     * Implodes the keys of this array.
3717
     *
3718
     * @param string $glue
3719
     *
3720
     * @return string
3721
     * @psalm-mutation-free
3722
     */
3723
    public function implodeKeys(string $glue = ''): string
3724
    {
3725
        return $this->implode_recursive($glue, $this->toArray(), true);
56 ✔
3726
    }
3727

3728
    /**
3729
     * Given a list and an iterate-function that returns
3730
     * a key for each element in the list (or a property name),
3731
     * returns an object with an index of each item.
3732
     *
3733
     * @param int|string $key
3734
     *
3735
     * @return static
3736
     *                <p>(Immutable)</p>
3737
     *
3738
     * @phpstan-param array-key $key
3739
     * @phpstan-return static<TKey,T>
3740
     * @psalm-mutation-free
3741
     */
3742
    public function indexBy($key): self
3743
    {
3744
        // init
3745
        $results = [];
28 ✔
3746

3747
        foreach ($this->getGenerator() as $a) {
28 ✔
3748
            if (\array_key_exists($key, $a) === true) {
28 ✔
3749
                $results[$a[$key]] = $a;
21 ✔
3750
            }
3751
        }
3752

3753
        return static::create(
28 ✔
3754
            $results,
28 ✔
3755
            $this->iteratorClass,
28 ✔
3756
            false
28 ✔
3757
        );
28 ✔
3758
    }
3759

3760
    /**
3761
     * alias: for "Arrayy->searchIndex()"
3762
     *
3763
     * @param mixed $value
3764
     *                     <p>The value to search for.</p>
3765
     *
3766
     * @return false|int|string
3767
     *
3768
     * @phpstan-param T $value
3769
     * @phpstan-return false|TKey
3770
     *
3771
     * @see Arrayy::searchIndex()
3772
     */
3773
    public function indexOf($value)
3774
    {
3775
        return $this->searchIndex($value);
28 ✔
3776
    }
3777

3778
    /**
3779
     * Get everything but the last..$to items.
3780
     *
3781
     * EXAMPLE: <code>
3782
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->initial(2); // Arrayy[0 => 'foo']
3783
     * </code>
3784
     *
3785
     * @param int $to
3786
     *
3787
     * @return static
3788
     *                <p>(Immutable)</p>
3789
     *
3790
     * @phpstan-return static<TKey,T>
3791
     * @psalm-mutation-free
3792
     */
3793
    public function initial(int $to = 1): self
3794
    {
3795
        return $this->firstsImmutable(\count($this->toArray(), \COUNT_NORMAL) - $to);
84 ✔
3796
    }
3797

3798
    /**
3799
     * Return an array with all elements found in input array.
3800
     *
3801
     * EXAMPLE: <code>
3802
     * a(['foo', 'bar'])->intersection(['bar', 'baz']); // Arrayy['bar']
3803
     * </code>
3804
     *
3805
     * @param array $search
3806
     * @param bool  $keepKeys
3807
     *
3808
     * @return static
3809
     *                <p>(Immutable)</p>
3810
     *
3811
     * @phpstan-param  array<TKey,T> $search
3812
     * @phpstan-return static<TKey,T>
3813
     * @psalm-mutation-free
3814
     */
3815
    public function intersection(array $search, bool $keepKeys = false): self
3816
    {
3817
        if ($keepKeys) {
28 ✔
3818
            /**
3819
             * @psalm-suppress MissingClosureReturnType
3820
             * @psalm-suppress MissingClosureParamType
3821
             */
3822
            return static::create(
7 ✔
3823
                \array_uintersect(
7 ✔
3824
                    $this->toArray(),
7 ✔
3825
                    $search,
7 ✔
3826
                    static function ($a, $b) {
7 ✔
3827
                        return $a === $b ? 0 : -1;
7 ✔
3828
                    }
7 ✔
3829
                ),
7 ✔
3830
                $this->iteratorClass,
7 ✔
3831
                false
7 ✔
3832
            );
7 ✔
3833
        }
3834

3835
        return static::create(
21 ✔
3836
            \array_values(\array_intersect($this->toArray(), $search)),
21 ✔
3837
            $this->iteratorClass,
21 ✔
3838
            false
21 ✔
3839
        );
21 ✔
3840
    }
3841

3842
    /**
3843
     * Return an array with all elements found in input array.
3844
     *
3845
     * @param array ...$array
3846
     *
3847
     * @return static
3848
     *                <p>(Immutable)</p>
3849
     *
3850
     * @phpstan-param  array<array<TKey,T>> ...$array
3851
     * @phpstan-return static<TKey,T>
3852
     * @psalm-mutation-free
3853
     */
3854
    public function intersectionMulti(...$array): self
3855
    {
3856
        return static::create(
7 ✔
3857
            \array_values(\array_intersect($this->toArray(), ...$array)),
7 ✔
3858
            $this->iteratorClass,
7 ✔
3859
            false
7 ✔
3860
        );
7 ✔
3861
    }
3862

3863
    /**
3864
     * Return a boolean flag which indicates whether the two input arrays have any common elements.
3865
     *
3866
     * EXAMPLE: <code>
3867
     * a(['foo', 'bar'])->intersects(['fΓΆΓΆ', 'bΓ€r']); // false
3868
     * </code>
3869
     *
3870
     * @param array $search
3871
     *
3872
     * @return bool
3873
     *
3874
     * @phpstan-param array<TKey,T> $search
3875
     */
3876
    public function intersects(array $search): bool
3877
    {
3878
        return $this->intersection($search)->count() > 0;
7 ✔
3879
    }
3880

3881
    /**
3882
     * Invoke a function on all of an array's values.
3883
     *
3884
     * @param callable $callable
3885
     * @param mixed    $arguments
3886
     *
3887
     * @return static
3888
     *                <p>(Immutable)</p>
3889
     *
3890
     * @phpstan-param  callable(T,mixed=):mixed $callable
3891
     * @phpstan-return static<int, T>|static<TKey, T>
3892
     * @psalm-mutation-free
3893
     */
3894
    public function invoke($callable, $arguments = []): self
3895
    {
3896
        // If one argument given for each iteration, create an array for it.
3897
        if (!\is_array($arguments)) {
7 ✔
3898
            $arguments = \array_fill(
7 ✔
3899
                0,
7 ✔
3900
                $this->count(),
7 ✔
3901
                $arguments
7 ✔
3902
            );
7 ✔
3903
        }
3904

3905
        // If the callable has arguments, pass them.
3906
        if ($arguments) {
7 ✔
3907
            $array = \array_map($callable, $this->toArray(), $arguments);
7 ✔
3908
        } else {
3909
            $array = $this->map($callable);
7 ✔
3910
        }
3911

3912
        return static::create(
7 ✔
3913
            $array,
7 ✔
3914
            $this->iteratorClass,
7 ✔
3915
            false
7 ✔
3916
        );
7 ✔
3917
    }
3918

3919
    /**
3920
     * Check whether array is associative or not.
3921
     *
3922
     * EXAMPLE: <code>
3923
     * a(['foo' => 'bar', 2, 3])->isAssoc(); // true
3924
     * </code>
3925
     *
3926
     * @param bool $recursive
3927
     *
3928
     * @return bool
3929
     *              <p>Returns true if associative, false otherwise.</p>
3930
     */
3931
    public function isAssoc(bool $recursive = false): bool
3932
    {
3933
        if ($this->isEmpty()) {
105 ✔
3934
            return false;
21 ✔
3935
        }
3936

3937
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3938
        foreach ($this->keys($recursive)->getGeneratorByReference() as &$key) {
91 ✔
3939
            if ((string) $key !== $key) {
91 ✔
3940
                return false;
77 ✔
3941
            }
3942
        }
3943

3944
        return true;
21 ✔
3945
    }
3946

3947
    /**
3948
     * Check if a given key or keys are empty.
3949
     *
3950
     * @param int|int[]|string|string[]|null $keys
3951
     *
3952
     * @return bool
3953
     *              <p>Returns true if empty, false otherwise.</p>
3954
     * @psalm-mutation-free
3955
     */
3956
    public function isEmpty($keys = null): bool
3957
    {
3958
        if ($this->generator) {
315 ✔
3959
            return $this->toArray() === [];
×
3960
        }
3961

3962
        if ($keys === null) {
315 ✔
3963
            return $this->array === [];
301 ✔
3964
        }
3965

3966
        foreach ((array) $keys as $key) {
14 ✔
3967
            if (!empty($this->get($key))) {
14 ✔
3968
                return false;
14 ✔
3969
            }
3970
        }
3971

3972
        return true;
14 ✔
3973
    }
3974

3975
    /**
3976
     * Check if the current array is equal to the given "$array" or not.
3977
     *
3978
     * EXAMPLE: <code>
3979
     * a(['πŸ’©'])->isEqual(['πŸ’©']); // true
3980
     * </code>
3981
     *
3982
     * @param array $array
3983
     *
3984
     * @return bool
3985
     *
3986
     * @phpstan-param array<TKey,T> $array
3987
     */
3988
    public function isEqual(array $array): bool
3989
    {
3990
        return $this->toArray() === $array;
7 ✔
3991
    }
3992

3993
    /**
3994
     * Check if the current array is a multi-array.
3995
     *
3996
     * EXAMPLE: <code>
3997
     * a(['foo' => [1, 2 , 3]])->isMultiArray(); // true
3998
     * </code>
3999
     *
4000
     * @return bool
4001
     */
4002
    public function isMultiArray(): bool
4003
    {
4004
        foreach ($this->getGenerator() as $value) {
154 ✔
4005
            if (\is_array($value)) {
140 ✔
4006
                return true;
35 ✔
4007
            }
4008
        }
4009

4010
        return false;
126 ✔
4011
    }
4012

4013
    /**
4014
     * Check whether array is numeric or not.
4015
     *
4016
     * @return bool
4017
     *              <p>Returns true if numeric, false otherwise.</p>
4018
     */
4019
    public function isNumeric(): bool
4020
    {
4021
        if ($this->isEmpty()) {
35 ✔
4022
            return false;
14 ✔
4023
        }
4024

4025
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4026
        foreach ($this->keys()->getGeneratorByReference() as &$key) {
28 ✔
4027
            if ((int) $key !== $key) {
28 ✔
4028
                return false;
14 ✔
4029
            }
4030
        }
4031

4032
        return true;
14 ✔
4033
    }
4034

4035
    /**
4036
     * Check if the current array is sequential [0, 1, 2, 3, 4, 5 ...] or not.
4037
     *
4038
     * EXAMPLE: <code>
4039
     * a([0 => 'foo', 1 => 'lall', 2 => 'foobar'])->isSequential(); // true
4040
     * </code>
4041
     *
4042
     * INFO: If the array is empty we count it as non-sequential.
4043
     *
4044
     * @param bool $recursive
4045
     *
4046
     * @return bool
4047
     * @psalm-mutation-free
4048
     */
4049
    public function isSequential(bool $recursive = false): bool
4050
    {
4051
        $i = 0;
70 ✔
4052
        foreach ($this->getGenerator() as $key => $value) {
70 ✔
4053
            if (
4054
                $recursive
63 ✔
4055
                &&
4056
                (\is_array($value) || $value instanceof \Traversable)
63 ✔
4057
                &&
4058
                self::create($value)->isSequential() === false
63 ✔
4059
            ) {
4060
                return false;
7 ✔
4061
            }
4062

4063
            if ($key !== $i) {
63 ✔
4064
                return false;
21 ✔
4065
            }
4066

4067
            ++$i;
56 ✔
4068
        }
4069

4070
        return !($i === 0);
63 ✔
4071
    }
4072

4073
    /**
4074
     * @return array
4075
     *
4076
     * @phpstan-return array<TKey,T>
4077
     */
4078
    public function jsonSerialize(): array
4079
    {
4080
        /** @var array<TKey,T> $return */
4081
        $return = $this->toArray();
14 ✔
4082

4083
        return $return;
14 ✔
4084
    }
4085

4086
    /**
4087
     * Gets the key/index of the element at the current internal iterator position.
4088
     *
4089
     * @return int|string|null
4090
     * @phpstan-return array-key|null
4091
     */
4092
    public function key()
4093
    {
4094
        if ($this->generator) {
×
4095
            return $this->generator->key();
×
4096
        }
4097

4098
        return \key($this->array);
×
4099
    }
4100

4101
    /**
4102
     * Checks if the given key exists in the provided array.
4103
     *
4104
     * INFO: This method only use "array_key_exists()" if you want to use "dot"-notation,
4105
     *       then you need to use "Arrayy->offsetExists()".
4106
     *
4107
     * @param int|string $key the key to look for
4108
     *
4109
     * @return bool
4110
     * @psalm-mutation-free
4111
     */
4112
    public function keyExists($key): bool
4113
    {
4114
        foreach ($this->getGenerator() as $keyTmp => $value) {
1,363 ✔
4115
            if ($key === $keyTmp) {
1,328 ✔
4116
                return true;
1,223 ✔
4117
            }
4118
        }
4119

4120
        return false;
1,001 ✔
4121
    }
4122

4123
    /**
4124
     * Get all keys from the current array.
4125
     *
4126
     * EXAMPLE: <code>
4127
     * a([1 => 'foo', 2 => 'foo2', 3 => 'bar'])->keys(); // Arrayy[1, 2, 3]
4128
     * </code>
4129
     *
4130
     * @param bool       $recursive
4131
     *                                  [optional] <p>
4132
     *                                  Get all keys, also from all sub-arrays from an multi-dimensional array.
4133
     *                                  </p>
4134
     * @param mixed|null $search_values
4135
     *                                  [optional] <p>
4136
     *                                  If specified, then only keys containing these values are returned.
4137
     *                                  </p>
4138
     * @param bool       $strict
4139
     *                                  [optional] <p>
4140
     *                                  Determines if strict comparison (===) should be used during the search.
4141
     *                                  </p>
4142
     *
4143
     * @return static
4144
     *                <p>(Immutable) An array of all the keys in input.</p>
4145
     *
4146
     * @phpstan-param null|T|T[] $search_values
4147
     * @phpstan-return static<int,TKey>
4148
     *
4149
     * @psalm-mutation-free
4150
     */
4151
    public function keys(
4152
        bool $recursive = false,
4153
        $search_values = null,
4154
        bool $strict = true
4155
    ): self {
4156
        // recursive
4157

4158
        if ($recursive === true) {
210 ✔
4159
            $array = $this->array_keys_recursive(
28 ✔
4160
                null,
28 ✔
4161
                $search_values,
28 ✔
4162
                $strict
28 ✔
4163
            );
28 ✔
4164

4165
            return static::create(
28 ✔
4166
                $array,
28 ✔
4167
                $this->iteratorClass,
28 ✔
4168
                false
28 ✔
4169
            );
28 ✔
4170
        }
4171

4172
        // non recursive
4173

4174
        if ($search_values === null) {
203 ✔
4175
            $arrayFunction = function (): \Generator {
203 ✔
4176
                foreach ($this->getGenerator() as $key => $value) {
203 ✔
4177
                    yield $key;
189 ✔
4178
                }
4179
            };
203 ✔
4180
        } else {
4181
            $arrayFunction = function () use ($search_values, $strict): \Generator {
7 ✔
4182
                $is_array_tmp = \is_array($search_values);
7 ✔
4183

4184
                /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4185
                foreach ($this->getGeneratorByReference() as $key => &$value) {
7 ✔
4186
                    if (
4187
                        (
4188
                            $is_array_tmp === false
7 ✔
4189
                            &&
7 ✔
4190
                            $strict === true
7 ✔
4191
                            &&
7 ✔
4192
                            $search_values === $value
7 ✔
4193
                        )
4194
                        ||
4195
                        (
4196
                            $is_array_tmp === false
7 ✔
4197
                            &&
7 ✔
4198
                            $strict === false
7 ✔
4199
                            &&
7 ✔
4200
                            $search_values == $value
7 ✔
4201
                        )
4202
                        ||
4203
                        (
4204
                            $is_array_tmp === true
7 ✔
4205
                            &&
7 ✔
4206
                            \in_array($value, $search_values, $strict)
7 ✔
4207
                        )
4208
                    ) {
4209
                        yield $key;
7 ✔
4210
                    }
4211
                }
4212
            };
7 ✔
4213
        }
4214

4215
        return static::create(
203 ✔
4216
            $arrayFunction,
203 ✔
4217
            $this->iteratorClass,
203 ✔
4218
            false
203 ✔
4219
        );
203 ✔
4220
    }
4221

4222
    /**
4223
     * Sort an array by key in reverse order.
4224
     *
4225
     * @param int $sort_flags [optional] <p>
4226
     *                        You may modify the behavior of the sort using the optional
4227
     *                        parameter sort_flags, for details
4228
     *                        see sort.
4229
     *                        </p>
4230
     *
4231
     * @return $this
4232
     *               <p>(Mutable) Return this Arrayy object.</p>
4233
     *
4234
     * @phpstan-return static<TKey,T>
4235
     */
4236
    public function krsort(int $sort_flags = 0): self
4237
    {
4238
        $this->generatorToArray();
28 ✔
4239

4240
        \krsort($this->array, $sort_flags);
28 ✔
4241

4242
        return $this;
28 ✔
4243
    }
4244

4245
    /**
4246
     * Sort an array by key in reverse order.
4247
     *
4248
     * @param int $sort_flags [optional] <p>
4249
     *                        You may modify the behavior of the sort using the optional
4250
     *                        parameter sort_flags, for details
4251
     *                        see sort.
4252
     *                        </p>
4253
     *
4254
     * @return $this
4255
     *               <p>(Immutable)</p>
4256
     *
4257
     * @phpstan-return static<TKey,T>
4258
     * @psalm-mutation-free
4259
     */
4260
    public function krsortImmutable(int $sort_flags = 0): self
4261
    {
4262
        $that = clone $this;
28 ✔
4263

4264
        /**
4265
         * @psalm-suppress ImpureMethodCall - object is already cloned
4266
         */
4267
        $that->krsort($sort_flags);
28 ✔
4268

4269
        return $that;
28 ✔
4270
    }
4271

4272
    /**
4273
     * Get the last value from the current array.
4274
     *
4275
     * EXAMPLE: <code>
4276
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->last(); // 'lall'
4277
     * </code>
4278
     *
4279
     * @return mixed|null
4280
     *                    <p>Return null if there wasn't a element.</p>
4281
     *
4282
     * @phpstan-return T|null
4283
     * @psalm-mutation-free
4284
     */
4285
    public function last()
4286
    {
4287
        $key_last = $this->lastKey();
119 ✔
4288
        if ($key_last === null) {
119 ✔
4289
            return null;
14 ✔
4290
        }
4291

4292
        /** @var T $value_last */
4293
        $value_last = $this->get($key_last);
105 ✔
4294

4295
        return $value_last;
105 ✔
4296
    }
4297

4298
    /**
4299
     * Get the last key from the current array.
4300
     *
4301
     * @return mixed|null
4302
     *                    <p>Return null if there wasn't a element.</p>
4303
     *
4304
     * @phpstan-return null|TKey
4305
     * @psalm-mutation-free
4306
     */
4307
    public function lastKey()
4308
    {
4309
        $this->generatorToArray();
147 ✔
4310

4311
        return \array_key_last($this->array);
147 ✔
4312
    }
4313

4314
    /**
4315
     * Get the last value(s) from the current array.
4316
     *
4317
     * EXAMPLE: <code>
4318
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->lasts(2); // Arrayy[0 => 'bar', 1 => 'lall']
4319
     * </code>
4320
     *
4321
     * @param int|null $number
4322
     *
4323
     * @return static
4324
     *                <p>(Immutable)</p>
4325
     *
4326
     * @phpstan-return static<TKey,T>
4327
     * @psalm-mutation-free
4328
     */
4329
    public function lastsImmutable(?int $number = null): self
4330
    {
4331
        if ($this->isEmpty()) {
91 ✔
4332
            return static::create(
7 ✔
4333
                [],
7 ✔
4334
                $this->iteratorClass,
7 ✔
4335
                false
7 ✔
4336
            );
7 ✔
4337
        }
4338

4339
        if ($number === null) {
84 ✔
4340
            $poppedValue = $this->last();
56 ✔
4341

4342
            if ($poppedValue === null) {
56 ✔
4343
                $poppedValue = [$poppedValue];
7 ✔
4344
            } else {
4345
                $poppedValue = (array) $poppedValue;
49 ✔
4346
            }
4347

4348
            $arrayy = static::create(
56 ✔
4349
                $poppedValue,
56 ✔
4350
                $this->iteratorClass,
56 ✔
4351
                false
56 ✔
4352
            );
56 ✔
4353
        } else {
4354
            $arrayy = $this->rest(-$number);
28 ✔
4355
        }
4356

4357
        return $arrayy;
84 ✔
4358
    }
4359

4360
    /**
4361
     * Get the last value(s) from the current array.
4362
     *
4363
     * EXAMPLE: <code>
4364
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->lasts(2); // Arrayy[0 => 'bar', 1 => 'lall']
4365
     * </code>
4366
     *
4367
     * @param int|null $number
4368
     *
4369
     * @return $this
4370
     *               <p>(Mutable)</p>
4371
     *
4372
     * @phpstan-return static<TKey,T>
4373
     */
4374
    public function lastsMutable(?int $number = null): self
4375
    {
4376
        if ($this->isEmpty()) {
91 ✔
4377
            return $this;
7 ✔
4378
        }
4379

4380
        $this->array = $this->lastsImmutable($number)->toArray();
84 ✔
4381
        $this->generator = null;
84 ✔
4382

4383
        return $this;
84 ✔
4384
    }
4385

4386
    /**
4387
     * Count the values from the current array.
4388
     *
4389
     * alias: for "Arrayy->count()"
4390
     *
4391
     * @param int $mode
4392
     *
4393
     * @return int
4394
     *
4395
     * @see Arrayy::count()
4396
     */
4397
    public function length(int $mode = \COUNT_NORMAL): int
4398
    {
4399
        return $this->count($mode);
140 ✔
4400
    }
4401

4402
    /**
4403
     * Apply the given function to the every element of the array,
4404
     * collecting the results.
4405
     *
4406
     * EXAMPLE: <code>
4407
     * a(['foo', 'Foo'])->map('mb_strtoupper'); // Arrayy['FOO', 'FOO']
4408
     * </code>
4409
     *
4410
     * @param callable $callable
4411
     * @param bool     $useKeyAsSecondParameter
4412
     * @param mixed    ...$arguments
4413
     *
4414
     * @return static
4415
     *                <p>(Immutable) Arrayy object with modified elements.</p>
4416
     *
4417
     * @template T2
4418
     *              <p>The output value type.</p>
4419
     *
4420
     * @phpstan-param callable(T,TKey=,mixed=):T2 $callable
4421
     * @phpstan-return static<TKey,T2>
4422
     * @psalm-mutation-free
4423
     */
4424
    public function map(
4425
        callable $callable,
4426
        bool $useKeyAsSecondParameter = false,
4427
        ...$arguments
4428
    ) {
4429
        /**
4430
         * @psalm-suppress ImpureFunctionCall - func_num_args is only used to detect the number of args
4431
         */
4432
        $useArguments = \func_num_args() > 2;
49 ✔
4433

4434
        return static::create(
49 ✔
4435
            function () use ($useArguments, $callable, $useKeyAsSecondParameter, $arguments) {
49 ✔
4436
                foreach ($this->getGenerator() as $key => $value) {
49 ✔
4437
                    if ($useArguments) {
42 ✔
4438
                        if ($useKeyAsSecondParameter) {
21 ✔
4439
                            yield $key => $callable($value, $key, ...$arguments);
×
4440
                        } else {
4441
                            yield $key => $callable($value, ...$arguments);
21 ✔
4442
                        }
4443
                    } else {
4444
                        /** @noinspection NestedPositiveIfStatementsInspection */
4445
                        if ($useKeyAsSecondParameter) {
42 ✔
4446
                            yield $key => $callable($value, $key);
×
4447
                        } else {
4448
                            yield $key => $callable($value);
42 ✔
4449
                        }
4450
                    }
4451
                }
4452
            },
49 ✔
4453
            $this->iteratorClass,
49 ✔
4454
            false
49 ✔
4455
        );
49 ✔
4456
    }
4457

4458
    /**
4459
     * Check if all items in current array match a truth test.
4460
     *
4461
     * EXAMPLE: <code>
4462
     * $closure = function ($value, $key) {
4463
     *     return ($value % 2 === 0);
4464
     * };
4465
     * a([2, 4, 8])->matches($closure); // true
4466
     * </code>
4467
     *
4468
     * @param \Closure $closure
4469
     *
4470
     * @return bool
4471
     *
4472
     * @phpstan-param \Closure(T,TKey):bool $closure
4473
     */
4474
    public function matches(\Closure $closure): bool
4475
    {
4476
        if ($this->count() === 0) {
105 ✔
4477
            return false;
14 ✔
4478
        }
4479

4480
        foreach ($this->getGenerator() as $key => $value) {
91 ✔
4481
            $value = $closure($value, $key);
91 ✔
4482

4483
            if ($value === false) {
91 ✔
4484
                return false;
49 ✔
4485
            }
4486
        }
4487

4488
        return true;
49 ✔
4489
    }
4490

4491
    /**
4492
     * Check if any item in the current array matches a truth test.
4493
     *
4494
     * EXAMPLE: <code>
4495
     * $closure = function ($value, $key) {
4496
     *     return ($value % 2 === 0);
4497
     * };
4498
     * a([1, 4, 7])->matches($closure); // true
4499
     * </code>
4500
     *
4501
     * @param \Closure $closure
4502
     *
4503
     * @return bool
4504
     *
4505
     * @phpstan-param \Closure(T,TKey):bool $closure
4506
     */
4507
    public function matchesAny(\Closure $closure): bool
4508
    {
4509
        if ($this->count() === 0) {
98 ✔
4510
            return false;
14 ✔
4511
        }
4512

4513
        foreach ($this->getGenerator() as $key => $value) {
84 ✔
4514
            $value = $closure($value, $key);
84 ✔
4515

4516
            if ($value === true) {
84 ✔
4517
                return true;
63 ✔
4518
            }
4519
        }
4520

4521
        return false;
28 ✔
4522
    }
4523

4524
    /**
4525
     * Get the max value from an array.
4526
     *
4527
     * EXAMPLE: <code>
4528
     * a([-9, -8, -7, 1.32])->max(); // 1.32
4529
     * </code>
4530
     *
4531
     * @return false|float|int|string
4532
     *                                <p>Will return false if there are no values.</p>
4533
     */
4534
    public function max()
4535
    {
4536
        if ($this->count() === 0) {
77 ✔
4537
            return false;
7 ✔
4538
        }
4539

4540
        $max = false;
70 ✔
4541
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4542
        foreach ($this->getGeneratorByReference() as &$value) {
70 ✔
4543
            if (
4544
                $max === false
70 ✔
4545
                ||
4546
                $value > $max
70 ✔
4547
            ) {
4548
                $max = $value;
70 ✔
4549
            }
4550
        }
4551

4552
        return $max;
70 ✔
4553
    }
4554

4555
    /**
4556
     * Merge the new $array into the current array.
4557
     *
4558
     * - keep key,value from the current array, also if the index is in the new $array
4559
     *
4560
     * EXAMPLE: <code>
4561
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4562
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4563
     * a($array1)->mergeAppendKeepIndex($array2); // Arrayy[1 => 'one', 'foo' => 'bar2', 3 => 'three']
4564
     * // ---
4565
     * $array1 = [0 => 'one', 1 => 'foo'];
4566
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4567
     * a($array1)->mergeAppendKeepIndex($array2); // Arrayy[0 => 'foo', 1 => 'bar2']
4568
     * </code>
4569
     *
4570
     * @param array $array
4571
     * @param bool  $recursive
4572
     *
4573
     * @return static
4574
     *                <p>(Immutable)</p>
4575
     *
4576
     * @phpstan-param  array<int|TKey,T> $array
4577
     * @phpstan-return static<int|TKey,T>
4578
     * @psalm-mutation-free
4579
     */
4580
    public function mergeAppendKeepIndex(array $array = [], bool $recursive = false): self
4581
    {
4582
        if ($recursive === true) {
231 ✔
4583
            $array = $this->getArrayRecursiveHelperArrayy($array);
63 ✔
4584
            $result = \array_replace_recursive($this->toArray(), $array);
63 ✔
4585
        } else {
4586
            $result = \array_replace($this->toArray(), $array);
168 ✔
4587
        }
4588

4589
        return static::create(
231 ✔
4590
            $result,
231 ✔
4591
            $this->iteratorClass,
231 ✔
4592
            false
231 ✔
4593
        );
231 ✔
4594
    }
4595

4596
    /**
4597
     * Merge the new $array into the current array.
4598
     *
4599
     * - replace duplicate assoc-keys from the current array with the key,values from the new $array
4600
     * - create new indexes
4601
     *
4602
     * EXAMPLE: <code>
4603
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4604
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4605
     * a($array1)->mergeAppendNewIndex($array2); // Arrayy[0 => 'one', 'foo' => 'bar2', 1 => 'three']
4606
     * // ---
4607
     * $array1 = [0 => 'one', 1 => 'foo'];
4608
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4609
     * a($array1)->mergeAppendNewIndex($array2); // Arrayy[0 => 'one', 1 => 'foo', 2 => 'foo', 3 => 'bar2']
4610
     * </code>
4611
     *
4612
     * @param array $array
4613
     * @param bool  $recursive
4614
     *
4615
     * @return static
4616
     *                <p>(Immutable)</p>
4617
     *
4618
     * @phpstan-param  array<TKey,T> $array
4619
     * @phpstan-return static<int,T>
4620
     * @psalm-mutation-free
4621
     */
4622
    public function mergeAppendNewIndex(array $array = [], bool $recursive = false): self
4623
    {
4624
        if ($recursive === true) {
140 ✔
4625
            $array = $this->getArrayRecursiveHelperArrayy($array);
35 ✔
4626
            $result = \array_merge_recursive($this->toArray(), $array);
35 ✔
4627
        } else {
4628
            $result = \array_merge($this->toArray(), $array);
105 ✔
4629
        }
4630

4631
        return static::create(
140 ✔
4632
            $result,
140 ✔
4633
            $this->iteratorClass,
140 ✔
4634
            false
140 ✔
4635
        );
140 ✔
4636
    }
4637

4638
    /**
4639
     * Merge the the current array into the $array.
4640
     *
4641
     * - use key,value from the new $array, also if the index is in the current array
4642
     *
4643
     * EXAMPLE: <code>
4644
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4645
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4646
     * a($array1)->mergePrependKeepIndex($array2); // Arrayy['foo' => 'bar1', 3 => 'three', 1 => 'one']
4647
     * // ---
4648
     * $array1 = [0 => 'one', 1 => 'foo'];
4649
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4650
     * a($array1)->mergePrependKeepIndex($array2); // Arrayy[0 => 'one', 1 => 'foo']
4651
     * </code>
4652
     *
4653
     * @param array $array
4654
     * @param bool  $recursive
4655
     *
4656
     * @return static
4657
     *                <p>(Immutable)</p>
4658
     *
4659
     * @phpstan-param  array<TKey,T> $array
4660
     * @phpstan-return static<TKey,T>
4661
     * @psalm-mutation-free
4662
     */
4663
    public function mergePrependKeepIndex(array $array = [], bool $recursive = false): self
4664
    {
4665
        if ($recursive === true) {
119 ✔
4666
            $array = $this->getArrayRecursiveHelperArrayy($array);
28 ✔
4667
            $result = \array_replace_recursive($array, $this->toArray());
28 ✔
4668
        } else {
4669
            $result = \array_replace($array, $this->toArray());
91 ✔
4670
        }
4671

4672
        return static::create(
119 ✔
4673
            $result,
119 ✔
4674
            $this->iteratorClass,
119 ✔
4675
            false
119 ✔
4676
        );
119 ✔
4677
    }
4678

4679
    /**
4680
     * Merge the current array into the new $array.
4681
     *
4682
     * - replace duplicate assoc-keys from new $array with the key,values from the current array
4683
     * - create new indexes
4684
     *
4685
     * EXAMPLE: <code>
4686
     * $array1 = [1 => 'one', 'foo' => 'bar1'];
4687
     * $array2 = ['foo' => 'bar2', 3 => 'three'];
4688
     * a($array1)->mergePrependNewIndex($array2); // Arrayy['foo' => 'bar1', 0 => 'three', 1 => 'one']
4689
     * // ---
4690
     * $array1 = [0 => 'one', 1 => 'foo'];
4691
     * $array2 = [0 => 'foo', 1 => 'bar2'];
4692
     * a($array1)->mergePrependNewIndex($array2); // Arrayy[0 => 'foo', 1 => 'bar2', 2 => 'one', 3 => 'foo']
4693
     * </code>
4694
     *
4695
     * @param array $array
4696
     * @param bool  $recursive
4697
     *
4698
     * @return static
4699
     *                <p>(Immutable)</p>
4700
     *
4701
     * @phpstan-param  array<TKey,T> $array
4702
     * @phpstan-return static<int,T>
4703
     * @psalm-mutation-free
4704
     */
4705
    public function mergePrependNewIndex(array $array = [], bool $recursive = false): self
4706
    {
4707
        if ($recursive === true) {
147 ✔
4708
            $array = $this->getArrayRecursiveHelperArrayy($array);
49 ✔
4709
            $result = \array_merge_recursive($array, $this->toArray());
49 ✔
4710
        } else {
4711
            $result = \array_merge($array, $this->toArray());
98 ✔
4712
        }
4713

4714
        return static::create(
147 ✔
4715
            $result,
147 ✔
4716
            $this->iteratorClass,
147 ✔
4717
            false
147 ✔
4718
        );
147 ✔
4719
    }
4720

4721
    /**
4722
     * Return a meta object with property names from phpdoc `@property` tags and
4723
     * native declared properties.
4724
     *
4725
     * @return ArrayyMeta|mixed|static
4726
     */
4727
    public static function meta()
4728
    {
4729
        return (new ArrayyMeta())->getMetaObject(static::class);
222 ✔
4730
    }
4731

4732
    /**
4733
     * Get the min value from an array.
4734
     *
4735
     * EXAMPLE: <code>
4736
     * a([-9, -8, -7, 1.32])->min(); // -9
4737
     * </code>
4738
     *
4739
     * @return false|mixed
4740
     *                     <p>Will return false if there are no values.</p>
4741
     *
4742
     * @phpstan-return false|T
4743
     */
4744
    public function min()
4745
    {
4746
        if ($this->count() === 0) {
77 ✔
4747
            return false;
7 ✔
4748
        }
4749

4750
        $min = false;
70 ✔
4751
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4752
        foreach ($this->getGeneratorByReference() as &$value) {
70 ✔
4753
            if (
4754
                $min === false
70 ✔
4755
                ||
4756
                $value < $min
70 ✔
4757
            ) {
4758
                $min = $value;
70 ✔
4759
            }
4760
        }
4761

4762
        return $min;
70 ✔
4763
    }
4764

4765
    /**
4766
     * Get the most used value from the array.
4767
     *
4768
     * @return mixed|null
4769
     *                    <p>(Immutable) Return null if there wasn't an element.</p>
4770
     *
4771
     * @phpstan-return T|null
4772
     * @psalm-mutation-free
4773
     */
4774
    public function mostUsedValue()
4775
    {
4776
        /* @phpstan-ignore-next-line | false-positive? maybe because we switch key-value via "countValues"? */
4777
        return $this->countValues()->arsortImmutable()->firstKey();
21 ✔
4778
    }
4779

4780
    /**
4781
     * Get the most used value from the array.
4782
     *
4783
     * @param int|null $number <p>How many values you will take?</p>
4784
     *
4785
     * @return static
4786
     *                <p>(Immutable)</p>
4787
     *
4788
     * @phpstan-return static<array-key,T>
4789
     * @psalm-mutation-free
4790
     */
4791
    public function mostUsedValues(?int $number = null): self
4792
    {
4793
        return $this->countValues()->arsortImmutable()->firstsKeys($number);
21 ✔
4794
    }
4795

4796
    /**
4797
     * Move an array element to a new index.
4798
     *
4799
     * EXAMPLE: <code>
4800
     * $arr2 = new A(['A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e']);
4801
     * $newArr2 = $arr2->moveElement('D', 1); // Arrayy['A' => 'a', 'D' => 'd', 'B' => 'b', 'C' => 'c', 'E' => 'e']
4802
     * </code>
4803
     *
4804
     * @param int|string $from
4805
     * @param int        $to
4806
     *
4807
     * @return static
4808
     *                <p>(Immutable)</p>
4809
     *
4810
     * @phpstan-return static<TKey,T>
4811
     * @psalm-mutation-free
4812
     */
4813
    public function moveElement($from, $to): self
4814
    {
4815
        $array = $this->toArray();
7 ✔
4816

4817
        if ((int) $from === $from) {
7 ✔
4818
            $tmp = \array_splice($array, $from, 1);
7 ✔
4819
            \array_splice($array, (int) $to, 0, $tmp);
7 ✔
4820
            $output = $array;
7 ✔
4821
        } elseif ((string) $from === $from) {
7 ✔
4822
            $indexToMove = \array_search($from, \array_keys($array), true);
7 ✔
4823
            $itemToMove = $array[$from];
7 ✔
4824
            if ($indexToMove !== false) {
7 ✔
4825
                \array_splice($array, $indexToMove, 1);
7 ✔
4826
            }
4827
            $i = 0;
7 ✔
4828
            $output = [];
7 ✔
4829
            foreach ($array as $key => $item) {
7 ✔
4830
                if ($i === $to) {
7 ✔
4831
                    $output[$from] = $itemToMove;
7 ✔
4832
                }
4833
                $output[$key] = $item;
7 ✔
4834
                ++$i;
7 ✔
4835
            }
4836
        } else {
4837
            $output = [];
×
4838
        }
4839

4840
        return static::create(
7 ✔
4841
            $output,
7 ✔
4842
            $this->iteratorClass,
7 ✔
4843
            false
7 ✔
4844
        );
7 ✔
4845
    }
4846

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

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

4871
        return static::create(
7 ✔
4872
            $array,
7 ✔
4873
            $this->iteratorClass,
7 ✔
4874
            false
7 ✔
4875
        );
7 ✔
4876
    }
4877

4878
    /**
4879
     * Move an array element to the last place.
4880
     *
4881
     * INFO: Instead of "Arrayy->moveElement()" this method will NOT
4882
     *       loss the keys of an indexed array.
4883
     *
4884
     * @param int|string $key
4885
     *
4886
     * @return static
4887
     *                <p>(Immutable)</p>
4888
     *
4889
     * @phpstan-return static<TKey,T>
4890
     * @psalm-mutation-free
4891
     */
4892
    public function moveElementToLastPlace($key): self
4893
    {
4894
        $array = $this->toArray();
7 ✔
4895

4896
        if ($this->offsetExists($key)) {
7 ✔
4897
            $tmpValue = $this->get($key);
7 ✔
4898
            unset($array[$key]);
7 ✔
4899
            $array += [$key => $tmpValue];
7 ✔
4900
        }
4901

4902
        return static::create(
7 ✔
4903
            $array,
7 ✔
4904
            $this->iteratorClass,
7 ✔
4905
            false
7 ✔
4906
        );
7 ✔
4907
    }
4908

4909
    /**
4910
     * Moves the internal iterator position to the next element and returns this element.
4911
     *
4912
     * @return false|mixed
4913
     *                     <p>(Mutable) Will return false if there are no values.</p>
4914
     *
4915
     * @phpstan-return false|T
4916
     */
4917
    public function next()
4918
    {
4919
        if ($this->generator) {
×
4920
            $this->generator->next();
×
4921

4922
            return $this->generator->current() ?? false;
×
4923
        }
4924

4925
        return \next($this->array);
×
4926
    }
4927

4928
    /**
4929
     * Get the next nth keys and values from the array.
4930
     *
4931
     * @param int $step
4932
     * @param int $offset
4933
     *
4934
     * @return static
4935
     *                <p>(Immutable)</p>
4936
     *
4937
     * @phpstan-return static<TKey,T>
4938
     * @psalm-mutation-free
4939
     */
4940
    public function nth(int $step, int $offset = 0): self
4941
    {
4942
        $arrayFunction = function () use ($step, $offset): \Generator {
7 ✔
4943
            $position = 0;
7 ✔
4944
            foreach ($this->getGenerator() as $key => $value) {
7 ✔
4945
                if ($position++ % $step !== $offset) {
7 ✔
4946
                    continue;
7 ✔
4947
                }
4948

4949
                yield $key => $value;
7 ✔
4950
            }
4951
        };
7 ✔
4952

4953
        return static::create(
7 ✔
4954
            $arrayFunction,
7 ✔
4955
            $this->iteratorClass,
7 ✔
4956
            false
7 ✔
4957
        );
7 ✔
4958
    }
4959

4960
    /**
4961
     * Get a subset of the items from the given array.
4962
     *
4963
     * @param int[]|string[] $keys
4964
     *
4965
     * @return static
4966
     *                <p>(Immutable)</p>
4967
     *
4968
     * @phpstan-param array-key[] $keys
4969
     * @phpstan-return static<TKey,T>
4970
     * @psalm-mutation-free
4971
     */
4972
    public function only(array $keys): self
4973
    {
4974
        $keys = \array_flip($keys);
7 ✔
4975

4976
        $generator = function () use ($keys): \Generator {
7 ✔
4977
            foreach ($this->getGenerator() as $key => $value) {
7 ✔
4978
                if (isset($keys[$key])) {
7 ✔
4979
                    yield $key => $value;
7 ✔
4980
                }
4981
            }
4982
        };
7 ✔
4983

4984
        return static::create(
7 ✔
4985
            $generator,
7 ✔
4986
            $this->iteratorClass,
7 ✔
4987
            false
7 ✔
4988
        );
7 ✔
4989
    }
4990

4991
    /**
4992
     * Pad array to the specified size with a given value.
4993
     *
4994
     * @param int   $size  <p>Size of the result array.</p>
4995
     * @param mixed $value <p>Empty value by default.</p>
4996
     *
4997
     * @return static
4998
     *                <p>(Immutable) Arrayy object padded to $size with $value.</p>
4999
     *
5000
     * @phpstan-return static<TKey,T>
5001
     * @psalm-mutation-free
5002
     */
5003
    public function pad(int $size, $value): self
5004
    {
5005
        return static::create(
35 ✔
5006
            \array_pad($this->toArray(), $size, $value),
35 ✔
5007
            $this->iteratorClass,
35 ✔
5008
            false
35 ✔
5009
        );
35 ✔
5010
    }
5011

5012
    /**
5013
     * Partitions this array in two array according to a predicate.
5014
     * Keys are preserved in the resulting array.
5015
     *
5016
     * @param \Closure $closure
5017
     *                          <p>The predicate on which to partition.</p>
5018
     *
5019
     * @return array<int, static>
5020
     *                    <p>An array with two elements. The first element contains the array
5021
     *                    of elements where the predicate returned TRUE, the second element
5022
     *                    contains the array of elements where the predicate returned FALSE.</p>
5023
     *
5024
     * @phpstan-param \Closure(T,TKey):bool $closure
5025
     * @phpstan-return array<int, static<TKey,T>>
5026
     */
5027
    public function partition(\Closure $closure): array
5028
    {
5029
        // init
5030
        $matches = [];
7 ✔
5031
        $noMatches = [];
7 ✔
5032

5033
        foreach ($this->getGenerator() as $key => $value) {
7 ✔
5034
            if ($closure($value, $key)) {
7 ✔
5035
                $matches[$key] = $value;
7 ✔
5036
            } else {
5037
                $noMatches[$key] = $value;
7 ✔
5038
            }
5039
        }
5040

5041
        return [self::create($matches), self::create($noMatches)];
7 ✔
5042
    }
5043

5044
    /**
5045
     * Pop a specified value off the end of the current array.
5046
     *
5047
     * @return mixed|null
5048
     *                    <p>(Mutable) The popped element from the current array or null if the array is e.g. empty.</p>
5049
     *
5050
     * @phpstan-return T|null
5051
     */
5052
    public function pop()
5053
    {
5054
        $this->generatorToArray();
35 ✔
5055

5056
        return \array_pop($this->array);
35 ✔
5057
    }
5058

5059
    /**
5060
     * Prepend a (key) + value to the current array.
5061
     *
5062
     * EXAMPLE: <code>
5063
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->prepend('foo'); // Arrayy[0 => 'foo', 'fΓ²Γ΄' => 'bΓ Ε™']
5064
     * </code>
5065
     *
5066
     * @param mixed $value
5067
     * @param mixed $key
5068
     *
5069
     * @return $this
5070
     *               <p>(Mutable) Return this Arrayy object, with the prepended value.</p>
5071
     *
5072
     * @phpstan-param T $value
5073
     * @phpstan-param TKey|null $key
5074
     * @phpstan-return static<TKey,T>
5075
     */
5076
    public function prepend($value, $key = null)
5077
    {
5078
        $this->generatorToArray();
77 ✔
5079

5080
        if ($this->properties !== []) {
77 ✔
5081
            $this->checkType($key, $value);
21 ✔
5082
        }
5083

5084
        if ($key === null) {
63 ✔
5085
            \array_unshift($this->array, $value);
56 ✔
5086
        } else {
5087
            $this->array = [$key => $value] + $this->array; // @phpstan-ignore assign.propertyType
14 ✔
5088
        }
5089

5090
        return $this;
63 ✔
5091
    }
5092

5093
    /**
5094
     * Prepend a (key) + value to the current array.
5095
     *
5096
     * EXAMPLE: <code>
5097
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->prependImmutable('foo')->getArray(); // [0 => 'foo', 'fΓ²Γ΄' => 'bΓ Ε™']
5098
     * </code>
5099
     *
5100
     * @param mixed $value
5101
     * @param mixed $key
5102
     *
5103
     * @return $this
5104
     *               <p>(Immutable) Return this Arrayy object, with the prepended value.</p>
5105
     *
5106
     * @phpstan-param T $value
5107
     * @phpstan-param TKey $key
5108
     * @phpstan-return static<TKey,T>
5109
     * @psalm-mutation-free
5110
     */
5111
    public function prependImmutable($value, $key = null)
5112
    {
5113
        $generator = function () use ($key, $value): \Generator {
7 ✔
5114
            if ($this->properties !== []) {
7 ✔
5115
                $this->checkType($key, $value);
×
5116
            }
5117

5118
            if ($key !== null) {
7 ✔
5119
                yield $key => $value;
×
5120
            } else {
5121
                yield $value;
7 ✔
5122
            }
5123

5124
            foreach ($this->getGenerator() as $keyOld => $itemOld) {
7 ✔
5125
                yield $keyOld => $itemOld;
7 ✔
5126
            }
5127
        };
7 ✔
5128

5129
        return static::create(
7 ✔
5130
            $generator,
7 ✔
5131
            $this->iteratorClass,
7 ✔
5132
            false
7 ✔
5133
        );
7 ✔
5134
    }
5135

5136
    /**
5137
     * Add a suffix to each key.
5138
     *
5139
     * @param float|int|string $suffix
5140
     *
5141
     * @return static
5142
     *                <p>(Immutable) Return an Arrayy object, with the prepended keys.</p>
5143
     *
5144
     * @phpstan-return static<TKey,T>
5145
     * @psalm-mutation-free
5146
     */
5147
    public function prependToEachKey($suffix): self
5148
    {
5149
        // init
5150
        $result = [];
70 ✔
5151

5152
        foreach ($this->getGenerator() as $key => $item) {
70 ✔
5153
            if ($item instanceof self) {
63 ✔
5154
                $result[$key] = $item->prependToEachKey($suffix);
×
5155
            } elseif (\is_array($item)) {
63 ✔
5156
                $result[$key] = self::create(
×
5157
                    $item,
×
5158
                    $this->iteratorClass,
×
5159
                    false
×
5160
                )->prependToEachKey($suffix)
×
5161
                    ->toArray();
×
5162
            } else {
5163
                $result[$key . $suffix] = $item;
63 ✔
5164
            }
5165
        }
5166

5167
        return self::create(
70 ✔
5168
            $result,
70 ✔
5169
            $this->iteratorClass,
70 ✔
5170
            false
70 ✔
5171
        );
70 ✔
5172
    }
5173

5174
    /**
5175
     * Add a suffix to each value.
5176
     *
5177
     * @param float|int|string $suffix
5178
     *
5179
     * @return static
5180
     *                <p>(Immutable) Return an Arrayy object, with the prepended values.</p>
5181
     *
5182
     * @phpstan-return static<TKey,T>
5183
     * @psalm-mutation-free
5184
     */
5185
    public function prependToEachValue($suffix): self
5186
    {
5187
        // init
5188
        $result = [];
70 ✔
5189

5190
        foreach ($this->getGenerator() as $key => $item) {
70 ✔
5191
            if ($item instanceof self) {
63 ✔
5192
                $result[$key] = $item->prependToEachValue($suffix);
×
5193
            } elseif (\is_array($item)) {
63 ✔
5194
                $result[$key] = self::create(
×
5195
                    $item,
×
5196
                    $this->iteratorClass,
×
5197
                    false
×
5198
                )->prependToEachValue($suffix)
×
5199
                    ->toArray();
×
5200
            } elseif (\is_object($item) === true) {
63 ✔
5201
                $result[$key] = $item;
7 ✔
5202
            } else {
5203
                $result[$key] = $item . $suffix;
56 ✔
5204
            }
5205
        }
5206

5207
        return self::create(
70 ✔
5208
            $result,
70 ✔
5209
            $this->iteratorClass,
70 ✔
5210
            false
70 ✔
5211
        );
70 ✔
5212
    }
5213

5214
    /**
5215
     * Return the value of a given key and
5216
     * delete the key.
5217
     *
5218
     * @param int|int[]|string|string[]|null $keyOrKeys
5219
     * @param mixed                          $fallback
5220
     *
5221
     * @return mixed
5222
     *
5223
     * @template TFallback $fallback
5224
     * @phpstan-param TFallback $fallback
5225
     * @phpstan-return TFallback|T|T[]
5226
     */
5227
    public function pull($keyOrKeys = null, $fallback = null)
5228
    {
5229
        if ($keyOrKeys === null) {
42 ✔
5230
            $array = $this->toArray();
7 ✔
5231
            $this->clear();
7 ✔
5232

5233
            return $array;
7 ✔
5234
        }
5235

5236
        if (\is_array($keyOrKeys)) {
35 ✔
5237
            $valueOrValues = [];
7 ✔
5238
            foreach ($keyOrKeys as $key) {
7 ✔
5239
                $valueOrValues[] = $this->get($key, $fallback);
7 ✔
5240
                $this->offsetUnset($key);
7 ✔
5241
            }
5242
        } else {
5243
            $valueOrValues = $this->get($keyOrKeys, $fallback);
35 ✔
5244
            $this->offsetUnset($keyOrKeys);
35 ✔
5245
        }
5246

5247
        /** @var T|T[]|TFallback $valueOrValues */
5248
        return $valueOrValues;
35 ✔
5249
    }
5250

5251
    /**
5252
     * Push one or more values onto the end of array at once.
5253
     *
5254
     * @param mixed ...$args
5255
     *
5256
     * @return $this
5257
     *               <p>(Mutable) Return this Arrayy object, with pushed elements to the end of array.</p>
5258
     *
5259
     * @noinspection ReturnTypeCanBeDeclaredInspection
5260
     *
5261
     * @phpstan-param  array<TKey,T> ...$args
5262
     * @phpstan-return static<TKey,T>
5263
     */
5264
    public function push(...$args)
5265
    {
5266
        $this->generatorToArray();
63 ✔
5267

5268
        if (
5269
            $this->checkPropertyTypes
63 ✔
5270
            &&
5271
            $this->properties !== []
63 ✔
5272
        ) {
5273
            foreach ($args as $key => $value) {
21 ✔
5274
                $this->checkType($key, $value);
21 ✔
5275
            }
5276
        }
5277

5278
        \array_push($this->array, ...$args); // @phpstan-ignore assign.propertyType
56 ✔
5279

5280
        return $this;
56 ✔
5281
    }
5282

5283
    /**
5284
     * Get a random value from the current array.
5285
     *
5286
     * EXAMPLE: <code>
5287
     * a([1, 2, 3, 4])->randomImmutable(2); // e.g.: Arrayy[1, 4]
5288
     * </code>
5289
     *
5290
     * @param int|null $number <p>How many values you will take?</p>
5291
     *
5292
     * @return static
5293
     *                <p>(Immutable)</p>
5294
     *
5295
     * @phpstan-return static<array-key,T>
5296
     */
5297
    public function randomImmutable(?int $number = null): self
5298
    {
5299
        $this->generatorToArray();
133 ✔
5300

5301
        if ($this->count() === 0) {
133 ✔
5302
            return static::create(
7 ✔
5303
                [],
7 ✔
5304
                $this->iteratorClass,
7 ✔
5305
                false
7 ✔
5306
            );
7 ✔
5307
        }
5308

5309
        if ($number === null) {
126 ✔
5310
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
91 ✔
5311

5312
            return static::create(
91 ✔
5313
                $arrayRandValue,
91 ✔
5314
                $this->iteratorClass,
91 ✔
5315
                false
91 ✔
5316
            );
91 ✔
5317
        }
5318

5319
        $arrayTmp = $this->array;
42 ✔
5320
        \shuffle($arrayTmp);
42 ✔
5321

5322
        return static::create(
42 ✔
5323
            $arrayTmp,
42 ✔
5324
            $this->iteratorClass,
42 ✔
5325
            false
42 ✔
5326
        )->firstsImmutable($number);
42 ✔
5327
    }
5328

5329
    /**
5330
     * Pick a random key/index from the keys of this array.
5331
     *
5332
     * EXAMPLE: <code>
5333
     * $arrayy = A::create([1 => 'one', 2 => 'two']);
5334
     * $arrayy->randomKey(); // e.g. 2
5335
     * </code>
5336
     *
5337
     * @throws \RangeException If array is empty
5338
     *
5339
     * @return mixed|null
5340
     *                    <p>Get a key/index or null if there wasn't a key/index.</p>
5341
     *
5342
     * @phpstan-return null|TKey
5343
     */
5344
    public function randomKey()
5345
    {
5346
        $result = $this->randomKeys(1);
28 ✔
5347

5348
        if (!isset($result[0])) {
28 ✔
5349
            $result[0] = null;
×
5350
        }
5351

5352
        return $result[0];
28 ✔
5353
    }
5354

5355
    /**
5356
     * Pick a given number of random keys/indexes out of this array.
5357
     *
5358
     * EXAMPLE: <code>
5359
     * a([1 => 'one', 2 => 'two'])->randomKeys(); // e.g. Arrayy[1, 2]
5360
     * </code>
5361
     *
5362
     * @param int $number <p>The number of keys/indexes (should be <= \count($this->array))</p>
5363
     *
5364
     * @throws \RangeException If array is empty
5365
     *
5366
     * @return static
5367
     *                <p>(Immutable)</p>
5368
     *
5369
     * @phpstan-return static<TKey,T>
5370
     */
5371
    public function randomKeys(int $number): self
5372
    {
5373
        $this->generatorToArray();
91 ✔
5374

5375
        $count = $this->count();
91 ✔
5376

5377
        if (
5378
            $number === 0
91 ✔
5379
            ||
5380
            $number > $count
91 ✔
5381
        ) {
5382
            throw new \RangeException(
14 ✔
5383
                \sprintf(
14 ✔
5384
                    'Number of requested keys (%s) must be equal or lower than number of elements in this array (%s)',
14 ✔
5385
                    $number,
14 ✔
5386
                    $count
14 ✔
5387
                )
14 ✔
5388
            );
14 ✔
5389
        }
5390

5391
        $result = (array) \array_rand($this->array, $number);
77 ✔
5392

5393
        return static::create(
77 ✔
5394
            $result,
77 ✔
5395
            $this->iteratorClass,
77 ✔
5396
            false
77 ✔
5397
        );
77 ✔
5398
    }
5399

5400
    /**
5401
     * Get a random value from the current array.
5402
     *
5403
     * EXAMPLE: <code>
5404
     * a([1, 2, 3, 4])->randomMutable(2); // e.g.: Arrayy[1, 4]
5405
     * </code>
5406
     *
5407
     * @param int|null $number <p>How many values you will take?</p>
5408
     *
5409
     * @return $this
5410
     *               <p>(Mutable) Return this Arrayy object.</p>
5411
     *
5412
     * @phpstan-return static<TKey,T>
5413
     */
5414
    public function randomMutable(?int $number = null): self
5415
    {
5416
        $this->generatorToArray();
119 ✔
5417

5418
        if ($this->count() === 0) {
119 ✔
5419
            return static::create(
×
5420
                [],
×
5421
                $this->iteratorClass,
×
5422
                false
×
5423
            );
×
5424
        }
5425

5426
        if ($number === null) {
119 ✔
5427
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
49 ✔
5428
            $this->array = $arrayRandValue; // @phpstan-ignore assign.propertyType
49 ✔
5429

5430
            return $this;
49 ✔
5431
        }
5432

5433
        \shuffle($this->array);
77 ✔
5434

5435
        return $this->firstsMutable($number);
77 ✔
5436
    }
5437

5438
    /**
5439
     * Pick a random value from the values of this array.
5440
     *
5441
     * EXAMPLE: <code>
5442
     * a([1 => 'one', 2 => 'two'])->randomValue(); // e.g. 'one'
5443
     * </code>
5444
     *
5445
     * @return mixed
5446
     *               <p>Get a random value or null if there wasn't a value.</p>
5447
     *
5448
     * @phpstan-return T|null
5449
     */
5450
    public function randomValue()
5451
    {
5452
        $result = $this->randomImmutable();
28 ✔
5453

5454
        if (!isset($result[0])) {
28 ✔
5455
            $result[0] = null;
×
5456
        }
5457

5458
        return $result[0];
28 ✔
5459
    }
5460

5461
    /**
5462
     * Pick a given number of random values out of this array.
5463
     *
5464
     * EXAMPLE: <code>
5465
     * a([1 => 'one', 2 => 'two'])->randomValues(); // e.g. Arrayy['one', 'two']
5466
     * </code>
5467
     *
5468
     * @param int $number
5469
     *
5470
     * @return static
5471
     *                <p>(Mutable)</p>
5472
     *
5473
     * @phpstan-return static<TKey,T>
5474
     */
5475
    public function randomValues(int $number): self
5476
    {
5477
        return $this->randomMutable($number);
49 ✔
5478
    }
5479

5480
    /**
5481
     * Get a random value from an array, with the ability to skew the results.
5482
     *
5483
     * EXAMPLE: <code>
5484
     * a([0 => 3, 1 => 4])->randomWeighted([1 => 4]); // e.g.: Arrayy[4] (has a 66% chance of returning 4)
5485
     * </code>
5486
     *
5487
     * @param array    $array
5488
     * @param int|null $number <p>How many values you will take?</p>
5489
     *
5490
     * @return static<int,mixed>
5491
     *                           <p>(Immutable)</p>
5492
     *
5493
     * @phpstan-param  array<(int&T)|(string&T),int> $array
5494
     * @phpstan-return static<array-key,T>
5495
     */
5496
    public function randomWeighted(array $array, ?int $number = null): self
5497
    {
5498
        // init
5499
        $options = [];
63 ✔
5500

5501
        foreach ($array as $option => $weight) {
63 ✔
5502
            /** @phpstan-var T $option - hack: we protect this method via (int&T)|(string&T) */
5503
            if ($this->searchIndex($option) !== false) {
63 ✔
5504
                for ($i = 0; $i < $weight; ++$i) {
14 ✔
5505
                    $options[] = $option;
7 ✔
5506
                }
5507
            }
5508
        }
5509

5510
        return $this->mergeAppendKeepIndex($options)->randomImmutable($number);
63 ✔
5511
    }
5512

5513
    /**
5514
     * Reduce the current array via callable e.g. anonymous-function and return the end result.
5515
     *
5516
     * EXAMPLE: <code>
5517
     * a([1, 2, 3, 4])->reduce(
5518
     *     function ($carry, $item) {
5519
     *         return $carry * $item;
5520
     *     },
5521
     *     1
5522
     * ); // Arrayy[24]
5523
     * </code>
5524
     *
5525
     * @param callable $callable
5526
     * @param mixed    $initial
5527
     *
5528
     * @return static
5529
     *                <p>(Immutable)</p>
5530
     *
5531
     * @template T2
5532
     *              <p>The output value type.</p>
5533
     *
5534
     * @phpstan-param callable(T2, T, TKey): T2 $callable
5535
     * @phpstan-param T2                        $initial
5536
     *
5537
     * @phpstan-return static<TKey,T2>
5538
     * @psalm-mutation-free
5539
     */
5540
    public function reduce($callable, $initial = []): self
5541
    {
5542
        foreach ($this->getGenerator() as $key => $value) {
126 ✔
5543
            $initial = $callable($initial, $value, $key);
119 ✔
5544
        }
5545

5546
        /** @var static<TKey,T2> $return - help for phpstan */
5547
        $return = static::create(
126 ✔
5548
            $initial,
126 ✔
5549
            $this->iteratorClass,
126 ✔
5550
            false
126 ✔
5551
        );
126 ✔
5552

5553
        return $return;
126 ✔
5554
    }
5555

5556
    /**
5557
     * @param bool $unique
5558
     *
5559
     * @return static
5560
     *                <p>(Immutable)</p>
5561
     *
5562
     * @phpstan-return static<int,mixed>
5563
     * @psalm-mutation-free
5564
     */
5565
    public function reduce_dimension(bool $unique = true): self
5566
    {
5567
        // init
5568
        $result = [];
98 ✔
5569

5570
        foreach ($this->getGenerator() as $val) {
98 ✔
5571
            if (\is_array($val)) {
84 ✔
5572
                $result[] = static::create($val)->reduce_dimension($unique)->toArray();
35 ✔
5573
            } else {
5574
                $result[] = [$val];
84 ✔
5575
            }
5576
        }
5577

5578
        $result = $result === [] ? [] : \array_merge(...$result);
98 ✔
5579

5580
        $resultArrayy = static::create($result);
98 ✔
5581

5582
        /**
5583
         * @psalm-suppress ImpureMethodCall - object is already re-created
5584
         * @psalm-suppress InvalidReturnStatement - why?
5585
         */
5586
        return $unique ? $resultArrayy->unique() : $resultArrayy;
98 ✔
5587
    }
5588

5589
    /**
5590
     * Create a numerically re-indexed Arrayy object.
5591
     *
5592
     * EXAMPLE: <code>
5593
     * a([2 => 1, 3 => 2])->reindex(); // Arrayy[0 => 1, 1 => 2]
5594
     * </code>
5595
     *
5596
     * @return $this
5597
     *               <p>(Mutable) Return this Arrayy object, with re-indexed array-elements.</p>
5598
     *
5599
     * @phpstan-return static<TKey,T>
5600
     */
5601
    public function reindex(): self
5602
    {
5603
        $this->generatorToArray(false);
63 ✔
5604

5605
        $this->array = \array_values($this->array);
63 ✔
5606

5607
        return $this;
63 ✔
5608
    }
5609

5610
    /**
5611
     * Return all items that fail the truth test.
5612
     *
5613
     * EXAMPLE: <code>
5614
     * $closure = function ($value) {
5615
     *     return $value % 2 !== 0;
5616
     * }
5617
     * a([1, 2, 3, 4])->reject($closure); // Arrayy[1 => 2, 3 => 4]
5618
     * </code>
5619
     *
5620
     * @param \Closure $closure
5621
     *
5622
     * @return static
5623
     *                <p>(Immutable)</p>
5624
     *
5625
     * @phpstan-param \Closure(T,TKey):bool  $closure
5626
     * @phpstan-return static<TKey,T>
5627
     * @psalm-mutation-free
5628
     */
5629
    public function reject(\Closure $closure): self
5630
    {
5631
        // init
5632
        $filtered = [];
7 ✔
5633

5634
        foreach ($this->getGenerator() as $key => $value) {
7 ✔
5635
            if (!$closure($value, $key)) {
7 ✔
5636
                $filtered[$key] = $value;
7 ✔
5637
            }
5638
        }
5639

5640
        return static::create(
7 ✔
5641
            $filtered,
7 ✔
5642
            $this->iteratorClass,
7 ✔
5643
            false
7 ✔
5644
        );
7 ✔
5645
    }
5646

5647
    /**
5648
     * Remove a value from the current array (optional using dot-notation).
5649
     *
5650
     * EXAMPLE: <code>
5651
     * a([1 => 'bar', 'foo' => 'foo'])->remove(1); // Arrayy['foo' => 'foo']
5652
     * </code>
5653
     *
5654
     * @param mixed $key
5655
     *
5656
     * @return static
5657
     *                <p>(Mutable)</p>
5658
     *
5659
     * @phpstan-param  TKey|TKey[] $key
5660
     * @phpstan-return static<TKey,T>
5661
     */
5662
    public function remove($key)
5663
    {
5664
        // recursive call
5665
        if (\is_array($key)) {
154 ✔
5666
            foreach ($key as $k) {
7 ✔
5667
                $this->internalRemove($k);
7 ✔
5668
            }
5669

5670
            return static::create(
7 ✔
5671
                $this->toArray(),
7 ✔
5672
                $this->iteratorClass,
7 ✔
5673
                false
7 ✔
5674
            );
7 ✔
5675
        }
5676

5677
        $this->internalRemove($key);
147 ✔
5678

5679
        return static::create(
147 ✔
5680
            $this->toArray(),
147 ✔
5681
            $this->iteratorClass,
147 ✔
5682
            false
147 ✔
5683
        );
147 ✔
5684
    }
5685

5686
    /**
5687
     * alias: for "Arrayy->removeValue()"
5688
     *
5689
     * @param mixed $element
5690
     *
5691
     * @return static
5692
     *                <p>(Immutable)</p>
5693
     *
5694
     * @phpstan-param  T $element
5695
     * @phpstan-return static<TKey,T>
5696
     * @psalm-mutation-free
5697
     */
5698
    public function removeElement($element)
5699
    {
5700
        return $this->removeValue($element);
56 ✔
5701
    }
5702

5703
    /**
5704
     * Remove the first value from the current array.
5705
     *
5706
     * EXAMPLE: <code>
5707
     * a([1 => 'bar', 'foo' => 'foo'])->removeFirst(); // Arrayy['foo' => 'foo']
5708
     * </code>
5709
     *
5710
     * @return static
5711
     *                <p>(Immutable)</p>
5712
     *
5713
     * @phpstan-return static<TKey,T>
5714
     * @psalm-mutation-free
5715
     */
5716
    public function removeFirst(): self
5717
    {
5718
        $tmpArray = $this->toArray();
49 ✔
5719

5720
        \array_shift($tmpArray);
49 ✔
5721

5722
        return static::create(
49 ✔
5723
            $tmpArray,
49 ✔
5724
            $this->iteratorClass,
49 ✔
5725
            false
49 ✔
5726
        );
49 ✔
5727
    }
5728

5729
    /**
5730
     * Remove the last value from the current array.
5731
     *
5732
     * EXAMPLE: <code>
5733
     * a([1 => 'bar', 'foo' => 'foo'])->removeLast(); // Arrayy[1 => 'bar']
5734
     * </code>
5735
     *
5736
     * @return static
5737
     *                <p>(Immutable)</p>
5738
     *
5739
     * @phpstan-return static<TKey,T>
5740
     * @psalm-mutation-free
5741
     */
5742
    public function removeLast(): self
5743
    {
5744
        $tmpArray = $this->toArray();
49 ✔
5745

5746
        \array_pop($tmpArray);
49 ✔
5747

5748
        return static::create(
49 ✔
5749
            $tmpArray,
49 ✔
5750
            $this->iteratorClass,
49 ✔
5751
            false
49 ✔
5752
        );
49 ✔
5753
    }
5754

5755
    /**
5756
     * Removes a particular value from an array (numeric or associative).
5757
     *
5758
     * EXAMPLE: <code>
5759
     * a([1 => 'bar', 'foo' => 'foo'])->removeValue('foo'); // Arrayy[1 => 'bar']
5760
     * </code>
5761
     *
5762
     * @param mixed $value
5763
     *
5764
     * @return static
5765
     *                <p>(Immutable)</p>
5766
     *
5767
     * @phpstan-param  T $value
5768
     * @phpstan-return static<TKey,T>
5769
     * @psalm-mutation-free
5770
     */
5771
    public function removeValue($value): self
5772
    {
5773
        $this->generatorToArray();
56 ✔
5774

5775
        // init
5776
        $isSequentialArray = $this->isSequential();
56 ✔
5777

5778
        foreach ($this->array as $key => $item) {
56 ✔
5779
            if ($item === $value) {
49 ✔
5780
                unset($this->array[$key]);
49 ✔
5781
            }
5782
        }
5783

5784
        if ($isSequentialArray) {
56 ✔
5785
            $this->array = \array_values($this->array);
42 ✔
5786
        }
5787

5788
        return static::create(
56 ✔
5789
            $this->array,
56 ✔
5790
            $this->iteratorClass,
56 ✔
5791
            false
56 ✔
5792
        );
56 ✔
5793
    }
5794

5795
    /**
5796
     * Generate array of repeated arrays.
5797
     *
5798
     * @param int $times <p>How many times has to be repeated.</p>
5799
     *
5800
     * @return static
5801
     *                <p>(Immutable)</p>
5802
     *
5803
     * @phpstan-return static<TKey,T>
5804
     * @psalm-mutation-free
5805
     */
5806
    public function repeat($times): self
5807
    {
5808
        if ($times === 0) {
7 ✔
5809
            return static::create([], $this->iteratorClass);
7 ✔
5810
        }
5811

5812
        return static::create(
7 ✔
5813
            \array_fill(0, (int) $times, $this->toArray()),
7 ✔
5814
            $this->iteratorClass,
7 ✔
5815
            false
7 ✔
5816
        );
7 ✔
5817
    }
5818

5819
    /**
5820
     * Replace a key with a new key/value pair.
5821
     *
5822
     * EXAMPLE: <code>
5823
     * $arrayy = a([1 => 'foo', 2 => 'foo2', 3 => 'bar']);
5824
     * $arrayy->replace(2, 'notfoo', 'notbar'); // Arrayy[1 => 'foo', 'notfoo' => 'notbar', 3 => 'bar']
5825
     * </code>
5826
     *
5827
     * @param mixed $oldKey
5828
     * @param mixed $newKey
5829
     * @param mixed $newValue
5830
     *
5831
     * @return static
5832
     *                <p>(Immutable)</p>
5833
     *
5834
     * @phpstan-param TKey $oldKey
5835
     * @phpstan-param TKey $newKey
5836
     * @phpstan-param T $newValue
5837
     * @phpstan-return static<TKey,T>
5838
     * @psalm-mutation-free
5839
     */
5840
    public function replace($oldKey, $newKey, $newValue): self
5841
    {
5842
        $that = clone $this;
35 ✔
5843

5844
        /**
5845
         * @psalm-suppress ImpureMethodCall - object is already cloned
5846
         */
5847
        return $that->remove($oldKey)
35 ✔
5848
            ->set($newKey, $newValue);
35 ✔
5849
    }
5850

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

5888
        return static::create(
14 ✔
5889
            $data,
14 ✔
5890
            $this->iteratorClass,
14 ✔
5891
            false
14 ✔
5892
        );
14 ✔
5893
    }
5894

5895
    /**
5896
     * Create an array using the current array as keys and the other array as values.
5897
     *
5898
     * EXAMPLE: <code>
5899
     * $firstArray = [
5900
     *     1 => 'one',
5901
     *     2 => 'two',
5902
     *     3 => 'three',
5903
     * ];
5904
     * $secondArray = [
5905
     *     'one' => 1,
5906
     *     1     => 'one',
5907
     *     2     => 2,
5908
     * ];
5909
     * $arrayy = a($firstArray);
5910
     * $arrayy->replaceAllValues($secondArray); // Arrayy['one' => 1, 'two' => 'one', 'three' => 2]
5911
     * </code>
5912
     *
5913
     * @param array $array <p>An array of values.</p>
5914
     *
5915
     * @return static
5916
     *                <p>(Immutable) Arrayy object with values from the other array, empty Arrayy object if the number of elements
5917
     *                for each array isn't equal or if the arrays are empty.
5918
     *                </p>
5919
     *
5920
     * @phpstan-param  array<T> $array
5921
     * @phpstan-return static<TKey,T>
5922
     * @psalm-mutation-free
5923
     */
5924
    public function replaceAllValues(array $array): self
5925
    {
5926
        $data = \array_combine($this->toArray(), $array);
14 ✔
5927
        /* @phpstan-ignore-next-line | change from PHP >= 8, but we still support old versions */
5928
        if ($data === false) {
14 ✔
5929
            $data = [];
×
5930
        }
5931

5932
        return static::create(
14 ✔
5933
            $data,
14 ✔
5934
            $this->iteratorClass,
14 ✔
5935
            false
14 ✔
5936
        );
14 ✔
5937
    }
5938

5939
    /**
5940
     * Replace the keys in an array with another set.
5941
     *
5942
     * EXAMPLE: <code>
5943
     * a([1 => 'bar', 'foo' => 'foo'])->replaceKeys([1 => 2, 'foo' => 'replaced']); // Arrayy[2 => 'bar', 'replaced' => 'foo']
5944
     * </code>
5945
     *
5946
     * @param array $keys <p>An array of keys matching the array's size.</p>
5947
     *
5948
     * @return static
5949
     *                <p>(Immutable)</p>
5950
     *
5951
     * @phpstan-param  array<TKey> $keys
5952
     * @phpstan-return static<TKey,T>
5953
     * @psalm-mutation-free
5954
     */
5955
    public function replaceKeys(array $keys): self
5956
    {
5957
        $values = \array_values($this->toArray());
7 ✔
5958
        $result = \array_combine($keys, $values);
7 ✔
5959
        /* @phpstan-ignore-next-line | change from PHP >= 8, but we still support old versions */
5960
        if ($result === false) {
7 ✔
5961
            $result = [];
×
5962
        }
5963

5964
        return static::create(
7 ✔
5965
            $result,
7 ✔
5966
            $this->iteratorClass,
7 ✔
5967
            false
7 ✔
5968
        );
7 ✔
5969
    }
5970

5971
    /**
5972
     * Replace the first matched value in an array.
5973
     *
5974
     * EXAMPLE: <code>
5975
     * $testArray = ['bar', 'foo' => 'foo', 'foobar' => 'foobar'];
5976
     * a($testArray)->replaceOneValue('foo', 'replaced'); // Arrayy['bar', 'foo' => 'replaced', 'foobar' => 'foobar']
5977
     * </code>
5978
     *
5979
     * @param mixed $search      <p>The value to replace.</p>
5980
     * @param mixed $replacement <p>The value to replace.</p>
5981
     *
5982
     * @return static
5983
     *                <p>(Immutable)</p>
5984
     *
5985
     * @phpstan-param T $search
5986
     * @phpstan-param T $replacement
5987
     * @phpstan-return static<TKey,T>
5988
     * @psalm-mutation-free
5989
     */
5990
    public function replaceOneValue($search, $replacement = ''): self
5991
    {
5992
        $array = $this->toArray();
21 ✔
5993
        $key = \array_search($search, $array, true);
21 ✔
5994

5995
        if ($key !== false) {
21 ✔
5996
            $array[$key] = $replacement;
21 ✔
5997
        }
5998

5999
        return static::create(
21 ✔
6000
            $array,
21 ✔
6001
            $this->iteratorClass,
21 ✔
6002
            false
21 ✔
6003
        );
21 ✔
6004
    }
6005

6006
    /**
6007
     * Replace values in the current array.
6008
     *
6009
     * EXAMPLE: <code>
6010
     * $testArray = ['bar', 'foo' => 'foo', 'foobar' => 'foobar'];
6011
     * a($testArray)->replaceValues('foo', 'replaced'); // Arrayy['bar', 'foo' => 'replaced', 'foobar' => 'replacedbar']
6012
     * </code>
6013
     *
6014
     * @param string $search      <p>The value to replace.</p>
6015
     * @param string $replacement <p>What to replace it with.</p>
6016
     *
6017
     * @return static
6018
     *                <p>(Immutable)</p>
6019
     *
6020
     * @phpstan-return static<TKey,T>
6021
     * @psalm-mutation-free
6022
     */
6023
    public function replaceValues($search, $replacement = ''): self
6024
    {
6025
        $callable = static function ($value) use ($search, $replacement) {
7 ✔
6026
            return \str_replace($search, $replacement, $value);
7 ✔
6027
        };
7 ✔
6028

6029
        /* @phpstan-ignore-next-line | ignore Closure with one or two parameters, is this a bug in phpstan? */
6030
        return $this->each($callable);
7 ✔
6031
    }
6032

6033
    /**
6034
     * Get the last elements from index $from until the end of this array.
6035
     *
6036
     * EXAMPLE: <code>
6037
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->rest(2); // Arrayy[0 => 'lall']
6038
     * </code>
6039
     *
6040
     * @param int $from
6041
     *
6042
     * @return static
6043
     *                <p>(Immutable)</p>
6044
     *
6045
     * @phpstan-return static<TKey,T>
6046
     * @psalm-mutation-free
6047
     */
6048
    public function rest(int $from = 1): self
6049
    {
6050
        $tmpArray = $this->toArray();
105 ✔
6051

6052
        return static::create(
105 ✔
6053
            \array_splice($tmpArray, $from),
105 ✔
6054
            $this->iteratorClass,
105 ✔
6055
            false
105 ✔
6056
        );
105 ✔
6057
    }
6058

6059
    /**
6060
     * Return the array in the reverse order.
6061
     *
6062
     * EXAMPLE: <code>
6063
     * a([1 => 1, 2 => 2, 3 => 3])->reverse(); // self[3, 2, 1]
6064
     * </code>
6065
     *
6066
     * @return $this
6067
     *               <p>(Mutable) Return this Arrayy object.</p>
6068
     *
6069
     * @phpstan-return static<TKey,T>
6070
     */
6071
    public function reverse(): self
6072
    {
6073
        $this->generatorToArray();
63 ✔
6074

6075
        $this->array = \array_reverse($this->array);
63 ✔
6076

6077
        return $this;
63 ✔
6078
    }
6079

6080
    /**
6081
     * Return the array with keys in the reverse order.
6082
     *
6083
     * EXAMPLE: <code>
6084
     * a([1 => 1, 2 => 2, 3 => 3])->reverse(); // self[3 => 3, 2 => 2, 1 => 1]
6085
     * </code>
6086
     *
6087
     * @return $this
6088
     *               <p>(Mutable) Return this Arrayy object.</p>
6089
     *
6090
     * @phpstan-return static<TKey,T>
6091
     */
6092
    public function reverseKeepIndex(): self
6093
    {
6094
        $this->generatorToArray();
35 ✔
6095

6096
        $this->array = \array_reverse($this->array, true);
35 ✔
6097

6098
        return $this;
35 ✔
6099
    }
6100

6101
    /**
6102
     * Sort an array in reverse order.
6103
     *
6104
     * @param int $sort_flags [optional] <p>
6105
     *                        You may modify the behavior of the sort using the optional
6106
     *                        parameter sort_flags, for details
6107
     *                        see sort.
6108
     *                        </p>
6109
     *
6110
     * @return $this
6111
     *               <p>(Mutable) Return this Arrayy object.</p>
6112
     *
6113
     * @phpstan-return static<TKey,T>
6114
     */
6115
    public function rsort(int $sort_flags = 0): self
6116
    {
6117
        $this->generatorToArray();
28 ✔
6118

6119
        \rsort($this->array, $sort_flags);
28 ✔
6120

6121
        return $this;
28 ✔
6122
    }
6123

6124
    /**
6125
     * Sort an array in reverse order.
6126
     *
6127
     * @param int $sort_flags [optional] <p>
6128
     *                        You may modify the behavior of the sort using the optional
6129
     *                        parameter sort_flags, for details
6130
     *                        see sort.
6131
     *                        </p>
6132
     *
6133
     * @return $this
6134
     *               <p>(Immutable) Return this Arrayy object.</p>
6135
     *
6136
     * @phpstan-return static<TKey,T>
6137
     * @psalm-mutation-free
6138
     */
6139
    public function rsortImmutable(int $sort_flags = 0): self
6140
    {
6141
        $that = clone $this;
28 ✔
6142

6143
        /**
6144
         * @psalm-suppress ImpureMethodCall - object is already cloned
6145
         */
6146
        $that->rsort($sort_flags);
28 ✔
6147

6148
        return $that;
28 ✔
6149
    }
6150

6151
    /**
6152
     * Search for the first index of the current array via $value.
6153
     *
6154
     * EXAMPLE: <code>
6155
     * a(['fΓ²Γ΄' => 'bΓ Ε™', 'lall' => 'bΓ Ε™'])->searchIndex('bΓ Ε™'); // Arrayy[0 => 'fΓ²Γ΄']
6156
     * </code>
6157
     *
6158
     * @param mixed $value
6159
     *
6160
     * @return false|int|string
6161
     *                          <p>Will return <b>FALSE</b> if the value can't be found.</p>
6162
     *
6163
     * @phpstan-param T $value
6164
     * @phpstan-return false|TKey
6165
     *
6166
     * @psalm-mutation-free
6167
     */
6168
    public function searchIndex($value)
6169
    {
6170
        foreach ($this->getGenerator() as $keyFromArray => $valueFromArray) {
147 ✔
6171
            if ($value === $valueFromArray) {
140 ✔
6172
                return $keyFromArray;
70 ✔
6173
            }
6174
        }
6175

6176
        return false;
77 ✔
6177
    }
6178

6179
    /**
6180
     * Search for the value of the current array via $index.
6181
     *
6182
     * EXAMPLE: <code>
6183
     * a(['fΓ²Γ΄' => 'bΓ Ε™'])->searchValue('fΓ²Γ΄'); // Arrayy[0 => 'bΓ Ε™']
6184
     * </code>
6185
     *
6186
     * @param mixed $index
6187
     *
6188
     * @return static
6189
     *                <p>(Immutable) Will return a empty Arrayy if the value wasn't found.</p>
6190
     *
6191
     * @phpstan-param TKey $index
6192
     * @phpstan-return static<TKey,T>
6193
     * @psalm-mutation-free
6194
     */
6195
    public function searchValue($index): self
6196
    {
6197
        $this->generatorToArray();
63 ✔
6198

6199
        // init
6200
        $return = [];
63 ✔
6201

6202
        if ($this->array === []) {
63 ✔
6203
            return static::create(
×
6204
                [],
×
6205
                $this->iteratorClass,
×
6206
                false
×
6207
            );
×
6208
        }
6209

6210
        // php cast "bool"-index into "int"-index
6211
        /* @phpstan-ignore-next-line | array-key helper */
6212
        if ((bool) $index === $index) {
63 ✔
6213
            $index = (int) $index;
7 ✔
6214
        }
6215

6216
        if ($this->offsetExists($index)) {
63 ✔
6217
            $return = [$this->array[$index]];
49 ✔
6218
        }
6219

6220
        return static::create(
63 ✔
6221
            $return,
63 ✔
6222
            $this->iteratorClass,
63 ✔
6223
            false
63 ✔
6224
        );
63 ✔
6225
    }
6226

6227
    /**
6228
     * Set a value for the current array (optional using dot-notation).
6229
     *
6230
     * EXAMPLE: <code>
6231
     * $arrayy = a(['Lars' => ['lastname' => 'Moelleken']]);
6232
     * $arrayy->set('Lars.lastname', 'MΓΌller'); // Arrayy['Lars', ['lastname' => 'MΓΌller']]]
6233
     * </code>
6234
     *
6235
     * @param string $key   <p>The key to set.</p>
6236
     * @param mixed  $value <p>Its value.</p>
6237
     *
6238
     * @return $this
6239
     *               <p>(Mutable) Return this Arrayy object.</p>
6240
     *
6241
     * @phpstan-param  TKey $key
6242
     * @phpstan-param  T $value
6243
     * @phpstan-return static<TKey,T>
6244
     */
6245
    public function set($key, $value): self
6246
    {
6247
        $this->internalSet($key, $value);
196 ✔
6248

6249
        return $this;
189 ✔
6250
    }
6251

6252
    /**
6253
     * Get a value from a array and set it if it was not.
6254
     *
6255
     * WARNING: this method only set the value, if the $key is not already set
6256
     *
6257
     * EXAMPLE: <code>
6258
     * $arrayy = a([1 => 1, 2 => 2, 3 => 3]);
6259
     * $arrayy->setAndGet(1, 4); // 1
6260
     * $arrayy->setAndGet(0, 4); // 4
6261
     * </code>
6262
     *
6263
     * @param mixed $key      <p>The key</p>
6264
     * @param mixed $fallback <p>The default value to set if it isn't.</p>
6265
     *
6266
     * @return mixed
6267
     *               <p>(Mutable)</p>
6268
     *
6269
     * @phpstan-param TKey $key
6270
     * @phpstan-param T $fallback
6271
     */
6272
    public function setAndGet($key, $fallback = null)
6273
    {
6274
        $this->generatorToArray();
77 ✔
6275

6276
        // If the key doesn't exist, set it.
6277
        if (!$this->has($key)) {
77 ✔
6278
            $this->array = $this->set($key, $fallback)->toArray();
28 ✔
6279
        }
6280

6281
        return $this->get($key);
77 ✔
6282
    }
6283

6284
    /**
6285
     * Shifts a specified value off the beginning of array.
6286
     *
6287
     * @return mixed|null
6288
     *                    <p>(Mutable) A shifted element from the current array.</p>
6289
     *
6290
     * @phpstan-return T|null
6291
     */
6292
    public function shift()
6293
    {
6294
        $this->generatorToArray();
35 ✔
6295

6296
        return \array_shift($this->array);
35 ✔
6297
    }
6298

6299
    /**
6300
     * Shuffle the current array.
6301
     *
6302
     * EXAMPLE: <code>
6303
     * a([1 => 'bar', 'foo' => 'foo'])->shuffle(); // e.g.: Arrayy[['foo' => 'foo', 1 => 'bar']]
6304
     * </code>
6305
     *
6306
     * @param bool       $secure <p>using a CSPRNG | @see https://paragonie.com/b/JvICXzh_jhLyt4y3</p>
6307
     * @param array|null $array  [optional]
6308
     *
6309
     * @return static
6310
     *                <p>(Immutable)</p>
6311
     *
6312
     * @phpstan-param  array<TKey,T> $array
6313
     * @phpstan-return static<TKey,T>
6314
     */
6315
    public function shuffle(bool $secure = false, ?array $array = null): self
6316
    {
6317
        if ($array === null) {
14 ✔
6318
            $array = $this->toArray(false);
14 ✔
6319
        }
6320

6321
        if ($secure !== true) {
14 ✔
6322
            \shuffle($array);
14 ✔
6323
        } else {
6324
            $size = \count($array, \COUNT_NORMAL);
7 ✔
6325
            $keys = \array_keys($array);
7 ✔
6326
            for ($i = $size - 1; $i > 0; --$i) {
7 ✔
6327
                try {
6328
                    $r = \random_int(0, $i);
7 ✔
6329
                } catch (\Exception $e) {
×
6330
                    /** @noinspection RandomApiMigrationInspection - "random_int" is already in use */
6331
                    $r = \mt_rand(0, $i);
×
6332
                }
6333
                if ($r !== $i) {
7 ✔
6334
                    $temp = $array[$keys[$r]];
5 ✔
6335
                    $array[$keys[$r]] = $array[$keys[$i]];
5 ✔
6336
                    $array[$keys[$i]] = $temp;
5 ✔
6337
                }
6338
            }
6339
        }
6340

6341
        foreach ($array as $key => $value) {
14 ✔
6342
            // check if recursive is needed
6343
            if (\is_array($value)) {
14 ✔
6344
                /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
6345
                /** @phpstan-var array<TKey,T> $value */
6346
                $value = $value;
×
6347

6348
                $array[$key] = $this->shuffle($secure, $value);
×
6349
            }
6350
        }
6351

6352
        return static::create(
14 ✔
6353
            $array,
14 ✔
6354
            $this->iteratorClass,
14 ✔
6355
            false
14 ✔
6356
        );
14 ✔
6357
    }
6358

6359
    /**
6360
     * Count the values from the current array.
6361
     *
6362
     * alias: for "Arrayy->count()"
6363
     *
6364
     * @param int $mode
6365
     *
6366
     * @return int
6367
     */
6368
    public function size(int $mode = \COUNT_NORMAL): int
6369
    {
6370
        return $this->count($mode);
140 ✔
6371
    }
6372

6373
    /**
6374
     * Checks whether array has exactly $size items.
6375
     *
6376
     * @param int $size
6377
     *
6378
     * @return bool
6379
     */
6380
    public function sizeIs(int $size): bool
6381
    {
6382
        // init
6383
        $itemsTempCount = 0;
7 ✔
6384

6385
        /** @noinspection PhpUnusedLocalVariableInspection */
6386
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
6387
        foreach ($this->getGeneratorByReference() as &$value) {
7 ✔
6388
            ++$itemsTempCount;
7 ✔
6389
            if ($itemsTempCount > $size) {
7 ✔
6390
                return false;
7 ✔
6391
            }
6392
        }
6393

6394
        return $itemsTempCount === $size;
7 ✔
6395
    }
6396

6397
    /**
6398
     * Checks whether array has between $fromSize to $toSize items. $toSize can be
6399
     * smaller than $fromSize.
6400
     *
6401
     * @param int $fromSize
6402
     * @param int $toSize
6403
     *
6404
     * @return bool
6405
     */
6406
    public function sizeIsBetween(int $fromSize, int $toSize): bool
6407
    {
6408
        if ($fromSize > $toSize) {
7 ✔
6409
            $tmp = $toSize;
7 ✔
6410
            $toSize = $fromSize;
7 ✔
6411
            $fromSize = $tmp;
7 ✔
6412
        }
6413

6414
        // init
6415
        $itemsTempCount = 0;
7 ✔
6416

6417
        /** @noinspection PhpUnusedLocalVariableInspection */
6418
        foreach ($this->getGenerator() as $value) {
7 ✔
6419
            ++$itemsTempCount;
7 ✔
6420
            if ($itemsTempCount > $toSize) {
7 ✔
6421
                return false;
7 ✔
6422
            }
6423
        }
6424

6425
        return $fromSize < $itemsTempCount && $itemsTempCount < $toSize;
7 ✔
6426
    }
6427

6428
    /**
6429
     * Checks whether array has more than $size items.
6430
     *
6431
     * @param int $size
6432
     *
6433
     * @return bool
6434
     */
6435
    public function sizeIsGreaterThan(int $size): bool
6436
    {
6437
        // init
6438
        $itemsTempCount = 0;
7 ✔
6439

6440
        /** @noinspection PhpUnusedLocalVariableInspection */
6441
        foreach ($this->getGenerator() as $value) {
7 ✔
6442
            ++$itemsTempCount;
7 ✔
6443
            if ($itemsTempCount > $size) {
7 ✔
6444
                return true;
7 ✔
6445
            }
6446
        }
6447

6448
        return $itemsTempCount > $size;
7 ✔
6449
    }
6450

6451
    /**
6452
     * Checks whether array has less than $size items.
6453
     *
6454
     * @param int $size
6455
     *
6456
     * @return bool
6457
     */
6458
    public function sizeIsLessThan(int $size): bool
6459
    {
6460
        // init
6461
        $itemsTempCount = 0;
7 ✔
6462

6463
        /** @noinspection PhpUnusedLocalVariableInspection */
6464
        foreach ($this->getGenerator() as $value) {
7 ✔
6465
            ++$itemsTempCount;
7 ✔
6466
            if ($itemsTempCount > $size) {
7 ✔
6467
                return false;
7 ✔
6468
            }
6469
        }
6470

6471
        return $itemsTempCount < $size;
7 ✔
6472
    }
6473

6474
    /**
6475
     * Counts all elements in an array, or something in an object.
6476
     *
6477
     * <p>
6478
     * For objects, if you have SPL installed, you can hook into count() by implementing interface {@see Countable}.
6479
     * The interface has exactly one method, {@see Countable::count()}, which returns the return value for the count()
6480
     * function. Please see the {@see Array} section of the manual for a detailed explanation of how arrays are
6481
     * implemented and used in PHP.
6482
     * </p>
6483
     *
6484
     * @return int
6485
     *             <p>
6486
     *             The number of elements in var, which is
6487
     *             typically an array, since anything else will have one
6488
     *             element.
6489
     *             </p>
6490
     *             <p>
6491
     *             If var is not an array or an object with
6492
     *             implemented Countable interface,
6493
     *             1 will be returned.
6494
     *             There is one exception, if var is &null;,
6495
     *             0 will be returned.
6496
     *             </p>
6497
     *             <p>
6498
     *             Caution: count may return 0 for a variable that isn't set,
6499
     *             but it may also return 0 for a variable that has been initialized with an
6500
     *             empty array. Use isset to test if a variable is set.
6501
     *             </p>
6502
     */
6503
    public function sizeRecursive(): int
6504
    {
6505
        return \count($this->toArray(), \COUNT_RECURSIVE);
70 ✔
6506
    }
6507

6508
    /**
6509
     * Extract a slice of the array.
6510
     *
6511
     * @param int      $offset       <p>Slice begin index.</p>
6512
     * @param int|null $length       <p>Length of the slice.</p>
6513
     * @param bool     $preserveKeys <p>Whether array keys are preserved or no.</p>
6514
     *
6515
     * @return static
6516
     *                <p>(Immutable) A slice of the original array with length $length.</p>
6517
     *
6518
     * @phpstan-return static<array-key,T>
6519
     * @psalm-mutation-free
6520
     */
6521
    public function slice(int $offset, ?int $length = null, bool $preserveKeys = false)
6522
    {
6523
        return static::create(
35 ✔
6524
            \array_slice(
35 ✔
6525
                $this->toArray(),
35 ✔
6526
                $offset,
35 ✔
6527
                $length,
35 ✔
6528
                $preserveKeys
35 ✔
6529
            ),
35 ✔
6530
            $this->iteratorClass,
35 ✔
6531
            false
35 ✔
6532
        );
35 ✔
6533
    }
6534

6535
    /**
6536
     * Sort the current array and optional you can keep the keys.
6537
     *
6538
     * EXAMPLE: <code>
6539
     * a(3 => 'd', 2 => 'f', 0 => 'a')->sort(SORT_ASC, SORT_NATURAL, false); // Arrayy[0 => 'a', 1 => 'd', 2 => 'f']
6540
     * </code>
6541
     *
6542
     * @param int|string $direction
6543
     *                              <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6544
     * @param int        $strategy
6545
     *                              <p>sort_flags => use e.g.: <strong>SORT_REGULAR</strong> (default) or
6546
     *                              <strong>SORT_NATURAL</strong></p>
6547
     * @param bool       $keepKeys
6548
     *
6549
     * @return static
6550
     *                <p>(Mutable) Return this Arrayy object.</p>
6551
     *
6552
     * @phpstan-return static<int|TKey,T>
6553
     */
6554
    public function sort(
6555
        $direction = \SORT_ASC,
6556
        int $strategy = \SORT_REGULAR,
6557
        bool $keepKeys = false
6558
    ): self {
6559
        $this->generatorToArray();
140 ✔
6560

6561
        return $this->sorting(
140 ✔
6562
            $this->array,
140 ✔
6563
            $direction,
140 ✔
6564
            $strategy,
140 ✔
6565
            $keepKeys
140 ✔
6566
        );
140 ✔
6567
    }
6568

6569
    /**
6570
     * Sort the current array and optional you can keep the keys.
6571
     *
6572
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6573
     * @param int        $strategy  <p>sort_flags => use e.g.: <strong>SORT_REGULAR</strong> (default) or
6574
     *                              <strong>SORT_NATURAL</strong></p>
6575
     * @param bool       $keepKeys
6576
     *
6577
     * @return static
6578
     *                <p>(Immutable) Return this Arrayy object.</p>
6579
     *
6580
     * @phpstan-return static<int|TKey,T>
6581
     */
6582
    public function sortImmutable(
6583
        $direction = \SORT_ASC,
6584
        int $strategy = \SORT_REGULAR,
6585
        bool $keepKeys = false
6586
    ): self {
6587
        $that = clone $this;
84 ✔
6588

6589
        $that->generatorToArray();
84 ✔
6590

6591
        return $that->sorting(
84 ✔
6592
            $that->array,
84 ✔
6593
            $direction,
84 ✔
6594
            $strategy,
84 ✔
6595
            $keepKeys
84 ✔
6596
        );
84 ✔
6597
    }
6598

6599
    /**
6600
     * Sort the current array by key.
6601
     *
6602
     * EXAMPLE: <code>
6603
     * a([1 => 2, 0 => 1])->sortKeys(\SORT_ASC); // Arrayy[0 => 1, 1 => 2]
6604
     * </code>
6605
     *
6606
     * @see http://php.net/manual/en/function.ksort.php
6607
     * @see http://php.net/manual/en/function.krsort.php
6608
     *
6609
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6610
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6611
     *                              <strong>SORT_NATURAL</strong></p>
6612
     *
6613
     * @return $this
6614
     *               <p>(Mutable) Return this Arrayy object.</p>
6615
     *
6616
     * @phpstan-return static<TKey,T>
6617
     */
6618
    public function sortKeys(
6619
        $direction = \SORT_ASC,
6620
        int $strategy = \SORT_REGULAR
6621
    ): self {
6622
        $this->generatorToArray();
126 ✔
6623

6624
        $this->sorterKeys($this->array, $direction, $strategy);
126 ✔
6625

6626
        return $this;
126 ✔
6627
    }
6628

6629
    /**
6630
     * Sort the current array by key.
6631
     *
6632
     * @see          http://php.net/manual/en/function.ksort.php
6633
     * @see          http://php.net/manual/en/function.krsort.php
6634
     *
6635
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6636
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6637
     *                              <strong>SORT_NATURAL</strong></p>
6638
     *
6639
     * @return $this
6640
     *               <p>(Immutable) Return this Arrayy object.</p>
6641
     *
6642
     * @phpstan-return static<TKey,T>
6643
     * @psalm-mutation-free
6644
     */
6645
    public function sortKeysImmutable(
6646
        $direction = \SORT_ASC,
6647
        int $strategy = \SORT_REGULAR
6648
    ): self {
6649
        $that = clone $this;
56 ✔
6650

6651
        /**
6652
         * @psalm-suppress ImpureMethodCall - object is already cloned
6653
         */
6654
        $that->sortKeys($direction, $strategy);
56 ✔
6655

6656
        return $that;
56 ✔
6657
    }
6658

6659
    /**
6660
     * Sort the current array by value.
6661
     *
6662
     * EXAMPLE: <code>
6663
     * a(3 => 'd', 2 => 'f', 0 => 'a')->sortValueKeepIndex(SORT_ASC, SORT_REGULAR); // Arrayy[0 => 'a', 3 => 'd', 2 => 'f']
6664
     * </code>
6665
     *
6666
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6667
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6668
     *                              <strong>SORT_NATURAL</strong></p>
6669
     *
6670
     * @return static
6671
     *                <p>(Mutable)</p>
6672
     *
6673
     * @phpstan-return static<int|TKey,T>
6674
     */
6675
    public function sortValueKeepIndex(
6676
        $direction = \SORT_ASC,
6677
        int $strategy = \SORT_REGULAR
6678
    ): self {
6679
        return $this->sort($direction, $strategy, true);
7 ✔
6680
    }
6681

6682
    /**
6683
     * Sort the current array by value.
6684
     *
6685
     * EXAMPLE: <code>
6686
     * a(3 => 'd', 2 => 'f', 0 => 'a')->sortValueNewIndex(SORT_ASC, SORT_NATURAL); // Arrayy[0 => 'a', 1 => 'd', 2 => 'f']
6687
     * </code>
6688
     *
6689
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
6690
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6691
     *                              <strong>SORT_NATURAL</strong></p>
6692
     *
6693
     * @return static
6694
     *                <p>(Mutable)</p>
6695
     *
6696
     * @phpstan-return static<int|TKey,T>
6697
     */
6698
    public function sortValueNewIndex($direction = \SORT_ASC, int $strategy = \SORT_REGULAR): self
6699
    {
6700
        return $this->sort($direction, $strategy, false);
7 ✔
6701
    }
6702

6703
    /**
6704
     * Sort a array by value or by a closure.
6705
     *
6706
     * - If the sorter is null, the array is sorted naturally.
6707
     * - Associative (string) keys will be maintained, but numeric keys will be re-indexed.
6708
     *
6709
     * EXAMPLE: <code>
6710
     * $testArray = range(1, 5);
6711
     * $under = a($testArray)->sorter(
6712
     *     function ($value) {
6713
     *         return $value % 2 === 0;
6714
     *     }
6715
     * );
6716
     * var_dump($under); // Arrayy[1, 3, 5, 2, 4]
6717
     * </code>
6718
     *
6719
     * @param callable|mixed|null $sorter
6720
     * @param int|string          $direction <p>use <strong>SORT_ASC</strong> (default) or
6721
     *                                       <strong>SORT_DESC</strong></p>
6722
     * @param int                 $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
6723
     *                                       <strong>SORT_NATURAL</strong></p>
6724
     *
6725
     * @return static
6726
     *                <p>(Immutable)</p>
6727
     *
6728
     * @pslam-param callable|T|null $sorter
6729
     * @phpstan-return static<TKey,T>
6730
     * @psalm-mutation-free
6731
     */
6732
    public function sorter($sorter = null, $direction = \SORT_ASC, int $strategy = \SORT_REGULAR): self
6733
    {
6734
        $array = $this->toArray();
7 ✔
6735
        $direction = $this->getDirection($direction);
7 ✔
6736

6737
        // Transform all values into their results.
6738
        if ($sorter) {
7 ✔
6739
            $arrayy = static::create(
7 ✔
6740
                $array,
7 ✔
6741
                $this->iteratorClass,
7 ✔
6742
                false
7 ✔
6743
            );
7 ✔
6744

6745
            /**
6746
             * @psalm-suppress MissingClosureReturnType
6747
             * @psalm-suppress MissingClosureParamType
6748
             */
6749
            $results = $arrayy->each(
7 ✔
6750
                static function ($value) use ($sorter) {
7 ✔
6751
                    if (\is_callable($sorter) === true) {
7 ✔
6752
                        return $sorter($value);
7 ✔
6753
                    }
6754

6755
                    return $sorter === $value;
7 ✔
6756
                }
7 ✔
6757
            );
7 ✔
6758

6759
            $results = $results->toArray();
7 ✔
6760
        } else {
6761
            $results = $array;
7 ✔
6762
        }
6763

6764
        // Sort by the results and replace by original values
6765
        \array_multisort($results, $direction, $strategy, $array);
7 ✔
6766

6767
        return static::create(
7 ✔
6768
            $array,
7 ✔
6769
            $this->iteratorClass,
7 ✔
6770
            false
7 ✔
6771
        );
7 ✔
6772
    }
6773

6774
    /**
6775
     * @param int      $offset
6776
     * @param int|null $length
6777
     * @param array    $replacement
6778
     *
6779
     * @return static
6780
     *                <p>(Immutable)</p>
6781
     *
6782
     * @phpstan-param  array<T> $replacement
6783
     * @phpstan-return static<TKey,T>
6784
     * @psalm-mutation-free
6785
     */
6786
    public function splice(int $offset, ?int $length = null, $replacement = []): self
6787
    {
6788
        $tmpArray = $this->toArray();
7 ✔
6789

6790
        \array_splice(
7 ✔
6791
            $tmpArray,
7 ✔
6792
            $offset,
7 ✔
6793
            $length ?? $this->count(),
7 ✔
6794
            $replacement
7 ✔
6795
        );
7 ✔
6796

6797
        return static::create(
7 ✔
6798
            $tmpArray,
7 ✔
6799
            $this->iteratorClass,
7 ✔
6800
            false
7 ✔
6801
        );
7 ✔
6802
    }
6803

6804
    /**
6805
     * Split an array in the given amount of pieces.
6806
     *
6807
     * EXAMPLE: <code>
6808
     * a(['a' => 1, 'b' => 2])->split(2, true); // Arrayy[['a' => 1], ['b' => 2]]
6809
     * </code>
6810
     *
6811
     * @param int  $numberOfPieces
6812
     * @param bool $keepKeys
6813
     *
6814
     * @return static
6815
     *                <p>(Immutable)</p>
6816
     *
6817
     * @phpstan-return static<TKey,T>
6818
     * @psalm-mutation-free
6819
     */
6820
    public function split(int $numberOfPieces = 2, bool $keepKeys = false): self
6821
    {
6822
        if ($keepKeys) {
7 ✔
6823
            $generator = function () use ($numberOfPieces) {
7 ✔
6824
                $carry = [];
7 ✔
6825
                $i = 1;
7 ✔
6826
                foreach ($this->getGenerator() as $key => $value) {
7 ✔
6827
                    $carry[$key] = $value;
7 ✔
6828

6829
                    if ($i % $numberOfPieces !== 0) {
7 ✔
6830
                        ++$i;
7 ✔
6831

6832
                        continue;
7 ✔
6833
                    }
6834

6835
                    yield $carry;
7 ✔
6836

6837
                    $carry = [];
7 ✔
6838
                    $i = 1;
7 ✔
6839
                }
6840

6841
                if ($carry !== []) {
7 ✔
6842
                    yield $carry;
7 ✔
6843
                }
6844
            };
7 ✔
6845
        } else {
6846
            $generator = function () use ($numberOfPieces) {
7 ✔
6847
                $carry = [];
7 ✔
6848
                $i = 1;
7 ✔
6849
                foreach ($this->getGenerator() as $value) {
7 ✔
6850
                    $carry[] = $value;
7 ✔
6851

6852
                    if ($i % $numberOfPieces !== 0) {
7 ✔
6853
                        ++$i;
7 ✔
6854

6855
                        continue;
7 ✔
6856
                    }
6857

6858
                    yield $carry;
7 ✔
6859

6860
                    $carry = [];
7 ✔
6861
                    $i = 1;
7 ✔
6862
                }
6863

6864
                if ($carry !== []) {
7 ✔
6865
                    yield $carry;
7 ✔
6866
                }
6867
            };
7 ✔
6868
        }
6869

6870
        return static::create(
7 ✔
6871
            $generator,
7 ✔
6872
            $this->iteratorClass,
7 ✔
6873
            false
7 ✔
6874
        );
7 ✔
6875
    }
6876

6877
    /**
6878
     * Strip all empty items from the current array.
6879
     *
6880
     * EXAMPLE: <code>
6881
     * a(['a' => 1, 'b' => ''])->stripEmpty(); // Arrayy[['a' => 1]]
6882
     * </code>
6883
     *
6884
     * @return static
6885
     *                <p>(Immutable)</p>
6886
     *
6887
     * @phpstan-return static<TKey,T>
6888
     * @psalm-mutation-free
6889
     */
6890
    public function stripEmpty(): self
6891
    {
6892
        return $this->filter(
7 ✔
6893
            static function ($item) {
7 ✔
6894
                if ($item === null) {
7 ✔
6895
                    return false;
7 ✔
6896
                }
6897

6898
                return (bool) \trim((string) $item);
7 ✔
6899
            }
7 ✔
6900
        );
7 ✔
6901
    }
6902

6903
    /**
6904
     * Swap two values between positions by key.
6905
     *
6906
     * EXAMPLE: <code>
6907
     * a(['a' => 1, 'b' => ''])->swap('a', 'b'); // Arrayy[['a' => '', 'b' => 1]]
6908
     * </code>
6909
     *
6910
     * @param int|string $swapA <p>a key in the array</p>
6911
     * @param int|string $swapB <p>a key in the array</p>
6912
     *
6913
     * @return static
6914
     *                <p>(Immutable)</p>
6915
     *
6916
     * @phpstan-return static<TKey,T>
6917
     * @psalm-mutation-free
6918
     */
6919
    public function swap($swapA, $swapB): self
6920
    {
6921
        $array = $this->toArray();
7 ✔
6922

6923
        list($array[$swapA], $array[$swapB]) = [$array[$swapB], $array[$swapA]];
7 ✔
6924

6925
        return static::create(
7 ✔
6926
            $array,
7 ✔
6927
            $this->iteratorClass,
7 ✔
6928
            false
7 ✔
6929
        );
7 ✔
6930
    }
6931

6932
    /**
6933
     * Get the current array from the "Arrayy"-object.
6934
     * alias for "getArray()"
6935
     *
6936
     * @param bool $convertAllArrayyElements <p>
6937
     *                                       Convert all Child-"Arrayy" objects also to arrays.
6938
     *                                       </p>
6939
     * @param bool $preserveKeys             <p>
6940
     *                                       e.g.: A generator maybe return the same key more than once,
6941
     *                                       so maybe you will ignore the keys.
6942
     *                                       </p>
6943
     *
6944
     * @return array
6945
     *
6946
     * @phpstan-return ($preserveKeys is true ? array<TKey,T> : T[])
6947
     * @psalm-mutation-free
6948
     */
6949
    public function toArray(
6950
        bool $convertAllArrayyElements = false,
6951
        bool $preserveKeys = true
6952
    ): array {
6953
        if ($convertAllArrayyElements) {
6,720 ✔
6954
            // init
6955
            $array = [];
21 ✔
6956

6957
            foreach ($this->getGenerator() as $key => $value) {
21 ✔
6958
                if ($value instanceof self) {
21 ✔
6959
                    $value = $value->toArray(
14 ✔
6960
                        $convertAllArrayyElements,
14 ✔
6961
                        $preserveKeys
14 ✔
6962
                    );
14 ✔
6963
                }
6964

6965
                if ($preserveKeys) {
21 ✔
6966
                    $array[$key] = $value;
14 ✔
6967
                } else {
6968
                    $array[] = $value;
7 ✔
6969
                }
6970
            }
6971

6972
            /* @phpstan-ignore-next-line - depends on the $convertAllArrayyElements parameter :/ */
6973
            return $array;
21 ✔
6974
        }
6975

6976
        return \iterator_to_array($this->getGenerator(), $preserveKeys);
6,713 ✔
6977
    }
6978

6979
    /**
6980
     * Get the current array from the "Arrayy"-object as list.
6981
     *
6982
     * @param bool $convertAllArrayyElements <p>
6983
     *                                       Convert all Child-"Arrayy" objects also to arrays.
6984
     *                                       </p>
6985
     *
6986
     * @return array
6987
     *
6988
     * @phpstan-return list<T>
6989
     * @psalm-mutation-free
6990
     */
6991
    public function toList(bool $convertAllArrayyElements = false): array
6992
    {
6993
        /** @var list<T> - currently phpstan can't return different types depending on the phpdocs params */
6994
        return $this->toArray(
7 ✔
6995
            $convertAllArrayyElements,
7 ✔
6996
            false
7 ✔
6997
        );
7 ✔
6998
    }
6999

7000
    /**
7001
     * Convert the current array to JSON.
7002
     *
7003
     * EXAMPLE: <code>
7004
     * a(['bar', ['foo']])->toJson(); // '["bar",{"1":"foo"}]'
7005
     * </code>
7006
     *
7007
     * @param int $options [optional] <p>e.g. JSON_PRETTY_PRINT</p>
7008
     * @param int $depth   [optional] <p>Set the maximum depth. Must be greater than zero.</p>
7009
     *
7010
     * @return string
7011
     */
7012
    public function toJson(int $options = 0, int $depth = 512): string
7013
    {
7014
        if ($depth < 1) {
91 ✔
7015
            $depth = 1;
×
7016
        }
7017

7018
        $return = \json_encode($this->toArray(), $options, $depth);
91 ✔
7019
        if ($return === false) {
91 ✔
7020
            return '';
×
7021
        }
7022

7023
        return $return;
91 ✔
7024
    }
7025

7026
    /**
7027
     * @param string[]|null $items  [optional]
7028
     * @param string[]      $helper [optional]
7029
     *
7030
     * @return static|static[]
7031
     *
7032
     * @phpstan-return static<int, static<TKey,T>>
7033
     */
7034
    public function toPermutation(?array $items = null, array $helper = []): self
7035
    {
7036
        // init
7037
        $return = [];
7 ✔
7038

7039
        if ($items === null) {
7 ✔
7040
            $items = $this->toArray();
7 ✔
7041
        }
7042

7043
        if (empty($items)) {
7 ✔
7044
            $return[] = $helper;
7 ✔
7045
        } else {
7046
            for ($i = \count($items) - 1; $i >= 0; --$i) {
7 ✔
7047
                $new_items = $items;
7 ✔
7048
                $new_helper = $helper;
7 ✔
7049
                list($tmp_helper) = \array_splice($new_items, $i, 1);
7 ✔
7050
                /** @noinspection PhpSillyAssignmentInspection */
7051
                /** @var string[] $new_items */
7052
                $new_items = $new_items;
7 ✔
7053
                \array_unshift($new_helper, $tmp_helper);
7 ✔
7054
                $return = \array_merge(
7 ✔
7055
                    $return,
7 ✔
7056
                    $this->toPermutation($new_items, $new_helper)->toArray()
7 ✔
7057
                );
7 ✔
7058
            }
7059
        }
7060

7061
        /** @var static<int, static<TKey,T>> $return  - help for phpstan */
7062
        $return = static::create(
7 ✔
7063
            $return,
7 ✔
7064
            $this->iteratorClass,
7 ✔
7065
            false
7 ✔
7066
        );
7 ✔
7067

7068
        return $return;
7 ✔
7069
    }
7070

7071
    /**
7072
     * Implodes array to a string with specified separator.
7073
     *
7074
     * @param string $separator [optional] <p>The element's separator.</p>
7075
     *
7076
     * @return string
7077
     *                <p>The string representation of array, separated by ",".</p>
7078
     */
7079
    public function toString(string $separator = ','): string
7080
    {
7081
        return $this->implode($separator);
133 ✔
7082
    }
7083

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

7100
        $this->array = $this->reduce(
91 ✔
7101
            static function ($resultArray, $value, $key) {
91 ✔
7102
                if (!\in_array($value, $resultArray, true)) {
84 ✔
7103
                    $resultArray[] = $value;
84 ✔
7104
                }
7105

7106
                return $resultArray;
84 ✔
7107
            },
91 ✔
7108
            []
91 ✔
7109
        )->toArray();
91 ✔
7110
        $this->generator = null;
91 ✔
7111

7112
        return $this;
91 ✔
7113
    }
7114

7115
    /**
7116
     * Return a duplicate free copy of the current array. (with the old keys)
7117
     *
7118
     * EXAMPLE: <code>
7119
     * a([2 => 1, 3 => 2, 4 => 2])->uniqueNewIndex(); // Arrayy[2 => 1, 3 => 2]
7120
     * </code>
7121
     *
7122
     * @return $this
7123
     *               <p>(Mutable)</p>
7124
     *
7125
     * @phpstan-return static<TKey,T>
7126
     */
7127
    public function uniqueKeepIndex(): self
7128
    {
7129
        // INFO: \array_unique() can't handle e.g. "stdClass"-values in an array
7130

7131
        // init
7132
        $array = $this->toArray();
77 ✔
7133

7134
        /**
7135
         * @psalm-suppress MissingClosureReturnType
7136
         * @psalm-suppress MissingClosureParamType
7137
         */
7138
        $this->array = \array_reduce(
77 ✔
7139
            \array_keys($array),
77 ✔
7140
            static function ($resultArray, $key) use ($array) {
77 ✔
7141
                if (!\in_array($array[$key], $resultArray, true)) {
70 ✔
7142
                    $resultArray[$key] = $array[$key];
70 ✔
7143
                }
7144

7145
                return $resultArray;
70 ✔
7146
            },
77 ✔
7147
            []
77 ✔
7148
        );
77 ✔
7149
        $this->generator = null;
77 ✔
7150

7151
        return $this;
77 ✔
7152
    }
7153

7154
    /**
7155
     * alias: for "Arrayy->uniqueNewIndex()"
7156
     *
7157
     * @return static
7158
     *                <p>(Mutable) Return this Arrayy object, with the appended values.</p>
7159
     *
7160
     * @see          Arrayy::unique()
7161
     *
7162
     * @phpstan-return static<int,T>
7163
     */
7164
    public function unique(): self
7165
    {
7166
        return $this->uniqueNewIndex();
91 ✔
7167
    }
7168

7169
    /**
7170
     * Prepends one or more values to the beginning of array at once.
7171
     *
7172
     * @param mixed ...$args
7173
     *
7174
     * @return $this
7175
     *               <p>(Mutable) Return this Arrayy object, with prepended elements to the beginning of array.</p>
7176
     *
7177
     * @phpstan-param  array<TKey,T> ...$args
7178
     * @phpstan-return static<TKey,T>
7179
     */
7180
    public function unshift(...$args): self
7181
    {
7182
        $this->generatorToArray();
42 ✔
7183

7184
        if (
7185
            $this->checkPropertyTypes
42 ✔
7186
            &&
7187
            $this->properties !== []
42 ✔
7188
        ) {
7189
            foreach ($args as $key => $value) {
14 ✔
7190
                $this->checkType($key, $value);
14 ✔
7191
            }
7192
        }
7193

7194
        \array_unshift($this->array, ...$args); // @phpstan-ignore assign.propertyType
35 ✔
7195

7196
        return $this;
35 ✔
7197
    }
7198

7199
    /**
7200
     * Tests whether the given closure return something valid for all elements of this array.
7201
     *
7202
     * @param \Closure $closure the predicate
7203
     *
7204
     * @return bool
7205
     *              <p>TRUE, if the predicate yields TRUE for all elements, FALSE otherwise.</p>
7206
     *
7207
     * @phpstan-param \Closure(T,TKey):bool $closure
7208
     */
7209
    public function validate(\Closure $closure): bool
7210
    {
7211
        foreach ($this->getGenerator() as $key => $value) {
7 ✔
7212
            if (!$closure($value, $key)) {
7 ✔
7213
                return false;
7 ✔
7214
            }
7215
        }
7216

7217
        return true;
7 ✔
7218
    }
7219

7220
    /**
7221
     * Get all values from a array.
7222
     *
7223
     * EXAMPLE: <code>
7224
     * $arrayy = a([1 => 'foo', 2 => 'foo2', 3 => 'bar']);
7225
     * $arrayyTmp->values(); // Arrayy[0 => 'foo', 1 => 'foo2', 2 => 'bar']
7226
     * </code>
7227
     *
7228
     * @return static
7229
     *                <p>(Immutable)</p>
7230
     *
7231
     * @phpstan-return static<int,T>
7232
     * @psalm-mutation-free
7233
     */
7234
    public function values(): self
7235
    {
7236
        return static::create(
14 ✔
7237
            function () {
14 ✔
7238
                foreach ($this->getGenerator() as $value) {
14 ✔
7239
                    yield $value;
14 ✔
7240
                }
7241
            },
14 ✔
7242
            $this->iteratorClass,
14 ✔
7243
            false
14 ✔
7244
        );
14 ✔
7245
    }
7246

7247
    /**
7248
     * Apply the given function to every element in the array, discarding the results.
7249
     *
7250
     * EXAMPLE: <code>
7251
     * $callable = function (&$value, $key) {
7252
     *     $value = $key;
7253
     * };
7254
     * $arrayy = a([1, 2, 3]);
7255
     * $arrayy->walk($callable); // Arrayy[0, 1, 2]
7256
     * </code>
7257
     *
7258
     * @param callable $callable
7259
     * @param bool     $recursive
7260
     *                            [optional] <p>Whether array will be walked recursively or no</p>
7261
     * @param mixed    $userData
7262
     *                            [optional] <p>
7263
     *                            If the optional $userData parameter is supplied,
7264
     *                            it will be passed as the third parameter to the $callable.
7265
     *                            </p>
7266
     *
7267
     * @return $this
7268
     *               <p>(Mutable) Return this Arrayy object, with modified elements.</p>
7269
     *
7270
     * @template TExtra
7271
     *              <p>The extra input value type.</p>
7272
     *
7273
     * @phostan-param TExtra $userData
7274
     * @phpstan-param  callable(T,TKey,?TExtra):void $callable
7275
     * @phpstan-return static<TKey,T>
7276
     */
7277
    public function walk(
7278
        $callable,
7279
        bool $recursive = false,
7280
        $userData = self::ARRAYY_HELPER_WALK
7281
    ): self {
7282
        $this->generatorToArray();
84 ✔
7283

7284
        if ($this->array !== []) {
84 ✔
7285
            if ($recursive === true) {
70 ✔
7286
                if ($userData !== self::ARRAYY_HELPER_WALK) {
35 ✔
7287
                    \array_walk_recursive($this->array, $callable, $userData);
×
7288
                } else {
7289
                    \array_walk_recursive($this->array, $callable);
35 ✔
7290
                }
7291
            } else {
7292
                if ($userData !== self::ARRAYY_HELPER_WALK) {
35 ✔
7293
                    \array_walk($this->array, $callable, $userData);
×
7294
                } else {
7295
                    /* @phpstan-ignore-next-line | callback with no arguments is ok here */
7296
                    \array_walk($this->array, $callable);
35 ✔
7297
                }
7298
            }
7299
        }
7300

7301
        return $this;
84 ✔
7302
    }
7303

7304
    /**
7305
     * Returns a collection of matching items.
7306
     *
7307
     * @param string $keyOrPropertyOrMethod
7308
     *                                      <p>The property or method to evaluate.</p>
7309
     * @param mixed  $value
7310
     *                                      <p>The value to match.</p>
7311
     *
7312
     * @throws \InvalidArgumentException if property or method is not defined
7313
     *
7314
     * @return static
7315
     *
7316
     * @phpstan-return static<TKey,T>
7317
     */
7318
    public function where(string $keyOrPropertyOrMethod, $value): self
7319
    {
7320
        return $this->filter(
7 ✔
7321
            function ($item) use ($keyOrPropertyOrMethod, $value) {
7 ✔
7322
                $accessorValue = $this->extractValue(
×
7323
                    $item,
×
7324
                    $keyOrPropertyOrMethod
×
7325
                );
×
7326

7327
                return $accessorValue === $value;
×
7328
            }
7 ✔
7329
        );
7 ✔
7330
    }
7331

7332
    /**
7333
     * Convert an array into an object.
7334
     *
7335
     * @param array $array
7336
     *
7337
     * @return \stdClass
7338
     *
7339
     * @phpstan-param array<int|string,mixed> $array
7340
     */
7341
    final protected static function arrayToObject(array $array = []): \stdClass
7342
    {
7343
        // init
7344
        $object = new \stdClass();
28 ✔
7345

7346
        if (\count($array, \COUNT_NORMAL) <= 0) {
28 ✔
7347
            return $object;
7 ✔
7348
        }
7349

7350
        foreach ($array as $name => $value) {
21 ✔
7351
            if (\is_array($value)) {
21 ✔
7352
                $object->{$name} = static::arrayToObject($value);
7 ✔
7353
            } else {
7354
                $object->{$name} = $value;
21 ✔
7355
            }
7356
        }
7357

7358
        return $object;
21 ✔
7359
    }
7360

7361
    /**
7362
     * @param array|\Generator|null $input         <p>
7363
     *                                             An array containing keys to return.
7364
     *                                             </p>
7365
     * @param mixed|null            $search_values [optional] <p>
7366
     *                                             If specified, then only keys containing these values are returned.
7367
     *                                             </p>
7368
     * @param bool                  $strict        [optional] <p>
7369
     *                                             Determines if strict comparison (===) should be used during the
7370
     *                                             search.
7371
     *                                             </p>
7372
     *
7373
     * @return array
7374
     *               <p>An array of all the keys in input.</p>
7375
     *
7376
     * @template TInput
7377
     *
7378
     * @phpstan-param  array<array-key,TInput>|\Generator<array-key,TInput>|null $input
7379
     * @phpstan-param T|T[]|null $search_values
7380
     * @phpstan-return array<int, TKey>
7381
     *
7382
     * @psalm-mutation-free
7383
     */
7384
    protected function array_keys_recursive(
7385
        $input = null,
7386
        $search_values = null,
7387
        bool $strict = true
7388
    ): array {
7389
        // init
7390
        $keys = [];
77 ✔
7391
        $keysTmp = [];
77 ✔
7392

7393
        if ($input === null) {
77 ✔
7394
            $input = $this->getGenerator();
28 ✔
7395
        }
7396

7397
        if ($search_values === null) {
77 ✔
7398
            foreach ($input as $key => $value) {
77 ✔
7399
                $keys[] = $key;
77 ✔
7400

7401
                // check if recursive is needed
7402
                if (\is_array($value)) {
77 ✔
7403
                    $keysTmp[] = $this->array_keys_recursive($value);
28 ✔
7404
                }
7405
            }
7406
        } else {
7407
            $is_array_tmp = \is_array($search_values);
7 ✔
7408

7409
            foreach ($input as $key => $value) {
7 ✔
7410
                if (
7411
                    (
7412
                        $is_array_tmp === false
7 ✔
7413
                        &&
7 ✔
7414
                        $strict === true
7 ✔
7415
                        &&
7 ✔
7416
                        $search_values === $value
7 ✔
7417
                    )
7418
                    ||
7419
                    (
7420
                        $is_array_tmp === false
7 ✔
7421
                        &&
7 ✔
7422
                        $strict === false
7 ✔
7423
                        &&
7 ✔
7424
                        $search_values == $value
7 ✔
7425
                    )
7426
                    ||
7427
                    (
7428
                        $is_array_tmp === true
7 ✔
7429
                        &&
7 ✔
7430
                        \in_array($value, $search_values, $strict)
7 ✔
7431
                    )
7432
                ) {
7433
                    $keys[] = $key;
7 ✔
7434
                }
7435

7436
                // check if recursive is needed
7437
                if (\is_array($value)) {
7 ✔
7438
                    $keysTmp[] = $this->array_keys_recursive($value);
7 ✔
7439
                }
7440
            }
7441
        }
7442

7443
        return $keysTmp === [] ? $keys : \array_merge($keys, ...$keysTmp);
77 ✔
7444
    }
7445

7446
    /**
7447
     * @param string     $path
7448
     * @param callable   $callable
7449
     * @param array|null $currentOffset
7450
     *
7451
     * @return void
7452
     *
7453
     * @phpstan-param array<TKey,T>|null $currentOffset
7454
     * @psalm-mutation-free
7455
     */
7456
    protected function callAtPath($path, $callable, &$currentOffset = null)
7457
    {
7458
        $this->generatorToArray();
70 ✔
7459

7460
        if ($currentOffset === null) {
70 ✔
7461
            $currentOffset = &$this->array;
70 ✔
7462
        }
7463

7464
        $explodedPath = \explode($this->pathSeparator, $path);
70 ✔
7465
        /* @phpstan-ignore-next-line | change from PHP >= 8, but we still support old versions */
7466
        if ($explodedPath === false) {
70 ✔
7467
            return;
×
7468
        }
7469

7470
        $nextPath = \array_shift($explodedPath);
70 ✔
7471
        if (!isset($currentOffset[$nextPath])) {
70 ✔
7472
            return;
7 ✔
7473
        }
7474

7475
        if ($explodedPath !== []) {
63 ✔
7476
            $this->callAtPath(
7 ✔
7477
                \implode($this->pathSeparator, $explodedPath),
7 ✔
7478
                $callable,
7 ✔
7479
                $currentOffset[$nextPath]
7 ✔
7480
            );
7 ✔
7481
        } else {
7482
            $callable($currentOffset[$nextPath]);
63 ✔
7483
        }
7484
    }
7485

7486
    /**
7487
     * Extracts the value of the given property or method from the object.
7488
     *
7489
     * @param static<T> $object
7490
     *                                         <p>The object to extract the value from.</p>
7491
     * @param string    $keyOrPropertyOrMethod
7492
     *                                         <p>The property or method for which the
7493
     *                                         value should be extracted.</p>
7494
     *
7495
     * @throws \InvalidArgumentException if the method or property is not defined
7496
     *
7497
     * @return mixed
7498
     *               <p>The value extracted from the specified property or method.</p>
7499
     *
7500
     * @phpstan-param self<TKey,T> $object
7501
     */
7502
    final protected function extractValue(self $object, string $keyOrPropertyOrMethod)
7503
    {
7504
        if (isset($object[$keyOrPropertyOrMethod])) {
7 ✔
7505
            $return = $object->get($keyOrPropertyOrMethod);
7 ✔
7506

7507
            if ($return instanceof self) {
7 ✔
7508
                return $return->toArray();
×
7509
            }
7510

7511
            return $return;
7 ✔
7512
        }
7513

7514
        if (\property_exists($object, $keyOrPropertyOrMethod)) {
×
7515
            return $object->{$keyOrPropertyOrMethod};
×
7516
        }
7517

7518
        if (\method_exists($object, $keyOrPropertyOrMethod)) {
×
7519
            return $object->{$keyOrPropertyOrMethod}();
×
7520
        }
7521

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

7525
    /**
7526
     * create a fallback for array
7527
     *
7528
     * 1. use the current array, if it's a array
7529
     * 2. fallback to empty array, if there is nothing
7530
     * 3. call "getArray()" on object, if there is a "Arrayy"-object
7531
     * 4. call "createFromObject()" on object, if there is a "\Traversable"-object
7532
     * 5. call "__toArray()" on object, if the method exists
7533
     * 6. cast a string or object with "__toString()" into an array
7534
     * 7. throw a "InvalidArgumentException"-Exception
7535
     *
7536
     * @param mixed $data
7537
     *
7538
     * @throws \InvalidArgumentException
7539
     *
7540
     * @return array
7541
     *
7542
     * @phpstan-return array<mixed>|array<TKey,T>
7543
     */
7544
    protected function fallbackForArray(&$data): array
7545
    {
7546
        $data = $this->internalGetArray($data);
8,965 ✔
7547

7548
        if ($data === null) {
8,965 ✔
7549
            throw new \InvalidArgumentException('Passed value should be a array');
14 ✔
7550
        }
7551

7552
        return $data;
8,951 ✔
7553
    }
7554

7555
    /**
7556
     * @param bool $preserveKeys <p>
7557
     *                           e.g.: A generator maybe return the same key more than once,
7558
     *                           so maybe you will ignore the keys.
7559
     *                           </p>
7560
     *
7561
     * @return bool
7562
     *
7563
     * @noinspection ReturnTypeCanBeDeclaredInspection
7564
     * @psalm-mutation-free :/
7565
     */
7566
    protected function generatorToArray(bool $preserveKeys = true)
7567
    {
7568
        if ($this->generator) {
8,286 ✔
7569
            $this->array = $this->toArray(false, $preserveKeys);
21 ✔
7570
            $this->generator = null;
21 ✔
7571

7572
            return true;
21 ✔
7573
        }
7574

7575
        return false;
8,286 ✔
7576
    }
7577

7578
    /**
7579
     * Get correct PHP constant for direction.
7580
     *
7581
     * @param int|string $direction
7582
     *
7583
     * @return int
7584
     * @psalm-mutation-free
7585
     */
7586
    protected function getDirection($direction): int
7587
    {
7588
        if ((string) $direction === $direction) {
301 ✔
7589
            $direction = \strtolower($direction);
70 ✔
7590

7591
            if ($direction === 'desc') {
70 ✔
7592
                $direction = \SORT_DESC;
14 ✔
7593
            } else {
7594
                $direction = \SORT_ASC;
63 ✔
7595
            }
7596
        }
7597

7598
        if (
7599
            $direction !== \SORT_DESC
301 ✔
7600
            &&
7601
            $direction !== \SORT_ASC
301 ✔
7602
        ) {
7603
            $direction = \SORT_ASC;
×
7604
        }
7605

7606
        return $direction;
301 ✔
7607
    }
7608

7609
    /**
7610
     * @return TypeCheckInterface[]
7611
     *
7612
     * @noinspection ReturnTypeCanBeDeclaredInspection
7613
     */
7614
    protected function getPropertiesFromPhpDoc()
7615
    {
7616
        static $PROPERTY_CACHE = [];
369 ✔
7617
        $cacheKey = 'Class::' . static::class;
369 ✔
7618

7619
        if (isset($PROPERTY_CACHE[$cacheKey])) {
369 ✔
7620
            return $PROPERTY_CACHE[$cacheKey];
362 ✔
7621
        }
7622

7623
        $properties = $this->getPropertiesFromNativeDefinitions();
61 ✔
7624

7625
        $reflector = new \ReflectionClass($this);
61 ✔
7626
        $factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
61 ✔
7627
        $docComment = $reflector->getDocComment();
61 ✔
7628
        if ($docComment) {
61 ✔
7629
            $docblock = $factory->create($docComment);
54 ✔
7630
            /** @var \phpDocumentor\Reflection\DocBlock\Tags\Property $tag */
7631
            foreach ($docblock->getTagsByName('property') as $tag) {
54 ✔
7632
                $typeName = $tag->getVariableName();
35 ✔
7633
                /** @var string|null $typeName */
7634
                if (
7635
                    $typeName !== null
35 ✔
7636
                    &&
7637
                    isset($properties[$typeName]) === false
35 ✔
7638
                ) {
7639
                    $typeCheckPhpDoc = TypeCheckPhpDoc::fromPhpDocumentorProperty($tag, $typeName);
35 ✔
7640
                    if ($typeCheckPhpDoc !== null) {
35 ✔
7641
                        $properties[$typeName] = $typeCheckPhpDoc;
35 ✔
7642
                    }
7643
                }
7644
            }
7645
        }
7646

7647
        /** @noinspection PhpAssignmentInConditionInspection */
7648
        while ($reflector = $reflector->getParentClass()) {
61 ✔
7649
            $docComment = $reflector->getDocComment();
61 ✔
7650
            if ($docComment) {
61 ✔
7651
                $docblock = $factory->create($docComment);
61 ✔
7652
                /** @var \phpDocumentor\Reflection\DocBlock\Tags\Property $tag */
7653
                foreach ($docblock->getTagsByName('property') as $tag) {
61 ✔
7654
                    $typeName = $tag->getVariableName();
7 ✔
7655
                    /** @var string|null $typeName */
7656
                    if ($typeName !== null) {
7 ✔
7657
                        if (isset($properties[$typeName])) {
7 ✔
7658
                            continue;
7 ✔
7659
                        }
7660

7661
                        $typeCheckPhpDoc = TypeCheckPhpDoc::fromPhpDocumentorProperty($tag, $typeName);
7 ✔
7662
                        if ($typeCheckPhpDoc !== null) {
7 ✔
7663
                            $properties[$typeName] = $typeCheckPhpDoc;
7 ✔
7664
                        }
7665
                    }
7666
                }
7667
            }
7668
        }
7669

7670
        return $PROPERTY_CACHE[$cacheKey] = $properties;
61 ✔
7671
    }
7672

7673
    /**
7674
     * @return TypeCheckInterface[]
7675
     */
7676
    protected function getPropertiesFromNativeDefinitions(): array
7677
    {
7678
        $properties = [];
61 ✔
7679
        $reflector = new \ReflectionClass($this);
61 ✔
7680
        $reservedProperties = self::getReservedPropertyNames();
61 ✔
7681

7682
        do {
7683
            if ($reflector->getName() === self::class) {
61 ✔
7684
                break;
61 ✔
7685
            }
7686

7687
            foreach ($reflector->getProperties() as $property) {
61 ✔
7688
                if (
7689
                    $property->getDeclaringClass()->getName() !== $reflector->getName()
61 ✔
7690
                    ||
7691
                    $property->isStatic()
47 ✔
7692
                    ||
7693
                    isset($reservedProperties[$property->getName()])
47 ✔
7694
                    ||
7695
                    isset($properties[$property->getName()])
61 ✔
7696
                ) {
7697
                    continue;
61 ✔
7698
                }
7699

7700
                $properties[$property->getName()] = TypeCheckPhpDoc::fromReflectionProperty($property);
19 ✔
7701
            }
7702
        } while ($reflector = $reflector->getParentClass());
61 ✔
7703

7704
        return $properties;
61 ✔
7705
    }
7706

7707
    /**
7708
     * @return array<string, true>
7709
     */
7710
    private static function getReservedPropertyNames(): array
7711
    {
7712
        static $reservedProperties = null;
61 ✔
7713

7714
        if ($reservedProperties !== null) {
61 ✔
7715
            return $reservedProperties;
54 ✔
7716
        }
7717

7718
        $reservedProperties = [];
7 ✔
7719
        $reflector = new \ReflectionClass(self::class);
7 ✔
7720
        foreach ($reflector->getProperties() as $property) {
7 ✔
7721
            if ($property->getDeclaringClass()->getName() !== self::class) {
7 ✔
NEW
7722
                continue;
×
7723
            }
7724

7725
            $reservedProperties[$property->getName()] = true;
7 ✔
7726
        }
7727

7728
        return $reservedProperties;
7 ✔
7729
    }
7730

7731
    /**
7732
     * @param string $glue
7733
     * @param mixed  $pieces
7734
     * @param bool   $useKeys
7735
     *
7736
     * @return string
7737
     *
7738
     * @phpstan-param scalar|object|self<TKey|T>|array<TKey,T>|array<T> $pieces
7739
     * @psalm-mutation-free
7740
     */
7741
    protected function implode_recursive(
7742
        $glue = '',
7743
        $pieces = [],
7744
        bool $useKeys = false
7745
    ): string {
7746
        if ($pieces instanceof self) {
259 ✔
7747
            $pieces = $pieces->toArray();
7 ✔
7748
        }
7749

7750
        if (\is_array($pieces)) {
259 ✔
7751
            /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
7752
            /** @phpstan-var array<TKey,T> $pieces */
7753
            $pieces = $pieces;
259 ✔
7754

7755
            $pieces_count = \count($pieces, \COUNT_NORMAL);
259 ✔
7756
            $pieces_count_not_zero = $pieces_count > 0;
259 ✔
7757

7758
            return \implode(
259 ✔
7759
                $glue,
259 ✔
7760
                \array_map(
259 ✔
7761
                    [$this, 'implode_recursive'],
259 ✔
7762
                    \array_fill(0, ($pieces_count_not_zero ? $pieces_count : 1), $glue),
259 ✔
7763
                    ($useKeys === true && $pieces_count_not_zero ? $this->array_keys_recursive($pieces) : $pieces)
259 ✔
7764
                )
259 ✔
7765
            );
259 ✔
7766
        }
7767

7768
        if (
7769
            \is_scalar($pieces) === true
259 ✔
7770
            ||
7771
            (\is_object($pieces) && \method_exists($pieces, '__toString'))
259 ✔
7772
        ) {
7773
            return (string) $pieces;
231 ✔
7774
        }
7775

7776
        return '';
56 ✔
7777
    }
7778

7779
    /**
7780
     * @param mixed                 $needle   <p>
7781
     *                                        The searched value.
7782
     *                                        </p>
7783
     *                                        <p>
7784
     *                                        If needle is a string, the comparison is done
7785
     *                                        in a case-sensitive manner.
7786
     *                                        </p>
7787
     * @param array|\Generator|null $haystack <p>
7788
     *                                        The array.
7789
     *                                        </p>
7790
     * @param bool                  $strict   [optional] <p>
7791
     *                                        If the third parameter strict is set to true
7792
     *                                        then the in_array function will also check the
7793
     *                                        types of the
7794
     *                                        needle in the haystack.
7795
     *                                        </p>
7796
     *
7797
     * @return bool
7798
     *              <p>true if needle is found in the array, false otherwise</p>
7799
     *
7800
     * @phpstan-param (array&T)|array<TKey,T>|\Generator<TKey,T>|null $haystack
7801
     *
7802
     * @psalm-mutation-free
7803
     */
7804
    protected function in_array_recursive($needle, $haystack = null, $strict = true): bool
7805
    {
7806
        if ($haystack === null) {
128 ✔
7807
            $haystack = $this->getGenerator();
×
7808
        }
7809

7810
        foreach ($haystack as $item) {
128 ✔
7811
            if (\is_array($item)) {
100 ✔
7812
                $returnTmp = $this->in_array_recursive($needle, $item, $strict);
23 ✔
7813
            } else {
7814
                /** @noinspection NestedPositiveIfStatementsInspection */
7815
                if ($strict === true) {
100 ✔
7816
                    $returnTmp = $item === $needle;
100 ✔
7817
                } else {
7818
                    $returnTmp = $item == $needle;
×
7819
                }
7820
            }
7821

7822
            if ($returnTmp === true) {
100 ✔
7823
                return true;
72 ✔
7824
            }
7825
        }
7826

7827
        return false;
56 ✔
7828
    }
7829

7830
    /**
7831
     * @param mixed $data
7832
     *
7833
     * @return array<mixed>|null
7834
     */
7835
    protected function internalGetArray(&$data)
7836
    {
7837
        if (\is_array($data)) {
8,965 ✔
7838
            return $data;
8,923 ✔
7839
        }
7840

7841
        if (!$data) {
791 ✔
7842
            return [];
49 ✔
7843
        }
7844

7845
        if (\is_object($data) === true) {
784 ✔
7846
            if ($data instanceof \ArrayObject) {
735 ✔
7847
                return $data->getArrayCopy();
35 ✔
7848
            }
7849

7850
            if ($data instanceof \Generator) {
707 ✔
7851
                return static::createFromGeneratorImmutable($data)->toArray();
×
7852
            }
7853

7854
            if ($data instanceof \Traversable) {
707 ✔
7855
                return static::createFromObject($data)->toArray();
×
7856
            }
7857

7858
            if ($data instanceof \JsonSerializable) {
707 ✔
7859
                return (array) $data->jsonSerialize();
×
7860
            }
7861

7862
            if (\method_exists($data, '__toArray')) {
707 ✔
7863
                return (array) $data->__toArray();
×
7864
            }
7865

7866
            if (\method_exists($data, '__toString')) {
707 ✔
7867
                return [(string) $data];
×
7868
            }
7869
        }
7870

7871
        if (\is_callable($data)) {
756 ✔
7872
            /**
7873
             * @psalm-suppress InvalidPropertyAssignmentValue - why?
7874
             */
7875
            $this->generator = new ArrayyRewindableGenerator($data);
693 ✔
7876

7877
            return [];
693 ✔
7878
        }
7879

7880
        if (\is_scalar($data)) {
77 ✔
7881
            return [$data];
63 ✔
7882
        }
7883

7884
        return null;
14 ✔
7885
    }
7886

7887
    /**
7888
     * Internal mechanics of remove method.
7889
     *
7890
     * @param float|int|string $key
7891
     *
7892
     * @return bool
7893
     */
7894
    protected function internalRemove($key): bool
7895
    {
7896
        $this->generatorToArray();
154 ✔
7897

7898
        if (
7899
            $this->pathSeparator
154 ✔
7900
            &&
7901
            (string) $key === $key
154 ✔
7902
            &&
7903
            \strpos($key, $this->pathSeparator) !== false
154 ✔
7904
        ) {
7905
            $path = \explode($this->pathSeparator, (string) $key);
×
7906

7907
            if ($path !== false) {
×
7908
                // crawl though the keys
7909
                while (\count($path, \COUNT_NORMAL) > 1) {
×
7910
                    $key = \array_shift($path);
×
7911

7912
                    if (!$this->has($key)) {
×
7913
                        return false;
×
7914
                    }
7915

7916
                    $this->array = &$this->array[$key];
×
7917
                }
7918

7919
                $key = \array_shift($path);
×
7920
            }
7921
        }
7922

7923
        unset($this->array[$key]);
154 ✔
7924

7925
        return true;
154 ✔
7926
    }
7927

7928
    /**
7929
     * Internal mechanic of set method.
7930
     *
7931
     * @param int|string|null $key
7932
     * @param mixed           $value
7933
     * @param bool            $checkProperties
7934
     *
7935
     * @return bool
7936
     *
7937
     * @phpstan-param TKey|null $key
7938
     * @phpstan-param T $value
7939
     */
7940
    protected function internalSet(
7941
        $key,
7942
        &$value,
7943
        bool $checkProperties = true
7944
    ): bool {
7945
        if (
7946
            $checkProperties === true
7,880 ✔
7947
            &&
7948
            $this->properties !== []
7,880 ✔
7949
        ) {
7950
            $this->checkType($key, $value);
1,078 ✔
7951
        }
7952

7953
        if ($key === null) {
7,852 ✔
7954
            return false;
×
7955
        }
7956

7957
        $this->generatorToArray();
7,852 ✔
7958

7959
        $array = &$this->array;
7,852 ✔
7960

7961
        /**
7962
         * https://github.com/vimeo/psalm/issues/2536
7963
         *
7964
         * @psalm-suppress PossiblyInvalidArgument
7965
         * @psalm-suppress InvalidScalarArgument
7966
         */
7967
        if (
7968
            $this->pathSeparator
7,852 ✔
7969
            &&
7970
            (string) $key === $key
7,852 ✔
7971
            &&
7972
            \strpos($key, $this->pathSeparator) !== false
7,852 ✔
7973
        ) {
7974
            $path = \explode($this->pathSeparator, (string) $key);
63 ✔
7975

7976
            if ($path !== false) {
63 ✔
7977
                // crawl through the keys
7978
                while (\count($path, \COUNT_NORMAL) > 1) {
63 ✔
7979
                    $key = \array_shift($path);
63 ✔
7980

7981
                    $array = &$array[$key];
63 ✔
7982
                }
7983

7984
                $key = \array_shift($path);
63 ✔
7985
            }
7986
        }
7987

7988
        if ($array === null) {
7,852 ✔
7989
            $array = [];
28 ✔
7990
        } elseif (!\is_array($array)) {
7,831 ✔
7991
            throw new \RuntimeException('Can not set value at this path "' . $key . '" because (' . \gettype($array) . ')"' . \print_r($array, true) . '" is not an array.');
7 ✔
7992
        }
7993

7994
        $array[$key] = $value;
7,852 ✔
7995

7996
        return true;
7,852 ✔
7997
    }
7998

7999
    /**
8000
     * Convert a object into an array.
8001
     *
8002
     * @param mixed|object $object
8003
     *
8004
     * @return array|mixed
8005
     *
8006
     * @psalm-mutation-free
8007
     */
8008
    protected static function objectToArray($object)
8009
    {
8010
        if (!\is_object($object)) {
35 ✔
8011
            return $object;
28 ✔
8012
        }
8013

8014
        $object = \get_object_vars($object);
35 ✔
8015

8016
        /**
8017
         * @psalm-suppress PossiblyInvalidArgument - the parameter is always some kind of array - false-positive from psalm?
8018
         */
8019
        return \array_map([static::class, 'objectToArray'], $object);
35 ✔
8020
    }
8021

8022
    /**
8023
     * @param array $data
8024
     * @param bool  $checkPropertiesInConstructor
8025
     *
8026
     * @return void
8027
     *
8028
     * @phpstan-param array<mixed,T> $data
8029
     */
8030
    protected function setInitialValuesAndProperties(array &$data, bool $checkPropertiesInConstructor)
8031
    {
8032
        $checkPropertiesInConstructor = $this->checkForMissingPropertiesInConstructor === true
8,951 ✔
8033
                                        &&
8,951 ✔
8034
                                        $checkPropertiesInConstructor === true;
8,951 ✔
8035

8036
        if ($this->properties === []) {
8,951 ✔
8037
            if (
8038
                $this->checkPropertyTypes === true
8,279 ✔
8039
                ||
8040
                $checkPropertiesInConstructor === true
8,279 ✔
8041
            ) {
8042
                $this->properties = $this->getPropertiesFromPhpDoc();
355 ✔
8043
            }
8044

8045
            /** @var TypeCheckInterface[] $properties */
8046
            $properties = $this->properties;
8,279 ✔
8047

8048
            if (
8049
                $this->checkPropertiesMismatchInConstructor === true
8,279 ✔
8050
                &&
8051
                \count($data) !== 0
8,279 ✔
8052
                &&
8053
                \count(\array_diff_key($properties, $data)) > 0
8,279 ✔
8054
            ) {
8055
                throw new \TypeError('Property mismatch - input: ' . \print_r(\array_keys($data), true) . ' | expected: ' . \print_r(\array_keys($properties), true));
14 ✔
8056
            }
8057
        }
8058

8059
        foreach ($data as $key => &$valueInner) {
8,937 ✔
8060
            $this->internalSet(
7,761 ✔
8061
                $key,
7,761 ✔
8062
                $valueInner,
7,761 ✔
8063
                $checkPropertiesInConstructor
7,761 ✔
8064
            );
7,761 ✔
8065
        }
8066
    }
8067

8068
    /**
8069
     * sorting keys
8070
     *
8071
     * @param array      $elements
8072
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
8073
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
8074
     *                              <strong>SORT_NATURAL</strong></p>
8075
     *
8076
     * @return $this
8077
     *               <p>(Mutable) Return this Arrayy object.</p>
8078
     *
8079
     * @phpstan-param  array<mixed|TKey,T> $elements
8080
     * @phpstan-return static<TKey,T>
8081
     */
8082
    protected function sorterKeys(
8083
        array &$elements,
8084
        $direction = \SORT_ASC,
8085
        int $strategy = \SORT_REGULAR
8086
    ): self {
8087
        $direction = $this->getDirection($direction);
126 ✔
8088

8089
        switch ($direction) {
8090
            case 'desc':
126 ✔
8091
            case \SORT_DESC:
8092
                \krsort($elements, $strategy);
42 ✔
8093

8094
                break;
42 ✔
8095
            case 'asc':
91 ✔
8096
            case \SORT_ASC:
91 ✔
8097
            default:
8098
                \ksort($elements, $strategy);
91 ✔
8099
        }
8100

8101
        return $this;
126 ✔
8102
    }
8103

8104
    /**
8105
     * @param array      $elements  <p>Warning: used as reference</p>
8106
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
8107
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
8108
     *                              <strong>SORT_NATURAL</strong></p>
8109
     * @param bool       $keepKeys
8110
     *
8111
     * @return $this
8112
     *               <p>(Mutable) Return this Arrayy object.</p>
8113
     *
8114
     * @phpstan-param array<mixed|TKey,T> $elements
8115
     * @phpstan-return static<int|TKey,T>
8116
     */
8117
    protected function sorting(
8118
        array &$elements,
8119
        $direction = \SORT_ASC,
8120
        int $strategy = \SORT_REGULAR,
8121
        bool $keepKeys = false
8122
    ): self {
8123
        $direction = $this->getDirection($direction);
168 ✔
8124

8125
        if (!$strategy) {
168 ✔
8126
            $strategy = \SORT_REGULAR;
168 ✔
8127
        }
8128

8129
        switch ($direction) {
8130
            case 'desc':
168 ✔
8131
            case \SORT_DESC:
8132
                if ($keepKeys) {
91 ✔
8133
                    \arsort($elements, $strategy);
63 ✔
8134
                } else {
8135
                    \rsort($elements, $strategy);
28 ✔
8136
                }
8137

8138
                break;
91 ✔
8139
            case 'asc':
77 ✔
8140
            case \SORT_ASC:
77 ✔
8141
            default:
8142
                if ($keepKeys) {
77 ✔
8143
                    \asort($elements, $strategy);
28 ✔
8144
                } else {
8145
                    \sort($elements, $strategy);
49 ✔
8146
                }
8147
        }
8148

8149
        return $this;
168 ✔
8150
    }
8151

8152
    /**
8153
     * @param array $array
8154
     *
8155
     * @return array
8156
     *
8157
     * @psalm-mutation-free
8158
     */
8159
    private function getArrayRecursiveHelperArrayy(array $array)
8160
    {
8161
        if ($array === []) {
175 ✔
8162
            return [];
×
8163
        }
8164

8165
        \array_walk_recursive(
175 ✔
8166
            $array,
175 ✔
8167
            /**
8168
             * @param array|self $item
8169
             *
8170
             * @return void
8171
             */
8172
            static function (&$item) {
175 ✔
8173
                if ($item instanceof self) {
175 ✔
8174
                    $item = $item->getArray();
7 ✔
8175
                }
8176
            }
175 ✔
8177
        );
175 ✔
8178

8179
        return $array;
175 ✔
8180
    }
8181

8182
    /**
8183
     * @param int|string|null $key
8184
     * @param mixed           $value
8185
     *
8186
     * @return void
8187
     */
8188
    private function checkType($key, $value)
8189
    {
8190
        if (
8191
            $key !== null
1,078 ✔
8192
            &&
8193
            isset($this->properties[$key]) === false
1,078 ✔
8194
            &&
8195
            $this->checkPropertiesMismatch === true
1,078 ✔
8196
        ) {
8197
            throw new \TypeError('The key "' . $key . '" does not exists as "@property" phpdoc. (' . \get_class($this) . ').');
14 ✔
8198
        }
8199

8200
        if (isset($this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES])) {
1,078 ✔
8201
            $this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES]->checkType($value);
812 ✔
8202
        } elseif ($key !== null && isset($this->properties[$key])) {
343 ✔
8203
            $this->properties[$key]->checkType($value);
343 ✔
8204
        }
8205
    }
8206
}
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