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

voku / Arrayy / 24635375961

19 Apr 2026 05:52PM UTC coverage: 89.336%. Remained the same
24635375961

Pull #157

github

web-flow
Merge bc0e7ed53 into 90bd15c24
Pull Request #157: Update dependency phpunit/phpunit to v12 [SECURITY]

2488 of 2785 relevant lines covered (89.34%)

100.7 hits per line

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

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

3
declare(strict_types=1);
4

5
namespace Arrayy;
6

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

169
        return $return;
×
170
    }
171

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

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

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

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

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

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

248
        return $return;
438 ✔
249
    }
250

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

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

279
            return $this;
12 ✔
280
        }
281

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

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

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

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

325
        return $this;
60 ✔
326
    }
327

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

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

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

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

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

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

395
        return $this;
12 ✔
396
    }
397

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

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

422
        return $that;
12 ✔
423
    }
424

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

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

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

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

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

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

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

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

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

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

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

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

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

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

561
        return $return;
×
562
    }
563

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

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

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

597
        return $this;
12 ✔
598
    }
599

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

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

623
        return $that;
12 ✔
624
    }
625

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

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

641
        return $this;
24 ✔
642
    }
643

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

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

662
        return $that;
12 ✔
663
    }
664

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

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

680
        return $this;
30 ✔
681
    }
682

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

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

701
        return $that;
12 ✔
702
    }
703

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

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

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

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

759
        return $offsetExists;
408 ✔
760
    }
761

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

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

782
        return $value;
435 ✔
783
    }
784

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

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

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

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

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

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

833
            return;
42 ✔
834
        }
835

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

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

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

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

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

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

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

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

911
            return;
3,732 ✔
912
        }
913

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

923
                return;
×
924
            }
925
        }
926

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

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

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

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

954
        return $this;
24 ✔
955
    }
956

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

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

980
        return $that;
12 ✔
981
    }
982

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

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

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

1041
            return $this;
×
1042
        }
1043

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

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

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

1088
        return $this;
3 ✔
1089
    }
1090

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

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

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

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

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

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

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

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

1171
        return $this;
12 ✔
1172
    }
1173

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

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

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

1191
        return $that;
30 ✔
1192
    }
1193

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

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

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

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

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

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

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

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

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

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

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

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

1313
        return $this;
33 ✔
1314
    }
1315

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

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

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

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

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

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

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

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

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

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

1430
            return $this;
9 ✔
1431
        }
1432

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

1436
        return $this;
21 ✔
1437
    }
1438

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

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

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

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

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

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

1513
        return false;
21 ✔
1514
    }
1515

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

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

1550
            return false;
24 ✔
1551
        }
1552

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

1560
        return false;
12 ✔
1561
    }
1562

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

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

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

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

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

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

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

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

1724
        return $return;
21 ✔
1725
    }
1726

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

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

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

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

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

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

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

1811
        return $this;
79 ✔
1812
    }
1813

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

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

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

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

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

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

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

1911
        return $arrayy;
12 ✔
1912
    }
1913

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

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

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

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

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

1977
        return $return;
30 ✔
1978
    }
1979

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

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

2018
        return $return;
6 ✔
2019
    }
2020

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

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

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

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

2069
        return $this;
15 ✔
2070
    }
2071

2072
    /**
2073
     * Custom sort by index via "uksort".
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>(Immutable) Return this Arrayy object.</p>
2083
     *
2084
     * @phpstan-param  callable(TKey,TKey):int $callable
2085
     * @phpstan-return static<TKey,T>
2086
     * @psalm-mutation-free
2087
     */
2088
    public function customSortKeysImmutable(callable $callable): self
2089
    {
2090
        $that = clone $this;
3 ✔
2091

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

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

2099
        return $that;
3 ✔
2100
    }
2101

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

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

2132
        return $this;
33 ✔
2133
    }
2134

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

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

2160
        return $that;
15 ✔
2161
    }
2162

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2487
                break;
3 ✔
2488
            }
2489
        }
2490

2491
        return $isExists;
12 ✔
2492
    }
2493

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2748
        return false;
9 ✔
2749
    }
2750

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

2778
        return false;
12 ✔
2779
    }
2780

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

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

2828
        return $this->get($key_first);
58 ✔
2829
    }
2830

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

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

2848
        return $return;
88 ✔
2849
    }
2850

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

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

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

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

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

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

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

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

2941
        return $this;
102 ✔
2942
    }
2943

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

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

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

3013
            return clone $this;
3 ✔
3014
        }
3015

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

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

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

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

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

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

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

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

3084
                        continue;
90 ✔
3085
                    }
3086

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

3094
                        continue;
3 ✔
3095
                    }
3096

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

3110
                                continue;
×
3111
                            }
3112

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

3124
                                continue;
×
3125
                            }
3126

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

3134
                                continue;
3 ✔
3135
                            }
3136
                        }
3137

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

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

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

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

3161
            return $usedArrayTmp;
84 ✔
3162
        }
3163

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

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

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

3189
        return $return;
45 ✔
3190
    }
3191

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

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

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

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

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

3245
        return $return;
12 ✔
3246
    }
3247

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

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

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

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

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

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

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

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

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

3378
            return;
15 ✔
3379
        }
3380

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

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

3401
            return;
234 ✔
3402
        }
3403

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3644
            return true;
3 ✔
3645
        }
3646

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3913
        return true;
9 ✔
3914
    }
3915

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

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

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

3941
        return true;
6 ✔
3942
    }
3943

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

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

3979
        return false;
54 ✔
3980
    }
3981

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

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

4001
        return true;
6 ✔
4002
    }
4003

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

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

4036
            ++$i;
24 ✔
4037
        }
4038

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

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

4052
        return $return;
6 ✔
4053
    }
4054

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

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

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

4089
        return false;
429 ✔
4090
    }
4091

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

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

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

4141
        // non recursive
4142

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

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

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

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

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

4211
        return $this;
12 ✔
4212
    }
4213

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

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

4238
        return $that;
12 ✔
4239
    }
4240

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

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

4264
        return $value_last;
45 ✔
4265
    }
4266

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

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

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

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

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

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

4326
        return $arrayy;
36 ✔
4327
    }
4328

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

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

4352
        return $this;
36 ✔
4353
    }
4354

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

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

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

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

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

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

4457
        return true;
21 ✔
4458
    }
4459

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

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

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

4490
        return false;
12 ✔
4491
    }
4492

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

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

4521
        return $max;
30 ✔
4522
    }
4523

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

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

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

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

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

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

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

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

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

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

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

4728
        return $min;
30 ✔
4729
    }
4730

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5056
        return $this;
27 ✔
5057
    }
5058

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

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

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

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

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

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

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

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

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

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

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

5199
            return $array;
3 ✔
5200
        }
5201

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

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

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

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

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

5246
        return $this;
24 ✔
5247
    }
5248

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5396
            return $this;
21 ✔
5397
        }
5398

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

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

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

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

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

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

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

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

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

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

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

5519
        return $return;
54 ✔
5520
    }
5521

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

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

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

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

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

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

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

5573
        return $this;
27 ✔
5574
    }
5575

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

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

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

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

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

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

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

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

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

5686
        \array_shift($tmpArray);
21 ✔
5687

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

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

5712
        \array_pop($tmpArray);
21 ✔
5713

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6043
        return $this;
27 ✔
6044
    }
6045

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

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

6064
        return $this;
15 ✔
6065
    }
6066

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

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

6087
        return $this;
12 ✔
6088
    }
6089

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

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

6114
        return $that;
12 ✔
6115
    }
6116

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

6142
        return false;
33 ✔
6143
    }
6144

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

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

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

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

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

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

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

6215
        return $this;
81 ✔
6216
    }
6217

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6592
        return $this;
54 ✔
6593
    }
6594

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

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

6622
        return $that;
24 ✔
6623
    }
6624

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6798
                        continue;
3 ✔
6799
                    }
6800

6801
                    yield $carry;
3 ✔
6802

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

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

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

6821
                        continue;
3 ✔
6822
                    }
6823

6824
                    yield $carry;
3 ✔
6825

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6989
        return $return;
39 ✔
6990
    }
6991

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

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

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

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

7034
        return $return;
3 ✔
7035
    }
7036

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

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

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

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

7078
        return $this;
39 ✔
7079
    }
7080

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

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

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

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

7117
        return $this;
33 ✔
7118
    }
7119

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

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

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

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

7162
        return $this;
15 ✔
7163
    }
7164

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

7183
        return true;
3 ✔
7184
    }
7185

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

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

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

7267
        return $this;
36 ✔
7268
    }
7269

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

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

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

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

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

7324
        return $object;
9 ✔
7325
    }
7326

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

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

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

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

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

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

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

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

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

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

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

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

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

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

7477
            return $return;
3 ✔
7478
        }
7479

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

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

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

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

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

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

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

7538
            return true;
9 ✔
7539
        }
7540

7541
        return false;
3,480 ✔
7542
    }
7543

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

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

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

7572
        return $direction;
129 ✔
7573
    }
7574

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

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

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

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

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

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

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

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

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

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

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

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

7681
        return '';
24 ✔
7682
    }
7683

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

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

7727
            if ($returnTmp === true) {
43 ✔
7728
                return true;
31 ✔
7729
            }
7730
        }
7731

7732
        return false;
24 ✔
7733
    }
7734

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

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

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

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

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

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

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

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

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

7782
            return [];
294 ✔
7783
        }
7784

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

7789
        return null;
6 ✔
7790
    }
7791

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

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

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

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

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

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

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

7830
        return true;
66 ✔
7831
    }
7832

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

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

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

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

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

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

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

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

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

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

7901
        return true;
3,294 ✔
7902
    }
7903

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

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

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

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

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

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

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

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

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

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

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

8006
        return $this;
54 ✔
8007
    }
8008

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

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

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

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

8054
        return $this;
72 ✔
8055
    }
8056

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

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

8084
        return $array;
75 ✔
8085
    }
8086

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

8105
        if (isset($this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES])) {
390 ✔
8106
            $this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES]->checkType($value);
345 ✔
8107
        } elseif ($key !== null && isset($this->properties[$key])) {
78 ✔
8108
            $this->properties[$key]->checkType($value);
78 ✔
8109
        }
8110
    }
8111
}
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