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

voku / Arrayy / 30222555271

26 Jul 2026 10:09PM UTC coverage: 92.747% (+0.4%) from 92.38%
30222555271

Pull #180

github

web-flow
Merge 84b38085e into 57c7fca16
Pull Request #180: Add PHPStan dot-notation inference & typing fixes; harden dot-path traversal and JSON mapping

139 of 177 new or added lines in 7 files covered. (78.53%)

2826 of 3047 relevant lines covered (92.75%)

106.24 hits per line

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

94.06
/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
 * @template TData of array<TKey, T>
36
 * @extends \ArrayObject<TKey,T>
37
 * @implements \IteratorAggregate<TKey,T>
38
 * @implements \ArrayAccess<TKey,T>
39
 */
40
class Arrayy extends \ArrayObject implements \IteratorAggregate, \ArrayAccess, \Serializable, \JsonSerializable, \Countable
41
{
42
    const ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES = '!!!!Arrayy_Helper_Types_For_All_Properties!!!!';
43

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

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

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

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

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

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

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

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

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

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

97
    /**
98
     * @var array<string, true>
99
     */
100
    protected $optionalProperties = [];
101

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

130
        // used only for serialize + unserialize, all other methods are overwritten
131
        /**
132
         * @psalm-suppress InvalidArgument - why?
133
         */
134
        parent::__construct([], 0, $iteratorClass);
3,948 ✔
135

136
        $this->setInitialValuesAndProperties($data, $checkPropertiesInConstructor);
3,948 ✔
137

138
        $this->setIteratorClass($iteratorClass);
3,867 ✔
139
    }
140

141
    /**
142
     * @return void
143
     */
144
    public function __clone()
145
    {
146
        if (!\is_array($this->properties)) {
159 ✔
147
            $this->properties = clone $this->properties;
3 ✔
148
        }
149

150
        if ($this->generator !== null) {
159 ✔
151
            $this->generator = clone $this->generator;
3 ✔
152
        }
153
    }
154

155
    /**
156
     * Call object as function.
157
     *
158
     * @param mixed $key
159
     *
160
     * @return mixed
161
     *
162
     * @phpstan-param TKey $key
163
     * @phpstan-return false|T|array<TKey,T>
164
     */
165
    public function __invoke($key = null)
166
    {
167
        if ($key !== null) {
3 ✔
168
            $this->generatorToArray();
3 ✔
169

170
            return $this->array[$key] ?? false;
3 ✔
171
        }
172

173
        /** @var array<TKey,T> $return */
174
        $return = $this->toArray();
×
175

176
        return $return;
×
177
    }
178

179
    /**
180
     * Whether or not an element exists by key.
181
     *
182
     * @param mixed $key
183
     *
184
     * @return bool
185
     *              <p>True is the key/index exists, otherwise false.</p>
186
     *
187
     * @phpstan-param TKey $key
188
     */
189
    public function __isset($key): bool
190
    {
191
        return $this->offsetExists($key);
3 ✔
192
    }
193

194
    /**
195
     * Assigns a value to the specified element.
196
     *
197
     * @param mixed $key
198
     * @param mixed $value
199
     *
200
     * @return void
201
     *
202
     * @phpstan-param TKey $key
203
     * @phpstan-param T $value
204
     */
205
    public function __set($key, $value)
206
    {
207
        $this->internalSet($key, $value);
6 ✔
208
    }
209

210
    /**
211
     * magic to string
212
     *
213
     * @return string
214
     */
215
    public function __toString(): string
216
    {
217
        return $this->toString();
45 ✔
218
    }
219

220
    /**
221
     * Unset element by key.
222
     *
223
     * @param mixed $key
224
     *
225
     * @phpstan-param TKey $key
226
     */
227
    public function __unset($key)
228
    {
229
        $this->internalRemove($key);
×
230
    }
231

232
    /**
233
     * Get a value by key.
234
     *
235
     * @param mixed $key
236
     *
237
     * @return mixed
238
     *               <p>Get a Value from the current array.</p>
239
     *
240
     * @template TAccessKey of key-of<TData>
241
     * @phpstan-param TAccessKey $key
242
     * @phpstan-return TData[TAccessKey]|null|self<array-key,T,array<array-key,T>>
243
     */
244
    public function &__get($key)
245
    {
246
        $return = $this->get($key, null, null, true);
513 ✔
247

248
        if (\is_array($return) === true) {
513 ✔
249
            $return = static::create(
×
NEW
250
                [], // @phpstan-ignore-line argument.type (an empty late-static instance cannot satisfy every possible invariant TData shape)
×
251
                $this->iteratorClass,
×
252
                false
×
253
            )->createByReference($return);
×
254
        }
255

256
        return $return;
513 ✔
257
    }
258

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

285
            $this->internalSet($key, $value); // @phpstan-ignore-line argument.type (add() can promote an existing scalar to an array during its documented recursive merge)
15 ✔
286

287
            return $this;
12 ✔
288
        }
289

290
        return $this->append($value);
27 ✔
291
    }
292

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

315
        if ($this->properties !== []) {
63 ✔
316
            $this->checkType($key, $value);
21 ✔
317
        }
318

319
        if ($key !== null) {
60 ✔
320
            if (
321
                isset($this->array[$key])
6 ✔
322
                &&
323
                \is_array($this->array[$key])
6 ✔
324
            ) {
325
                $this->array[$key][] = $value; // @phpstan-ignore assign.propertyType
×
326
            } else {
327
                $this->array[$key] = $value;
6 ✔
328
            }
329
        } else {
330
            $this->array[] = $value;
54 ✔
331
        }
332

333
        return $this;
60 ✔
334
    }
335

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

364
            foreach ($this->getGenerator() as $keyOld => $itemOld) {
3 ✔
365
                yield $keyOld => $itemOld;
3 ✔
366
            }
367

368
            if ($key !== null) {
3 ✔
369
                yield $key => $value;
×
370
            } else {
371
                yield $value;
3 ✔
372
            }
373
        };
3 ✔
374

375
        return static::create(
3 ✔
376
            $generator,
3 ✔
377
            $this->iteratorClass,
3 ✔
378
            false
3 ✔
379
        );
3 ✔
380
    }
381

382
    /**
383
     * Sort the entries by value.
384
     *
385
     * @param int $sort_flags [optional] <p>
386
     *                        You may modify the behavior of the sort using the optional
387
     *                        parameter sort_flags, for details
388
     *                        see sort.
389
     *                        </p>
390
     *
391
     * @return $this
392
     *               <p>(Mutable) Return this Arrayy object.</p>
393
     *
394
     * @phpstan-return static
395
     */
396
    #[\ReturnTypeWillChange]
397
    public function asort(int $sort_flags = 0): self
398
    {
399
        $this->generatorToArray();
12 ✔
400

401
        \asort($this->array, $sort_flags);
12 ✔
402

403
        return $this;
12 ✔
404
    }
405

406
    /**
407
     * Sort the entries by value.
408
     *
409
     * @param int $sort_flags [optional] <p>
410
     *                        You may modify the behavior of the sort using the optional
411
     *                        parameter sort_flags, for details
412
     *                        see sort.
413
     *                        </p>
414
     *
415
     * @return $this
416
     *               <p>(Immutable) Return this Arrayy object.</p>
417
     *
418
     * @phpstan-return static
419
     * @psalm-mutation-free
420
     */
421
    public function asortImmutable(int $sort_flags = 0): self
422
    {
423
        $that = clone $this;
12 ✔
424

425
        /**
426
         * @psalm-suppress ImpureMethodCall - object is already cloned
427
         */
428
        $that->asort($sort_flags);
12 ✔
429

430
        return $that;
12 ✔
431
    }
432

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

480
        if (
481
            $this->generator
465 ✔
482
            &&
483
            $mode === \COUNT_NORMAL
465 ✔
484
        ) {
485
            return \iterator_count($this->generator);
12 ✔
486
        }
487

488
        return \count($this->toArray(), $mode);
453 ✔
489
    }
490

491
    /**
492
     * Exchange the array for another one.
493
     *
494
     * @param array|mixed|static $data
495
     *
496
     * 1. use the current array, if it's a array
497
     * 2. fallback to empty array, if there is nothing
498
     * 3. call "getArray()" on object, if there is a "Arrayy"-object
499
     * 4. call "createFromObject()" on object, if there is a "\Traversable"-object
500
     * 5. call "__toArray()" on object, if the method exists
501
     * 6. cast a string or object with "__toString()" into an array
502
     * 7. throw a "InvalidArgumentException"-Exception
503
     *
504
     * @return array
505
     *
506
     * @phpstan-param  T|array<TKey,T>|self<TKey,T,TData> $data
507
     * @phpstan-return array<TKey,T>
508
     */
509
    public function exchangeArray($data): array
510
    {
511
        /** @phpstan-var array<TKey,T> array */
512
        $array = $this->fallbackForArray($data);
3 ✔
513

514
        $this->array = $array;
3 ✔
515
        $this->generator = null;
3 ✔
516

517
        return $this->array;
3 ✔
518
    }
519

520
    /**
521
     * Creates a copy of the ArrayyObject.
522
     *
523
     * @return array
524
     *
525
     * @phpstan-return array<int|string|TKey,T>
526
     */
527
    public function getArrayCopy(): array
528
    {
529
        $this->generatorToArray();
18 ✔
530

531
        return $this->array;
18 ✔
532
    }
533

534
    /**
535
     * Returns a new iterator, thus implementing the \Iterator interface.
536
     *
537
     * EXAMPLE: <code>
538
     * a(['foo', 'bar'])->getIterator(); // ArrayyIterator['foo', 'bar']
539
     * </code>
540
     *
541
     * @return \Iterator<mixed, mixed>
542
     *                          <p>An iterator for the values in the array.</p>
543
     * @phpstan-return \Iterator<TKey, T>
544
     */
545
    public function getIterator(): \Iterator
546
    {
547
        if ($this->generator instanceof ArrayyRewindableGenerator) {
105 ✔
548
            $generator = clone $this->generator;
6 ✔
549

550
            /** @phpstan-var \Arrayy\ArrayyRewindableGenerator<TKey,T> */
551
            $generatorTmp = new ArrayyRewindableExtendedGenerator(
6 ✔
552
                static function () use ($generator): \Generator {
6 ✔
553
                    yield from $generator;
6 ✔
554
                },
6 ✔
555
                null,
6 ✔
556
                static::class
6 ✔
557
            );
6 ✔
558

559
            $this->generator = $generatorTmp;
6 ✔
560

561
            return $this->generator;
6 ✔
562
        }
563

564
        $iterator = $this->getIteratorClass();
102 ✔
565

566
        if ($iterator === ArrayyIterator::class) {
102 ✔
567
            return new $iterator($this->toArray(), 0, static::class);
102 ✔
568
        }
569

570
        $return = new $iterator($this->toArray());
×
571
        \assert($return instanceof \Iterator);
572

573
        return $return;
×
574
    }
575

576
    /**
577
     * Gets the iterator classname for the ArrayObject.
578
     *
579
     * @return string
580
     *
581
     * @phpstan-return class-string
582
     */
583
    public function getIteratorClass(): string
584
    {
585
        return $this->iteratorClass;
102 ✔
586
    }
587

588
    /**
589
     * Sort the entries by key.
590
     *
591
     * @param int $sort_flags [optional] <p>
592
     *                        You may modify the behavior of the sort using the optional
593
     *                        parameter sort_flags, for details
594
     *                        see sort.
595
     *                        </p>
596
     *
597
     * @return $this
598
     *               <p>(Mutable) Return this Arrayy object.</p>
599
     *
600
     * @phpstan-return static
601
     */
602
    #[\ReturnTypeWillChange]
603
    public function ksort(int $sort_flags = 0): self
604
    {
605
        $this->generatorToArray();
12 ✔
606

607
        \ksort($this->array, $sort_flags);
12 ✔
608

609
        return $this;
12 ✔
610
    }
611

612
    /**
613
     * Sort the entries by key.
614
     *
615
     * @param int $sort_flags [optional] <p>
616
     *                        You may modify the behavior of the sort using the optional
617
     *                        parameter sort_flags, for details
618
     *                        see sort.
619
     *                        </p>
620
     *
621
     * @return $this
622
     *               <p>(Immutable) Return this Arrayy object.</p>
623
     *
624
     * @phpstan-return static
625
     */
626
    public function ksortImmutable(int $sort_flags = 0): self
627
    {
628
        $that = clone $this;
12 ✔
629

630
        /**
631
         * @psalm-suppress ImpureMethodCall - object is already cloned
632
         */
633
        $that->ksort($sort_flags);
12 ✔
634

635
        return $that;
12 ✔
636
    }
637

638
    /**
639
     * Sort an array using a case insensitive "natural order" algorithm.
640
     *
641
     * @return $this
642
     *               <p>(Mutable) Return this Arrayy object.</p>
643
     *
644
     * @phpstan-return static
645
     */
646
    #[\ReturnTypeWillChange]
647
    public function natcasesort(): self
648
    {
649
        $this->generatorToArray();
24 ✔
650

651
        \natcasesort($this->array);
24 ✔
652

653
        return $this;
24 ✔
654
    }
655

656
    /**
657
     * Sort an array using a case insensitive "natural order" algorithm.
658
     *
659
     * @return $this
660
     *               <p>(Immutable) Return this Arrayy object.</p>
661
     *
662
     * @phpstan-return static
663
     * @psalm-mutation-free
664
     */
665
    public function natcasesortImmutable(): self
666
    {
667
        $that = clone $this;
12 ✔
668

669
        /**
670
         * @psalm-suppress ImpureMethodCall - object is already cloned
671
         */
672
        $that->natcasesort();
12 ✔
673

674
        return $that;
12 ✔
675
    }
676

677
    /**
678
     * Sort entries using a "natural order" algorithm.
679
     *
680
     * @return $this
681
     *               <p>(Mutable) Return this Arrayy object.</p>
682
     *
683
     * @phpstan-return static
684
     */
685
    #[\ReturnTypeWillChange]
686
    public function natsort(): self
687
    {
688
        $this->generatorToArray();
30 ✔
689

690
        \natsort($this->array);
30 ✔
691

692
        return $this;
30 ✔
693
    }
694

695
    /**
696
     * Sort entries using a "natural order" algorithm.
697
     *
698
     * @return $this
699
     *               <p>(Immutable) Return this Arrayy object.</p>
700
     *
701
     * @phpstan-return static
702
     * @psalm-mutation-free
703
     */
704
    public function natsortImmutable(): self
705
    {
706
        $that = clone $this;
12 ✔
707

708
        /**
709
         * @psalm-suppress ImpureMethodCall - object is already cloned
710
         */
711
        $that->natsort();
12 ✔
712

713
        return $that;
12 ✔
714
    }
715

716
    /**
717
     * Whether or not an offset exists.
718
     *
719
     * @param bool|int|string $offset
720
     *
721
     * @return bool
722
     *
723
     * @psalm-mutation-free
724
     */
725
    #[\ReturnTypeWillChange]
726
    public function offsetExists($offset): bool
727
    {
728
        // php cast "bool"-index into "int"-index
729
        if ((bool) $offset === $offset) {
603 ✔
730
            $offset = (int) $offset;
3 ✔
731
        }
732
        \assert(\is_int($offset) || \is_string($offset));
733

734
        $offsetExists = $this->keyExists($offset);
603 ✔
735
        if ($offsetExists === true) {
603 ✔
736
            return true;
537 ✔
737
        }
738

739
        /**
740
         * https://github.com/vimeo/psalm/issues/2536
741
         *
742
         * @psalm-suppress PossiblyInvalidArgument
743
         * @psalm-suppress InvalidScalarArgument
744
         */
745
        if (
746
            $this->pathSeparator
426 ✔
747
            &&
748
            (string) $offset === $offset
426 ✔
749
            &&
750
            \strpos($offset, $this->pathSeparator) !== false
426 ✔
751
        ) {
752
            $explodedPath = \explode($this->pathSeparator, (string) $offset);
15 ✔
753
            /** @var string $lastOffset - helper for phpstan */
754
            $lastOffset = \array_pop($explodedPath);
15 ✔
755
            $containerPath = \implode($this->pathSeparator, $explodedPath);
15 ✔
756

757
            /**
758
             * @psalm-suppress MissingClosureReturnType
759
             * @psalm-suppress MissingClosureParamType
760
             */
761
            $this->callAtPath(
15 ✔
762
                $containerPath,
15 ✔
763
                static function ($container) use ($lastOffset, &$offsetExists) {
15 ✔
764
                    $offsetExists = \is_array($container) && \array_key_exists($lastOffset, $container);
15 ✔
765
                }
15 ✔
766
            );
15 ✔
767
        }
768

769
        return $offsetExists;
426 ✔
770
    }
771

772
    /**
773
     * Returns the value at specified offset.
774
     *
775
     * @param int|string $offset
776
     *
777
     * @return mixed
778
     *               <p>Will return null if the offset did not exists.</p>
779
     *
780
     * @template TOffset of key-of<TData>
781
     * @phpstan-param TOffset $offset
782
     * @phpstan-return TData[TOffset]|null
783
     */
784
    #[\ReturnTypeWillChange]
785
    public function &offsetGet($offset)
786
    {
787
        // init
788
        $value = null;
507 ✔
789

790
        if ($this->offsetExists($offset)) {
507 ✔
791
            $value = &$this->__get($offset); // @phpstan-ignore-line argument.templateType, argument.type (the dynamic value is intentionally forwarded through an invariant generic boundary)
501 ✔
792
        }
793

794
        return $value; // @phpstan-ignore return.type (offsetGet() intentionally returns the referenced value selected at runtime)
507 ✔
795
    }
796

797
    /**
798
     * Assigns a value to the specified offset + check the type.
799
     *
800
     * @param int|string|null $offset
801
     * @param mixed           $value
802
     *
803
     * @return void
804
     */
805
    #[\ReturnTypeWillChange]
806
    public function offsetSet($offset, $value)
807
    {
808
        $this->generatorToArray();
132 ✔
809

810
        if ($offset === null) {
132 ✔
811
            if ($this->properties !== []) {
27 ✔
812
                $this->checkType(null, $value);
12 ✔
813
            }
814

815
            $this->array[] = $value;
24 ✔
816
        } else {
817
            $this->internalSet(
108 ✔
818
                $offset,
108 ✔
819
                $value,
108 ✔
820
                true
108 ✔
821
            );
108 ✔
822
        }
823
    }
824

825
    /**
826
     * Unset an offset.
827
     *
828
     * @param int|string $offset
829
     *
830
     * @return void
831
     *              <p>(Mutable) Return nothing.</p>
832
     */
833
    #[\ReturnTypeWillChange]
834
    public function offsetUnset($offset)
835
    {
836
        $this->generatorToArray();
81 ✔
837

838
        if ($this->array === []) {
81 ✔
839
            return;
18 ✔
840
        }
841

842
        if ($this->keyExists($offset)) {
66 ✔
843
            unset($this->array[$offset]);
42 ✔
844

845
            return;
42 ✔
846
        }
847

848
        /**
849
         * https://github.com/vimeo/psalm/issues/2536
850
         *
851
         * @psalm-suppress PossiblyInvalidArgument
852
         * @psalm-suppress InvalidScalarArgument
853
         */
854
        if (
855
            $this->pathSeparator
33 ✔
856
            &&
857
            (string) $offset === $offset
33 ✔
858
            &&
859
            \strpos($offset, $this->pathSeparator) !== false
33 ✔
860
        ) {
861
            $path = \explode($this->pathSeparator, (string) $offset);
24 ✔
862
            $pathToUnset = \array_pop($path);
24 ✔
863

864
            /**
865
             * @psalm-suppress MissingClosureReturnType
866
             * @psalm-suppress MissingClosureParamType
867
             */
868
            $this->callAtPath(
24 ✔
869
                \implode($this->pathSeparator, $path),
24 ✔
870
                static function (&$offset) use ($pathToUnset) {
24 ✔
871
                    if (\is_array($offset)) {
21 ✔
872
                        unset($offset[$pathToUnset]);
15 ✔
873
                    } else {
874
                        $offset = null;
6 ✔
875
                    }
876
                }
24 ✔
877
            );
24 ✔
878
        }
879

880
        unset($this->array[$offset]);
33 ✔
881
    }
882

883
    /**
884
     * Serialize the current "Arrayy"-object.
885
     *
886
     * EXAMPLE: <code>
887
     * a([1, 4, 7])->serialize();
888
     * </code>
889
     *
890
     * @return string
891
     */
892
    public function serialize(): string
893
    {
894
        $this->generatorToArray();
3 ✔
895

896
        return \serialize($this);
3 ✔
897
    }
898

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

916
            return;
3,867 ✔
917
        }
918

919
        if (\strpos($iteratorClass, '\\') === 0) {
×
920
            /** @var class-string<\Arrayy\ArrayyIterator<TKey,T>> $iteratorClass */
921
            $iteratorClass = '\\' . $iteratorClass;
×
922
            if (\class_exists($iteratorClass)) {
×
923
                /**
924
                 * @psalm-suppress PropertyTypeCoercion
925
                 */
926
                $this->iteratorClass = $iteratorClass;
×
927

928
                return;
×
929
            }
930
        }
931

932
        throw new \InvalidArgumentException('The iterator class does not exist: ' . $iteratorClass);
×
933
    }
934

935
    /**
936
     * Sort the entries with a user-defined comparison function and maintain key association.
937
     *
938
     * @param callable $callable
939
     *
940
     *@throws \InvalidArgumentException
941
     *
942
     * @return $this
943
     *               <p>(Mutable) Return this Arrayy object.</p>
944
     *
945
     * @phpstan-param  callable(T,T):int $callable
946
     * @phpstan-return static
947
     */
948
    #[\ReturnTypeWillChange]
949
    public function uasort($callable): self
950
    {
951
        $this->generatorToArray();
24 ✔
952

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

955
        return $this;
24 ✔
956
    }
957

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

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

981
        return $that;
12 ✔
982
    }
983

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

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

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

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

1063
        if ($key !== null) {
3 ✔
1064
            if (
1065
                isset($this->array[$key])
3 ✔
1066
                &&
1067
                \is_array($this->array[$key])
3 ✔
1068
            ) {
1069
                foreach ($values as $value) {
3 ✔
1070
                    $this->array[$key][] = $value; // @phpstan-ignore-line assign.propertyType (runtime normalization intentionally rebuilds the generic backing array)
3 ✔
1071
                }
1072
            } else {
1073
                foreach ($values as $value) {
1 ✔
1074
                    $this->array[$key] = $value;
×
1075
                }
1076
            }
1077
        } else {
1078
            foreach ($values as $value) {
×
1079
                $this->array[] = $value;
×
1080
            }
1081
        }
1082

1083
        return $this;
3 ✔
1084
    }
1085

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

1102
        foreach ($this->getGenerator() as $key => $item) {
33 ✔
1103
            if ($item instanceof self) {
30 ✔
1104
                $result[$prefix . $key] = $item->appendToEachKey($prefix);
3 ✔
1105
            } elseif (\is_array($item)) {
30 ✔
1106
                $result[$prefix . $key] = self::create($item, $this->iteratorClass, false) // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
3 ✔
1107
                    ->appendToEachKey($prefix)
3 ✔
1108
                    ->toArray();
3 ✔
1109
            } else {
1110
                $result[$prefix . $key] = $item;
30 ✔
1111
            }
1112
        }
1113

1114
        return self::create(
33 ✔
1115
            $result, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
33 ✔
1116
            $this->iteratorClass,
33 ✔
1117
            false
33 ✔
1118
        );
33 ✔
1119
    }
1120

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

1137
        foreach ($this->getGenerator() as $key => $item) {
30 ✔
1138
            if ($item instanceof self) {
27 ✔
1139
                $result[$key] = $item->appendToEachValue($prefix);
×
1140
            } elseif (\is_array($item)) {
27 ✔
NEW
1141
                $result[$key] = self::create($item, $this->iteratorClass, false)->appendToEachValue($prefix)->toArray(); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
×
1142
            } elseif (\is_object($item) === true) {
27 ✔
1143
                $result[$key] = $item;
3 ✔
1144
            } else {
1145
                $result[$key] = $prefix . $item;
24 ✔
1146
            }
1147
        }
1148

1149
        return self::create($result, $this->iteratorClass, false); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
30 ✔
1150
    }
1151

1152
    /**
1153
     * Sort an array in reverse order and maintain index association.
1154
     *
1155
     * @return $this
1156
     *               <p>(Mutable) Return this Arrayy object.</p>
1157
     *
1158
     * @phpstan-return static
1159
     */
1160
    public function arsort(): self
1161
    {
1162
        $this->generatorToArray();
12 ✔
1163

1164
        \arsort($this->array);
12 ✔
1165

1166
        return $this;
12 ✔
1167
    }
1168

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

1182
        $that->generatorToArray();
30 ✔
1183

1184
        \arsort($that->array);
30 ✔
1185

1186
        return $that;
30 ✔
1187
    }
1188

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

1213
        foreach ($that->getGenerator() as $key => $value) {
9 ✔
1214
            $closure($value, $key);
9 ✔
1215
        }
1216

1217
        return static::create(
9 ✔
1218
            $that->toArray(), // @phpstan-ignore-line argument.type (the runtime conversion crosses from the receiver templates into a freshly constructed result shape)
9 ✔
1219
            $this->iteratorClass,
9 ✔
1220
            false
9 ✔
1221
        );
9 ✔
1222
    }
1223

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

1242
        if (!$count) {
30 ✔
1243
            return 0;
6 ✔
1244
        }
1245

1246
        if ((int) $decimals !== $decimals) {
24 ✔
1247
            $decimals = 0;
9 ✔
1248
        }
1249

1250
        $sum = 0;
24 ✔
1251
        foreach ($array as $value) {
24 ✔
1252
            if (
1253
                \is_int($value)
24 ✔
1254
                ||
1255
                \is_float($value)
21 ✔
1256
                ||
1257
                \is_bool($value)
24 ✔
1258
            ) {
1259
                $sum += $value;
18 ✔
1260
            } elseif (\is_string($value) && \is_numeric($value)) {
6 ✔
1261
                $sum += (float) $value;
×
1262
            }
1263
        }
1264

1265
        return \round($sum / $count, $decimals);
24 ✔
1266
    }
1267

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

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

1306
            $return[$key] = $value;
3 ✔
1307
        }
1308

1309
        return static::create(
3 ✔
1310
            $return, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
3 ✔
1311
            $this->iteratorClass,
3 ✔
1312
            false
3 ✔
1313
        );
3 ✔
1314
    }
1315

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

1332
        return $this;
36 ✔
1333
    }
1334

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

1360
                    $values[$key] = $value;
×
1361
                    if ($tmpCounter === $size) {
×
1362
                        yield $values;
×
1363

1364
                        $values = [];
×
1365
                        $tmpCounter = 0;
×
1366
                    }
1367
                }
1368

1369
                if ($values !== []) {
×
1370
                    yield $values;
×
1371
                }
1372
            };
×
1373
        } else {
1374
            $generator = function () use ($size) {
18 ✔
1375
                $values = [];
18 ✔
1376
                $tmpCounter = 0;
18 ✔
1377
                foreach ($this->getGenerator() as $value) {
18 ✔
1378
                    ++$tmpCounter;
18 ✔
1379

1380
                    $values[] = $value;
18 ✔
1381
                    if ($tmpCounter === $size) {
18 ✔
1382
                        yield $values;
18 ✔
1383

1384
                        $values = [];
18 ✔
1385
                        $tmpCounter = 0;
18 ✔
1386
                    }
1387
                }
1388

1389
                if ($values !== []) {
18 ✔
1390
                    yield $values;
15 ✔
1391
                }
1392
            };
18 ✔
1393
        }
1394

1395
        return static::create(
18 ✔
1396
            $generator,
18 ✔
1397
            $this->iteratorClass,
18 ✔
1398
            false
18 ✔
1399
        );
18 ✔
1400
    }
1401

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

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

1449
            return $this;
9 ✔
1450
        }
1451

1452
        $this->array = [];
21 ✔
1453
        $this->generator = null;
21 ✔
1454

1455
        return $this;
21 ✔
1456
    }
1457

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

1478
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1479
        $tmpCount = 0;
30 ✔
1480
        foreach ($this->getGeneratorByReference() as &$valueFromArray) {
30 ✔
1481
            $tmpCount++;
24 ✔
1482

1483
            if ($strict) {
24 ✔
1484
                if ($value !== $valueFromArray) {
24 ✔
1485
                    return false;
14 ✔
1486
                }
1487
            } else {
1488
                /** @noinspection NestedPositiveIfStatementsInspection */
1489
                if ($value != $valueFromArray) {
×
1490
                    return false;
×
1491
                }
1492
            }
1493
        }
1494

1495
        return $tmpCount !== 0;
21 ✔
1496
    }
1497

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

1518
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1519
        foreach ($this->getGeneratorByReference() as &$valueFromArray) {
42 ✔
1520
            if ($strict) {
33 ✔
1521
                if ($value === $valueFromArray) {
33 ✔
1522
                    return true;
27 ✔
1523
                }
1524
            } else {
1525
                /** @noinspection NestedPositiveIfStatementsInspection */
1526
                if ($value == $valueFromArray) {
×
1527
                    return true;
×
1528
                }
1529
            }
1530
        }
1531

1532
        return false;
21 ✔
1533
    }
1534

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

1556
        if ($recursive === true) {
72 ✔
1557
            /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1558
            foreach ($this->getGeneratorByReference() as &$valueTmp) {
72 ✔
1559
                if (\is_array($valueTmp)) {
66 ✔
1560
                    $return = (new self($valueTmp))->containsCaseInsensitive($value, $recursive);
15 ✔
1561
                    if ($return === true) {
15 ✔
1562
                        return $return;
11 ✔
1563
                    }
1564
                } elseif (\mb_strtoupper((string) $valueTmp) === \mb_strtoupper((string) $value)) {
66 ✔
1565
                    return true;
48 ✔
1566
                }
1567
            }
1568

1569
            return false;
24 ✔
1570
        }
1571

1572
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
1573
        foreach ($this->getGeneratorByReference() as &$valueTmp) {
36 ✔
1574
            if (\mb_strtoupper((string) $valueTmp) === \mb_strtoupper((string) $value)) {
33 ✔
1575
                return true;
24 ✔
1576
            }
1577
        }
1578

1579
        return false;
12 ✔
1580
    }
1581

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

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

1635
        return \count(
3 ✔
1636
            \array_intersect($needles, $this->keys()->toArray()),
3 ✔
1637
            \COUNT_NORMAL
3 ✔
1638
        )
3 ✔
1639
                ===
3 ✔
1640
                \count(
3 ✔
1641
                    $needles,
3 ✔
1642
                    \COUNT_NORMAL
3 ✔
1643
                );
3 ✔
1644
    }
1645

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

1662
    /**
1663
     * alias: for "Arrayy->contains()"
1664
     *
1665
     * @param float|int|string $value
1666
     *
1667
     * @return bool
1668
     *
1669
     * @see Arrayy::contains()
1670
     * @psalm-mutation-free
1671
     */
1672
    public function containsValue($value): bool
1673
    {
1674
        return $this->contains($value);
27 ✔
1675
    }
1676

1677
    /**
1678
     * alias: for "Arrayy->contains($value, true)"
1679
     *
1680
     * @param float|int|string $value
1681
     *
1682
     * @return bool
1683
     *
1684
     * @see Arrayy::contains()
1685
     * @psalm-mutation-free
1686
     */
1687
    public function containsValueRecursive($value): bool
1688
    {
1689
        return $this->contains($value, true);
54 ✔
1690
    }
1691

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

1723
    /**
1724
     * Counts all the values of an array
1725
     *
1726
     * @see          http://php.net/manual/en/function.array-count-values.php
1727
     *
1728
     * @return static
1729
     *                <p>
1730
     *                (Immutable)
1731
     *                An associative Arrayy-object of values from input as
1732
     *                keys and their count as value.
1733
     *                </p>
1734
     *
1735
     * @phpstan-return static<array-key,int,array<array-key,int>>
1736
     * @psalm-mutation-free
1737
     */
1738
    public function countValues(): self
1739
    {
1740
        /** @phpstan-var static<array-key,int,array<array-key,int>> $return */
1741
        $return = self::create(\array_count_values($this->toArray()), $this->iteratorClass); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
21 ✔
1742

1743
        return $return;
21 ✔
1744
    }
1745

1746
    /**
1747
     * Creates an Arrayy object.
1748
     *
1749
     * @param mixed  $data
1750
     * @param string $iteratorClass
1751
     * @param bool   $checkPropertiesInConstructor
1752
     *
1753
     * @return static
1754
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1755
     *
1756
     * @phpstan-param  TData|self<TKey,T,TData>|\Traversable<TKey,T>|callable|object|scalar|null $data
1757
     * @phpstan-param  class-string<\Arrayy\ArrayyIterator<TKey,T>> $iteratorClass
1758
     * @phpstan-return static
1759
     * @psalm-mutation-free
1760
     */
1761
    public static function create(
1762
        $data = [],
1763
        string $iteratorClass = ArrayyIterator::class,
1764
        bool $checkPropertiesInConstructor = true
1765
    ) {
1766
        /** @var static $instance */
1767
        $instance = new static( // @phpstan-ignore new.static
2,381 ✔
1768
            $data,
2,381 ✔
1769
            $iteratorClass,
2,381 ✔
1770
            $checkPropertiesInConstructor
2,381 ✔
1771
        );
2,381 ✔
1772

1773
        return $instance;
2,381 ✔
1774
    }
1775

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

1800
        if ($items === null) {
6 ✔
1801
            $items = $this->getArray();
6 ✔
1802
        }
1803

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

1812
        if (\count($flatten) === 0) {
6 ✔
1813
            return [];
×
1814
        }
1815

1816
        return \array_merge_recursive([], ...$flatten);
6 ✔
1817
    }
1818

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

1837
        return $this;
86 ✔
1838
    }
1839

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

1857
    /**
1858
     * Create an new instance filled with a copy of values from a "Generator"-object.
1859
     *
1860
     * @param \Generator $generator
1861
     *
1862
     * @return static
1863
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1864
     *
1865
     * @template TGenerator
1866
     *
1867
     * @phpstan-param \Generator<array-key,TGenerator> $generator
1868
     * @phpstan-return static<array-key,TGenerator,array<array-key,TGenerator>>
1869
     * @psalm-mutation-free
1870
     */
1871
    public static function createFromGeneratorImmutable(\Generator $generator): self
1872
    {
1873
        return self::create(\iterator_to_array($generator, true)); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
15 ✔
1874
    }
1875

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

1892
    /**
1893
     * Create an new Arrayy object via JSON.
1894
     *
1895
     * @param array $array
1896
     *
1897
     * @return static
1898
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1899
     *
1900
     * @template TArrayKey of array-key
1901
     * @template TArray
1902
     *
1903
     * @phpstan-param array<TArrayKey,TArray> $array
1904
     * @phpstan-return static<TArrayKey,TArray,array<TArrayKey,TArray>>
1905
     * @psalm-mutation-free
1906
     */
1907
    public static function createFromArray(array $array): self
1908
    {
1909
        return static::create($array); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
3 ✔
1910
    }
1911

1912
    /**
1913
     * Create an new instance filled with values from an object that is iterable.
1914
     *
1915
     * @param \Traversable $object <p>iterable object</p>
1916
     *
1917
     * @return static
1918
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1919
     *
1920
     * @phpstan-param \Traversable<array-key,T> $object
1921
     * @phpstan-return static
1922
     * @psalm-mutation-free
1923
     */
1924
    public static function createFromObject(\Traversable $object): self
1925
    {
1926
        // init
1927
        $arrayy = static::create();
12 ✔
1928

1929
        if ($object instanceof self) {
12 ✔
1930
            $objectArray = $object->getGenerator();
12 ✔
1931
        } else {
1932
            $objectArray = $object;
×
1933
        }
1934

1935
        foreach ($objectArray as $key => $value) {
12 ✔
1936
            /**
1937
             * @psalm-suppress ImpureMethodCall - object is already re-created
1938
             */
1939
            $arrayy->internalSet($key, $value);
9 ✔
1940
        }
1941

1942
        return $arrayy;
12 ✔
1943
    }
1944

1945
    /**
1946
     * Create an new instance filled with values from an object.
1947
     *
1948
     * @param object $object
1949
     *
1950
     * @return static
1951
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1952
     *
1953
     * @phpstan-return static
1954
     * @psalm-mutation-free
1955
     */
1956
    public static function createFromObjectVars($object): self
1957
    {
1958
        return self::create(self::objectToArray($object));
18 ✔
1959
    }
1960

1961
    /**
1962
     * Create an new Arrayy object via string.
1963
     *
1964
     * @param string                $str       <p>The input string.</p>
1965
     * @param non-empty-string|null $delimiter <p>The boundary string.</p>
1966
     * @param string|null           $regEx     <p>Use the $delimiter or the $regEx, so if $pattern is null, $delimiter will be
1967
     *                                         used.</p>
1968
     *
1969
     * @return static
1970
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
1971
     *
1972
     * @phpstan-return static
1973
     * @psalm-mutation-free
1974
     */
1975
    public static function createFromString(string $str, ?string $delimiter = null, ?string $regEx = null): self
1976
    {
1977
        if ($regEx) {
30 ✔
1978
            \preg_match_all($regEx, $str, $array);
3 ✔
1979

1980
            if (!empty($array)) {
3 ✔
1981
                $array = $array[0];
3 ✔
1982
            }
1983
        } else {
1984
            /** @noinspection NestedPositiveIfStatementsInspection */
1985
            if ($delimiter !== null) {
27 ✔
1986
                $array = \explode($delimiter, $str);
21 ✔
1987
            } else {
1988
                $array = [$str];
6 ✔
1989
            }
1990
        }
1991

1992
        // trim all string in the array
1993
        /**
1994
         * @psalm-suppress MissingClosureParamType
1995
         */
1996
        \array_walk(
30 ✔
1997
            $array,
30 ✔
1998
            static function (&$val) {
30 ✔
1999
                if ((string) $val === $val) {
30 ✔
2000
                    $val = \trim($val);
30 ✔
2001
                }
2002
            }
30 ✔
2003
        );
30 ✔
2004

2005
        /** @var static $return - help for phpstan */
2006
        $return = static::create($array); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
30 ✔
2007

2008
        return $return;
30 ✔
2009
    }
2010

2011
    /**
2012
     * Create an new instance filled with a copy of values from a "Traversable"-object.
2013
     *
2014
     * @param \Traversable $traversable
2015
     * @param bool         $use_keys    [optional] <p>
2016
     *                                  Whether to use the iterator element keys as index.
2017
     *                                  </p>
2018
     *
2019
     * @return static
2020
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
2021
     *
2022
     * @template TTraversableKey of array-key
2023
     * @template TTraversable
2024
     *
2025
     * @phpstan-param \Traversable<TTraversableKey,TTraversable> $traversable
2026
     * @phpstan-return static<array-key,TTraversable,array<array-key,TTraversable>>
2027
     * @psalm-mutation-free
2028
     */
2029
    public static function createFromTraversableImmutable(\Traversable $traversable, bool $use_keys = true): self
2030
    {
2031
        return self::create(\iterator_to_array($traversable, $use_keys)); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
3 ✔
2032
    }
2033

2034
    /**
2035
     * Create an new instance containing a range of elements.
2036
     *
2037
     * @param float|int|string $low  <p>First value of the sequence.</p>
2038
     * @param float|int|string $high <p>The sequence is ended upon reaching the end value.</p>
2039
     * @param float|int        $step <p>Used as the increment between elements in the sequence.</p>
2040
     *
2041
     * @return static
2042
     *                <p>(Immutable) Returns an new instance of the Arrayy object.</p>
2043
     *
2044
     * @phpstan-return static
2045
     * @psalm-mutation-free
2046
     */
2047
    public static function createWithRange($low, $high, $step = 1): self
2048
    {
2049
        /** @phpstan-var static $return - help for phpstan */
2050
        $return = static::create(\range($low, $high, $step)); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
6 ✔
2051

2052
        return $return;
6 ✔
2053
    }
2054

2055
    /**
2056
     * Gets the element of the array at the current internal iterator position.
2057
     *
2058
     * @return false|mixed
2059
     *
2060
     * @phpstan-return false|T
2061
     */
2062
    public function current()
2063
    {
2064
        if ($this->generator) {
×
2065
            return $this->generator->current();
×
2066
        }
2067

2068
        return \current($this->array);
×
2069
    }
2070

2071
    /**
2072
     * Custom sort by index via "uksort".
2073
     *
2074
     * EXAMPLE: <code>
2075
     * $callable = function ($a, $b) {
2076
     *     if ($a == $b) {
2077
     *         return 0;
2078
     *     }
2079
     *     return ($a > $b) ? 1 : -1;
2080
     * };
2081
     * $arrayy = a(['three' => 3, 'one' => 1, 'two' => 2]);
2082
     * $resultArrayy = $arrayy->customSortKeys($callable); // Arrayy['one' => 1, 'three' => 3, 'two' => 2]
2083
     * </code>
2084
     *
2085
     * @see          http://php.net/manual/en/function.uksort.php
2086
     *
2087
     * @param callable $callable
2088
     *
2089
     * @throws \InvalidArgumentException
2090
     *
2091
     * @return $this
2092
     *               <p>(Mutable) Return this Arrayy object.</p>
2093
     *
2094
     * @phpstan-param  callable(TKey,TKey):int $callable
2095
     * @phpstan-return static
2096
     */
2097
    public function customSortKeys(callable $callable): self
2098
    {
2099
        $this->generatorToArray();
15 ✔
2100

2101
        \uksort($this->array, $callable);
15 ✔
2102

2103
        return $this;
15 ✔
2104
    }
2105

2106
    /**
2107
     * Custom sort by index via "uksort".
2108
     *
2109
     * @see          http://php.net/manual/en/function.uksort.php
2110
     *
2111
     * @param callable $callable
2112
     *
2113
     * @throws \InvalidArgumentException
2114
     *
2115
     * @return $this
2116
     *               <p>(Immutable) Return this Arrayy object.</p>
2117
     *
2118
     * @phpstan-param  callable(TKey,TKey):int $callable
2119
     * @phpstan-return static
2120
     * @psalm-mutation-free
2121
     */
2122
    public function customSortKeysImmutable(callable $callable): self
2123
    {
2124
        $that = clone $this;
3 ✔
2125

2126
        $that->generatorToArray();
3 ✔
2127

2128
        /**
2129
         * @psalm-suppress ImpureFunctionCall - object is already cloned
2130
         */
2131
        \uksort($that->array, $callable);
3 ✔
2132

2133
        return $that;
3 ✔
2134
    }
2135

2136
    /**
2137
     * Custom sort by value via "usort".
2138
     *
2139
     * EXAMPLE: <code>
2140
     * $callable = function ($a, $b) {
2141
     *     if ($a == $b) {
2142
     *         return 0;
2143
     *     }
2144
     *     return ($a > $b) ? 1 : -1;
2145
     * };
2146
     * $arrayy = a(['three' => 3, 'one' => 1, 'two' => 2]);
2147
     * $resultArrayy = $arrayy->customSortValues($callable); // Arrayy[1, 2, 3]
2148
     * </code>
2149
     *
2150
     * @see          http://php.net/manual/en/function.usort.php
2151
     *
2152
     * @param callable $callable
2153
     *
2154
     * @return $this
2155
     *               <p>(Mutable) Return this Arrayy object.</p>
2156
     *
2157
     * @phpstan-param  callable(T,T):int $callable
2158
     * @phpstan-return static
2159
     */
2160
    public function customSortValues(callable $callable): self
2161
    {
2162
        $this->generatorToArray();
33 ✔
2163

2164
        \usort($this->array, $callable);
33 ✔
2165

2166
        return $this;
33 ✔
2167
    }
2168

2169
    /**
2170
     * Custom sort by value via "usort".
2171
     *
2172
     * @see          http://php.net/manual/en/function.usort.php
2173
     *
2174
     * @param callable $callable
2175
     *
2176
     * @throws \InvalidArgumentException
2177
     *
2178
     * @return $this
2179
     *               <p>(Immutable) Return this Arrayy object.</p>
2180
     *
2181
     * @phpstan-param  callable(T,T):int $callable
2182
     * @phpstan-return static
2183
     * @psalm-mutation-free
2184
     */
2185
    public function customSortValuesImmutable($callable): self
2186
    {
2187
        $that = clone $this;
15 ✔
2188

2189
        /**
2190
         * @psalm-suppress ImpureMethodCall - object is already cloned
2191
         */
2192
        $that->customSortValues($callable);
15 ✔
2193

2194
        return $that;
15 ✔
2195
    }
2196

2197
    /**
2198
     * Delete the given key or keys.
2199
     *
2200
     * @param int|int[]|string|string[] $keyOrKeys
2201
     *
2202
     * @return void
2203
     */
2204
    public function delete($keyOrKeys)
2205
    {
2206
        $keyOrKeys = (array) $keyOrKeys;
27 ✔
2207

2208
        foreach ($keyOrKeys as $key) {
27 ✔
2209
            $this->offsetUnset($key);
27 ✔
2210
        }
2211
    }
2212

2213
    /**
2214
     * Return elements where the values that are only in the current array.
2215
     *
2216
     * EXAMPLE: <code>
2217
     * a([1 => 1, 2 => 2])->diff([1 => 1]); // Arrayy[2 => 2]
2218
     * </code>
2219
     *
2220
     * @param array ...$array
2221
     *
2222
     * @return static
2223
     *                <p>(Immutable)</p>
2224
     *
2225
     * @phpstan-param  array<TKey,T> ...$array
2226
     * @phpstan-return static
2227
     * @psalm-mutation-free
2228
     */
2229
    public function diff(array ...$array): self
2230
    {
2231
        if (\count($array) > 1) {
39 ✔
2232
            $array = \array_merge([], ...$array);
3 ✔
2233
        } else {
2234
            $array = $array[0];
39 ✔
2235
        }
2236

2237
        $generator = function () use ($array): \Generator {
39 ✔
2238
            foreach ($this->getGenerator() as $key => $value) {
39 ✔
2239
                if (\in_array($value, $array, true) === false) {
33 ✔
2240
                    yield $key => $value;
15 ✔
2241
                }
2242
            }
2243
        };
39 ✔
2244

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

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

2272
        $generator = function () use ($array): \Generator {
27 ✔
2273
            foreach ($this->getGenerator() as $key => $value) {
27 ✔
2274
                if (\array_key_exists($key, $array) === false) {
24 ✔
2275
                    yield $key => $value;
6 ✔
2276
                }
2277
            }
2278
        };
27 ✔
2279

2280
        return static::create(
27 ✔
2281
            $generator,
27 ✔
2282
            $this->iteratorClass,
27 ✔
2283
            false
27 ✔
2284
        );
27 ✔
2285
    }
2286

2287
    /**
2288
     * Return elements where the values and keys are only in the current array.
2289
     *
2290
     * @param array ...$array
2291
     *
2292
     * @return static
2293
     *                <p>(Immutable)</p>
2294
     *
2295
     * @phpstan-param  array<TKey,T> $array
2296
     * @phpstan-return static
2297
     * @psalm-mutation-free
2298
     */
2299
    public function diffKeyAndValue(array ...$array): self
2300
    {
2301
        if (\count($array) > 1) {
27 ✔
2302
            $array = \array_merge([], ...$array);
3 ✔
2303
        } else {
2304
            $array = $array[0];
24 ✔
2305
        }
2306

2307
        $generator = function () use ($array): \Generator {
27 ✔
2308
            foreach ($this->getGenerator() as $key => $value) {
27 ✔
2309
                $isset = isset($array[$key]);
24 ✔
2310

2311
                if (
2312
                    !$isset
24 ✔
2313
                    ||
2314
                    $array[$key] !== $value
24 ✔
2315
                ) {
2316
                    yield $key => $value;
12 ✔
2317
                }
2318
            }
2319
        };
27 ✔
2320

2321
        return static::create(
27 ✔
2322
            $generator,
27 ✔
2323
            $this->iteratorClass,
27 ✔
2324
            false
27 ✔
2325
        );
27 ✔
2326
    }
2327

2328
    /**
2329
     * Return elements where the values are only in the current multi-dimensional array.
2330
     *
2331
     * EXAMPLE: <code>
2332
     * a([1 => [1 => 1], 2 => [2 => 2]])->diffRecursive([1 => [1 => 1]]); // Arrayy[2 => [2 => 2]]
2333
     * </code>
2334
     *
2335
     * @param array                 $array
2336
     * @param array|\Generator|null $helperVariableForRecursion <p>(only for internal usage)</p>
2337
     *
2338
     * @return static
2339
     *                <p>(Immutable)</p>
2340
     *
2341
     * @phpstan-param  array<TKey,T> $array
2342
     * @phpstan-param  null|array<TKey,T>|\Generator<TKey,T> $helperVariableForRecursion
2343
     * @phpstan-return static
2344
     * @psalm-mutation-free
2345
     */
2346
    public function diffRecursive(array $array = [], $helperVariableForRecursion = null): self
2347
    {
2348
        // init
2349
        $result = [];
3 ✔
2350

2351
        if (
2352
            $helperVariableForRecursion !== null
3 ✔
2353
            &&
2354
            \is_array($helperVariableForRecursion)
3 ✔
2355
        ) {
2356
            $arrayForTheLoop = $helperVariableForRecursion;
×
2357
        } else {
2358
            $arrayForTheLoop = $this->getGenerator();
3 ✔
2359
        }
2360

2361
        foreach ($arrayForTheLoop as $key => $value) {
3 ✔
2362
            if ($value instanceof self) {
3 ✔
2363
                $value = $value->toArray();
3 ✔
2364
            }
2365

2366
            if (\array_key_exists($key, $array)) {
3 ✔
2367
                if ($value !== $array[$key]) {
3 ✔
2368
                    $result[$key] = $value;
3 ✔
2369
                }
2370
            } else {
2371
                $result[$key] = $value;
3 ✔
2372
            }
2373
        }
2374

2375
        return static::create(
3 ✔
2376
            $result, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
3 ✔
2377
            $this->iteratorClass,
3 ✔
2378
            false
3 ✔
2379
        );
3 ✔
2380
    }
2381

2382
    /**
2383
     * Return elements where the values that are only in the new $array.
2384
     *
2385
     * EXAMPLE: <code>
2386
     * a([1 => 1])->diffReverse([1 => 1, 2 => 2]); // Arrayy[2 => 2]
2387
     * </code>
2388
     *
2389
     * @param array $array
2390
     *
2391
     * @return static
2392
     *                <p>(Immutable)</p>
2393
     *
2394
     * @phpstan-param  array<TKey,T> $array
2395
     * @phpstan-return static
2396
     * @psalm-mutation-free
2397
     */
2398
    public function diffReverse(array $array = []): self
2399
    {
2400
        return static::create(
24 ✔
2401
            \array_diff($array, $this->toArray()), // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
24 ✔
2402
            $this->iteratorClass,
24 ✔
2403
            false
24 ✔
2404
        );
24 ✔
2405
    }
2406

2407
    /**
2408
     * Divide an array into two arrays. One with keys and the other with values.
2409
     *
2410
     * EXAMPLE: <code>
2411
     * a(['a' => 1, 'b' => ''])->divide(); // Arrayy[Arrayy['a', 'b'], Arrayy[1, '']]
2412
     * </code>
2413
     *
2414
     * @return static
2415
     *                <p>(Immutable)</p>
2416
     *
2417
     * @phpstan-return static
2418
     * @psalm-mutation-free
2419
     */
2420
    public function divide(): self
2421
    {
2422
        return static::create(
3 ✔
2423
            [ // @phpstan-ignore-line argument.type (the runtime conversion crosses from the receiver templates into a freshly constructed result shape)
3 ✔
2424
                $this->keys(),
3 ✔
2425
                $this->values(),
3 ✔
2426
            ],
3 ✔
2427
            $this->iteratorClass,
3 ✔
2428
            false
3 ✔
2429
        );
3 ✔
2430
    }
2431

2432
    /**
2433
     * Iterate over the current array and modify the array's value.
2434
     *
2435
     * EXAMPLE: <code>
2436
     * $result = A::create();
2437
     * $closure = function ($value) {
2438
     *     return ':' . $value . ':';
2439
     * };
2440
     * a(['foo', 'bar' => 'bis'])->each($closure); // Arrayy[':foo:', 'bar' => ':bis:']
2441
     * </code>
2442
     *
2443
     * @param \Closure $closure
2444
     *
2445
     * @return static
2446
     *                <p>(Immutable)</p>
2447
     *
2448
     * @template TEach
2449
     *                 <p>The output value type.</p>
2450
     *
2451
     * @phpstan-param \Closure(T,?TKey):TEach $closure
2452
     * @phpstan-return static<TKey,TEach,array<TKey,TEach>>
2453
     * @psalm-mutation-free
2454
     */
2455
    public function each(\Closure $closure): self
2456
    {
2457
        // init
2458
        $array = [];
21 ✔
2459

2460
        foreach ($this->getGenerator() as $key => $value) {
21 ✔
2461
            $array[$key] = $closure($value, $key);
21 ✔
2462
        }
2463

2464
        return static::create( // @phpstan-ignore return.type (create() is intentionally re-parameterized with TEach)
21 ✔
2465
            $array, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
21 ✔
2466
            $this->iteratorClass,
21 ✔
2467
            false
21 ✔
2468
        );
21 ✔
2469
    }
2470

2471
    /**
2472
     * Sets the internal iterator to the last element in the array and returns this element.
2473
     *
2474
     * @return false|mixed
2475
     *
2476
     * @phpstan-return T|false
2477
     */
2478
    public function end()
2479
    {
2480
        if ($this->generator) {
×
2481
            $count = $this->count();
×
2482
            if ($count === 0) {
×
2483
                return false;
×
2484
            }
2485

2486
            $counter = 0;
×
2487
            /** @noinspection PhpUnusedLocalVariableInspection */
2488
            foreach ($this->getIterator() as $item) {
×
2489
                if (++$counter === $count - 1) {
×
2490
                    break;
×
2491
                }
2492
            }
2493
        }
2494

2495
        return \end($this->array);
×
2496
    }
2497

2498
    /**
2499
     * Check if a value is in the current array using a closure.
2500
     *
2501
     * EXAMPLE: <code>
2502
     * $callable = function ($value, $key) {
2503
     *     return 2 === $key and 'two' === $value;
2504
     * };
2505
     * a(['foo', 2 => 'two'])->exists($callable); // true
2506
     * </code>
2507
     *
2508
     * @param \Closure $closure
2509
     *
2510
     * @return bool
2511
     *              <p>Returns true if the given value is found, false otherwise.</p>
2512
     *
2513
     * @phpstan-param \Closure(T,TKey):bool $closure
2514
     */
2515
    public function exists(\Closure $closure): bool
2516
    {
2517
        // init
2518
        $isExists = false;
12 ✔
2519

2520
        foreach ($this->getGenerator() as $key => $value) {
12 ✔
2521
            if ($closure($value, $key)) {
9 ✔
2522
                $isExists = true;
3 ✔
2523

2524
                break;
3 ✔
2525
            }
2526
        }
2527

2528
        return $isExists;
12 ✔
2529
    }
2530

2531
    /**
2532
     * Fill the array until "$num" with "$default" values.
2533
     *
2534
     * EXAMPLE: <code>
2535
     * a(['bar'])->fillWithDefaults(3, 'foo'); // Arrayy['bar', 'foo', 'foo']
2536
     * </code>
2537
     *
2538
     * @param int   $num
2539
     * @param mixed $default
2540
     *
2541
     * @return static
2542
     *                <p>(Immutable)</p>
2543
     *
2544
     * @phpstan-param T $default
2545
     * @phpstan-return static
2546
     * @psalm-mutation-free
2547
     */
2548
    public function fillWithDefaults(int $num, $default = null): self
2549
    {
2550
        if ($num < 0) {
24 ✔
2551
            throw new \InvalidArgumentException('The $num parameter can only contain non-negative values.');
3 ✔
2552
        }
2553

2554
        $this->generatorToArray();
21 ✔
2555

2556
        $tmpArray = $this->array;
21 ✔
2557

2558
        $count = \count($tmpArray);
21 ✔
2559

2560
        while ($count < $num) {
21 ✔
2561
            $tmpArray[] = $default;
12 ✔
2562
            ++$count;
12 ✔
2563
        }
2564

2565
        return static::create(
21 ✔
2566
            $tmpArray, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
21 ✔
2567
            $this->iteratorClass,
21 ✔
2568
            false
21 ✔
2569
        );
21 ✔
2570
    }
2571

2572
    /**
2573
     * Find all items in an array that pass the truth test.
2574
     *
2575
     * EXAMPLE: <code>
2576
     * $closure = function ($value) {
2577
     *     return $value % 2 !== 0;
2578
     * }
2579
     * a([1, 2, 3, 4])->filter($closure); // Arrayy[0 => 1, 2 => 3]
2580
     * </code>
2581
     *
2582
     * @param \Closure|null $closure [optional] <p>
2583
     *                               The callback function to use
2584
     *                               </p>
2585
     *                               <p>
2586
     *                               If no callback is supplied, all entries of
2587
     *                               input equal to false (see
2588
     *                               converting to
2589
     *                               boolean) will be removed.
2590
     *                               </p>
2591
     * @param int           $flag    [optional] <p>
2592
     *                               Flag determining what arguments are sent to <i>callback</i>:
2593
     *                               </p>
2594
     *                               <ul>
2595
     *                               <li>
2596
     *                               <b>ARRAY_FILTER_USE_KEY</b> (1) - pass key as the only argument
2597
     *                               to <i>callback</i> instead of the value
2598
     *                               </li>
2599
     *                               <li>
2600
     *                               <b>ARRAY_FILTER_USE_BOTH</b> (2) - pass both value and key as
2601
     *                               arguments to <i>callback</i> instead of the value
2602
     *                               </li>
2603
     *                               </ul>
2604
     *
2605
     * @return static
2606
     *                <p>(Immutable)</p>
2607
     *
2608
     * @template TFilterFlag of int
2609
     *
2610
     * @phpstan-param (TFilterFlag is \ARRAY_FILTER_USE_KEY ? \Closure(TKey):bool : \Closure(T,TKey=):bool)|null $closure
2611
     * @phpstan-param TFilterFlag $flag
2612
     * @phpstan-return static
2613
     * @psalm-mutation-free
2614
     */
2615
    public function filter($closure = null, int $flag = \ARRAY_FILTER_USE_BOTH)
2616
    {
2617
        if (!$closure) {
39 ✔
2618
            return $this->clean();
3 ✔
2619
        }
2620

2621
        if ($flag === \ARRAY_FILTER_USE_KEY) {
39 ✔
2622
            $generator = function () use ($closure) {
3 ✔
2623
                foreach ($this->getGenerator() as $key => $value) {
3 ✔
2624
                    if ($closure($key) === true) {
3 ✔
2625
                        yield $key => $value;
3 ✔
2626
                    }
2627
                }
2628
            };
3 ✔
2629
        } elseif ($flag === \ARRAY_FILTER_USE_BOTH) {
39 ✔
2630
            /** @noinspection PhpSillyAssignmentInspection - hack for phpstan - https://github.com/phpstan/phpstan/issues/4192 */
2631
            /** @phpstan-var \Closure(T,TKey):bool $closure */
2632
            $closure = $closure;
39 ✔
2633

2634
            $generator = function () use ($closure) {
39 ✔
2635
                foreach ($this->getGenerator() as $key => $value) {
36 ✔
2636
                    if ($closure($value, $key) === true) {
33 ✔
2637
                        yield $key => $value;
30 ✔
2638
                    }
2639
                }
2640
            };
39 ✔
2641
        } else {
2642
            $generator = function () use ($closure) {
3 ✔
2643
                foreach ($this->getGenerator() as $key => $value) {
3 ✔
2644
                    if ($closure($value) === true) {
3 ✔
2645
                        yield $key => $value;
3 ✔
2646
                    }
2647
                }
2648
            };
3 ✔
2649
        }
2650

2651
        return static::create(
39 ✔
2652
            $generator,
39 ✔
2653
            $this->iteratorClass,
39 ✔
2654
            false
39 ✔
2655
        );
39 ✔
2656
    }
2657

2658
    /**
2659
     * Filters an array of objects (or a numeric array of associative arrays) based on the value of a particular
2660
     * property within that.
2661
     *
2662
     * @param string      $property
2663
     * @param mixed       $value
2664
     * @param string|null $comparisonOp
2665
     *                                  <p>
2666
     *                                  'eq' (equals),<br />
2667
     *                                  'gt' (greater),<br />
2668
     *                                  'gte' || 'ge' (greater or equals),<br />
2669
     *                                  'lt' (less),<br />
2670
     *                                  'lte' || 'le' (less or equals),<br />
2671
     *                                  'ne' (not equals),<br />
2672
     *                                  'contains',<br />
2673
     *                                  'notContains',<br />
2674
     *                                  'newer' (via strtotime),<br />
2675
     *                                  'older' (via strtotime),<br />
2676
     *                                  </p>
2677
     *
2678
     * @return static
2679
     *                <p>(Immutable)</p>
2680
     *
2681
     * @phpstan-param array<array-key, mixed>|T $value
2682
     * @phpstan-return static
2683
     * @psalm-mutation-free
2684
     *
2685
     * @psalm-suppress MissingClosureReturnType
2686
     * @psalm-suppress MissingClosureParamType
2687
     */
2688
    public function filterBy(
2689
        string $property,
2690
        $value,
2691
        ?string $comparisonOp = null
2692
    ): self {
2693
        if (!$comparisonOp) {
3 ✔
2694
            $comparisonOp = \is_array($value) ? 'contains' : 'eq';
3 ✔
2695
        }
2696

2697
        $ops = [
3 ✔
2698
            'eq' => static function ($item, $prop, $value): bool {
3 ✔
2699
                return $item[$prop] === $value;
3 ✔
2700
            },
3 ✔
2701
            'gt' => static function ($item, $prop, $value): bool {
3 ✔
2702
                return $item[$prop] > $value;
×
2703
            },
3 ✔
2704
            'ge' => static function ($item, $prop, $value): bool {
3 ✔
2705
                return $item[$prop] >= $value;
×
2706
            },
3 ✔
2707
            'gte' => static function ($item, $prop, $value): bool {
3 ✔
2708
                return $item[$prop] >= $value;
×
2709
            },
3 ✔
2710
            'lt' => static function ($item, $prop, $value): bool {
3 ✔
2711
                return $item[$prop] < $value;
3 ✔
2712
            },
3 ✔
2713
            'le' => static function ($item, $prop, $value): bool {
3 ✔
2714
                return $item[$prop] <= $value;
×
2715
            },
3 ✔
2716
            'lte' => static function ($item, $prop, $value): bool {
3 ✔
2717
                return $item[$prop] <= $value;
×
2718
            },
3 ✔
2719
            'ne' => static function ($item, $prop, $value): bool {
3 ✔
2720
                return $item[$prop] !== $value;
×
2721
            },
3 ✔
2722
            'contains' => static function ($item, $prop, $value): bool {
3 ✔
2723
                return \in_array($item[$prop], (array) $value, true);
3 ✔
2724
            },
3 ✔
2725
            'notContains' => static function ($item, $prop, $value): bool {
3 ✔
2726
                return !\in_array($item[$prop], (array) $value, true);
×
2727
            },
3 ✔
2728
            'newer' => static function ($item, $prop, $value): bool {
3 ✔
2729
                return \strtotime($item[$prop]) > \strtotime($value);
×
2730
            },
3 ✔
2731
            'older' => static function ($item, $prop, $value): bool {
3 ✔
2732
                return \strtotime($item[$prop]) < \strtotime($value);
×
2733
            },
3 ✔
2734
        ];
3 ✔
2735

2736
        $result = \array_values(
3 ✔
2737
            \array_filter(
3 ✔
2738
                $this->toArray(false, true),
3 ✔
2739
                static function ($item) use (
3 ✔
2740
                    $property,
3 ✔
2741
                    $value,
3 ✔
2742
                    $ops,
3 ✔
2743
                    $comparisonOp
3 ✔
2744
                ) {
3 ✔
2745
                    $item = (array) $item;
3 ✔
2746
                    $itemArrayy = static::create($item); // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
3 ✔
2747
                    $item[$property] = $itemArrayy->get($property, []);
3 ✔
2748

2749
                    return $ops[$comparisonOp]($item, $property, $value);
3 ✔
2750
                }
3 ✔
2751
            )
3 ✔
2752
        );
3 ✔
2753

2754
        return static::create(
3 ✔
2755
            $result, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
3 ✔
2756
            $this->iteratorClass,
3 ✔
2757
            false
3 ✔
2758
        );
3 ✔
2759
    }
2760

2761
    /**
2762
     * Find the first item in an array that passes the truth test, otherwise return false.
2763
     *
2764
     * EXAMPLE: <code>
2765
     * $search = 'foo';
2766
     * $closure = function ($value, $key) use ($search) {
2767
     *     return $value === $search;
2768
     * };
2769
     * a(['foo', 'bar', 'lall'])->find($closure); // 'foo'
2770
     * </code>
2771
     *
2772
     * @param \Closure $closure
2773
     *
2774
     * @return false|mixed
2775
     *                     <p>Return false if we did not find the value.</p>
2776
     *
2777
     * @phpstan-param \Closure(T,TKey):bool $closure
2778
     * @phpstan-return T|false
2779
     */
2780
    public function find(\Closure $closure)
2781
    {
2782
        foreach ($this->getGenerator() as $key => $value) {
27 ✔
2783
            if ($closure($value, $key)) {
21 ✔
2784
                return $value;
18 ✔
2785
            }
2786
        }
2787

2788
        return false;
9 ✔
2789
    }
2790

2791
    /**
2792
     * Find the key of the first item in an array that passes the truth test, otherwise return false.
2793
     *
2794
     * EXAMPLE: <code>
2795
     * $search = 'foo';
2796
     * $closure = function ($value, $key) use ($search) {
2797
     *     return $value === $search;
2798
     * };
2799
     * a(['foo', 'bar', 'lall'])->findKey($closure); // 0
2800
     * </code>
2801
     *
2802
     * @param \Closure $closure
2803
     *
2804
     * @return false|int|string
2805
     *                          <p>Return false if we did not find the key.</p>
2806
     *
2807
     * @phpstan-param \Closure(T,TKey):bool $closure
2808
     * @phpstan-return TKey|false
2809
     */
2810
    public function findKey(\Closure $closure)
2811
    {
2812
        foreach ($this->getGenerator() as $key => $value) {
39 ✔
2813
            if ($closure($value, $key)) {
36 ✔
2814
                return $key;
30 ✔
2815
            }
2816
        }
2817

2818
        return false;
12 ✔
2819
    }
2820

2821
    /**
2822
     * find by ...
2823
     *
2824
     * EXAMPLE: <code>
2825
     * $array = [
2826
     *     0 => ['id' => 123, 'name' => 'foo', 'group' => 'primary', 'value' => 123456, 'when' => '2014-01-01'],
2827
     *     1 => ['id' => 456, 'name' => 'bar', 'group' => 'primary', 'value' => 1468, 'when' => '2014-07-15'],
2828
     * ];
2829
     * a($array)->filterBy('name', 'foo'); // Arrayy[0 => ['id' => 123, 'name' => 'foo', 'group' => 'primary', 'value' => 123456, 'when' => '2014-01-01']]
2830
     * </code>
2831
     *
2832
     * @param string $property
2833
     * @param mixed  $value
2834
     * @param string $comparisonOp
2835
     *
2836
     * @return static
2837
     *                <p>(Immutable)</p>
2838
     *
2839
     * @phpstan-param array<array-key, mixed>|T $value
2840
     * @phpstan-return static
2841
     * @psalm-mutation-free
2842
     */
2843
    public function findBy(string $property, $value, string $comparisonOp = 'eq'): self
2844
    {
2845
        return $this->filterBy($property, $value, $comparisonOp);
3 ✔
2846
    }
2847

2848
    /**
2849
     * Get the first value from the current array.
2850
     *
2851
     * EXAMPLE: <code>
2852
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->first(); // 'foo'
2853
     * </code>
2854
     *
2855
     * @return mixed|null
2856
     *                    <p>Return null if there wasn't a element.</p>
2857
     *
2858
     * @phpstan-return T|null
2859
     * @psalm-mutation-free
2860
     */
2861
    public function first()
2862
    {
2863
        $key_first = $this->firstKey();
68 ✔
2864
        if ($key_first === null) {
68 ✔
2865
            return null;
9 ✔
2866
        }
2867

2868
        return $this->get($key_first);
59 ✔
2869
    }
2870

2871
    /**
2872
     * Get the first key from the current array.
2873
     *
2874
     * @return mixed|null
2875
     *                    <p>Return null if there wasn't a element.</p>
2876
     *
2877
     * @phpstan-return TKey|null
2878
     *
2879
     * @psalm-mutation-free
2880
     */
2881
    public function firstKey()
2882
    {
2883
        $this->generatorToArray();
89 ✔
2884

2885
        /** @phpstan-var TKey|null $return - help for phpstan */
2886
        $return = \array_key_first($this->array);
89 ✔
2887

2888
        return $return;
89 ✔
2889
    }
2890

2891
    /**
2892
     * Get the first value(s) from the current array.
2893
     * And will return an empty array if there was no first entry.
2894
     *
2895
     * EXAMPLE: <code>
2896
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->firstsImmutable(2); // Arrayy[0 => 'foo', 1 => 'bar']
2897
     * </code>
2898
     *
2899
     * @param int|null $number <p>How many values you will take?</p>
2900
     *
2901
     * @return static
2902
     *                <p>(Immutable)</p>
2903
     *
2904
     * @phpstan-return static
2905
     * @psalm-mutation-free
2906
     */
2907
    public function firstsImmutable(?int $number = null): self
2908
    {
2909
        $arrayTmp = $this->toArray();
111 ✔
2910

2911
        if ($number === null) {
111 ✔
2912
            $array = (array) \array_shift($arrayTmp);
42 ✔
2913
        } else {
2914
            $array = \array_splice($arrayTmp, 0, $number);
69 ✔
2915
        }
2916

2917
        return static::create(
111 ✔
2918
            $array, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
111 ✔
2919
            $this->iteratorClass,
111 ✔
2920
            false
111 ✔
2921
        );
111 ✔
2922
    }
2923

2924
    /**
2925
     * Get the first value(s) from the current array.
2926
     * And will return an empty array if there was no first entry.
2927
     *
2928
     * @param int|null $number <p>How many values you will take?</p>
2929
     *
2930
     * @return static
2931
     *                <p>(Immutable)</p>
2932
     *
2933
     * @phpstan-return static
2934
     * @psalm-mutation-free
2935
     */
2936
    public function firstsKeys(?int $number = null): self
2937
    {
2938
        $arrayTmp = $this->keys()->toArray();
9 ✔
2939

2940
        if ($number === null) {
9 ✔
2941
            $array = (array) \array_shift($arrayTmp);
×
2942
        } else {
2943
            $array = \array_splice($arrayTmp, 0, $number);
9 ✔
2944
        }
2945

2946
        return static::create(
9 ✔
2947
            $array, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
9 ✔
2948
            $this->iteratorClass,
9 ✔
2949
            false
9 ✔
2950
        );
9 ✔
2951
    }
2952

2953
    /**
2954
     * Get and remove the first value(s) from the current array.
2955
     * And will return an empty array if there was no first entry.
2956
     *
2957
     * EXAMPLE: <code>
2958
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->firstsMutable(); // 'foo'
2959
     * </code>
2960
     *
2961
     * @param int|null $number <p>How many values you will take?</p>
2962
     *
2963
     * @return $this
2964
     *               <p>(Mutable)</p>
2965
     *
2966
     * @phpstan-return ($number is null ? static : static)
2967
     */
2968
    public function firstsMutable(?int $number = null): self
2969
    {
2970
        $this->generatorToArray();
102 ✔
2971

2972
        if ($number === null) {
102 ✔
2973
            $shift = \array_shift($this->array);
57 ✔
2974
            /* @phpstan-ignore assign.propertyType */
2975
            $this->array = $shift !== null ? [$shift] : [];
57 ✔
2976
        } else {
2977
            $splice = \array_splice($this->array, 0, $number);
45 ✔
2978
            $this->array = $splice;
45 ✔
2979
        }
2980

2981
        return $this;
102 ✔
2982
    }
2983

2984
    /**
2985
     * Exchanges all keys with their associated values in an array.
2986
     *
2987
     * EXAMPLE: <code>
2988
     * a([0 => 'foo', 1 => 'bar'])->flip(); // Arrayy['foo' => 0, 'bar' => 1]
2989
     * </code>
2990
     *
2991
     * @return static
2992
     *                <p>(Immutable)</p>
2993
     *
2994
     * @phpstan-return static
2995
     * @psalm-mutation-free
2996
     */
2997
    public function flip(): self
2998
    {
2999
        $generator = function (): \Generator {
3 ✔
3000
            foreach ($this->getGenerator() as $key => $value) {
3 ✔
3001
                yield (string) $value => $key;
3 ✔
3002
            }
3003
        };
3 ✔
3004

3005
        return static::create(
3 ✔
3006
            $generator,
3 ✔
3007
            $this->iteratorClass,
3 ✔
3008
            false
3 ✔
3009
        );
3 ✔
3010
    }
3011

3012
    /**
3013
     * Get a value from an array (optional using dot-notation).
3014
     *
3015
     * EXAMPLE: <code>
3016
     * $arrayy = a(['user' => ['lastname' => 'Moelleken']]);
3017
     * $arrayy->get('user.lastname'); // 'Moelleken'
3018
     * // ---
3019
     * $arrayy = new A();
3020
     * $arrayy['user'] = ['lastname' => 'Moelleken'];
3021
     * $arrayy['user.firstname'] = 'Lars';
3022
     * $arrayy['user']['lastname']; // Moelleken
3023
     * $arrayy['user.lastname']; // Moelleken
3024
     * $arrayy['user.firstname']; // Lars
3025
     * </code>
3026
     *
3027
     * @param int|string $key
3028
     *                                   <p>The key to look for.</p>
3029
     * @param mixed      $fallback
3030
     *                                   <p>Value to fallback to.</p>
3031
     * @param array|null $array
3032
     *                                   <p>The array to get from, if it's set to "null" we use the current array from the
3033
     *                                   class.</p>
3034
     * @param bool       $useByReference
3035
     *
3036
     * @return mixed|static
3037
     *
3038
     * @phpstan-param TKey $key
3039
     * @phpstan-param array<array-key,mixed>|array<TKey,T> $array
3040
     * @psalm-mutation-free
3041
     */
3042
    public function get(
3043
        $key = null,
3044
        $fallback = null,
3045
        ?array $array = null,
3046
        bool $useByReference = false
3047
    ) {
3048
        if ($array === null && $key === null) {
867 ✔
3049
            if ($useByReference) {
3 ✔
3050
                return $this;
×
3051
            }
3052

3053
            return clone $this;
3 ✔
3054
        }
3055

3056
        if ($array !== null) {
867 ✔
3057
            if ($useByReference) {
12 ✔
3058
                $usedArray = &$array;
×
3059
            } else {
3060
                $usedArray = $array;
12 ✔
3061
            }
3062
        } else {
3063
            $this->generatorToArray();
858 ✔
3064

3065
            if ($useByReference) {
858 ✔
3066
                $usedArray = &$this->array;
513 ✔
3067
            } else {
3068
                $usedArray = $this->array;
407 ✔
3069
            }
3070
        }
3071

3072
        if ($key === null) {
867 ✔
3073
            return static::create(
3 ✔
3074
                [], // @phpstan-ignore-line argument.type (an empty late-static instance cannot satisfy every possible invariant TData shape)
3 ✔
3075
                $this->iteratorClass,
3 ✔
3076
                false
3 ✔
3077
            )->createByReference($usedArray);
3 ✔
3078
        }
3079

3080
        // php cast "bool"-index into "int"-index
3081
        /* @phpstan-ignore identical.alwaysFalse */
3082
        if ((bool) $key === $key) {
867 ✔
3083
            $key = (int) $key;
×
3084
        }
3085

3086
        if (\array_key_exists($key, $usedArray) === true) {
867 ✔
3087
            if (\is_array($usedArray[$key])) {
750 ✔
3088
                return static::create(
62 ✔
3089
                    [], // @phpstan-ignore-line argument.type (an empty late-static instance cannot satisfy every possible invariant TData shape)
62 ✔
3090
                    $this->iteratorClass,
62 ✔
3091
                    false
62 ✔
3092
                )->createByReference($usedArray[$key]);
62 ✔
3093
            }
3094

3095
            return $usedArray[$key];
699 ✔
3096
        }
3097

3098
        // crawl through array, get key according to object or not
3099
        $usePath = false;
195 ✔
3100
        if (
3101
            $this->pathSeparator
195 ✔
3102
            &&
3103
            (string) $key === $key
195 ✔
3104
            &&
3105
            \strpos($key, $this->pathSeparator) !== false
195 ✔
3106
        ) {
3107
            $segments = \explode($this->pathSeparator, (string) $key);
105 ✔
3108
            $usePath = true;
105 ✔
3109
            $usedArrayTmp = $usedArray; // do not use the reference for dot-annotations
105 ✔
3110

3111
            foreach ($segments as $segment) {
105 ✔
3112
                if (
3113
                    (
3114
                        \is_array($usedArrayTmp)
105 ✔
3115
                        ||
105 ✔
3116
                        $usedArrayTmp instanceof \ArrayAccess
105 ✔
3117
                    )
3118
                    &&
3119
                    isset($usedArrayTmp[$segment])
105 ✔
3120
                ) {
3121
                    $usedArrayTmp = $usedArrayTmp[$segment];
102 ✔
3122

3123
                    continue;
102 ✔
3124
                }
3125

3126
                if (
3127
                    \is_object($usedArrayTmp) === true
45 ✔
3128
                    &&
3129
                    \property_exists($usedArrayTmp, $segment)
45 ✔
3130
                ) {
3131
                    $usedArrayTmp = $usedArrayTmp->{$segment};
3 ✔
3132

3133
                    continue;
3 ✔
3134
                }
3135

3136
                if ($segments[0] === '*') {
42 ✔
3137
                    $segmentsTmp = $segments;
3 ✔
3138
                    unset($segmentsTmp[0]);
3 ✔
3139
                    $keyTmp = \implode('.', $segmentsTmp);
3 ✔
3140
                    $returnTmp = static::create(
3 ✔
3141
                        [], // @phpstan-ignore-line argument.type (an empty late-static instance cannot satisfy every possible invariant TData shape)
3 ✔
3142
                        $this->iteratorClass,
3 ✔
3143
                        false
3 ✔
3144
                    );
3 ✔
3145
                    foreach ($this->getAll() as $dataTmp) {
3 ✔
3146
                        if ($dataTmp instanceof self) {
3 ✔
3147
                            $returnTmp->add($dataTmp->get($keyTmp));
×
3148

3149
                            continue;
×
3150
                        }
3151

3152
                        if (
3153
                            (
3154
                                \is_array($dataTmp)
3 ✔
3155
                                ||
3 ✔
3156
                                $dataTmp instanceof \ArrayAccess
3 ✔
3157
                            )
3158
                            &&
3159
                            isset($dataTmp[$keyTmp])
3 ✔
3160
                        ) {
3161
                            $returnTmp->add($dataTmp[$keyTmp]);
×
3162

3163
                            continue;
×
3164
                        }
3165

3166
                        if (
3167
                            \is_object($dataTmp) === true
3 ✔
3168
                            &&
3169
                            \property_exists($dataTmp, $keyTmp)
3 ✔
3170
                        ) {
3171
                            $returnTmp->add($dataTmp->{$keyTmp});
3 ✔
3172

3173
                            continue;
3 ✔
3174
                        }
3175
                    }
3176

3177
                    if ($returnTmp->count() > 0) {
3 ✔
3178
                        return $returnTmp;
3 ✔
3179
                    }
3180
                }
3181

3182
                return $fallback instanceof \Closure ? $fallback() : $fallback;
39 ✔
3183
            }
3184

3185
            if (\is_array($usedArrayTmp)) {
96 ✔
3186
                return static::create(
18 ✔
3187
                    [], // @phpstan-ignore-line argument.type (an empty late-static instance cannot satisfy every possible invariant TData shape)
18 ✔
3188
                    $this->iteratorClass,
18 ✔
3189
                    false
18 ✔
3190
                )->createByReference($usedArrayTmp);
18 ✔
3191
            }
3192

3193
            return $usedArrayTmp;
96 ✔
3194
        }
3195

3196
        if (!isset($usedArray[$key])) {
93 ✔
3197
            return $fallback instanceof \Closure ? $fallback() : $fallback;
93 ✔
3198
        }
3199

3200
        return static::create(
×
NEW
3201
            [], // @phpstan-ignore-line argument.type (an empty late-static instance cannot satisfy every possible invariant TData shape)
×
3202
            $this->iteratorClass,
×
3203
            false
×
3204
        )->createByReference($usedArray);
×
3205
    }
3206

3207
    /**
3208
     * alias: for "Arrayy->toArray()"
3209
     *
3210
     * @return array
3211
     *
3212
     * @see          Arrayy::getArray()
3213
     *
3214
     * @phpstan-return array<TKey,T>
3215
     */
3216
    public function getAll(): array
3217
    {
3218
        /** @var array<TKey,T> $return */
3219
        $return = $this->toArray();
45 ✔
3220

3221
        return $return;
45 ✔
3222
    }
3223

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

3254
    /**
3255
     * Create an instance from JSON using the built-in mapper.
3256
     *
3257
     * For Arrayy models with property checks enabled, phpdoc array-shape annotations,
3258
     * legacy `@property` definitions, and native declared properties are used for metadata and type checks.
3259
     * Add a property-level `@var` annotation if a native `array` property also needs
3260
     * element-type validation.
3261
     *
3262
     * @param string $json
3263
     *
3264
     * @return static
3265
     *                <p>(Immutable)</p>
3266
     */
3267
    public static function createFromJsonMapper(string $json)
3268
    {
3269
        // init
3270
        $class = static::create();
24 ✔
3271

3272
        $jsonObject = \json_decode($json, false);
24 ✔
3273

3274
        $mapper = new \Arrayy\Mapper\Json();
24 ✔
3275
        $mapper->undefinedPropertyHandler = static function ($object, $key, $jsonValue) use ($class) {
24 ✔
3276
            if ($class->checkPropertiesMismatchInConstructor) {
×
3277
                throw new \TypeError('Property mismatch - input: ' . \print_r(['key' => $key, 'jsonValue' => $jsonValue], true) . ' for object: ' . \get_class($object));
×
3278
            }
3279
        };
24 ✔
3280

3281
        /** @var static $return - hack for phpstan */
3282
        $return = $mapper->map($jsonObject, $class);
24 ✔
3283

3284
        return $return;
15 ✔
3285
    }
3286

3287
    /**
3288
     * @return array<array-key,TypeCheckInterface>|TypeCheckArray<array-key,TypeCheckInterface>
3289
     *
3290
     * @internal
3291
     */
3292
    public function getPhpDocPropertiesFromClass()
3293
    {
3294
        if ($this->properties === []) {
72 ✔
3295
            $this->properties = $this->getPropertiesFromPhpDoc();
42 ✔
3296
        }
3297

3298
        return $this->properties;
72 ✔
3299
    }
3300

3301
    /**
3302
     * Get the current array from the "Arrayy"-object as list.
3303
     *
3304
     * alias for "toList()"
3305
     *
3306
     * @param bool $convertAllArrayyElements <p>
3307
     *                                       Convert all Child-"Arrayy" objects also to arrays.
3308
     *                                       </p>
3309
     *
3310
     * @return array
3311
     *
3312
     * @phpstan-return list<T>
3313
     * @psalm-mutation-free
3314
     *
3315
     * @see Arrayy::toList()
3316
     */
3317
    public function getList(bool $convertAllArrayyElements = false): array
3318
    {
3319
        return $this->toList($convertAllArrayyElements);
3 ✔
3320
    }
3321

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

3358
                    if ($indexKey !== null) {
3 ✔
3359
                        foreach ($value as $keyInner => $valueInner) {
3 ✔
3360
                            if ($indexKey === $keyInner) {
3 ✔
3361
                                $newKey = $valueInner;
3 ✔
3362
                            }
3363

3364
                            if ($columnKey === $keyInner) {
3 ✔
3365
                                $newValue = $valueInner;
3 ✔
3366
                                $newValueFound = true;
3 ✔
3367
                            }
3368
                        }
3369
                    } else {
3370
                        foreach ($value as $keyInner => $valueInner) {
3 ✔
3371
                            if ($columnKey === $keyInner) {
3 ✔
3372
                                $newValue = $valueInner;
3 ✔
3373
                                $newValueFound = true;
3 ✔
3374
                            }
3375
                        }
3376
                    }
3377

3378
                    if ($newValueFound === false) {
3 ✔
3379
                        if ($newKey !== null) {
3 ✔
3380
                            yield $newKey => $value;
3 ✔
3381
                        } else {
3382
                            yield $value;
3 ✔
3383
                        }
3384
                    } else {
3385
                        /** @noinspection NestedPositiveIfStatementsInspection */
3386
                        if ($newKey !== null) {
3 ✔
3387
                            yield $newKey => $newValue;
3 ✔
3388
                        } else {
3389
                            yield $newValue;
3 ✔
3390
                        }
3391
                    }
3392
                }
3393
            };
3 ✔
3394
        }
3395

3396
        return static::create(
3 ✔
3397
            $generator,
3 ✔
3398
            $this->iteratorClass,
3 ✔
3399
            false
3 ✔
3400
        );
3 ✔
3401
    }
3402

3403
    /**
3404
     * Get the current array from the "Arrayy"-object as generator by reference.
3405
     *
3406
     * @return \Generator
3407
     *
3408
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3409
     */
3410
    public function &getGeneratorByReference(): \Generator
3411
    {
3412
        if ($this->generator instanceof ArrayyRewindableGenerator) {
258 ✔
3413
            foreach ($this->generator as $key => $value) {
51 ✔
3414
                yield $key => $value;
51 ✔
3415
            }
3416

3417
            return;
15 ✔
3418
        }
3419

3420
        // -> false-positive -> see "&$value"
3421
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3422
        foreach ($this->array as $key => &$value) {
210 ✔
3423
            yield $key => $value;
189 ✔
3424
        }
3425
    }
3426

3427
    /**
3428
     * Get the current array from the "Arrayy"-object as generator.
3429
     *
3430
     * @return \Generator
3431
     *
3432
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3433
     * @psalm-mutation-free
3434
     */
3435
    public function getGenerator(): \Generator
3436
    {
3437
        if ($this->generator instanceof ArrayyRewindableGenerator) {
3,411 ✔
3438
            yield from $this->generator;
240 ✔
3439

3440
            return;
240 ✔
3441
        }
3442

3443
        yield from $this->array;
3,405 ✔
3444
    }
3445

3446
    /**
3447
     * Get the current array from the "Arrayy"-object as generator.
3448
     *
3449
     * @return \Generator
3450
     *
3451
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3452
     * @psalm-mutation-free
3453
     */
3454
    public function getBackwardsGenerator(): \Generator
3455
    {
3456
        yield from $this->reverseKeepIndex();
12 ✔
3457
    }
3458

3459
    /**
3460
     * alias: for "Arrayy->keys()"
3461
     *
3462
     * @return static
3463
     *                <p>(Immutable)</p>
3464
     *
3465
     * @see          Arrayy::keys()
3466
     *
3467
     * @phpstan-return static
3468
     * @psalm-mutation-free
3469
     */
3470
    public function getKeys()
3471
    {
3472
        return $this->keys();
6 ✔
3473
    }
3474

3475
    /**
3476
     * Get the current array from the "Arrayy"-object as object.
3477
     *
3478
     * @return \stdClass
3479
     */
3480
    public function getObject(): \stdClass
3481
    {
3482
        return self::arrayToObject($this->toArray());
12 ✔
3483
    }
3484

3485
    /**
3486
     * alias: for "Arrayy->randomImmutable()"
3487
     *
3488
     * @return static
3489
     *                <p>(Immutable)</p>
3490
     *
3491
     * @see          Arrayy::randomImmutable()
3492
     *
3493
     * @phpstan-return static
3494
     */
3495
    public function getRandom(): self
3496
    {
3497
        return $this->randomImmutable();
12 ✔
3498
    }
3499

3500
    /**
3501
     * alias: for "Arrayy->randomKey()"
3502
     *
3503
     * @return mixed|null
3504
     *                    <p>Get a key/index or null if there wasn't a key/index.</p>
3505
     *
3506
     * @phpstan-return null|TKey
3507
     *
3508
     * @see Arrayy::randomKey()
3509
     */
3510
    public function getRandomKey()
3511
    {
3512
        return $this->randomKey();
9 ✔
3513
    }
3514

3515
    /**
3516
     * alias: for "Arrayy->randomKeys()"
3517
     *
3518
     * @param int $number
3519
     *
3520
     * @return static
3521
     *                <p>(Immutable)</p>
3522
     *
3523
     * @see          Arrayy::randomKeys()
3524
     *
3525
     * @phpstan-return static
3526
     */
3527
    public function getRandomKeys(int $number): self
3528
    {
3529
        return $this->randomKeys($number);
24 ✔
3530
    }
3531

3532
    /**
3533
     * alias: for "Arrayy->randomValue()"
3534
     *
3535
     * @return mixed|null
3536
     *                    <p>Get a random value or null if there wasn't a value.</p>
3537
     *
3538
     * @phpstan-return null|T
3539
     *
3540
     * @see Arrayy::randomValue()
3541
     */
3542
    public function getRandomValue()
3543
    {
3544
        return $this->randomValue();
12 ✔
3545
    }
3546

3547
    /**
3548
     * alias: for "Arrayy->randomValues()"
3549
     *
3550
     * @param int $number
3551
     *
3552
     * @return static
3553
     *                <p>(Immutable)</p>
3554
     *
3555
     * @see          Arrayy::randomValues()
3556
     *
3557
     * @phpstan-return static
3558
     */
3559
    public function getRandomValues(int $number): self
3560
    {
3561
        return $this->randomValues($number);
21 ✔
3562
    }
3563

3564
    /**
3565
     * Gets all values.
3566
     *
3567
     * @return static
3568
     *                <p>The values of all elements in this array, in the order they
3569
     *                appear in the array.</p>
3570
     *
3571
     * @phpstan-return static
3572
     */
3573
    public function getValues()
3574
    {
3575
        $this->generatorToArray(false);
12 ✔
3576

3577
        return static::create(
12 ✔
3578
            \array_values($this->array), // @phpstan-ignore-line argument.type (the runtime conversion crosses from the receiver templates into a freshly constructed result shape)
12 ✔
3579
            $this->iteratorClass,
12 ✔
3580
            false
12 ✔
3581
        );
12 ✔
3582
    }
3583

3584
    /**
3585
     * Gets all values via Generator.
3586
     *
3587
     * @return \Generator
3588
     *                    <p>The values of all elements in this array, in the order they
3589
     *                    appear in the array as Generator.</p>
3590
     *
3591
     * @phpstan-return \Generator<TKey,T>
3592
     */
3593
    public function getValuesYield(): \Generator
3594
    {
3595
        yield from $this->getGenerator();
12 ✔
3596
    }
3597

3598
    /**
3599
     * Group values from a array according to the results of a closure.
3600
     *
3601
     * @param callable|int|string $grouper  <p>A callable function name.</p>
3602
     * @param bool                $saveKeys
3603
     *
3604
     * @return static
3605
     *                <p>(Immutable)</p>
3606
     *
3607
     * @phpstan-param \Closure(T,TKey):TKey|TKey $grouper
3608
     * @phpstan-return static
3609
     * @psalm-mutation-free
3610
     */
3611
    public function group($grouper, bool $saveKeys = false): self
3612
    {
3613
        // init
3614
        $result = [];
12 ✔
3615

3616
        // Iterate over values, group by property/results from closure.
3617
        foreach ($this->getGenerator() as $key => $value) {
12 ✔
3618
            if (\is_callable($grouper) === true) {
12 ✔
3619
                $groupKey = $grouper($value, $key);
9 ✔
3620
            } else {
3621
                $groupKey = $this->get($grouper);
3 ✔
3622
            }
3623

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

3626
            if ($groupKey instanceof self) {
12 ✔
3627
                $groupKey = $groupKey->toArray();
×
3628
            }
3629

3630
            if ($newValue instanceof self) {
12 ✔
3631
                $newValue = $newValue->toArray();
12 ✔
3632
            }
3633

3634
            // Add to result.
3635
            if ($groupKey !== null) {
12 ✔
3636
                $result[$groupKey] = $newValue;
9 ✔
3637

3638
                if ($saveKeys) {
9 ✔
3639
                    $result[$groupKey][$key] = $value;
6 ✔
3640
                } else {
3641
                    $result[$groupKey][] = $value;
3 ✔
3642
                }
3643
            }
3644
        }
3645

3646
        return static::create(
12 ✔
3647
            $result, // @phpstan-ignore-line argument.type (this transformation constructs a fresh result shape rather than preserving the receiver's invariant TData)
12 ✔
3648
            $this->iteratorClass,
12 ✔
3649
            false
12 ✔
3650
        );
12 ✔
3651
    }
3652

3653
    /**
3654
     * Check if an array has a given key.
3655
     *
3656
     * @param mixed $key
3657
     *
3658
     * @return bool
3659
     *
3660
     * @phpstan-param null|TKey|TKey[] $key
3661
     */
3662
    public function has($key): bool
3663
    {
3664
        static $UN_FOUND = null;
90 ✔
3665

3666
        if ($UN_FOUND === null) {
90 ✔
3667
            // Generate unique string to use as marker.
3668
            $UN_FOUND = 'arrayy--' . \uniqid('arrayy', true);
3 ✔
3669
        }
3670

3671
        if (\is_array($key)) {
90 ✔
3672
            if ($key === []) {
3 ✔
3673
                return false;
×
3674
            }
3675

3676
            foreach ($key as $keyTmp) {
3 ✔
3677
                $found = ($this->get($keyTmp, $UN_FOUND) !== $UN_FOUND);
3 ✔
3678
                if ($found === false) {
3 ✔
3679
                    return false;
3 ✔
3680
                }
3681
            }
3682

3683
            return true;
3 ✔
3684
        }
3685

3686
        return $this->get($key, $UN_FOUND) !== $UN_FOUND;
87 ✔
3687
    }
3688

3689
    /**
3690
     * Check if an array has a given value.
3691
     *
3692
     * INFO: If you need to search recursive please use ```contains($value, true)```.
3693
     *
3694
     * @param mixed $value
3695
     *
3696
     * @return bool
3697
     *
3698
     * @phpstan-param T $value
3699
     */
3700
    public function hasValue($value): bool
3701
    {
3702
        return $this->contains($value);
3 ✔
3703
    }
3704

3705
    /**
3706
     * Implodes the values of this array.
3707
     *
3708
     * EXAMPLE: <code>
3709
     * a([0 => -9, 1, 2])->implode('|'); // '-9|1|2'
3710
     * </code>
3711
     *
3712
     * @param string $glue
3713
     * @param string $prefix
3714
     *
3715
     * @return string
3716
     * @psalm-mutation-free
3717
     */
3718
    public function implode(string $glue = '', string $prefix = ''): string
3719
    {
3720
        return $prefix . $this->implode_recursive($glue, $this->toArray(), false);
87 ✔
3721
    }
3722

3723
    /**
3724
     * Implodes the keys of this array.
3725
     *
3726
     * @param string $glue
3727
     *
3728
     * @return string
3729
     * @psalm-mutation-free
3730
     */
3731
    public function implodeKeys(string $glue = ''): string
3732
    {
3733
        return $this->implode_recursive($glue, $this->toArray(), true);
24 ✔
3734
    }
3735

3736
    /**
3737
     * Given a list and an iterate-function that returns
3738
     * a key for each element in the list (or a property name),
3739
     * returns an object with an index of each item.
3740
     *
3741
     * @param int|string $key
3742
     *
3743
     * @return static
3744
     *                <p>(Immutable)</p>
3745
     *
3746
     * @phpstan-param array-key $key
3747
     * @phpstan-return static
3748
     * @psalm-mutation-free
3749
     */
3750
    public function indexBy($key): self
3751
    {
3752
        // init
3753
        $results = [];
12 ✔
3754

3755
        foreach ($this->getGenerator() as $a) {
12 ✔
3756
            if (\array_key_exists($key, $a) === true) {
12 ✔
3757
                $results[$a[$key]] = $a;
9 ✔
3758
            }
3759
        }
3760

3761
        return static::create(
12 ✔
3762
            $results, // @phpstan-ignore-line argument.type (indexBy() constructs a result shape that cannot be substituted for the receiver's invariant TData)
12 ✔
3763
            $this->iteratorClass,
12 ✔
3764
            false
12 ✔
3765
        );
12 ✔
3766
    }
3767

3768
    /**
3769
     * alias: for "Arrayy->searchIndex()"
3770
     *
3771
     * @param mixed $value
3772
     *                     <p>The value to search for.</p>
3773
     *
3774
     * @return false|int|string
3775
     *
3776
     * @phpstan-param T $value
3777
     * @phpstan-return false|TKey
3778
     *
3779
     * @see Arrayy::searchIndex()
3780
     */
3781
    public function indexOf($value)
3782
    {
3783
        return $this->searchIndex($value);
12 ✔
3784
    }
3785

3786
    /**
3787
     * Get everything but the last..$to items.
3788
     *
3789
     * EXAMPLE: <code>
3790
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->initial(2); // Arrayy[0 => 'foo']
3791
     * </code>
3792
     *
3793
     * @param int $to
3794
     *
3795
     * @return static
3796
     *                <p>(Immutable)</p>
3797
     *
3798
     * @phpstan-return static
3799
     * @psalm-mutation-free
3800
     */
3801
    public function initial(int $to = 1): self
3802
    {
3803
        return $this->firstsImmutable(\count($this->toArray(), \COUNT_NORMAL) - $to);
36 ✔
3804
    }
3805

3806
    /**
3807
     * Return an array with all elements found in input array.
3808
     *
3809
     * EXAMPLE: <code>
3810
     * a(['foo', 'bar'])->intersection(['bar', 'baz']); // Arrayy['bar']
3811
     * </code>
3812
     *
3813
     * @param array $search
3814
     * @param bool  $keepKeys
3815
     *
3816
     * @return static
3817
     *                <p>(Immutable)</p>
3818
     *
3819
     * @phpstan-param  array<TKey,T> $search
3820
     * @phpstan-return static
3821
     * @psalm-mutation-free
3822
     */
3823
    public function intersection(array $search, bool $keepKeys = false): self
3824
    {
3825
        if ($keepKeys) {
12 ✔
3826
            /**
3827
             * @psalm-suppress MissingClosureReturnType
3828
             * @psalm-suppress MissingClosureParamType
3829
             */
3830
            return static::create(
3 ✔
3831
                \array_uintersect( // @phpstan-ignore-line argument.type (intersection() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
3832
                    $this->toArray(),
3 ✔
3833
                    $search,
3 ✔
3834
                    static function ($a, $b) {
3 ✔
3835
                        return $a === $b ? 0 : -1;
3 ✔
3836
                    }
3 ✔
3837
                ),
3 ✔
3838
                $this->iteratorClass,
3 ✔
3839
                false
3 ✔
3840
            );
3 ✔
3841
        }
3842

3843
        return static::create(
9 ✔
3844
            \array_values(\array_intersect($this->toArray(), $search)), // @phpstan-ignore-line argument.type (intersection() constructs a result shape that cannot be substituted for the receiver's invariant TData)
9 ✔
3845
            $this->iteratorClass,
9 ✔
3846
            false
9 ✔
3847
        );
9 ✔
3848
    }
3849

3850
    /**
3851
     * Return an array with all elements found in input array.
3852
     *
3853
     * @param array ...$array
3854
     *
3855
     * @return static
3856
     *                <p>(Immutable)</p>
3857
     *
3858
     * @phpstan-param  array<array<TKey,T>> ...$array
3859
     * @phpstan-return static
3860
     * @psalm-mutation-free
3861
     */
3862
    public function intersectionMulti(...$array): self
3863
    {
3864
        return static::create(
3 ✔
3865
            \array_values(\array_intersect($this->toArray(), ...$array)), // @phpstan-ignore-line argument.type (intersectionMulti() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
3866
            $this->iteratorClass,
3 ✔
3867
            false
3 ✔
3868
        );
3 ✔
3869
    }
3870

3871
    /**
3872
     * Return a boolean flag which indicates whether the two input arrays have any common elements.
3873
     *
3874
     * EXAMPLE: <code>
3875
     * a(['foo', 'bar'])->intersects(['fΓΆΓΆ', 'bΓ€r']); // false
3876
     * </code>
3877
     *
3878
     * @param array $search
3879
     *
3880
     * @return bool
3881
     *
3882
     * @phpstan-param array<TKey,T> $search
3883
     */
3884
    public function intersects(array $search): bool
3885
    {
3886
        return $this->intersection($search)->count() > 0;
3 ✔
3887
    }
3888

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

3913
        // If the callable has arguments, pass them.
3914
        if ($arguments) {
3 ✔
3915
            $array = \array_map($callable, $this->toArray(), $arguments);
3 ✔
3916
        } else {
3917
            $array = $this->map($callable);
3 ✔
3918
        }
3919

3920
        return static::create(
3 ✔
3921
            $array, // @phpstan-ignore-line argument.type (invoke() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
3922
            $this->iteratorClass,
3 ✔
3923
            false
3 ✔
3924
        );
3 ✔
3925
    }
3926

3927
    /**
3928
     * Check whether array is associative or not.
3929
     *
3930
     * EXAMPLE: <code>
3931
     * a(['foo' => 'bar', 2, 3])->isAssoc(); // true
3932
     * </code>
3933
     *
3934
     * @param bool $recursive
3935
     *
3936
     * @return bool
3937
     *              <p>Returns true if associative, false otherwise.</p>
3938
     */
3939
    public function isAssoc(bool $recursive = false): bool
3940
    {
3941
        if ($this->isEmpty()) {
45 ✔
3942
            return false;
9 ✔
3943
        }
3944

3945
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3946
        foreach ($this->keys($recursive)->getGeneratorByReference() as &$key) {
39 ✔
3947
            if ((string) $key !== $key) {
39 ✔
3948
                return false;
33 ✔
3949
            }
3950
        }
3951

3952
        return true;
9 ✔
3953
    }
3954

3955
    /**
3956
     * Check if a given key or keys are empty.
3957
     *
3958
     * @param int|int[]|string|string[]|null $keys
3959
     *
3960
     * @return bool
3961
     *              <p>Returns true if empty, false otherwise.</p>
3962
     * @psalm-mutation-free
3963
     */
3964
    public function isEmpty($keys = null): bool
3965
    {
3966
        if ($this->generator) {
135 ✔
3967
            return $this->toArray() === [];
×
3968
        }
3969

3970
        if ($keys === null) {
135 ✔
3971
            return $this->array === [];
129 ✔
3972
        }
3973

3974
        foreach ((array) $keys as $key) {
6 ✔
3975
            if (!empty($this->get($key))) {
6 ✔
3976
                return false;
6 ✔
3977
            }
3978
        }
3979

3980
        return true;
6 ✔
3981
    }
3982

3983
    /**
3984
     * Check if the current array is equal to the given "$array" or not.
3985
     *
3986
     * EXAMPLE: <code>
3987
     * a(['πŸ’©'])->isEqual(['πŸ’©']); // true
3988
     * </code>
3989
     *
3990
     * @param array $array
3991
     *
3992
     * @return bool
3993
     *
3994
     * @phpstan-param array<TKey,T> $array
3995
     */
3996
    public function isEqual(array $array): bool
3997
    {
3998
        return $this->toArray() === $array;
3 ✔
3999
    }
4000

4001
    /**
4002
     * Check if the current array is a multi-array.
4003
     *
4004
     * EXAMPLE: <code>
4005
     * a(['foo' => [1, 2 , 3]])->isMultiArray(); // true
4006
     * </code>
4007
     *
4008
     * @return bool
4009
     */
4010
    public function isMultiArray(): bool
4011
    {
4012
        foreach ($this->getGenerator() as $value) {
66 ✔
4013
            if (\is_array($value)) {
60 ✔
4014
                return true;
15 ✔
4015
            }
4016
        }
4017

4018
        return false;
54 ✔
4019
    }
4020

4021
    /**
4022
     * Check whether array is numeric or not.
4023
     *
4024
     * @return bool
4025
     *              <p>Returns true if numeric, false otherwise.</p>
4026
     */
4027
    public function isNumeric(): bool
4028
    {
4029
        if ($this->isEmpty()) {
15 ✔
4030
            return false;
6 ✔
4031
        }
4032

4033
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4034
        foreach ($this->keys()->getGeneratorByReference() as &$key) {
12 ✔
4035
            if ((int) $key !== $key) {
12 ✔
4036
                return false;
6 ✔
4037
            }
4038
        }
4039

4040
        return true;
6 ✔
4041
    }
4042

4043
    /**
4044
     * Check if the current array is sequential [0, 1, 2, 3, 4, 5 ...] or not.
4045
     *
4046
     * EXAMPLE: <code>
4047
     * a([0 => 'foo', 1 => 'lall', 2 => 'foobar'])->isSequential(); // true
4048
     * </code>
4049
     *
4050
     * INFO: If the array is empty we count it as non-sequential.
4051
     *
4052
     * @param bool $recursive
4053
     *
4054
     * @return bool
4055
     * @psalm-mutation-free
4056
     */
4057
    public function isSequential(bool $recursive = false): bool
4058
    {
4059
        $i = 0;
30 ✔
4060
        foreach ($this->getGenerator() as $key => $value) {
30 ✔
4061
            if (
4062
                $recursive
27 ✔
4063
                &&
4064
                (\is_array($value) || $value instanceof \Traversable)
27 ✔
4065
                &&
4066
                self::create($value)->isSequential() === false // @phpstan-ignore-line argument.type (the nested iterable is normalized into a temporary Arrayy with an independent shape)
27 ✔
4067
            ) {
4068
                return false;
3 ✔
4069
            }
4070

4071
            if ($key !== $i) {
27 ✔
4072
                return false;
9 ✔
4073
            }
4074

4075
            ++$i;
24 ✔
4076
        }
4077

4078
        return !($i === 0);
27 ✔
4079
    }
4080

4081
    /**
4082
     * @return array
4083
     *
4084
     * @phpstan-return array<TKey,T>
4085
     */
4086
    public function jsonSerialize(): array
4087
    {
4088
        /** @var array<TKey,T> $return */
4089
        $return = $this->toArray();
6 ✔
4090

4091
        return $return;
6 ✔
4092
    }
4093

4094
    /**
4095
     * Gets the key/index of the element at the current internal iterator position.
4096
     *
4097
     * @return int|string|null
4098
     * @phpstan-return array-key|null
4099
     */
4100
    public function key()
4101
    {
4102
        if ($this->generator) {
×
4103
            return $this->generator->key();
×
4104
        }
4105

4106
        return \key($this->array);
×
4107
    }
4108

4109
    /**
4110
     * Checks if the given key exists in the provided array.
4111
     *
4112
     * INFO: This method only use "array_key_exists()" if you want to use "dot"-notation,
4113
     *       then you need to use "Arrayy->offsetExists()".
4114
     *
4115
     * @param int|string $key the key to look for
4116
     *
4117
     * @return bool
4118
     * @psalm-mutation-free
4119
     */
4120
    public function keyExists($key): bool
4121
    {
4122
        foreach ($this->getGenerator() as $keyTmp => $value) {
633 ✔
4123
            if ($key === $keyTmp) {
618 ✔
4124
                return true;
570 ✔
4125
            }
4126
        }
4127

4128
        return false;
447 ✔
4129
    }
4130

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

4166
        if ($recursive === true) {
90 ✔
4167
            $array = $this->array_keys_recursive(
12 ✔
4168
                null,
12 ✔
4169
                $search_values,
12 ✔
4170
                $strict
12 ✔
4171
            );
12 ✔
4172

4173
            return static::create(
12 ✔
4174
                $array, // @phpstan-ignore-line argument.type (keys() constructs a result shape that cannot be substituted for the receiver's invariant TData)
12 ✔
4175
                $this->iteratorClass,
12 ✔
4176
                false
12 ✔
4177
            );
12 ✔
4178
        }
4179

4180
        // non recursive
4181

4182
        if ($search_values === null) {
87 ✔
4183
            $arrayFunction = function (): \Generator {
87 ✔
4184
                foreach ($this->getGenerator() as $key => $value) {
87 ✔
4185
                    yield $key;
81 ✔
4186
                }
4187
            };
87 ✔
4188
        } else {
4189
            $arrayFunction = function () use ($search_values, $strict): \Generator {
3 ✔
4190
                $is_array_tmp = \is_array($search_values);
3 ✔
4191

4192
                /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4193
                foreach ($this->getGeneratorByReference() as $key => &$value) {
3 ✔
4194
                    if (
4195
                        (
4196
                            $is_array_tmp === false
3 ✔
4197
                            &&
3 ✔
4198
                            $strict === true
3 ✔
4199
                            &&
3 ✔
4200
                            $search_values === $value
3 ✔
4201
                        )
4202
                        ||
4203
                        (
4204
                            $is_array_tmp === false
3 ✔
4205
                            &&
3 ✔
4206
                            $strict === false
3 ✔
4207
                            &&
3 ✔
4208
                            $search_values == $value
3 ✔
4209
                        )
4210
                        ||
4211
                        (
4212
                            $is_array_tmp === true
3 ✔
4213
                            &&
3 ✔
4214
                            \in_array($value, $search_values, $strict)
3 ✔
4215
                        )
4216
                    ) {
4217
                        yield $key;
3 ✔
4218
                    }
4219
                }
4220
            };
3 ✔
4221
        }
4222

4223
        return static::create(
87 ✔
4224
            $arrayFunction,
87 ✔
4225
            $this->iteratorClass,
87 ✔
4226
            false
87 ✔
4227
        );
87 ✔
4228
    }
4229

4230
    /**
4231
     * Sort an array by key in reverse order.
4232
     *
4233
     * @param int $sort_flags [optional] <p>
4234
     *                        You may modify the behavior of the sort using the optional
4235
     *                        parameter sort_flags, for details
4236
     *                        see sort.
4237
     *                        </p>
4238
     *
4239
     * @return $this
4240
     *               <p>(Mutable) Return this Arrayy object.</p>
4241
     *
4242
     * @phpstan-return static
4243
     */
4244
    public function krsort(int $sort_flags = 0): self
4245
    {
4246
        $this->generatorToArray();
12 ✔
4247

4248
        \krsort($this->array, $sort_flags);
12 ✔
4249

4250
        return $this;
12 ✔
4251
    }
4252

4253
    /**
4254
     * Sort an array by key in reverse order.
4255
     *
4256
     * @param int $sort_flags [optional] <p>
4257
     *                        You may modify the behavior of the sort using the optional
4258
     *                        parameter sort_flags, for details
4259
     *                        see sort.
4260
     *                        </p>
4261
     *
4262
     * @return $this
4263
     *               <p>(Immutable)</p>
4264
     *
4265
     * @phpstan-return static
4266
     * @psalm-mutation-free
4267
     */
4268
    public function krsortImmutable(int $sort_flags = 0): self
4269
    {
4270
        $that = clone $this;
12 ✔
4271

4272
        /**
4273
         * @psalm-suppress ImpureMethodCall - object is already cloned
4274
         */
4275
        $that->krsort($sort_flags);
12 ✔
4276

4277
        return $that;
12 ✔
4278
    }
4279

4280
    /**
4281
     * Get the last value from the current array.
4282
     *
4283
     * EXAMPLE: <code>
4284
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->last(); // 'lall'
4285
     * </code>
4286
     *
4287
     * @return mixed|null
4288
     *                    <p>Return null if there wasn't a element.</p>
4289
     *
4290
     * @phpstan-return T|null
4291
     * @psalm-mutation-free
4292
     */
4293
    public function last()
4294
    {
4295
        $key_last = $this->lastKey();
51 ✔
4296
        if ($key_last === null) {
51 ✔
4297
            return null;
6 ✔
4298
        }
4299

4300
        /** @var T $value_last */
4301
        $value_last = $this->get($key_last);
45 ✔
4302

4303
        return $value_last;
45 ✔
4304
    }
4305

4306
    /**
4307
     * Get the last key from the current array.
4308
     *
4309
     * @return mixed|null
4310
     *                    <p>Return null if there wasn't a element.</p>
4311
     *
4312
     * @phpstan-return null|TKey
4313
     * @psalm-mutation-free
4314
     */
4315
    public function lastKey()
4316
    {
4317
        $this->generatorToArray();
63 ✔
4318

4319
        return \array_key_last($this->array);
63 ✔
4320
    }
4321

4322
    /**
4323
     * Get the last value(s) from the current array.
4324
     *
4325
     * EXAMPLE: <code>
4326
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->lasts(2); // Arrayy[0 => 'bar', 1 => 'lall']
4327
     * </code>
4328
     *
4329
     * @param int|null $number
4330
     *
4331
     * @return static
4332
     *                <p>(Immutable)</p>
4333
     *
4334
     * @phpstan-return static
4335
     * @psalm-mutation-free
4336
     */
4337
    public function lastsImmutable(?int $number = null): self
4338
    {
4339
        if ($this->isEmpty()) {
39 ✔
4340
            return static::create(
3 ✔
4341
                [], // @phpstan-ignore-line argument.type (lastsImmutable() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
4342
                $this->iteratorClass,
3 ✔
4343
                false
3 ✔
4344
            );
3 ✔
4345
        }
4346

4347
        if ($number === null) {
36 ✔
4348
            $poppedValue = $this->last();
24 ✔
4349

4350
            if ($poppedValue === null) {
24 ✔
4351
                $poppedValue = [$poppedValue];
3 ✔
4352
            } else {
4353
                $poppedValue = (array) $poppedValue;
21 ✔
4354
            }
4355

4356
            $arrayy = static::create(
24 ✔
4357
                $poppedValue, // @phpstan-ignore-line argument.type (lastsImmutable() constructs a result shape that cannot be substituted for the receiver's invariant TData)
24 ✔
4358
                $this->iteratorClass,
24 ✔
4359
                false
24 ✔
4360
            );
24 ✔
4361
        } else {
4362
            $arrayy = $this->rest(-$number);
12 ✔
4363
        }
4364

4365
        return $arrayy;
36 ✔
4366
    }
4367

4368
    /**
4369
     * Get the last value(s) from the current array.
4370
     *
4371
     * EXAMPLE: <code>
4372
     * a([2 => 'foo', 3 => 'bar', 4 => 'lall'])->lasts(2); // Arrayy[0 => 'bar', 1 => 'lall']
4373
     * </code>
4374
     *
4375
     * @param int|null $number
4376
     *
4377
     * @return $this
4378
     *               <p>(Mutable)</p>
4379
     *
4380
     * @phpstan-return static
4381
     */
4382
    public function lastsMutable(?int $number = null): self
4383
    {
4384
        if ($this->isEmpty()) {
39 ✔
4385
            return $this;
3 ✔
4386
        }
4387

4388
        $this->array = $this->lastsImmutable($number)->toArray();
36 ✔
4389
        $this->generator = null;
36 ✔
4390

4391
        return $this;
36 ✔
4392
    }
4393

4394
    /**
4395
     * Count the values from the current array.
4396
     *
4397
     * alias: for "Arrayy->count()"
4398
     *
4399
     * @param int $mode
4400
     *
4401
     * @return int
4402
     *
4403
     * @see Arrayy::count()
4404
     */
4405
    public function length(int $mode = \COUNT_NORMAL): int
4406
    {
4407
        return $this->count($mode);
60 ✔
4408
    }
4409

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

4442
        return static::create(
24 ✔
4443
            function () use ($useArguments, $callable, $useKeyAsSecondParameter, $arguments) {
24 ✔
4444
                foreach ($this->getGenerator() as $key => $value) {
24 ✔
4445
                    if ($useArguments) {
21 ✔
4446
                        if ($useKeyAsSecondParameter) {
9 ✔
4447
                            yield $key => $callable($value, $key, ...$arguments);
×
4448
                        } else {
4449
                            yield $key => $callable($value, ...$arguments);
9 ✔
4450
                        }
4451
                    } else {
4452
                        /** @noinspection NestedPositiveIfStatementsInspection */
4453
                        if ($useKeyAsSecondParameter) {
21 ✔
4454
                            yield $key => $callable($value, $key);
3 ✔
4455
                        } else {
4456
                            yield $key => $callable($value);
18 ✔
4457
                        }
4458
                    }
4459
                }
4460
            },
24 ✔
4461
            $this->iteratorClass,
24 ✔
4462
            false
24 ✔
4463
        );
24 ✔
4464
    }
4465

4466
    /**
4467
     * Check if all items in current array match a truth test.
4468
     *
4469
     * EXAMPLE: <code>
4470
     * $closure = function ($value, $key) {
4471
     *     return ($value % 2 === 0);
4472
     * };
4473
     * a([2, 4, 8])->matches($closure); // true
4474
     * </code>
4475
     *
4476
     * @param \Closure $closure
4477
     *
4478
     * @return bool
4479
     *
4480
     * @phpstan-param \Closure(T,TKey):bool $closure
4481
     */
4482
    public function matches(\Closure $closure): bool
4483
    {
4484
        if ($this->count() === 0) {
45 ✔
4485
            return false;
6 ✔
4486
        }
4487

4488
        foreach ($this->getGenerator() as $key => $value) {
39 ✔
4489
            $value = $closure($value, $key);
39 ✔
4490

4491
            if ($value === false) {
39 ✔
4492
                return false;
21 ✔
4493
            }
4494
        }
4495

4496
        return true;
21 ✔
4497
    }
4498

4499
    /**
4500
     * Check if any item in the current array matches a truth test.
4501
     *
4502
     * EXAMPLE: <code>
4503
     * $closure = function ($value, $key) {
4504
     *     return ($value % 2 === 0);
4505
     * };
4506
     * a([1, 4, 7])->matches($closure); // true
4507
     * </code>
4508
     *
4509
     * @param \Closure $closure
4510
     *
4511
     * @return bool
4512
     *
4513
     * @phpstan-param \Closure(T,TKey):bool $closure
4514
     */
4515
    public function matchesAny(\Closure $closure): bool
4516
    {
4517
        if ($this->count() === 0) {
42 ✔
4518
            return false;
6 ✔
4519
        }
4520

4521
        foreach ($this->getGenerator() as $key => $value) {
36 ✔
4522
            $value = $closure($value, $key);
36 ✔
4523

4524
            if ($value === true) {
36 ✔
4525
                return true;
27 ✔
4526
            }
4527
        }
4528

4529
        return false;
12 ✔
4530
    }
4531

4532
    /**
4533
     * Get the max value from an array.
4534
     *
4535
     * EXAMPLE: <code>
4536
     * a([-9, -8, -7, 1.32])->max(); // 1.32
4537
     * </code>
4538
     *
4539
     * @return false|float|int|string
4540
     *                                <p>Will return false if there are no values.</p>
4541
     */
4542
    public function max()
4543
    {
4544
        if ($this->count() === 0) {
33 ✔
4545
            return false;
3 ✔
4546
        }
4547

4548
        $max = false;
30 ✔
4549
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4550
        foreach ($this->getGeneratorByReference() as &$value) {
30 ✔
4551
            if (
4552
                $max === false
30 ✔
4553
                ||
4554
                $value > $max
30 ✔
4555
            ) {
4556
                $max = $value;
30 ✔
4557
            }
4558
        }
4559

4560
        return $max;
30 ✔
4561
    }
4562

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

4597
        return static::create(
99 ✔
4598
            $result, // @phpstan-ignore-line argument.type (mergeAppendKeepIndex() constructs a result shape that cannot be substituted for the receiver's invariant TData)
99 ✔
4599
            $this->iteratorClass,
99 ✔
4600
            false
99 ✔
4601
        );
99 ✔
4602
    }
4603

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

4639
        return static::create(
60 ✔
4640
            $result, // @phpstan-ignore-line argument.type (mergeAppendNewIndex() constructs a result shape that cannot be substituted for the receiver's invariant TData)
60 ✔
4641
            $this->iteratorClass,
60 ✔
4642
            false
60 ✔
4643
        );
60 ✔
4644
    }
4645

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

4680
        return static::create(
51 ✔
4681
            $result, // @phpstan-ignore-line argument.type (mergePrependKeepIndex() constructs a result shape that cannot be substituted for the receiver's invariant TData)
51 ✔
4682
            $this->iteratorClass,
51 ✔
4683
            false
51 ✔
4684
        );
51 ✔
4685
    }
4686

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

4722
        return static::create(
63 ✔
4723
            $result, // @phpstan-ignore-line argument.type (mergePrependNewIndex() constructs a result shape that cannot be substituted for the receiver's invariant TData)
63 ✔
4724
            $this->iteratorClass,
63 ✔
4725
            false
63 ✔
4726
        );
63 ✔
4727
    }
4728

4729
    /**
4730
     * Return a meta object with property names from phpdoc array-shape annotations,
4731
     * `@property` tags, and native declared properties.
4732
     *
4733
     * @return ArrayyMeta|mixed|static
4734
     */
4735
    public static function meta()
4736
    {
4737
        return (new ArrayyMeta())->getMetaObject(static::class);
129 ✔
4738
    }
4739

4740
    /**
4741
     * Get the min value from an array.
4742
     *
4743
     * EXAMPLE: <code>
4744
     * a([-9, -8, -7, 1.32])->min(); // -9
4745
     * </code>
4746
     *
4747
     * @return false|mixed
4748
     *                     <p>Will return false if there are no values.</p>
4749
     *
4750
     * @phpstan-return false|T
4751
     */
4752
    public function min()
4753
    {
4754
        if ($this->count() === 0) {
33 ✔
4755
            return false;
3 ✔
4756
        }
4757

4758
        $min = false;
30 ✔
4759
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4760
        foreach ($this->getGeneratorByReference() as &$value) {
30 ✔
4761
            if (
4762
                $min === false
30 ✔
4763
                ||
4764
                $value < $min
30 ✔
4765
            ) {
4766
                $min = $value;
30 ✔
4767
            }
4768
        }
4769

4770
        return $min;
30 ✔
4771
    }
4772

4773
    /**
4774
     * Get the most used value from the array.
4775
     *
4776
     * @return mixed|null
4777
     *                    <p>(Immutable) Return null if there wasn't an element.</p>
4778
     *
4779
     * @phpstan-return T|null
4780
     * @psalm-mutation-free
4781
     */
4782
    public function mostUsedValue()
4783
    {
4784
        return $this->countValues()->arsortImmutable()->firstKey(); // @phpstan-ignore return.type (countValues() changes the intermediate value type, while firstKey() restores the original value)
9 ✔
4785
    }
4786

4787
    /**
4788
     * Get the most used value from the array.
4789
     *
4790
     * @param int|null $number <p>How many values you will take?</p>
4791
     *
4792
     * @return static
4793
     *                <p>(Immutable)</p>
4794
     *
4795
     * @phpstan-return static
4796
     * @psalm-mutation-free
4797
     */
4798
    public function mostUsedValues(?int $number = null): self
4799
    {
4800
        return $this->countValues()->arsortImmutable()->firstsKeys($number);
9 ✔
4801
    }
4802

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

4824
        if ((int) $from === $from) {
3 ✔
4825
            $tmp = \array_splice($array, $from, 1);
3 ✔
4826
            \array_splice($array, (int) $to, 0, $tmp);
3 ✔
4827
            $output = $array;
3 ✔
4828
        } elseif ((string) $from === $from) {
3 ✔
4829
            $indexToMove = \array_search($from, \array_keys($array), true);
3 ✔
4830
            $itemToMove = $array[$from];
3 ✔
4831
            if ($indexToMove !== false) {
3 ✔
4832
                \array_splice($array, $indexToMove, 1);
3 ✔
4833
            }
4834
            $i = 0;
3 ✔
4835
            $output = [];
3 ✔
4836
            foreach ($array as $key => $item) {
3 ✔
4837
                if ($i === $to) {
3 ✔
4838
                    $output[$from] = $itemToMove;
3 ✔
4839
                }
4840
                $output[$key] = $item;
3 ✔
4841
                ++$i;
3 ✔
4842
            }
4843
        } else {
4844
            $output = [];
×
4845
        }
4846

4847
        return static::create(
3 ✔
4848
            $output, // @phpstan-ignore-line argument.type (moveElement() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
4849
            $this->iteratorClass,
3 ✔
4850
            false
3 ✔
4851
        );
3 ✔
4852
    }
4853

4854
    /**
4855
     * Move an array element to the first place.
4856
     *
4857
     * INFO: Instead of "Arrayy->moveElement()" this method will NOT
4858
     *       loss the keys of an indexed array.
4859
     *
4860
     * @param int|string $key
4861
     *
4862
     * @return static
4863
     *                <p>(Immutable)</p>
4864
     *
4865
     * @phpstan-return static
4866
     * @psalm-mutation-free
4867
     */
4868
    public function moveElementToFirstPlace($key): self
4869
    {
4870
        $array = $this->toArray();
3 ✔
4871

4872
        if ($this->offsetExists($key)) {
3 ✔
4873
            $tmpValue = $this->get($key);
3 ✔
4874
            unset($array[$key]);
3 ✔
4875
            $array = [$key => $tmpValue] + $array;
3 ✔
4876
        }
4877

4878
        return static::create(
3 ✔
4879
            $array, // @phpstan-ignore-line argument.type (moveElementToFirstPlace() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
4880
            $this->iteratorClass,
3 ✔
4881
            false
3 ✔
4882
        );
3 ✔
4883
    }
4884

4885
    /**
4886
     * Move an array element to the last place.
4887
     *
4888
     * INFO: Instead of "Arrayy->moveElement()" this method will NOT
4889
     *       loss the keys of an indexed array.
4890
     *
4891
     * @param int|string $key
4892
     *
4893
     * @return static
4894
     *                <p>(Immutable)</p>
4895
     *
4896
     * @phpstan-return static
4897
     * @psalm-mutation-free
4898
     */
4899
    public function moveElementToLastPlace($key): self
4900
    {
4901
        $array = $this->toArray();
3 ✔
4902

4903
        if ($this->offsetExists($key)) {
3 ✔
4904
            $tmpValue = $this->get($key);
3 ✔
4905
            unset($array[$key]);
3 ✔
4906
            $array += [$key => $tmpValue];
3 ✔
4907
        }
4908

4909
        return static::create(
3 ✔
4910
            $array, // @phpstan-ignore-line argument.type (moveElementToLastPlace() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
4911
            $this->iteratorClass,
3 ✔
4912
            false
3 ✔
4913
        );
3 ✔
4914
    }
4915

4916
    /**
4917
     * Moves the internal iterator position to the next element and returns this element.
4918
     *
4919
     * @return false|mixed
4920
     *                     <p>(Mutable) Will return false if there are no values.</p>
4921
     *
4922
     * @phpstan-return false|T
4923
     */
4924
    public function next()
4925
    {
4926
        if ($this->generator) {
×
4927
            $this->generator->next();
×
4928

4929
            return $this->generator->current() ?? false;
×
4930
        }
4931

4932
        return \next($this->array);
×
4933
    }
4934

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

4956
                yield $key => $value;
3 ✔
4957
            }
4958
        };
3 ✔
4959

4960
        return static::create(
3 ✔
4961
            $arrayFunction,
3 ✔
4962
            $this->iteratorClass,
3 ✔
4963
            false
3 ✔
4964
        );
3 ✔
4965
    }
4966

4967
    /**
4968
     * Get a subset of the items from the given array.
4969
     *
4970
     * @param int[]|string[] $keys
4971
     *
4972
     * @return static
4973
     *                <p>(Immutable)</p>
4974
     *
4975
     * @phpstan-param array-key[] $keys
4976
     * @phpstan-return static
4977
     * @psalm-mutation-free
4978
     */
4979
    public function only(array $keys): self
4980
    {
4981
        $keys = \array_flip($keys);
3 ✔
4982

4983
        $generator = function () use ($keys): \Generator {
3 ✔
4984
            foreach ($this->getGenerator() as $key => $value) {
3 ✔
4985
                if (isset($keys[$key])) {
3 ✔
4986
                    yield $key => $value;
3 ✔
4987
                }
4988
            }
4989
        };
3 ✔
4990

4991
        return static::create(
3 ✔
4992
            $generator,
3 ✔
4993
            $this->iteratorClass,
3 ✔
4994
            false
3 ✔
4995
        );
3 ✔
4996
    }
4997

4998
    /**
4999
     * Pad array to the specified size with a given value.
5000
     *
5001
     * @param int   $size  <p>Size of the result array.</p>
5002
     * @param mixed $value <p>Empty value by default.</p>
5003
     *
5004
     * @return static
5005
     *                <p>(Immutable) Arrayy object padded to $size with $value.</p>
5006
     *
5007
     * @phpstan-return static
5008
     * @psalm-mutation-free
5009
     */
5010
    public function pad(int $size, $value): self
5011
    {
5012
        return static::create(
15 ✔
5013
            \array_pad($this->toArray(), $size, $value), // @phpstan-ignore-line argument.type (pad() constructs a result shape that cannot be substituted for the receiver's invariant TData)
15 ✔
5014
            $this->iteratorClass,
15 ✔
5015
            false
15 ✔
5016
        );
15 ✔
5017
    }
5018

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

5040
        foreach ($this->getGenerator() as $key => $value) {
3 ✔
5041
            if ($closure($value, $key)) {
3 ✔
5042
                $matches[$key] = $value;
3 ✔
5043
            } else {
5044
                $noMatches[$key] = $value;
3 ✔
5045
            }
5046
        }
5047

5048
        return [self::create($matches), self::create($noMatches)]; // @phpstan-ignore-line argument.type (partition() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
5049
    }
5050

5051
    /**
5052
     * Pop a specified value off the end of the current array.
5053
     *
5054
     * @return mixed|null
5055
     *                    <p>(Mutable) The popped element from the current array or null if the array is e.g. empty.</p>
5056
     *
5057
     * @phpstan-return T|null
5058
     */
5059
    public function pop()
5060
    {
5061
        $this->generatorToArray();
15 ✔
5062

5063
        return \array_pop($this->array);
15 ✔
5064
    }
5065

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

5087
        if ($this->properties !== []) {
36 ✔
5088
            $this->checkType($key, $value);
12 ✔
5089
        }
5090

5091
        if ($key === null) {
30 ✔
5092
            \array_unshift($this->array, $value);
24 ✔
5093
        } else {
5094
            $this->array = [$key => $value] + $this->array; // @phpstan-ignore assign.propertyType
9 ✔
5095
        }
5096

5097
        return $this;
30 ✔
5098
    }
5099

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

5125
            if ($key !== null) {
3 ✔
5126
                yield $key => $value;
×
5127
            } else {
5128
                yield $value;
3 ✔
5129
            }
5130

5131
            foreach ($this->getGenerator() as $keyOld => $itemOld) {
3 ✔
5132
                yield $keyOld => $itemOld;
3 ✔
5133
            }
5134
        };
3 ✔
5135

5136
        return static::create(
3 ✔
5137
            $generator,
3 ✔
5138
            $this->iteratorClass,
3 ✔
5139
            false
3 ✔
5140
        );
3 ✔
5141
    }
5142

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

5159
        foreach ($this->getGenerator() as $key => $item) {
33 ✔
5160
            if ($item instanceof self) {
30 ✔
5161
                $result[$key] = $item->prependToEachKey($suffix);
3 ✔
5162
            } elseif (\is_array($item)) {
30 ✔
5163
                $result[$key] = self::create(
3 ✔
5164
                    $item, // @phpstan-ignore-line argument.type (prependToEachKey() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
5165
                    $this->iteratorClass,
3 ✔
5166
                    false
3 ✔
5167
                )->prependToEachKey($suffix)
3 ✔
5168
                    ->toArray();
3 ✔
5169
            } else {
5170
                $result[$key . $suffix] = $item;
30 ✔
5171
            }
5172
        }
5173

5174
        return self::create(
33 ✔
5175
            $result, // @phpstan-ignore-line argument.type (prependToEachKey() constructs a result shape that cannot be substituted for the receiver's invariant TData)
33 ✔
5176
            $this->iteratorClass,
33 ✔
5177
            false
33 ✔
5178
        );
33 ✔
5179
    }
5180

5181
    /**
5182
     * Add a suffix to each value.
5183
     *
5184
     * @param float|int|string $suffix
5185
     *
5186
     * @return static
5187
     *                <p>(Immutable) Return an Arrayy object, with the prepended values.</p>
5188
     *
5189
     * @phpstan-return static
5190
     * @psalm-mutation-free
5191
     */
5192
    public function prependToEachValue($suffix): self
5193
    {
5194
        // init
5195
        $result = [];
33 ✔
5196

5197
        foreach ($this->getGenerator() as $key => $item) {
33 ✔
5198
            if ($item instanceof self) {
30 ✔
5199
                $result[$key] = $item->prependToEachValue($suffix);
3 ✔
5200
            } elseif (\is_array($item)) {
30 ✔
5201
                $result[$key] = self::create(
3 ✔
5202
                    $item, // @phpstan-ignore-line argument.type (prependToEachValue() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
5203
                    $this->iteratorClass,
3 ✔
5204
                    false
3 ✔
5205
                )->prependToEachValue($suffix)
3 ✔
5206
                    ->toArray();
3 ✔
5207
            } elseif (\is_object($item) === true) {
30 ✔
5208
                $result[$key] = $item;
6 ✔
5209
            } else {
5210
                $result[$key] = $item . $suffix;
27 ✔
5211
            }
5212
        }
5213

5214
        return self::create(
33 ✔
5215
            $result, // @phpstan-ignore-line argument.type (prependToEachValue() constructs a result shape that cannot be substituted for the receiver's invariant TData)
33 ✔
5216
            $this->iteratorClass,
33 ✔
5217
            false
33 ✔
5218
        );
33 ✔
5219
    }
5220

5221
    /**
5222
     * Return the value of a given key and
5223
     * delete the key.
5224
     *
5225
     * @param int|int[]|string|string[]|null $keyOrKeys
5226
     * @param mixed                          $fallback
5227
     *
5228
     * @return mixed
5229
     *
5230
     * @template TFallback $fallback
5231
     * @phpstan-param TFallback $fallback
5232
     * @phpstan-return TFallback|T|T[]
5233
     */
5234
    public function pull($keyOrKeys = null, $fallback = null)
5235
    {
5236
        if ($keyOrKeys === null) {
18 ✔
5237
            $array = $this->toArray();
3 ✔
5238
            $this->clear();
3 ✔
5239

5240
            return $array;
3 ✔
5241
        }
5242

5243
        if (\is_array($keyOrKeys)) {
15 ✔
5244
            $valueOrValues = [];
3 ✔
5245
            foreach ($keyOrKeys as $key) {
3 ✔
5246
                $valueOrValues[] = $this->get($key, $fallback);
3 ✔
5247
                $this->offsetUnset($key);
3 ✔
5248
            }
5249
        } else {
5250
            $valueOrValues = $this->get($keyOrKeys, $fallback);
15 ✔
5251
            $this->offsetUnset($keyOrKeys);
15 ✔
5252
        }
5253

5254
        /** @var T|T[]|TFallback $valueOrValues */
5255
        return $valueOrValues;
15 ✔
5256
    }
5257

5258
    /**
5259
     * Push one or more values onto the end of array at once.
5260
     *
5261
     * @param mixed ...$args
5262
     *
5263
     * @return $this
5264
     *               <p>(Mutable) Return this Arrayy object, with pushed elements to the end of array.</p>
5265
     *
5266
     * @noinspection ReturnTypeCanBeDeclaredInspection
5267
     *
5268
     * @phpstan-param  array<TKey,T> ...$args
5269
     * @phpstan-return static
5270
     */
5271
    public function push(...$args)
5272
    {
5273
        $this->generatorToArray();
27 ✔
5274

5275
        if (
5276
            $this->checkPropertyTypes
27 ✔
5277
            &&
5278
            $this->properties !== []
27 ✔
5279
        ) {
5280
            foreach ($args as $key => $value) {
9 ✔
5281
                $this->checkType($key, $value);
9 ✔
5282
            }
5283
        }
5284

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

5287
        return $this;
24 ✔
5288
    }
5289

5290
    /**
5291
     * Get a random value from the current array.
5292
     *
5293
     * EXAMPLE: <code>
5294
     * a([1, 2, 3, 4])->randomImmutable(2); // e.g.: Arrayy[1, 4]
5295
     * </code>
5296
     *
5297
     * @param int|null $number <p>How many values you will take?</p>
5298
     *
5299
     * @return static
5300
     *                <p>(Immutable)</p>
5301
     *
5302
     * @phpstan-return static
5303
     */
5304
    public function randomImmutable(?int $number = null): self
5305
    {
5306
        $this->generatorToArray();
60 ✔
5307

5308
        if ($this->count() === 0) {
60 ✔
5309
            return static::create(
6 ✔
5310
                [], // @phpstan-ignore-line argument.type (randomImmutable() constructs a result shape that cannot be substituted for the receiver's invariant TData)
6 ✔
5311
                $this->iteratorClass,
6 ✔
5312
                false
6 ✔
5313
            );
6 ✔
5314
        }
5315

5316
        if ($number === null) {
54 ✔
5317
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
39 ✔
5318

5319
            return static::create(
39 ✔
5320
                $arrayRandValue, // @phpstan-ignore-line argument.type (randomImmutable() constructs a result shape that cannot be substituted for the receiver's invariant TData)
39 ✔
5321
                $this->iteratorClass,
39 ✔
5322
                false
39 ✔
5323
            );
39 ✔
5324
        }
5325

5326
        $arrayTmp = $this->array;
18 ✔
5327
        \shuffle($arrayTmp);
18 ✔
5328

5329
        return static::create(
18 ✔
5330
            $arrayTmp, // @phpstan-ignore-line argument.type (randomImmutable() constructs a result shape that cannot be substituted for the receiver's invariant TData)
18 ✔
5331
            $this->iteratorClass,
18 ✔
5332
            false
18 ✔
5333
        )->firstsImmutable($number);
18 ✔
5334
    }
5335

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

5355
        if (!isset($result[0])) {
12 ✔
5356
            $result[0] = null;
×
5357
        }
5358

5359
        return $result[0];
12 ✔
5360
    }
5361

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

5382
        $count = $this->count();
39 ✔
5383

5384
        if (
5385
            $number === 0
39 ✔
5386
            ||
5387
            $number > $count
39 ✔
5388
        ) {
5389
            throw new \RangeException(
6 ✔
5390
                \sprintf(
6 ✔
5391
                    'Number of requested keys (%s) must be equal or lower than number of elements in this array (%s)',
6 ✔
5392
                    $number,
6 ✔
5393
                    $count
6 ✔
5394
                )
6 ✔
5395
            );
6 ✔
5396
        }
5397

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

5400
        return static::create(
33 ✔
5401
            $result, // @phpstan-ignore-line argument.type (randomKeys() constructs a result shape that cannot be substituted for the receiver's invariant TData)
33 ✔
5402
            $this->iteratorClass,
33 ✔
5403
            false
33 ✔
5404
        );
33 ✔
5405
    }
5406

5407
    /**
5408
     * Get a random value from the current array.
5409
     *
5410
     * EXAMPLE: <code>
5411
     * a([1, 2, 3, 4])->randomMutable(2); // e.g.: Arrayy[1, 4]
5412
     * </code>
5413
     *
5414
     * @param int|null $number <p>How many values you will take?</p>
5415
     *
5416
     * @return $this
5417
     *               <p>(Mutable) Return this Arrayy object.</p>
5418
     *
5419
     * @phpstan-return static
5420
     */
5421
    public function randomMutable(?int $number = null): self
5422
    {
5423
        $this->generatorToArray();
57 ✔
5424

5425
        if ($this->count() === 0) {
57 ✔
5426
            return static::create(
6 ✔
5427
                [], // @phpstan-ignore-line argument.type (randomMutable() constructs a result shape that cannot be substituted for the receiver's invariant TData)
6 ✔
5428
                $this->iteratorClass,
6 ✔
5429
                false
6 ✔
5430
            );
6 ✔
5431
        }
5432

5433
        if ($number === null) {
51 ✔
5434
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
21 ✔
5435
            $this->array = $arrayRandValue; // @phpstan-ignore assign.propertyType
21 ✔
5436

5437
            return $this;
21 ✔
5438
        }
5439

5440
        \shuffle($this->array);
33 ✔
5441

5442
        return $this->firstsMutable($number);
33 ✔
5443
    }
5444

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

5461
        if (!isset($result[0])) {
15 ✔
5462
            $result[0] = null;
3 ✔
5463
        }
5464

5465
        return $result[0];
15 ✔
5466
    }
5467

5468
    /**
5469
     * Pick a given number of random values out of this array.
5470
     *
5471
     * EXAMPLE: <code>
5472
     * a([1 => 'one', 2 => 'two'])->randomValues(); // e.g. Arrayy['one', 'two']
5473
     * </code>
5474
     *
5475
     * @param int $number
5476
     *
5477
     * @return static
5478
     *                <p>(Mutable)</p>
5479
     *
5480
     * @phpstan-return static
5481
     */
5482
    public function randomValues(int $number): self
5483
    {
5484
        return $this->randomMutable($number);
24 ✔
5485
    }
5486

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

5508
        foreach ($array as $option => $weight) {
27 ✔
5509
            if ($this->searchIndex($option) !== false) {
27 ✔
5510
                for ($i = 0; $i < $weight; ++$i) {
6 ✔
5511
                    $options[] = $option;
3 ✔
5512
                }
5513
            }
5514
        }
5515

5516
        return $this->mergeAppendKeepIndex($options)->randomImmutable($number);
27 ✔
5517
    }
5518

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

5552
        /** @var static $return - help for phpstan */
5553
        $return = static::create(
54 ✔
5554
            $initial,
54 ✔
5555
            $this->iteratorClass,
54 ✔
5556
            false
54 ✔
5557
        );
54 ✔
5558

5559
        return $return;
54 ✔
5560
    }
5561

5562
    /**
5563
     * @param bool $unique
5564
     *
5565
     * @return static
5566
     *                <p>(Immutable)</p>
5567
     *
5568
     * @phpstan-return static
5569
     * @psalm-mutation-free
5570
     */
5571
    public function reduce_dimension(bool $unique = true): self
5572
    {
5573
        // init
5574
        $result = [];
42 ✔
5575

5576
        foreach ($this->getGenerator() as $val) {
42 ✔
5577
            if (\is_array($val)) {
36 ✔
5578
                $result[] = static::create($val)->reduce_dimension($unique)->toArray(); // @phpstan-ignore-line argument.type (reduce_dimension() constructs a result shape that cannot be substituted for the receiver's invariant TData)
15 ✔
5579
            } else {
5580
                $result[] = [$val];
36 ✔
5581
            }
5582
        }
5583

5584
        $result = $result === [] ? [] : \array_merge(...$result);
42 ✔
5585

5586
        $resultArrayy = static::create($result); // @phpstan-ignore-line argument.type (reduce_dimension() constructs a result shape that cannot be substituted for the receiver's invariant TData)
42 ✔
5587

5588
        /**
5589
         * @psalm-suppress ImpureMethodCall - object is already re-created
5590
         * @psalm-suppress InvalidReturnStatement - why?
5591
         */
5592
        return $unique ? $resultArrayy->unique() : $resultArrayy;
42 ✔
5593
    }
5594

5595
    /**
5596
     * Create a numerically re-indexed Arrayy object.
5597
     *
5598
     * EXAMPLE: <code>
5599
     * a([2 => 1, 3 => 2])->reindex(); // Arrayy[0 => 1, 1 => 2]
5600
     * </code>
5601
     *
5602
     * @return $this
5603
     *               <p>(Mutable) Return this Arrayy object, with re-indexed array-elements.</p>
5604
     *
5605
     * @phpstan-return static
5606
     */
5607
    public function reindex(): self
5608
    {
5609
        $this->generatorToArray(false);
27 ✔
5610

5611
        $this->array = \array_values($this->array);
27 ✔
5612

5613
        return $this;
27 ✔
5614
    }
5615

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

5640
        foreach ($this->getGenerator() as $key => $value) {
3 ✔
5641
            if (!$closure($value, $key)) {
3 ✔
5642
                $filtered[$key] = $value;
3 ✔
5643
            }
5644
        }
5645

5646
        return static::create(
3 ✔
5647
            $filtered, // @phpstan-ignore-line argument.type (reject() constructs a result shape that cannot be substituted for the receiver's invariant TData)
3 ✔
5648
            $this->iteratorClass,
3 ✔
5649
            false
3 ✔
5650
        );
3 ✔
5651
    }
5652

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

5676
            return static::create(
3 ✔
5677
                $this->toArray(), // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
5678
                $this->iteratorClass,
3 ✔
5679
                false
3 ✔
5680
            );
3 ✔
5681
        }
5682

5683
        $this->internalRemove($key);
69 ✔
5684

5685
        return static::create(
69 ✔
5686
            $this->toArray(), // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
69 ✔
5687
            $this->iteratorClass,
69 ✔
5688
            false
69 ✔
5689
        );
69 ✔
5690
    }
5691

5692
    /**
5693
     * alias: for "Arrayy->removeValue()"
5694
     *
5695
     * @param mixed $element
5696
     *
5697
     * @return static
5698
     *                <p>(Immutable)</p>
5699
     *
5700
     * @phpstan-param  T $element
5701
     * @phpstan-return static
5702
     * @psalm-mutation-free
5703
     */
5704
    public function removeElement($element)
5705
    {
5706
        return $this->removeValue($element);
24 ✔
5707
    }
5708

5709
    /**
5710
     * Remove the first value from the current array.
5711
     *
5712
     * EXAMPLE: <code>
5713
     * a([1 => 'bar', 'foo' => 'foo'])->removeFirst(); // Arrayy['foo' => 'foo']
5714
     * </code>
5715
     *
5716
     * @return static
5717
     *                <p>(Immutable)</p>
5718
     *
5719
     * @phpstan-return static
5720
     * @psalm-mutation-free
5721
     */
5722
    public function removeFirst(): self
5723
    {
5724
        $tmpArray = $this->toArray();
21 ✔
5725

5726
        \array_shift($tmpArray);
21 ✔
5727

5728
        return static::create(
21 ✔
5729
            $tmpArray, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
21 ✔
5730
            $this->iteratorClass,
21 ✔
5731
            false
21 ✔
5732
        );
21 ✔
5733
    }
5734

5735
    /**
5736
     * Remove the last value from the current array.
5737
     *
5738
     * EXAMPLE: <code>
5739
     * a([1 => 'bar', 'foo' => 'foo'])->removeLast(); // Arrayy[1 => 'bar']
5740
     * </code>
5741
     *
5742
     * @return static
5743
     *                <p>(Immutable)</p>
5744
     *
5745
     * @phpstan-return static
5746
     * @psalm-mutation-free
5747
     */
5748
    public function removeLast(): self
5749
    {
5750
        $tmpArray = $this->toArray();
21 ✔
5751

5752
        \array_pop($tmpArray);
21 ✔
5753

5754
        return static::create(
21 ✔
5755
            $tmpArray, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
21 ✔
5756
            $this->iteratorClass,
21 ✔
5757
            false
21 ✔
5758
        );
21 ✔
5759
    }
5760

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

5781
        // init
5782
        $isSequentialArray = $this->isSequential();
24 ✔
5783

5784
        foreach ($this->array as $key => $item) {
24 ✔
5785
            if ($item === $value) {
21 ✔
5786
                unset($this->array[$key]);
21 ✔
5787
            }
5788
        }
5789

5790
        if ($isSequentialArray) {
24 ✔
5791
            $this->array = \array_values($this->array);
18 ✔
5792
        }
5793

5794
        return static::create(
24 ✔
5795
            $this->array, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
24 ✔
5796
            $this->iteratorClass,
24 ✔
5797
            false
24 ✔
5798
        );
24 ✔
5799
    }
5800

5801
    /**
5802
     * Generate array of repeated arrays.
5803
     *
5804
     * @param int $times <p>How many times has to be repeated.</p>
5805
     *
5806
     * @return static
5807
     *                <p>(Immutable)</p>
5808
     *
5809
     * @phpstan-return static
5810
     * @psalm-mutation-free
5811
     */
5812
    public function repeat($times): self
5813
    {
5814
        if ($times === 0) {
3 ✔
5815
            return static::create([], $this->iteratorClass); // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
5816
        }
5817

5818
        return static::create(
3 ✔
5819
            \array_fill(0, (int) $times, $this->toArray()), // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
5820
            $this->iteratorClass,
3 ✔
5821
            false
3 ✔
5822
        );
3 ✔
5823
    }
5824

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

5850
        /**
5851
         * @psalm-suppress ImpureMethodCall - object is already cloned
5852
         */
5853
        return $that->remove($oldKey)
15 ✔
5854
            ->set($newKey, $newValue);
15 ✔
5855
    }
5856

5857
    /**
5858
     * Create an array using the current array as values and the other array as keys.
5859
     *
5860
     * EXAMPLE: <code>
5861
     * $firstArray = [
5862
     *     1 => 'one',
5863
     *     2 => 'two',
5864
     *     3 => 'three',
5865
     * ];
5866
     * $secondArray = [
5867
     *     'one' => 1,
5868
     *     1     => 'one',
5869
     *     2     => 2,
5870
     * ];
5871
     * $arrayy = a($firstArray);
5872
     * $arrayy->replaceAllKeys($secondArray); // Arrayy[1 => "one", 'one' => "two", 2 => "three"]
5873
     * </code>
5874
     *
5875
     * @param int[]|string[] $keys <p>An array of keys.</p>
5876
     *
5877
     * @return static
5878
     *                <p>(Immutable) Arrayy object with keys from the other array, empty Arrayy object if the number of elements
5879
     *                for each array isn't equal or if the arrays are empty.
5880
     *                </p>
5881
     *
5882
     * @phpstan-param  array<TKey> $keys
5883
     * @phpstan-return static
5884
     * @psalm-mutation-free
5885
     */
5886
    public function replaceAllKeys(array $keys): self
5887
    {
5888
        $values = $this->toArray();
9 ✔
5889
        $data = \count($keys) === \count($values) ? \array_combine($keys, $values) : [];
9 ✔
5890

5891
        return static::create(
9 ✔
5892
            $data, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
9 ✔
5893
            $this->iteratorClass,
9 ✔
5894
            false
9 ✔
5895
        );
9 ✔
5896
    }
5897

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

5932
        return static::create(
9 ✔
5933
            $data, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
9 ✔
5934
            $this->iteratorClass,
9 ✔
5935
            false
9 ✔
5936
        );
9 ✔
5937
    }
5938

5939
    /**
5940
     * Replace the keys in an array with another set.
5941
     *
5942
     * EXAMPLE: <code>
5943
     * a([1 => 'bar', 'foo' => 'foo'])->replaceKeys([1 => 2, 'foo' => 'replaced']); // Arrayy[2 => 'bar', 'replaced' => 'foo']
5944
     * </code>
5945
     *
5946
     * @param array $keys <p>An array of keys matching the array's size.</p>
5947
     *
5948
     * @return static
5949
     *                <p>(Immutable)</p>
5950
     *
5951
     * @phpstan-param  array<TKey> $keys
5952
     * @phpstan-return static
5953
     * @psalm-mutation-free
5954
     */
5955
    public function replaceKeys(array $keys): self
5956
    {
5957
        $values = \array_values($this->toArray());
6 ✔
5958
        $result = \count($keys) === \count($values) ? \array_combine($keys, $values) : [];
6 ✔
5959

5960
        return static::create(
6 ✔
5961
            $result, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
6 ✔
5962
            $this->iteratorClass,
6 ✔
5963
            false
6 ✔
5964
        );
6 ✔
5965
    }
5966

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

5991
        if ($key !== false) {
9 ✔
5992
            $array[$key] = $replacement;
9 ✔
5993
        }
5994

5995
        return static::create(
9 ✔
5996
            $array, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
9 ✔
5997
            $this->iteratorClass,
9 ✔
5998
            false
9 ✔
5999
        );
9 ✔
6000
    }
6001

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

6025
        return $this->each($callable); // @phpstan-ignore return.type (the replacement callback intentionally changes values while preserving the collection class)
3 ✔
6026
    }
6027

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

6047
        return static::create(
45 ✔
6048
            \array_splice($tmpArray, $from), // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
45 ✔
6049
            $this->iteratorClass,
45 ✔
6050
            false
45 ✔
6051
        );
45 ✔
6052
    }
6053

6054
    /**
6055
     * Return the array in the reverse order.
6056
     *
6057
     * EXAMPLE: <code>
6058
     * a([1 => 1, 2 => 2, 3 => 3])->reverse(); // self[3, 2, 1]
6059
     * </code>
6060
     *
6061
     * @return $this
6062
     *               <p>(Mutable) Return this Arrayy object.</p>
6063
     *
6064
     * @phpstan-return static
6065
     */
6066
    public function reverse(): self
6067
    {
6068
        $this->generatorToArray();
27 ✔
6069

6070
        $this->array = \array_reverse($this->array);
27 ✔
6071

6072
        return $this;
27 ✔
6073
    }
6074

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

6091
        $this->array = \array_reverse($this->array, true);
15 ✔
6092

6093
        return $this;
15 ✔
6094
    }
6095

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

6114
        \rsort($this->array, $sort_flags);
12 ✔
6115

6116
        return $this;
12 ✔
6117
    }
6118

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

6138
        /**
6139
         * @psalm-suppress ImpureMethodCall - object is already cloned
6140
         */
6141
        $that->rsort($sort_flags);
12 ✔
6142

6143
        return $that;
12 ✔
6144
    }
6145

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

6171
        return false;
33 ✔
6172
    }
6173

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

6194
        // init
6195
        $return = [];
30 ✔
6196

6197
        if ($this->array === []) {
30 ✔
6198
            return static::create(
3 ✔
6199
                [], // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
6200
                $this->iteratorClass,
3 ✔
6201
                false
3 ✔
6202
            );
3 ✔
6203
        }
6204

6205
        // php cast "bool"-index into "int"-index
6206
        /* @phpstan-ignore identical.alwaysFalse */
6207
        if ((bool) $index === $index) {
27 ✔
6208
            $index = (int) $index;
3 ✔
6209
        }
6210

6211
        if ($this->offsetExists($index)) {
27 ✔
6212
            $return = [$this->array[$index]];
21 ✔
6213
        }
6214

6215
        return static::create(
27 ✔
6216
            $return, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
27 ✔
6217
            $this->iteratorClass,
27 ✔
6218
            false
27 ✔
6219
        );
27 ✔
6220
    }
6221

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

6244
        return $this;
87 ✔
6245
    }
6246

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

6271
        // If the key doesn't exist, set it.
6272
        if (!$this->has($key)) {
33 ✔
6273
            $this->array = $this->set($key, $fallback)->toArray();
12 ✔
6274
        }
6275

6276
        return $this->get($key);
33 ✔
6277
    }
6278

6279
    /**
6280
     * Shifts a specified value off the beginning of array.
6281
     *
6282
     * @return mixed|null
6283
     *                    <p>(Mutable) A shifted element from the current array.</p>
6284
     *
6285
     * @phpstan-return T|null
6286
     */
6287
    public function shift()
6288
    {
6289
        $this->generatorToArray();
15 ✔
6290

6291
        return \array_shift($this->array);
15 ✔
6292
    }
6293

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

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

6336
        foreach ($array as $key => $value) {
6 ✔
6337
            // check if recursive is needed
6338
            if (\is_array($value)) {
6 ✔
6339
                /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
6340
                /** @phpstan-var array<TKey,T> $value */
6341
                $value = $value;
×
6342

6343
                $array[$key] = $this->shuffle($secure, $value);
×
6344
            }
6345
        }
6346

6347
        return static::create(
6 ✔
6348
            $array, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
6 ✔
6349
            $this->iteratorClass,
6 ✔
6350
            false
6 ✔
6351
        );
6 ✔
6352
    }
6353

6354
    /**
6355
     * Count the values from the current array.
6356
     *
6357
     * alias: for "Arrayy->count()"
6358
     *
6359
     * @param int $mode
6360
     *
6361
     * @return int
6362
     */
6363
    public function size(int $mode = \COUNT_NORMAL): int
6364
    {
6365
        return $this->count($mode);
60 ✔
6366
    }
6367

6368
    /**
6369
     * Checks whether array has exactly $size items.
6370
     *
6371
     * @param int $size
6372
     *
6373
     * @return bool
6374
     */
6375
    public function sizeIs(int $size): bool
6376
    {
6377
        // init
6378
        $itemsTempCount = 0;
3 ✔
6379

6380
        /** @noinspection PhpUnusedLocalVariableInspection */
6381
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
6382
        foreach ($this->getGeneratorByReference() as &$value) {
3 ✔
6383
            ++$itemsTempCount;
3 ✔
6384
            if ($itemsTempCount > $size) {
3 ✔
6385
                return false;
3 ✔
6386
            }
6387
        }
6388

6389
        return $itemsTempCount === $size;
3 ✔
6390
    }
6391

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

6409
        // init
6410
        $itemsTempCount = 0;
3 ✔
6411

6412
        /** @noinspection PhpUnusedLocalVariableInspection */
6413
        foreach ($this->getGenerator() as $value) {
3 ✔
6414
            ++$itemsTempCount;
3 ✔
6415
            if ($itemsTempCount > $toSize) {
3 ✔
6416
                return false;
3 ✔
6417
            }
6418
        }
6419

6420
        return $fromSize < $itemsTempCount && $itemsTempCount < $toSize;
3 ✔
6421
    }
6422

6423
    /**
6424
     * Checks whether array has more than $size items.
6425
     *
6426
     * @param int $size
6427
     *
6428
     * @return bool
6429
     */
6430
    public function sizeIsGreaterThan(int $size): bool
6431
    {
6432
        // init
6433
        $itemsTempCount = 0;
3 ✔
6434

6435
        /** @noinspection PhpUnusedLocalVariableInspection */
6436
        foreach ($this->getGenerator() as $value) {
3 ✔
6437
            ++$itemsTempCount;
3 ✔
6438
            if ($itemsTempCount > $size) {
3 ✔
6439
                return true;
3 ✔
6440
            }
6441
        }
6442

6443
        return $itemsTempCount > $size;
3 ✔
6444
    }
6445

6446
    /**
6447
     * Checks whether array has less than $size items.
6448
     *
6449
     * @param int $size
6450
     *
6451
     * @return bool
6452
     */
6453
    public function sizeIsLessThan(int $size): bool
6454
    {
6455
        // init
6456
        $itemsTempCount = 0;
3 ✔
6457

6458
        /** @noinspection PhpUnusedLocalVariableInspection */
6459
        foreach ($this->getGenerator() as $value) {
3 ✔
6460
            ++$itemsTempCount;
3 ✔
6461
            if ($itemsTempCount > $size) {
3 ✔
6462
                return false;
3 ✔
6463
            }
6464
        }
6465

6466
        return $itemsTempCount < $size;
3 ✔
6467
    }
6468

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

6503
    /**
6504
     * Extract a slice of the array.
6505
     *
6506
     * @param int      $offset       <p>Slice begin index.</p>
6507
     * @param int|null $length       <p>Length of the slice.</p>
6508
     * @param bool     $preserveKeys <p>Whether array keys are preserved or no.</p>
6509
     *
6510
     * @return static
6511
     *                <p>(Immutable) A slice of the original array with length $length.</p>
6512
     *
6513
     * @phpstan-return static
6514
     * @psalm-mutation-free
6515
     */
6516
    public function slice(int $offset, ?int $length = null, bool $preserveKeys = false)
6517
    {
6518
        return static::create(
15 ✔
6519
            \array_slice( // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
15 ✔
6520
                $this->toArray(),
15 ✔
6521
                $offset,
15 ✔
6522
                $length,
15 ✔
6523
                $preserveKeys
15 ✔
6524
            ),
15 ✔
6525
            $this->iteratorClass,
15 ✔
6526
            false
15 ✔
6527
        );
15 ✔
6528
    }
6529

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

6556
        return $this->sorting(
60 ✔
6557
            $this->array,
60 ✔
6558
            $direction,
60 ✔
6559
            $strategy,
60 ✔
6560
            $keepKeys
60 ✔
6561
        );
60 ✔
6562
    }
6563

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

6584
        $that->generatorToArray();
36 ✔
6585

6586
        return $that->sorting(
36 ✔
6587
            $that->array,
36 ✔
6588
            $direction,
36 ✔
6589
            $strategy,
36 ✔
6590
            $keepKeys
36 ✔
6591
        );
36 ✔
6592
    }
6593

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

6619
        $this->sorterKeys($this->array, $direction, $strategy);
54 ✔
6620

6621
        return $this;
54 ✔
6622
    }
6623

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

6646
        /**
6647
         * @psalm-suppress ImpureMethodCall - object is already cloned
6648
         */
6649
        $that->sortKeys($direction, $strategy);
24 ✔
6650

6651
        return $that;
24 ✔
6652
    }
6653

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

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

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

6732
        // Transform all values into their results.
6733
        if ($sorter) {
3 ✔
6734
            $arrayy = static::create(
3 ✔
6735
                $array, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
6736
                $this->iteratorClass,
3 ✔
6737
                false
3 ✔
6738
            );
3 ✔
6739

6740
            /**
6741
             * @psalm-suppress MissingClosureReturnType
6742
             * @psalm-suppress MissingClosureParamType
6743
             */
6744
            $results = $arrayy->each(
3 ✔
6745
                static function ($value) use ($sorter) {
3 ✔
6746
                    if (\is_callable($sorter) === true) {
3 ✔
6747
                        return $sorter($value);
3 ✔
6748
                    }
6749

6750
                    return $sorter === $value;
3 ✔
6751
                }
3 ✔
6752
            );
3 ✔
6753

6754
            $results = $results->toArray();
3 ✔
6755
        } else {
6756
            $results = $array;
3 ✔
6757
        }
6758

6759
        // Sort by the results and replace by original values
6760
        \array_multisort($results, $direction, $strategy, $array);
3 ✔
6761

6762
        return static::create(
3 ✔
6763
            $array, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
6764
            $this->iteratorClass,
3 ✔
6765
            false
3 ✔
6766
        );
3 ✔
6767
    }
6768

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

6785
        \array_splice(
3 ✔
6786
            $tmpArray,
3 ✔
6787
            $offset,
3 ✔
6788
            $length ?? $this->count(),
3 ✔
6789
            $replacement
3 ✔
6790
        );
3 ✔
6791

6792
        return static::create(
3 ✔
6793
            $tmpArray, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
6794
            $this->iteratorClass,
3 ✔
6795
            false
3 ✔
6796
        );
3 ✔
6797
    }
6798

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

6824
                    if ($i % $numberOfPieces !== 0) {
3 ✔
6825
                        ++$i;
3 ✔
6826

6827
                        continue;
3 ✔
6828
                    }
6829

6830
                    yield $carry;
3 ✔
6831

6832
                    $carry = [];
3 ✔
6833
                    $i = 1;
3 ✔
6834
                }
6835

6836
                if ($carry !== []) {
3 ✔
6837
                    yield $carry;
3 ✔
6838
                }
6839
            };
3 ✔
6840
        } else {
6841
            $generator = function () use ($numberOfPieces) {
3 ✔
6842
                $carry = [];
3 ✔
6843
                $i = 1;
3 ✔
6844
                foreach ($this->getGenerator() as $value) {
3 ✔
6845
                    $carry[] = $value;
3 ✔
6846

6847
                    if ($i % $numberOfPieces !== 0) {
3 ✔
6848
                        ++$i;
3 ✔
6849

6850
                        continue;
3 ✔
6851
                    }
6852

6853
                    yield $carry;
3 ✔
6854

6855
                    $carry = [];
3 ✔
6856
                    $i = 1;
3 ✔
6857
                }
6858

6859
                if ($carry !== []) {
3 ✔
6860
                    yield $carry;
3 ✔
6861
                }
6862
            };
3 ✔
6863
        }
6864

6865
        return static::create(
3 ✔
6866
            $generator,
3 ✔
6867
            $this->iteratorClass,
3 ✔
6868
            false
3 ✔
6869
        );
3 ✔
6870
    }
6871

6872
    /**
6873
     * Strip all empty items from the current array.
6874
     *
6875
     * EXAMPLE: <code>
6876
     * a(['a' => 1, 'b' => ''])->stripEmpty(); // Arrayy[['a' => 1]]
6877
     * </code>
6878
     *
6879
     * @return static
6880
     *                <p>(Immutable)</p>
6881
     *
6882
     * @phpstan-return static
6883
     * @psalm-mutation-free
6884
     */
6885
    public function stripEmpty(): self
6886
    {
6887
        $generator = function () {
3 ✔
6888
            foreach ($this->getGenerator() as $key => $item) {
3 ✔
6889
                if ($item === null) {
3 ✔
6890
                    continue;
3 ✔
6891
                }
6892

6893
                if ((bool) \trim((string) $item)) {
3 ✔
6894
                    yield $key => $item;
3 ✔
6895
                }
6896
            }
6897
        };
3 ✔
6898

6899
        return static::create(
3 ✔
6900
            $generator(),
3 ✔
6901
            $this->iteratorClass,
3 ✔
6902
            false
3 ✔
6903
        );
3 ✔
6904
    }
6905

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

6926
        list($array[$swapA], $array[$swapB]) = [$array[$swapB], $array[$swapA]];
3 ✔
6927

6928
        return static::create(
3 ✔
6929
            $array, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
6930
            $this->iteratorClass,
3 ✔
6931
            false
3 ✔
6932
        );
3 ✔
6933
    }
6934

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

6960
            foreach ($this->getGenerator() as $key => $value) {
12 ✔
6961
                if ($value instanceof self) {
12 ✔
6962
                    $value = $value->toArray(
9 ✔
6963
                        $convertAllArrayyElements,
9 ✔
6964
                        $preserveKeys
9 ✔
6965
                    );
9 ✔
6966
                }
6967

6968
                if ($preserveKeys) {
12 ✔
6969
                    $array[$key] = $value;
9 ✔
6970
                } else {
6971
                    $array[] = $value;
3 ✔
6972
                }
6973
            }
6974

6975
            return $array; // @phpstan-ignore return.type (recursive Arrayy conversion produces the documented runtime array shape)
12 ✔
6976
        }
6977

6978
        return \iterator_to_array($this->getGenerator(), $preserveKeys);
2,916 ✔
6979
    }
6980

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

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

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

7025
        return $return;
39 ✔
7026
    }
7027

7028
    /**
7029
     * @param string[]|null $items  [optional]
7030
     * @param string[]      $helper [optional]
7031
     *
7032
     * @return static|static[]
7033
     *
7034
     * @phpstan-return static
7035
     */
7036
    public function toPermutation(?array $items = null, array $helper = []): self
7037
    {
7038
        // init
7039
        $return = [];
3 ✔
7040

7041
        if ($items === null) {
3 ✔
7042
            $items = $this->toArray();
3 ✔
7043
        }
7044

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

7063
        /** @var static $return  - help for phpstan */
7064
        $return = static::create(
3 ✔
7065
            $return, // @phpstan-ignore-line argument.type (the runtime API intentionally accepts or transforms a value PHPStan cannot reconcile with the invariant template)
3 ✔
7066
            $this->iteratorClass,
3 ✔
7067
            false
3 ✔
7068
        );
3 ✔
7069

7070
        return $return;
3 ✔
7071
    }
7072

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

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

7102
        $this->array = $this->reduce(
39 ✔
7103
            static function ($resultArray, $value, $key) {
39 ✔
7104
                if (!\in_array($value, $resultArray, true)) {
36 ✔
7105
                    $resultArray[] = $value;
36 ✔
7106
                }
7107

7108
                return $resultArray;
36 ✔
7109
            },
39 ✔
7110
            []
39 ✔
7111
        )->toArray();
39 ✔
7112
        $this->generator = null;
39 ✔
7113

7114
        return $this;
39 ✔
7115
    }
7116

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

7133
        // init
7134
        $array = $this->toArray();
33 ✔
7135

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

7147
                return $resultArray;
30 ✔
7148
            },
33 ✔
7149
            []
33 ✔
7150
        );
33 ✔
7151
        $this->generator = null;
33 ✔
7152

7153
        return $this;
33 ✔
7154
    }
7155

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

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

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

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

7198
        return $this;
15 ✔
7199
    }
7200

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

7219
        return true;
3 ✔
7220
    }
7221

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

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

7286
        if ($this->array !== []) {
36 ✔
7287
            if ($recursive === true) {
30 ✔
7288
                if ($userData !== self::ARRAYY_HELPER_WALK) {
15 ✔
7289
                    \array_walk_recursive($this->array, $callable, $userData);
×
7290
                } else {
7291
                    \array_walk_recursive($this->array, $callable);
15 ✔
7292
                }
7293
            } else {
7294
                if ($userData !== self::ARRAYY_HELPER_WALK) {
15 ✔
7295
                    \array_walk($this->array, $callable, $userData);
×
7296
                } else {
7297
                    /* @phpstan-ignore argument.type */
7298
                    \array_walk($this->array, $callable);
15 ✔
7299
                }
7300
            }
7301
        }
7302

7303
        return $this;
36 ✔
7304
    }
7305

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

7329
                return $accessorValue === $value;
3 ✔
7330
            }
6 ✔
7331
        );
6 ✔
7332
    }
7333

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

7348
        if (\count($array, \COUNT_NORMAL) <= 0) {
12 ✔
7349
            return $object;
3 ✔
7350
        }
7351

7352
        foreach ($array as $name => $value) {
9 ✔
7353
            if (\is_array($value)) {
9 ✔
7354
                $object->{$name} = static::arrayToObject($value);
3 ✔
7355
            } else {
7356
                $object->{$name} = $value;
9 ✔
7357
            }
7358
        }
7359

7360
        return $object;
9 ✔
7361
    }
7362

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

7395
        if ($input === null) {
33 ✔
7396
            $input = $this->getGenerator();
12 ✔
7397
        }
7398

7399
        if ($search_values === null) {
33 ✔
7400
            foreach ($input as $key => $value) {
33 ✔
7401
                $keys[] = $key;
33 ✔
7402

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

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

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

7445
        return $keysTmp === [] ? $keys : \array_merge($keys, ...$keysTmp);
33 ✔
7446
    }
7447

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

7462
        if ($currentOffset === null) {
33 ✔
7463
            $currentOffset = &$this->array;
33 ✔
7464
        }
7465

7466
        $explodedPath = \explode($this->pathSeparator, $path);
33 ✔
7467

7468
        $nextPath = \array_shift($explodedPath);
33 ✔
7469
        if (!isset($currentOffset[$nextPath])) {
33 ✔
7470
            return;
3 ✔
7471
        }
7472

7473
        if ($explodedPath !== []) {
30 ✔
7474
            if (!\is_array($currentOffset[$nextPath])) {
3 ✔
NEW
7475
                return;
×
7476
            }
7477

7478
            $nestedOffset = &$currentOffset[$nextPath];
3 ✔
7479
            $this->callAtPath(
3 ✔
7480
                \implode($this->pathSeparator, $explodedPath),
3 ✔
7481
                $callable,
3 ✔
7482
                $nestedOffset
3 ✔
7483
            );
3 ✔
7484
        } else {
7485
            $callable($currentOffset[$nextPath]);
30 ✔
7486
        }
7487
    }
7488

7489
    /**
7490
     * Extracts the value of the given property or method from the object.
7491
     *
7492
     * @param array|object $object
7493
     *                                         <p>The object to extract the value from.</p>
7494
     * @param string    $keyOrPropertyOrMethod
7495
     *                                         <p>The property or method for which the
7496
     *                                         value should be extracted.</p>
7497
     *
7498
     * @throws \InvalidArgumentException if the method or property is not defined
7499
     *
7500
     * @return mixed
7501
     *               <p>The value extracted from the specified property or method.</p>
7502
     *
7503
     * @phpstan-param array<array-key,mixed>|object $object
7504
     */
7505
    final protected function extractValue($object, string $keyOrPropertyOrMethod)
7506
    {
7507
        if (\is_array($object)) {
6 ✔
7508
            if (\array_key_exists($keyOrPropertyOrMethod, $object)) {
3 ✔
7509
                return $object[$keyOrPropertyOrMethod];
3 ✔
7510
            }
7511
        } elseif ($object instanceof self && isset($object[$keyOrPropertyOrMethod])) {
6 ✔
7512
            $return = $object->get($keyOrPropertyOrMethod);
3 ✔
7513

7514
            if ($return instanceof self) {
3 ✔
7515
                return $return->toArray();
×
7516
            }
7517

7518
            return $return;
3 ✔
7519
        }
7520

7521
        if (\is_object($object) && \property_exists($object, $keyOrPropertyOrMethod)) {
3 ✔
7522
            return $object->{$keyOrPropertyOrMethod};
3 ✔
7523
        }
7524

NEW
7525
        if (\is_object($object) && \method_exists($object, $keyOrPropertyOrMethod)) {
×
7526
            return $object->{$keyOrPropertyOrMethod}();
×
7527
        }
7528

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

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

7555
        if ($data === null) {
3,954 ✔
7556
            throw new \InvalidArgumentException('Passed value should be a array');
6 ✔
7557
        }
7558

7559
        return $data;
3,948 ✔
7560
    }
7561

7562
    /**
7563
     * @param bool $preserveKeys <p>
7564
     *                           e.g.: A generator maybe return the same key more than once,
7565
     *                           so maybe you will ignore the keys.
7566
     *                           </p>
7567
     *
7568
     * @return bool
7569
     *
7570
     * @noinspection ReturnTypeCanBeDeclaredInspection
7571
     * @psalm-mutation-free :/
7572
     */
7573
    protected function generatorToArray(bool $preserveKeys = true)
7574
    {
7575
        if ($this->generator) {
3,660 ✔
7576
            $this->array = $this->toArray(false, $preserveKeys);
9 ✔
7577
            $this->generator = null;
9 ✔
7578

7579
            return true;
9 ✔
7580
        }
7581

7582
        return false;
3,660 ✔
7583
    }
7584

7585
    /**
7586
     * Get correct PHP constant for direction.
7587
     *
7588
     * @param int|string $direction
7589
     *
7590
     * @return int
7591
     * @psalm-mutation-free
7592
     */
7593
    protected function getDirection($direction): int
7594
    {
7595
        if ((string) $direction === $direction) {
129 ✔
7596
            $direction = \strtolower($direction);
30 ✔
7597

7598
            if ($direction === 'desc') {
30 ✔
7599
                $direction = \SORT_DESC;
6 ✔
7600
            } else {
7601
                $direction = \SORT_ASC;
27 ✔
7602
            }
7603
        }
7604

7605
        if (
7606
            $direction !== \SORT_DESC
129 ✔
7607
            &&
7608
            $direction !== \SORT_ASC
129 ✔
7609
        ) {
7610
            $direction = \SORT_ASC;
×
7611
        }
7612

7613
        return $direction;
129 ✔
7614
    }
7615

7616
    /**
7617
     * @return TypeCheckInterface[]
7618
     *
7619
     * @noinspection ReturnTypeCanBeDeclaredInspection
7620
     */
7621
    protected function getPropertiesFromPhpDoc()
7622
    {
7623
        static $PROPERTY_CACHE = [];
225 ✔
7624
        static $OPTIONAL_PROPERTY_CACHE = [];
225 ✔
7625
        $cacheKey = 'Class::' . static::class;
225 ✔
7626

7627
        if (isset($PROPERTY_CACHE[$cacheKey])) {
225 ✔
7628
            $this->optionalProperties = $OPTIONAL_PROPERTY_CACHE[$cacheKey] ?? [];
201 ✔
7629

7630
            return $PROPERTY_CACHE[$cacheKey];
201 ✔
7631
        }
7632

7633
        $properties = $this->getPropertiesFromNativeDefinitions();
63 ✔
7634
        $optionalProperties = [];
63 ✔
7635
        $phpDocPropertyAnnotationStyle = null;
63 ✔
7636

7637
        $reflector = new \ReflectionClass($this);
63 ✔
7638
        $factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
63 ✔
7639
        $docComment = $reflector->getDocComment();
63 ✔
7640
        if ($docComment) {
63 ✔
7641
            $docblock = $factory->create($docComment);
60 ✔
7642
            $this->addPropertiesFromDocBlock($docblock, $properties, $optionalProperties, $phpDocPropertyAnnotationStyle);
60 ✔
7643
        }
7644

7645
        /** @noinspection PhpAssignmentInConditionInspection */
7646
        while ($reflector = $reflector->getParentClass()) {
60 ✔
7647
            $docComment = $reflector->getDocComment();
60 ✔
7648
            if ($docComment) {
60 ✔
7649
                $docblock = $factory->create($docComment);
60 ✔
7650
                $this->addPropertiesFromDocBlock($docblock, $properties, $optionalProperties, $phpDocPropertyAnnotationStyle);
60 ✔
7651
            }
7652
        }
7653

7654
        $this->optionalProperties = $optionalProperties;
57 ✔
7655
        $OPTIONAL_PROPERTY_CACHE[$cacheKey] = $optionalProperties;
57 ✔
7656

7657
        return $PROPERTY_CACHE[$cacheKey] = $properties;
57 ✔
7658
    }
7659

7660
    /**
7661
     * Merge property definitions from a docblock into the collected property map.
7662
     *
7663
     * @param \phpDocumentor\Reflection\DocBlock $docblock
7664
     * @param TypeCheckInterface[]               $properties
7665
     * @param array<string, true>                $optionalProperties
7666
     * @param 'array-shape'|'property'|null      $phpDocPropertyAnnotationStyle
7667
     *
7668
     * @return void
7669
     */
7670
    private function addPropertiesFromDocBlock($docblock, array &$properties, array &$optionalProperties, ?string &$phpDocPropertyAnnotationStyle): void
7671
    {
7672
        $propertyTags = $docblock->getTagsByName('property');
63 ✔
7673
        $arrayShapeItems = $this->getArrayShapeItemsFromDocBlock($docblock);
63 ✔
7674

7675
        if ($propertyTags !== [] && $arrayShapeItems !== []) {
63 ✔
7676
            throw new \TypeError('Use either @property tags or array-shape annotations for Arrayy property definitions, not both.');
3 ✔
7677
        }
7678

7679
        $currentPhpDocPropertyAnnotationStyle = null;
60 ✔
7680
        if ($propertyTags !== []) {
60 ✔
7681
            $currentPhpDocPropertyAnnotationStyle = 'property';
21 ✔
7682
        } elseif ($arrayShapeItems !== []) {
60 ✔
7683
            $currentPhpDocPropertyAnnotationStyle = 'array-shape';
24 ✔
7684
        }
7685

7686
        if (
7687
            $currentPhpDocPropertyAnnotationStyle !== null
60 ✔
7688
            &&
7689
            $phpDocPropertyAnnotationStyle !== null
60 ✔
7690
            &&
7691
            $phpDocPropertyAnnotationStyle !== $currentPhpDocPropertyAnnotationStyle
60 ✔
7692
        ) {
7693
            throw new \TypeError('Use either @property tags or array-shape annotations for Arrayy property definitions, not both.');
3 ✔
7694
        }
7695

7696
        if ($currentPhpDocPropertyAnnotationStyle !== null) {
60 ✔
7697
            $phpDocPropertyAnnotationStyle = $currentPhpDocPropertyAnnotationStyle;
42 ✔
7698
        }
7699

7700
        /** @var \phpDocumentor\Reflection\DocBlock\Tags\Property $tag */
7701
        foreach ($propertyTags as $tag) {
60 ✔
7702
            $typeName = $tag->getVariableName();
18 ✔
7703
            /** @var string|null $typeName */
7704
            if (
7705
                $typeName !== null
18 ✔
7706
                &&
7707
                isset($properties[$typeName]) === false
18 ✔
7708
            ) {
7709
                $typeCheckPhpDoc = TypeCheckPhpDoc::fromPhpDocumentorProperty($tag, $typeName);
18 ✔
7710
                if ($typeCheckPhpDoc !== null) {
18 ✔
7711
                    $properties[$typeName] = $typeCheckPhpDoc;
18 ✔
7712
                    unset($optionalProperties[$typeName]);
18 ✔
7713
                }
7714
            }
7715
        }
7716

7717
        foreach ($arrayShapeItems as $item) {
60 ✔
7718
            $typeName = (string) $item->getKey();
24 ✔
7719
            if ($typeName === '') {
24 ✔
7720
                continue;
×
7721
            }
7722

7723
            $typeName = \trim($typeName, '\'"');
24 ✔
7724
            if (isset($properties[$typeName])) {
24 ✔
7725
                continue;
×
7726
            }
7727

7728
            $typeCheckPhpDoc = TypeCheckPhpDoc::fromDocTypeObject($typeName, $item->getValue());
24 ✔
7729
            $properties[$typeName] = $typeCheckPhpDoc;
24 ✔
7730
            if ($item->isOptional()) {
24 ✔
7731
                $optionalProperties[$typeName] = true;
15 ✔
7732
            }
7733
        }
7734
    }
7735

7736
    /**
7737
     * Extract array-shape items from supported @template and @extends annotations.
7738
     *
7739
     * @param \phpDocumentor\Reflection\DocBlock $docblock
7740
     *
7741
     * @return \phpDocumentor\Reflection\PseudoTypes\ArrayShapeItem[]
7742
     */
7743
    private function getArrayShapeItemsFromDocBlock($docblock): array
7744
    {
7745
        if (!\class_exists('\phpDocumentor\Reflection\PseudoTypes\ArrayShape')) {
63 ✔
7746
            return [];
×
7747
        }
7748

7749
        $items = [];
63 ✔
7750
        foreach ($docblock->getTagsByName('template') as $tag) {
63 ✔
7751
            if (
7752
                $tag instanceof \phpDocumentor\Reflection\DocBlock\Tags\Template
63 ✔
7753
                &&
7754
                $tag->getTemplateName() === 'T'
63 ✔
7755
                &&
7756
                $tag->getBound() instanceof \phpDocumentor\Reflection\PseudoTypes\ArrayShape
63 ✔
7757
            ) {
7758
                foreach ($tag->getBound()->getItems() as $item) {
21 ✔
7759
                    $items[] = $item;
21 ✔
7760
                }
7761
            }
7762
        }
7763

7764
        foreach ($docblock->getTagsByName('extends') as $tag) {
63 ✔
7765
            if (!$tag instanceof \phpDocumentor\Reflection\DocBlock\Tags\Extends_) {
63 ✔
7766
                continue;
×
7767
            }
7768

7769
            $type = $tag->getType();
63 ✔
7770
            if (
7771
                !$type instanceof \phpDocumentor\Reflection\PseudoTypes\Generic
63 ✔
7772
                ||
7773
                !$this->isArrayyGenericTarget((string) $type->getFqsen())
63 ✔
7774
            ) {
7775
                continue;
57 ✔
7776
            }
7777

7778
            foreach ($type->getTypes() as $genericType) {
60 ✔
7779
                if ($genericType instanceof \phpDocumentor\Reflection\PseudoTypes\ArrayShape) {
60 ✔
7780
                    foreach ($genericType->getItems() as $item) {
6 ✔
7781
                        $items[] = $item;
6 ✔
7782
                    }
7783
                }
7784
            }
7785
        }
7786

7787
        return $items;
63 ✔
7788
    }
7789

7790
    /**
7791
     * Check whether a generic annotation target is Arrayy, ArrayyStrict, or an Arrayy subclass.
7792
     *
7793
     * @param string $fqcn
7794
     *
7795
     * @return bool
7796
     */
7797
    private function isArrayyGenericTarget(string $fqcn): bool
7798
    {
7799
        $fqcn = \ltrim($fqcn, '\\');
63 ✔
7800
        if ($fqcn === '') {
63 ✔
7801
            return false;
×
7802
        }
7803

7804
        if (\in_array($fqcn, [self::class, ArrayyStrict::class], true)) {
63 ✔
7805
            return true;
60 ✔
7806
        }
7807

7808
        return \class_exists($fqcn) && \is_a($fqcn, self::class, true);
57 ✔
7809
    }
7810

7811
    /**
7812
     * @return TypeCheckInterface[]
7813
     */
7814
    protected function getPropertiesFromNativeDefinitions(): array
7815
    {
7816
        $properties = [];
63 ✔
7817
        $reflector = new \ReflectionClass($this);
63 ✔
7818
        $reservedProperties = self::getReservedPropertyNames();
63 ✔
7819

7820
        do {
7821
            if ($reflector->getName() === self::class) {
63 ✔
7822
                break;
63 ✔
7823
            }
7824

7825
            foreach ($reflector->getProperties() as $property) {
63 ✔
7826
                if (
7827
                    $property->getDeclaringClass()->getName() !== $reflector->getName()
63 ✔
7828
                    ||
7829
                    $property->isStatic()
54 ✔
7830
                    ||
7831
                    isset($reservedProperties[$property->getName()])
54 ✔
7832
                    ||
7833
                    isset($properties[$property->getName()])
63 ✔
7834
                ) {
7835
                    continue;
63 ✔
7836
                }
7837

7838
                $properties[$property->getName()] = TypeCheckPhpDoc::fromReflectionProperty($property);
9 ✔
7839
            }
7840
        } while ($reflector = $reflector->getParentClass());
63 ✔
7841

7842
        return $properties;
63 ✔
7843
    }
7844

7845
    /**
7846
     * @return array<string, true>
7847
     */
7848
    private static function getReservedPropertyNames(): array
7849
    {
7850
        static $reservedProperties = null;
63 ✔
7851

7852
        if ($reservedProperties !== null) {
63 ✔
7853
            return $reservedProperties;
60 ✔
7854
        }
7855

7856
        $reservedProperties = [];
3 ✔
7857
        $reflector = new \ReflectionClass(self::class);
3 ✔
7858
        foreach ($reflector->getProperties() as $property) {
3 ✔
7859
            if ($property->getDeclaringClass()->getName() !== self::class) {
3 ✔
7860
                continue;
×
7861
            }
7862

7863
            $reservedProperties[$property->getName()] = true;
3 ✔
7864
        }
7865

7866
        return $reservedProperties;
3 ✔
7867
    }
7868

7869
    /**
7870
     * @param string $glue
7871
     * @param mixed  $pieces
7872
     * @param bool   $useKeys
7873
     *
7874
     * @return string
7875
     *
7876
     * @phpstan-param scalar|object|self<TKey|T>|array<TKey,T>|array<T> $pieces
7877
     * @psalm-mutation-free
7878
     */
7879
    protected function implode_recursive(
7880
        $glue = '',
7881
        $pieces = [],
7882
        bool $useKeys = false
7883
    ): string {
7884
        if ($pieces instanceof self) {
111 ✔
7885
            $pieces = $pieces->toArray();
3 ✔
7886
        }
7887

7888
        if (\is_array($pieces)) {
111 ✔
7889
            /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
7890
            /** @phpstan-var array<TKey,T> $pieces */
7891
            $pieces = $pieces;
111 ✔
7892

7893
            $pieces_count = \count($pieces, \COUNT_NORMAL);
111 ✔
7894
            $pieces_count_not_zero = $pieces_count > 0;
111 ✔
7895

7896
            return \implode(
111 ✔
7897
                $glue,
111 ✔
7898
                \array_map(
111 ✔
7899
                    [$this, 'implode_recursive'],
111 ✔
7900
                    \array_fill(0, ($pieces_count_not_zero ? $pieces_count : 1), $glue),
111 ✔
7901
                    ($useKeys === true && $pieces_count_not_zero ? $this->array_keys_recursive($pieces) : $pieces)
111 ✔
7902
                )
111 ✔
7903
            );
111 ✔
7904
        }
7905

7906
        if (
7907
            \is_scalar($pieces) === true
111 ✔
7908
            ||
7909
            $pieces instanceof \Stringable
111 ✔
7910
        ) {
7911
            return (string) $pieces;
99 ✔
7912
        }
7913

7914
        return '';
24 ✔
7915
    }
7916

7917
    /**
7918
     * @param mixed                 $needle   <p>
7919
     *                                        The searched value.
7920
     *                                        </p>
7921
     *                                        <p>
7922
     *                                        If needle is a string, the comparison is done
7923
     *                                        in a case-sensitive manner.
7924
     *                                        </p>
7925
     * @param array|\Generator|null $haystack <p>
7926
     *                                        The array.
7927
     *                                        </p>
7928
     * @param bool                  $strict   [optional] <p>
7929
     *                                        If the third parameter strict is set to true
7930
     *                                        then the in_array function will also check the
7931
     *                                        types of the
7932
     *                                        needle in the haystack.
7933
     *                                        </p>
7934
     *
7935
     * @return bool
7936
     *              <p>true if needle is found in the array, false otherwise</p>
7937
     *
7938
     * @phpstan-param array<array-key, mixed>|array<TKey,T>|\Generator<TKey,T>|null $haystack
7939
     *
7940
     * @psalm-mutation-free
7941
     */
7942
    protected function in_array_recursive($needle, $haystack = null, $strict = true): bool
7943
    {
7944
        if ($haystack === null) {
56 ✔
7945
            $haystack = $this->getGenerator();
×
7946
        }
7947

7948
        foreach ($haystack as $item) {
56 ✔
7949
            if (\is_array($item)) {
44 ✔
7950
                $returnTmp = $this->in_array_recursive($needle, $item, $strict);
11 ✔
7951
            } else {
7952
                /** @noinspection NestedPositiveIfStatementsInspection */
7953
                if ($strict === true) {
44 ✔
7954
                    $returnTmp = $item === $needle;
44 ✔
7955
                } else {
7956
                    $returnTmp = $item == $needle;
×
7957
                }
7958
            }
7959

7960
            if ($returnTmp === true) {
44 ✔
7961
                return true;
32 ✔
7962
            }
7963
        }
7964

7965
        return false;
24 ✔
7966
    }
7967

7968
    /**
7969
     * @param mixed $data
7970
     *
7971
     * @return array<mixed>|null
7972
     */
7973
    protected function internalGetArray(&$data)
7974
    {
7975
        if (\is_array($data)) {
3,954 ✔
7976
            return $data;
3,936 ✔
7977
        }
7978

7979
        if (!$data) {
345 ✔
7980
            return [];
21 ✔
7981
        }
7982

7983
        if (\is_object($data) === true) {
342 ✔
7984
            if ($data instanceof \ArrayObject) {
321 ✔
7985
                return $data->getArrayCopy();
15 ✔
7986
            }
7987

7988
            if ($data instanceof \Generator) {
309 ✔
7989
                return static::createFromGeneratorImmutable($data)->toArray();
3 ✔
7990
            }
7991

7992
            if ($data instanceof \Traversable) {
306 ✔
7993
                return static::createFromObject($data)->toArray();
×
7994
            }
7995

7996
            if ($data instanceof \JsonSerializable) {
306 ✔
7997
                return (array) $data->jsonSerialize();
×
7998
            }
7999

8000
            if (\method_exists($data, '__toArray')) {
306 ✔
8001
                return (array) $data->__toArray();
×
8002
            }
8003

8004
            if (\method_exists($data, '__toString')) {
306 ✔
8005
                return [(string) $data];
×
8006
            }
8007
        }
8008

8009
        if (\is_callable($data)) {
327 ✔
8010
            /**
8011
             * @psalm-suppress InvalidPropertyAssignmentValue - why?
8012
             */
8013
            $this->generator = new ArrayyRewindableGenerator($data);
300 ✔
8014

8015
            return [];
300 ✔
8016
        }
8017

8018
        if (\is_scalar($data)) {
33 ✔
8019
            return [$data];
27 ✔
8020
        }
8021

8022
        return null;
6 ✔
8023
    }
8024

8025
    /**
8026
     * Internal mechanics of remove method.
8027
     *
8028
     * @param float|int|string $key
8029
     *
8030
     * @return bool
8031
     */
8032
    protected function internalRemove($key): bool
8033
    {
8034
        $this->generatorToArray();
72 ✔
8035

8036
        if (\is_float($key)) {
72 ✔
NEW
8037
            $key = (int) $key;
×
8038
        }
8039

8040
        if (
8041
            $this->pathSeparator
72 ✔
8042
            &&
8043
            (string) $key === $key
72 ✔
8044
            &&
8045
            \strpos($key, $this->pathSeparator) !== false
72 ✔
8046
        ) {
8047
            $path = \explode($this->pathSeparator, (string) $key);
6 ✔
8048
            $array = &$this->array;
6 ✔
8049

8050
            // crawl though the keys
8051
            while (\count($path, \COUNT_NORMAL) > 1) {
6 ✔
8052
                $key = \array_shift($path);
6 ✔
8053

8054
                if (!\is_array($array) || !\array_key_exists($key, $array)) {
6 ✔
8055
                    return false;
×
8056
                }
8057

8058
                $array = &$array[$key];
6 ✔
8059
            }
8060

8061
            $key = \array_shift($path);
6 ✔
8062

8063
            if (!\is_array($array)) {
6 ✔
8064
                return false;
3 ✔
8065
            }
8066

8067
            unset($array[$key]);
3 ✔
8068

8069
            return true;
3 ✔
8070
        }
8071

8072
        unset($this->array[$key]);
66 ✔
8073

8074
        return true;
66 ✔
8075
    }
8076

8077
    /**
8078
     * Internal mechanic of set method.
8079
     *
8080
     * @param int|string|null $key
8081
     * @param mixed           $value
8082
     * @param bool            $checkProperties
8083
     *
8084
     * @return bool
8085
     *
8086
     * @phpstan-param TKey|null $key
8087
     * @phpstan-param T $value
8088
     */
8089
    protected function internalSet(
8090
        $key,
8091
        &$value,
8092
        bool $checkProperties = true
8093
    ): bool {
8094
        if (
8095
            $checkProperties === true
3,483 ✔
8096
            &&
8097
            $this->properties !== []
3,483 ✔
8098
        ) {
8099
            $this->checkType($key, $value);
510 ✔
8100
        }
8101

8102
        if ($key === null) {
3,465 ✔
8103
            return false;
×
8104
        }
8105

8106
        $this->generatorToArray();
3,465 ✔
8107

8108
        $array = &$this->array;
3,465 ✔
8109

8110
        /**
8111
         * https://github.com/vimeo/psalm/issues/2536
8112
         *
8113
         * @psalm-suppress PossiblyInvalidArgument
8114
         * @psalm-suppress InvalidScalarArgument
8115
         */
8116
        if (
8117
            $this->pathSeparator
3,465 ✔
8118
            &&
8119
            (string) $key === $key
3,465 ✔
8120
            &&
8121
            \strpos($key, $this->pathSeparator) !== false
3,465 ✔
8122
        ) {
8123
            $path = \explode($this->pathSeparator, (string) $key);
27 ✔
8124
            // crawl through the keys
8125
            while (\count($path, \COUNT_NORMAL) > 1) {
27 ✔
8126
                $key = \array_shift($path);
27 ✔
8127

8128
                $array = &$array[$key];
27 ✔
8129
            }
8130

8131
            $key = \array_shift($path);
27 ✔
8132
        }
8133

8134
        if ($array === null) {
3,465 ✔
8135
            $array = [];
12 ✔
8136
        } elseif (!\is_array($array)) {
3,456 ✔
8137
            throw new \RuntimeException('Can not set value at this path "' . $key . '" because (' . \gettype($array) . ')"' . \print_r($array, true) . '" is not an array.');
3 ✔
8138
        }
8139

8140
        $array[$key] = $value;
3,465 ✔
8141

8142
        return true;
3,465 ✔
8143
    }
8144

8145
    /**
8146
     * Convert a object into an array.
8147
     *
8148
     * @param mixed|object $object
8149
     *
8150
     * @return array|mixed
8151
     *
8152
     * @psalm-mutation-free
8153
     */
8154
    protected static function objectToArray($object)
8155
    {
8156
        if (!\is_object($object)) {
18 ✔
8157
            return $object;
15 ✔
8158
        }
8159

8160
        $object = \get_object_vars($object);
18 ✔
8161

8162
        /**
8163
         * @psalm-suppress PossiblyInvalidArgument - the parameter is always some kind of array - false-positive from psalm?
8164
         */
8165
        return \array_map([static::class, 'objectToArray'], $object);
18 ✔
8166
    }
8167

8168
    /**
8169
     * @param array $data
8170
     * @param bool  $checkPropertiesInConstructor
8171
     *
8172
     * @return void
8173
     *
8174
     * @phpstan-param array<mixed,T> $data
8175
     */
8176
    protected function setInitialValuesAndProperties(array &$data, bool $checkPropertiesInConstructor)
8177
    {
8178
        $checkPropertiesInConstructor = $this->checkForMissingPropertiesInConstructor === true
3,948 ✔
8179
                                        &&
3,948 ✔
8180
                                        $checkPropertiesInConstructor === true;
3,948 ✔
8181

8182
        if ($this->properties === []) {
3,948 ✔
8183
            if (
8184
                $this->checkPropertyTypes === true
3,651 ✔
8185
                ||
8186
                $checkPropertiesInConstructor === true
3,651 ✔
8187
            ) {
8188
                $this->properties = $this->getPropertiesFromPhpDoc();
213 ✔
8189
            }
8190

8191
            /** @var TypeCheckInterface[] $properties */
8192
            $properties = $this->properties;
3,645 ✔
8193
            $requiredProperties = \array_diff_key($properties, $this->optionalProperties);
3,645 ✔
8194

8195
            if (
8196
                $this->checkPropertiesMismatchInConstructor === true
3,645 ✔
8197
                &&
8198
                \count($data) !== 0
3,645 ✔
8199
                &&
8200
                \count(\array_diff_key($requiredProperties, $data)) > 0
3,645 ✔
8201
            ) {
8202
                throw new \TypeError('Property mismatch - input: ' . \print_r(\array_keys($data), true) . ' | expected: ' . \print_r(\array_keys($requiredProperties), true));
6 ✔
8203
            }
8204
        }
8205

8206
        foreach ($data as $key => &$valueInner) {
3,936 ✔
8207
            $this->internalSet(
3,426 ✔
8208
                $key,
3,426 ✔
8209
                $valueInner,
3,426 ✔
8210
                $checkPropertiesInConstructor
3,426 ✔
8211
            );
3,426 ✔
8212
        }
8213
    }
8214

8215
    /**
8216
     * sorting keys
8217
     *
8218
     * @param array      $elements
8219
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
8220
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
8221
     *                              <strong>SORT_NATURAL</strong></p>
8222
     *
8223
     * @return $this
8224
     *               <p>(Mutable) Return this Arrayy object.</p>
8225
     *
8226
     * @phpstan-param  array<mixed|TKey,T> $elements
8227
     * @phpstan-return static
8228
     */
8229
    protected function sorterKeys(
8230
        array &$elements,
8231
        $direction = \SORT_ASC,
8232
        int $strategy = \SORT_REGULAR
8233
    ): self {
8234
        $direction = $this->getDirection($direction);
54 ✔
8235

8236
        switch ($direction) {
8237
            case 'desc':
54 ✔
8238
            case \SORT_DESC:
8239
                \krsort($elements, $strategy);
18 ✔
8240

8241
                break;
18 ✔
8242
            case 'asc':
39 ✔
8243
            case \SORT_ASC:
39 ✔
8244
            default:
8245
                \ksort($elements, $strategy);
39 ✔
8246
        }
8247

8248
        return $this;
54 ✔
8249
    }
8250

8251
    /**
8252
     * @param array      $elements  <p>Warning: used as reference</p>
8253
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
8254
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
8255
     *                              <strong>SORT_NATURAL</strong></p>
8256
     * @param bool       $keepKeys
8257
     *
8258
     * @return $this
8259
     *               <p>(Mutable) Return this Arrayy object.</p>
8260
     *
8261
     * @phpstan-param array<mixed|TKey,T> $elements
8262
     * @phpstan-return static
8263
     */
8264
    protected function sorting(
8265
        array &$elements,
8266
        $direction = \SORT_ASC,
8267
        int $strategy = \SORT_REGULAR,
8268
        bool $keepKeys = false
8269
    ): self {
8270
        $direction = $this->getDirection($direction);
72 ✔
8271

8272
        if (!$strategy) {
72 ✔
8273
            $strategy = \SORT_REGULAR;
72 ✔
8274
        }
8275

8276
        switch ($direction) {
8277
            case 'desc':
72 ✔
8278
            case \SORT_DESC:
8279
                if ($keepKeys) {
39 ✔
8280
                    \arsort($elements, $strategy);
27 ✔
8281
                } else {
8282
                    \rsort($elements, $strategy);
12 ✔
8283
                }
8284

8285
                break;
39 ✔
8286
            case 'asc':
33 ✔
8287
            case \SORT_ASC:
33 ✔
8288
            default:
8289
                if ($keepKeys) {
33 ✔
8290
                    \asort($elements, $strategy);
12 ✔
8291
                } else {
8292
                    \sort($elements, $strategy);
21 ✔
8293
                }
8294
        }
8295

8296
        return $this;
72 ✔
8297
    }
8298

8299
    /**
8300
     * @param array $array
8301
     *
8302
     * @return array
8303
     *
8304
     * @phpstan-param array<array-key, mixed> $array
8305
     * @phpstan-return array<array-key, mixed>
8306
     *
8307
     * @psalm-mutation-free
8308
     */
8309
    private function getArrayRecursiveHelperArrayy(array $array)
8310
    {
8311
        if ($array === []) {
75 ✔
8312
            return [];
×
8313
        }
8314

8315
        \array_walk_recursive(
75 ✔
8316
            $array,
75 ✔
8317
            /**
8318
             * @param array|self $item
8319
             *
8320
             * @return void
8321
             */
8322
            static function (&$item) {
75 ✔
8323
                if ($item instanceof self) {
75 ✔
8324
                    $item = $item->getArray();
3 ✔
8325
                }
8326
            }
75 ✔
8327
        );
75 ✔
8328

8329
        return $array;
75 ✔
8330
    }
8331

8332
    /**
8333
     * @param int|string|null $key
8334
     * @param mixed           $value
8335
     *
8336
     * @return void
8337
     */
8338
    private function checkType($key, $value)
8339
    {
8340
        if (
8341
            $key !== null
510 ✔
8342
            &&
8343
            isset($this->properties[$key]) === false
510 ✔
8344
            &&
8345
            $this->checkPropertiesMismatch === true
510 ✔
8346
        ) {
8347
            throw new \TypeError('The key "' . $key . '" does not exist as a property definition. (' . \get_class($this) . ').');
12 ✔
8348
        }
8349

8350
        if (isset($this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES])) {
510 ✔
8351
            $this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES]->checkType($value);
357 ✔
8352
        } elseif ($key !== null && isset($this->properties[$key])) {
186 ✔
8353
            $this->properties[$key]->checkType($value);
186 ✔
8354
        }
8355
    }
8356
}
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