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

voku / Arrayy / 30580528362

30 Jul 2026 08:45PM UTC coverage: 92.38%. Remained the same
30580528362

push

github

web-flow
Merge pull request #172 from voku/renovate/codecov-codecov-action-7.x

Update codecov/codecov-action action to v7

2764 of 2992 relevant lines covered (92.38%)

249.44 hits per line

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

91.96
/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);
9,133 ✔
129

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

136
        $this->setInitialValuesAndProperties($data, $checkPropertiesInConstructor);
9,119 ✔
137

138
        $this->setIteratorClass($iteratorClass);
8,930 ✔
139
    }
140

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

150
        if ($this->generator !== null) {
371 ✔
151
            $this->generator = clone $this->generator;
7 ✔
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) {
7 ✔
168
            $this->generatorToArray();
7 ✔
169

170
            return $this->array[$key] ?? false;
7 ✔
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);
7 ✔
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);
14 ✔
208
    }
209

210
    /**
211
     * magic to string
212
     *
213
     * @return string
214
     */
215
    public function __toString(): string
216
    {
217
        return $this->toString();
105 ✔
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);
1,174 ✔
247

248
        if (\is_array($return) === true) {
1,174 ✔
249
            $return = static::create(
×
250
                [],
×
251
                $this->iteratorClass,
×
252
                false
×
253
            )->createByReference($return);
×
254
        }
255

256
        return $return;
1,174 ✔
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) {
98 ✔
277
            $get = $this->get($key);
35 ✔
278
            if ($get !== null) {
35 ✔
279
                $value = \array_merge_recursive(
7 ✔
280
                    !$get instanceof self ? [$get] : $get->getArray(),
7 ✔
281
                    !\is_array($value) ? [$value] : $value
7 ✔
282
                );
7 ✔
283
            }
284

285
            $this->internalSet($key, $value);
35 ✔
286

287
            return $this;
28 ✔
288
        }
289

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

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

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

333
        return $this;
140 ✔
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 {
7 ✔
360
            if ($this->properties !== []) {
7 ✔
361
                $this->checkType($key, $value);
×
362
            }
363

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

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

375
        return static::create(
7 ✔
376
            $generator,
7 ✔
377
            $this->iteratorClass,
7 ✔
378
            false
7 ✔
379
        );
7 ✔
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();
28 ✔
400

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

403
        return $this;
28 ✔
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;
28 ✔
424

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

430
        return $that;
28 ✔
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) {
1,050 ✔
477
            throw new \ValueError('count(): Argument #2 ($mode) must be either COUNT_NORMAL or COUNT_RECURSIVE');
×
478
        }
479

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

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

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

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

531
        return $this->array;
42 ✔
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) {
245 ✔
548
            $generator = clone $this->generator;
14 ✔
549

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

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

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

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

566
        if ($iterator === ArrayyIterator::class) {
238 ✔
567
            return new $iterator($this->toArray(), 0, static::class);
238 ✔
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;
238 ✔
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();
28 ✔
606

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

609
        return $this;
28 ✔
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;
28 ✔
629

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

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

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

653
        return $this;
56 ✔
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;
28 ✔
668

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

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

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

692
        return $this;
70 ✔
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;
28 ✔
707

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

713
        return $that;
28 ✔
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) {
1,384 ✔
730
            $offset = (int) $offset;
7 ✔
731
        }
732
        \assert(\is_int($offset) || \is_string($offset));
733

734
        $offsetExists = $this->keyExists($offset);
1,384 ✔
735
        if ($offsetExists === true) {
1,384 ✔
736
            return true;
1,237 ✔
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
973 ✔
747
            &&
748
            (string) $offset === $offset
973 ✔
749
            &&
750
            \strpos($offset, $this->pathSeparator) !== false
973 ✔
751
        ) {
752
            $explodedPath = \explode($this->pathSeparator, (string) $offset);
28 ✔
753
            /** @var string $lastOffset - helper for phpstan */
754
            $lastOffset = \array_pop($explodedPath);
28 ✔
755
            $containerPath = \implode($this->pathSeparator, $explodedPath);
28 ✔
756

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

769
        return $offsetExists;
973 ✔
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;
1,167 ✔
789

790
        if ($this->offsetExists($offset)) {
1,167 ✔
791
            $value = &$this->__get($offset);
1,153 ✔
792
        }
793

794
        return $value;
1,167 ✔
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();
301 ✔
809

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

815
            $this->array[] = $value;
56 ✔
816
        } else {
817
            $this->internalSet(
245 ✔
818
                $offset,
245 ✔
819
                $value,
245 ✔
820
                true
245 ✔
821
            );
245 ✔
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();
182 ✔
837

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

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

845
            return;
98 ✔
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
70 ✔
856
            &&
857
            (string) $offset === $offset
70 ✔
858
            &&
859
            \strpos($offset, $this->pathSeparator) !== false
70 ✔
860
        ) {
861
            $path = \explode($this->pathSeparator, (string) $offset);
49 ✔
862
            $pathToUnset = \array_pop($path);
49 ✔
863

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

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

896
        return \serialize($this);
7 ✔
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)) {
8,930 ✔
914
            $this->iteratorClass = $iteratorClass;
8,930 ✔
915

916
            return;
8,930 ✔
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();
56 ✔
952

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

955
        return $this;
56 ✔
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;
28 ✔
975

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

981
        return $that;
28 ✔
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);
35 ✔
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);
7 ✔
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]]);
7 ✔
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();
7 ✔
1062

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

1083
        return $this;
7 ✔
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 = [];
70 ✔
1101

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

1114
        return self::create(
70 ✔
1115
            $result,
70 ✔
1116
            $this->iteratorClass,
70 ✔
1117
            false
70 ✔
1118
        );
70 ✔
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 = [];
70 ✔
1136

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

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

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

1166
        return $this;
28 ✔
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;
70 ✔
1181

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

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

1186
        return $that;
70 ✔
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;
21 ✔
1212

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

1217
        return static::create(
21 ✔
1218
            $that->toArray(),
21 ✔
1219
            $this->iteratorClass,
21 ✔
1220
            false
21 ✔
1221
        );
21 ✔
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();
70 ✔
1240
        $count = \count($array, \COUNT_NORMAL);
70 ✔
1241

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

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

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

1265
        return \round($sum / $count, $decimals);
56 ✔
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
7 ✔
1284
            &&
1285
            $case !== \CASE_UPPER
7 ✔
1286
        ) {
1287
            $case = \CASE_LOWER;
×
1288
        }
1289

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

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

1309
        return static::create(
7 ✔
1310
            $return,
7 ✔
1311
            $this->iteratorClass,
7 ✔
1312
            false
7 ✔
1313
        );
7 ✔
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;
77 ✔
1331

1332
        return $this;
77 ✔
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 static
1349
     * @psalm-mutation-free
1350
     */
1351
    public function chunk($size, $preserveKeys = false): self
1352
    {
1353
        if ($preserveKeys) {
42 ✔
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) {
42 ✔
1375
                $values = [];
42 ✔
1376
                $tmpCounter = 0;
42 ✔
1377
                foreach ($this->getGenerator() as $value) {
42 ✔
1378
                    ++$tmpCounter;
42 ✔
1379

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

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

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

1395
        return static::create(
42 ✔
1396
            $generator,
42 ✔
1397
            $this->iteratorClass,
42 ✔
1398
            false
42 ✔
1399
        );
42 ✔
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(
56 ✔
1418
            static function ($value) {
56 ✔
1419
                return (bool) $value;
49 ✔
1420
            }
56 ✔
1421
        );
56 ✔
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) {
70 ✔
1441
            if (\is_array($key)) {
21 ✔
1442
                foreach ($key as $keyTmp) {
7 ✔
1443
                    $this->offsetUnset($keyTmp);
7 ✔
1444
                }
1445
            } else {
1446
                $this->offsetUnset($key);
14 ✔
1447
            }
1448

1449
            return $this;
21 ✔
1450
        }
1451

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

1455
        return $this;
49 ✔
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) {
70 ✔
1475
            return $this->in_array_recursive($value, $this->toArray(), $strict);
×
1476
        }
1477

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

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

1495
        return $tmpCount !== 0;
49 ✔
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) {
163 ✔
1515
            return $this->in_array_recursive($value, $this->toArray(), $strict);
128 ✔
1516
        }
1517

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

1532
        return false;
49 ✔
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) {
182 ✔
1553
            return false;
14 ✔
1554
        }
1555

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

1569
            return false;
56 ✔
1570
        }
1571

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

1579
        return false;
28 ✔
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);
28 ✔
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) {
14 ✔
1620
            return
14 ✔
1621
                \count(
14 ✔
1622
                    \array_intersect(
14 ✔
1623
                        $needles,
14 ✔
1624
                        $this->keys(true)->toArray()
14 ✔
1625
                    ),
14 ✔
1626
                    \COUNT_RECURSIVE
14 ✔
1627
                )
14 ✔
1628
                ===
14 ✔
1629
                \count(
14 ✔
1630
                    $needles,
14 ✔
1631
                    \COUNT_RECURSIVE
14 ✔
1632
                );
14 ✔
1633
        }
1634

1635
        return \count(
7 ✔
1636
            \array_intersect($needles, $this->keys()->toArray()),
7 ✔
1637
            \COUNT_NORMAL
7 ✔
1638
        )
7 ✔
1639
                ===
7 ✔
1640
                \count(
7 ✔
1641
                    $needles,
7 ✔
1642
                    \COUNT_NORMAL
7 ✔
1643
                );
7 ✔
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);
7 ✔
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);
63 ✔
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);
126 ✔
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(
7 ✔
1710
            \array_intersect(
7 ✔
1711
                $needles,
7 ✔
1712
                $this->toArray()
7 ✔
1713
            ),
7 ✔
1714
            \COUNT_NORMAL
7 ✔
1715
        )
7 ✔
1716
               ===
7 ✔
1717
               \count(
7 ✔
1718
                   $needles,
7 ✔
1719
                   \COUNT_NORMAL
7 ✔
1720
               );
7 ✔
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
1736
     * @psalm-mutation-free
1737
     */
1738
    public function countValues(): self
1739
    {
1740
        /** @phpstan-var static $return - help for phpstan */
1741
        $return = self::create(\array_count_values($this->toArray()), $this->iteratorClass);
49 ✔
1742

1743
        return $return;
49 ✔
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
5,469 ✔
1768
            $data,
5,469 ✔
1769
            $iteratorClass,
5,469 ✔
1770
            $checkPropertiesInConstructor
5,469 ✔
1771
        );
5,469 ✔
1772

1773
        return $instance;
5,469 ✔
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 = [];
14 ✔
1799

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

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

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

1816
        return \array_merge_recursive([], ...$flatten);
14 ✔
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;
198 ✔
1835
        $this->generator = null;
198 ✔
1836

1837
        return $this;
198 ✔
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);
56 ✔
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
     * @phpstan-param \Generator<TKey,T> $generator
1866
     * @phpstan-return static
1867
     * @psalm-mutation-free
1868
     */
1869
    public static function createFromGeneratorImmutable(\Generator $generator): self
1870
    {
1871
        return self::create(\iterator_to_array($generator, true));
35 ✔
1872
    }
1873

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

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

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

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

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

1937
        return $arrayy;
28 ✔
1938
    }
1939

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

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

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

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

2000
        /** @var static $return - help for phpstan */
2001
        $return = static::create($array);
70 ✔
2002

2003
        return $return;
70 ✔
2004
    }
2005

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

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

2044
        return $return;
14 ✔
2045
    }
2046

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

2060
        return \current($this->array);
×
2061
    }
2062

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

2093
        \uksort($this->array, $callable);
35 ✔
2094

2095
        return $this;
35 ✔
2096
    }
2097

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

2118
        $that->generatorToArray();
7 ✔
2119

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

2125
        return $that;
7 ✔
2126
    }
2127

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

2156
        \usort($this->array, $callable);
77 ✔
2157

2158
        return $this;
77 ✔
2159
    }
2160

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

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

2186
        return $that;
35 ✔
2187
    }
2188

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2484
        return \end($this->array);
×
2485
    }
2486

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

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

2513
                break;
7 ✔
2514
            }
2515
        }
2516

2517
        return $isExists;
28 ✔
2518
    }
2519

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

2543
        $this->generatorToArray();
49 ✔
2544

2545
        $tmpArray = $this->array;
49 ✔
2546

2547
        $count = \count($tmpArray);
49 ✔
2548

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

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

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

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

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

2637
        return static::create(
84 ✔
2638
            $generator,
84 ✔
2639
            $this->iteratorClass,
84 ✔
2640
            false
84 ✔
2641
        );
84 ✔
2642
    }
2643

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

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

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

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

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

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

2774
        return false;
21 ✔
2775
    }
2776

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

2804
        return false;
28 ✔
2805
    }
2806

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

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

2854
        return $this->get($key_first);
135 ✔
2855
    }
2856

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

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

2874
        return $return;
205 ✔
2875
    }
2876

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

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

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

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

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

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

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

2958
        if ($number === null) {
238 ✔
2959
            $shift = \array_shift($this->array);
133 ✔
2960
            /* @phpstan-ignore assign.propertyType */
2961
            $this->array = $shift !== null ? [$shift] : [];
133 ✔
2962
        } else {
2963
            $splice = \array_splice($this->array, 0, $number);
105 ✔
2964
            $this->array = $splice;
105 ✔
2965
        }
2966

2967
        return $this;
238 ✔
2968
    }
2969

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

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

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

3039
            return clone $this;
7 ✔
3040
        }
3041

3042
        if ($array !== null) {
1,986 ✔
3043
            if ($useByReference) {
28 ✔
3044
                $usedArray = &$array;
×
3045
            } else {
3046
                $usedArray = $array;
28 ✔
3047
            }
3048
        } else {
3049
            $this->generatorToArray();
1,965 ✔
3050

3051
            if ($useByReference) {
1,965 ✔
3052
                $usedArray = &$this->array;
1,174 ✔
3053
            } else {
3054
                $usedArray = $this->array;
919 ✔
3055
            }
3056
        }
3057

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

3066
        // php cast "bool"-index into "int"-index
3067
        /* @phpstan-ignore identical.alwaysFalse */
3068
        if ((bool) $key === $key) {
1,986 ✔
3069
            $key = (int) $key;
×
3070
        }
3071

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

3081
            return $usedArray[$key];
1,608 ✔
3082
        }
3083

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

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

3109
                    continue;
210 ✔
3110
                }
3111

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

3119
                    continue;
7 ✔
3120
                }
3121

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

3135
                            continue;
×
3136
                        }
3137

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

3149
                            continue;
×
3150
                        }
3151

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

3159
                            continue;
7 ✔
3160
                        }
3161
                    }
3162

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

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

3171
            if (\is_array($usedArrayTmp)) {
196 ✔
3172
                return static::create(
42 ✔
3173
                    [],
42 ✔
3174
                    $this->iteratorClass,
42 ✔
3175
                    false
42 ✔
3176
                )->createByReference($usedArrayTmp);
42 ✔
3177
            }
3178

3179
            return $usedArrayTmp;
196 ✔
3180
        }
3181

3182
        if (!isset($usedArray[$key])) {
210 ✔
3183
            return $fallback instanceof \Closure ? $fallback() : $fallback;
210 ✔
3184
        }
3185

3186
        return static::create(
×
3187
            [],
×
3188
            $this->iteratorClass,
×
3189
            false
×
3190
        )->createByReference($usedArray);
×
3191
    }
3192

3193
    /**
3194
     * alias: for "Arrayy->toArray()"
3195
     *
3196
     * @return array
3197
     *
3198
     * @see          Arrayy::getArray()
3199
     *
3200
     * @phpstan-return array<TKey,T>
3201
     */
3202
    public function getAll(): array
3203
    {
3204
        /** @var array<TKey,T> $return */
3205
        $return = $this->toArray();
105 ✔
3206

3207
        return $return;
105 ✔
3208
    }
3209

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

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

3258
        $jsonObject = \json_decode($json, false);
56 ✔
3259

3260
        $mapper = new \Arrayy\Mapper\Json();
56 ✔
3261
        $mapper->undefinedPropertyHandler = static function ($object, $key, $jsonValue) use ($class) {
56 ✔
3262
            if ($class->checkPropertiesMismatchInConstructor) {
×
3263
                throw new \TypeError('Property mismatch - input: ' . \print_r(['key' => $key, 'jsonValue' => $jsonValue], true) . ' for object: ' . \get_class($object));
×
3264
            }
3265
        };
56 ✔
3266

3267
        /** @var static $return - hack for phpstan */
3268
        $return = $mapper->map($jsonObject, $class);
56 ✔
3269

3270
        return $return;
35 ✔
3271
    }
3272

3273
    /**
3274
     * @return array<array-key,TypeCheckInterface>|TypeCheckArray<array-key,TypeCheckInterface>
3275
     *
3276
     * @internal
3277
     */
3278
    public function getPhpDocPropertiesFromClass()
3279
    {
3280
        if ($this->properties === []) {
166 ✔
3281
            $this->properties = $this->getPropertiesFromPhpDoc();
96 ✔
3282
        }
3283

3284
        return $this->properties;
166 ✔
3285
    }
3286

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

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

3344
                    if ($indexKey !== null) {
7 ✔
3345
                        foreach ($value as $keyInner => $valueInner) {
7 ✔
3346
                            if ($indexKey === $keyInner) {
7 ✔
3347
                                $newKey = $valueInner;
7 ✔
3348
                            }
3349

3350
                            if ($columnKey === $keyInner) {
7 ✔
3351
                                $newValue = $valueInner;
7 ✔
3352
                                $newValueFound = true;
7 ✔
3353
                            }
3354
                        }
3355
                    } else {
3356
                        foreach ($value as $keyInner => $valueInner) {
7 ✔
3357
                            if ($columnKey === $keyInner) {
7 ✔
3358
                                $newValue = $valueInner;
7 ✔
3359
                                $newValueFound = true;
7 ✔
3360
                            }
3361
                        }
3362
                    }
3363

3364
                    if ($newValueFound === false) {
7 ✔
3365
                        if ($newKey !== null) {
7 ✔
3366
                            yield $newKey => $value;
7 ✔
3367
                        } else {
3368
                            yield $value;
7 ✔
3369
                        }
3370
                    } else {
3371
                        /** @noinspection NestedPositiveIfStatementsInspection */
3372
                        if ($newKey !== null) {
7 ✔
3373
                            yield $newKey => $newValue;
7 ✔
3374
                        } else {
3375
                            yield $newValue;
7 ✔
3376
                        }
3377
                    }
3378
                }
3379
            };
7 ✔
3380
        }
3381

3382
        return static::create(
7 ✔
3383
            $generator,
7 ✔
3384
            $this->iteratorClass,
7 ✔
3385
            false
7 ✔
3386
        );
7 ✔
3387
    }
3388

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

3403
            return;
35 ✔
3404
        }
3405

3406
        // -> false-positive -> see "&$value"
3407
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3408
        foreach ($this->array as $key => &$value) {
490 ✔
3409
            yield $key => $value;
441 ✔
3410
        }
3411
    }
3412

3413
    /**
3414
     * Get the current array from the "Arrayy"-object as generator.
3415
     *
3416
     * @return \Generator
3417
     *
3418
     * @phpstan-return \Generator<mixed,T>|\Generator<TKey,T>
3419
     * @psalm-mutation-free
3420
     */
3421
    public function getGenerator(): \Generator
3422
    {
3423
        if ($this->generator instanceof ArrayyRewindableGenerator) {
7,880 ✔
3424
            yield from $this->generator;
546 ✔
3425

3426
            return;
546 ✔
3427
        }
3428

3429
        yield from $this->array;
7,866 ✔
3430
    }
3431

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

3445
    /**
3446
     * alias: for "Arrayy->keys()"
3447
     *
3448
     * @return static
3449
     *                <p>(Immutable)</p>
3450
     *
3451
     * @see          Arrayy::keys()
3452
     *
3453
     * @phpstan-return static
3454
     * @psalm-mutation-free
3455
     */
3456
    public function getKeys()
3457
    {
3458
        return $this->keys();
14 ✔
3459
    }
3460

3461
    /**
3462
     * Get the current array from the "Arrayy"-object as object.
3463
     *
3464
     * @return \stdClass
3465
     */
3466
    public function getObject(): \stdClass
3467
    {
3468
        return self::arrayToObject($this->toArray());
28 ✔
3469
    }
3470

3471
    /**
3472
     * alias: for "Arrayy->randomImmutable()"
3473
     *
3474
     * @return static
3475
     *                <p>(Immutable)</p>
3476
     *
3477
     * @see          Arrayy::randomImmutable()
3478
     *
3479
     * @phpstan-return static
3480
     */
3481
    public function getRandom(): self
3482
    {
3483
        return $this->randomImmutable();
28 ✔
3484
    }
3485

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

3501
    /**
3502
     * alias: for "Arrayy->randomKeys()"
3503
     *
3504
     * @param int $number
3505
     *
3506
     * @return static
3507
     *                <p>(Immutable)</p>
3508
     *
3509
     * @see          Arrayy::randomKeys()
3510
     *
3511
     * @phpstan-return static
3512
     */
3513
    public function getRandomKeys(int $number): self
3514
    {
3515
        return $this->randomKeys($number);
56 ✔
3516
    }
3517

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

3533
    /**
3534
     * alias: for "Arrayy->randomValues()"
3535
     *
3536
     * @param int $number
3537
     *
3538
     * @return static
3539
     *                <p>(Immutable)</p>
3540
     *
3541
     * @see          Arrayy::randomValues()
3542
     *
3543
     * @phpstan-return static
3544
     */
3545
    public function getRandomValues(int $number): self
3546
    {
3547
        return $this->randomValues($number);
42 ✔
3548
    }
3549

3550
    /**
3551
     * Gets all values.
3552
     *
3553
     * @return static
3554
     *                <p>The values of all elements in this array, in the order they
3555
     *                appear in the array.</p>
3556
     *
3557
     * @phpstan-return static
3558
     */
3559
    public function getValues()
3560
    {
3561
        $this->generatorToArray(false);
28 ✔
3562

3563
        return static::create(
28 ✔
3564
            \array_values($this->array),
28 ✔
3565
            $this->iteratorClass,
28 ✔
3566
            false
28 ✔
3567
        );
28 ✔
3568
    }
3569

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

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

3602
        // Iterate over values, group by property/results from closure.
3603
        foreach ($this->getGenerator() as $key => $value) {
28 ✔
3604
            if (\is_callable($grouper) === true) {
28 ✔
3605
                $groupKey = $grouper($value, $key);
21 ✔
3606
            } else {
3607
                $groupKey = $this->get($grouper);
7 ✔
3608
            }
3609

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

3612
            if ($groupKey instanceof self) {
28 ✔
3613
                $groupKey = $groupKey->toArray();
×
3614
            }
3615

3616
            if ($newValue instanceof self) {
28 ✔
3617
                $newValue = $newValue->toArray();
28 ✔
3618
            }
3619

3620
            // Add to result.
3621
            if ($groupKey !== null) {
28 ✔
3622
                $result[$groupKey] = $newValue;
21 ✔
3623

3624
                if ($saveKeys) {
21 ✔
3625
                    $result[$groupKey][$key] = $value;
14 ✔
3626
                } else {
3627
                    $result[$groupKey][] = $value;
7 ✔
3628
                }
3629
            }
3630
        }
3631

3632
        return static::create(
28 ✔
3633
            $result,
28 ✔
3634
            $this->iteratorClass,
28 ✔
3635
            false
28 ✔
3636
        );
28 ✔
3637
    }
3638

3639
    /**
3640
     * Check if an array has a given key.
3641
     *
3642
     * @param mixed $key
3643
     *
3644
     * @return bool
3645
     *
3646
     * @phpstan-param null|TKey|TKey[] $key
3647
     */
3648
    public function has($key): bool
3649
    {
3650
        static $UN_FOUND = null;
210 ✔
3651

3652
        if ($UN_FOUND === null) {
210 ✔
3653
            // Generate unique string to use as marker.
3654
            $UN_FOUND = 'arrayy--' . \uniqid('arrayy', true);
7 ✔
3655
        }
3656

3657
        if (\is_array($key)) {
210 ✔
3658
            if ($key === []) {
7 ✔
3659
                return false;
×
3660
            }
3661

3662
            foreach ($key as $keyTmp) {
7 ✔
3663
                $found = ($this->get($keyTmp, $UN_FOUND) !== $UN_FOUND);
7 ✔
3664
                if ($found === false) {
7 ✔
3665
                    return false;
7 ✔
3666
                }
3667
            }
3668

3669
            return true;
7 ✔
3670
        }
3671

3672
        return $this->get($key, $UN_FOUND) !== $UN_FOUND;
203 ✔
3673
    }
3674

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

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

3709
    /**
3710
     * Implodes the keys of this array.
3711
     *
3712
     * @param string $glue
3713
     *
3714
     * @return string
3715
     * @psalm-mutation-free
3716
     */
3717
    public function implodeKeys(string $glue = ''): string
3718
    {
3719
        return $this->implode_recursive($glue, $this->toArray(), true);
56 ✔
3720
    }
3721

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

3741
        foreach ($this->getGenerator() as $a) {
28 ✔
3742
            if (\array_key_exists($key, $a) === true) {
28 ✔
3743
                $results[$a[$key]] = $a;
21 ✔
3744
            }
3745
        }
3746

3747
        return static::create(
28 ✔
3748
            $results,
28 ✔
3749
            $this->iteratorClass,
28 ✔
3750
            false
28 ✔
3751
        );
28 ✔
3752
    }
3753

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

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

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

3829
        return static::create(
21 ✔
3830
            \array_values(\array_intersect($this->toArray(), $search)),
21 ✔
3831
            $this->iteratorClass,
21 ✔
3832
            false
21 ✔
3833
        );
21 ✔
3834
    }
3835

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

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

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

3899
        // If the callable has arguments, pass them.
3900
        if ($arguments) {
7 ✔
3901
            $array = \array_map($callable, $this->toArray(), $arguments);
7 ✔
3902
        } else {
3903
            $array = $this->map($callable);
7 ✔
3904
        }
3905

3906
        return static::create(
7 ✔
3907
            $array,
7 ✔
3908
            $this->iteratorClass,
7 ✔
3909
            false
7 ✔
3910
        );
7 ✔
3911
    }
3912

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

3931
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
3932
        foreach ($this->keys($recursive)->getGeneratorByReference() as &$key) {
91 ✔
3933
            if ((string) $key !== $key) {
91 ✔
3934
                return false;
77 ✔
3935
            }
3936
        }
3937

3938
        return true;
21 ✔
3939
    }
3940

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

3956
        if ($keys === null) {
315 ✔
3957
            return $this->array === [];
301 ✔
3958
        }
3959

3960
        foreach ((array) $keys as $key) {
14 ✔
3961
            if (!empty($this->get($key))) {
14 ✔
3962
                return false;
14 ✔
3963
            }
3964
        }
3965

3966
        return true;
14 ✔
3967
    }
3968

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

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

4004
        return false;
126 ✔
4005
    }
4006

4007
    /**
4008
     * Check whether array is numeric or not.
4009
     *
4010
     * @return bool
4011
     *              <p>Returns true if numeric, false otherwise.</p>
4012
     */
4013
    public function isNumeric(): bool
4014
    {
4015
        if ($this->isEmpty()) {
35 ✔
4016
            return false;
14 ✔
4017
        }
4018

4019
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4020
        foreach ($this->keys()->getGeneratorByReference() as &$key) {
28 ✔
4021
            if ((int) $key !== $key) {
28 ✔
4022
                return false;
14 ✔
4023
            }
4024
        }
4025

4026
        return true;
14 ✔
4027
    }
4028

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

4057
            if ($key !== $i) {
63 ✔
4058
                return false;
21 ✔
4059
            }
4060

4061
            ++$i;
56 ✔
4062
        }
4063

4064
        return !($i === 0);
63 ✔
4065
    }
4066

4067
    /**
4068
     * @return array
4069
     *
4070
     * @phpstan-return array<TKey,T>
4071
     */
4072
    public function jsonSerialize(): array
4073
    {
4074
        /** @var array<TKey,T> $return */
4075
        $return = $this->toArray();
14 ✔
4076

4077
        return $return;
14 ✔
4078
    }
4079

4080
    /**
4081
     * Gets the key/index of the element at the current internal iterator position.
4082
     *
4083
     * @return int|string|null
4084
     * @phpstan-return array-key|null
4085
     */
4086
    public function key()
4087
    {
4088
        if ($this->generator) {
×
4089
            return $this->generator->key();
×
4090
        }
4091

4092
        return \key($this->array);
×
4093
    }
4094

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

4114
        return false;
1,022 ✔
4115
    }
4116

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

4152
        if ($recursive === true) {
210 ✔
4153
            $array = $this->array_keys_recursive(
28 ✔
4154
                null,
28 ✔
4155
                $search_values,
28 ✔
4156
                $strict
28 ✔
4157
            );
28 ✔
4158

4159
            return static::create(
28 ✔
4160
                $array,
28 ✔
4161
                $this->iteratorClass,
28 ✔
4162
                false
28 ✔
4163
            );
28 ✔
4164
        }
4165

4166
        // non recursive
4167

4168
        if ($search_values === null) {
203 ✔
4169
            $arrayFunction = function (): \Generator {
203 ✔
4170
                foreach ($this->getGenerator() as $key => $value) {
203 ✔
4171
                    yield $key;
189 ✔
4172
                }
4173
            };
203 ✔
4174
        } else {
4175
            $arrayFunction = function () use ($search_values, $strict): \Generator {
7 ✔
4176
                $is_array_tmp = \is_array($search_values);
7 ✔
4177

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

4209
        return static::create(
203 ✔
4210
            $arrayFunction,
203 ✔
4211
            $this->iteratorClass,
203 ✔
4212
            false
203 ✔
4213
        );
203 ✔
4214
    }
4215

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

4234
        \krsort($this->array, $sort_flags);
28 ✔
4235

4236
        return $this;
28 ✔
4237
    }
4238

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

4258
        /**
4259
         * @psalm-suppress ImpureMethodCall - object is already cloned
4260
         */
4261
        $that->krsort($sort_flags);
28 ✔
4262

4263
        return $that;
28 ✔
4264
    }
4265

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

4286
        /** @var T $value_last */
4287
        $value_last = $this->get($key_last);
105 ✔
4288

4289
        return $value_last;
105 ✔
4290
    }
4291

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

4305
        return \array_key_last($this->array);
147 ✔
4306
    }
4307

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

4333
        if ($number === null) {
84 ✔
4334
            $poppedValue = $this->last();
56 ✔
4335

4336
            if ($poppedValue === null) {
56 ✔
4337
                $poppedValue = [$poppedValue];
7 ✔
4338
            } else {
4339
                $poppedValue = (array) $poppedValue;
49 ✔
4340
            }
4341

4342
            $arrayy = static::create(
56 ✔
4343
                $poppedValue,
56 ✔
4344
                $this->iteratorClass,
56 ✔
4345
                false
56 ✔
4346
            );
56 ✔
4347
        } else {
4348
            $arrayy = $this->rest(-$number);
28 ✔
4349
        }
4350

4351
        return $arrayy;
84 ✔
4352
    }
4353

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

4374
        $this->array = $this->lastsImmutable($number)->toArray();
84 ✔
4375
        $this->generator = null;
84 ✔
4376

4377
        return $this;
84 ✔
4378
    }
4379

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

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

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

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

4474
        foreach ($this->getGenerator() as $key => $value) {
91 ✔
4475
            $value = $closure($value, $key);
91 ✔
4476

4477
            if ($value === false) {
91 ✔
4478
                return false;
49 ✔
4479
            }
4480
        }
4481

4482
        return true;
49 ✔
4483
    }
4484

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

4507
        foreach ($this->getGenerator() as $key => $value) {
84 ✔
4508
            $value = $closure($value, $key);
84 ✔
4509

4510
            if ($value === true) {
84 ✔
4511
                return true;
63 ✔
4512
            }
4513
        }
4514

4515
        return false;
28 ✔
4516
    }
4517

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

4534
        $max = false;
70 ✔
4535
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4536
        foreach ($this->getGeneratorByReference() as &$value) {
70 ✔
4537
            if (
4538
                $max === false
70 ✔
4539
                ||
4540
                $value > $max
70 ✔
4541
            ) {
4542
                $max = $value;
70 ✔
4543
            }
4544
        }
4545

4546
        return $max;
70 ✔
4547
    }
4548

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

4583
        return static::create(
231 ✔
4584
            $result,
231 ✔
4585
            $this->iteratorClass,
231 ✔
4586
            false
231 ✔
4587
        );
231 ✔
4588
    }
4589

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

4625
        return static::create(
140 ✔
4626
            $result,
140 ✔
4627
            $this->iteratorClass,
140 ✔
4628
            false
140 ✔
4629
        );
140 ✔
4630
    }
4631

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

4666
        return static::create(
119 ✔
4667
            $result,
119 ✔
4668
            $this->iteratorClass,
119 ✔
4669
            false
119 ✔
4670
        );
119 ✔
4671
    }
4672

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

4708
        return static::create(
147 ✔
4709
            $result,
147 ✔
4710
            $this->iteratorClass,
147 ✔
4711
            false
147 ✔
4712
        );
147 ✔
4713
    }
4714

4715
    /**
4716
     * Return a meta object with property names from phpdoc array-shape annotations,
4717
     * `@property` tags, and native declared properties.
4718
     *
4719
     * @return ArrayyMeta|mixed|static
4720
     */
4721
    public static function meta()
4722
    {
4723
        return (new ArrayyMeta())->getMetaObject(static::class);
320 ✔
4724
    }
4725

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

4744
        $min = false;
70 ✔
4745
        /** @noinspection PhpParameterByRefIsNotUsedAsReferenceInspection */
4746
        foreach ($this->getGeneratorByReference() as &$value) {
70 ✔
4747
            if (
4748
                $min === false
70 ✔
4749
                ||
4750
                $value < $min
70 ✔
4751
            ) {
4752
                $min = $value;
70 ✔
4753
            }
4754
        }
4755

4756
        return $min;
70 ✔
4757
    }
4758

4759
    /**
4760
     * Get the most used value from the array.
4761
     *
4762
     * @return mixed|null
4763
     *                    <p>(Immutable) Return null if there wasn't an element.</p>
4764
     *
4765
     * @phpstan-return T|null
4766
     * @psalm-mutation-free
4767
     */
4768
    public function mostUsedValue()
4769
    {
4770
        /* @phpstan-ignore return.type */
4771
        return $this->countValues()->arsortImmutable()->firstKey();
21 ✔
4772
    }
4773

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

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

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

4834
        return static::create(
7 ✔
4835
            $output,
7 ✔
4836
            $this->iteratorClass,
7 ✔
4837
            false
7 ✔
4838
        );
7 ✔
4839
    }
4840

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

4859
        if ($this->offsetExists($key)) {
7 ✔
4860
            $tmpValue = $this->get($key);
7 ✔
4861
            unset($array[$key]);
7 ✔
4862
            $array = [$key => $tmpValue] + $array;
7 ✔
4863
        }
4864

4865
        return static::create(
7 ✔
4866
            $array,
7 ✔
4867
            $this->iteratorClass,
7 ✔
4868
            false
7 ✔
4869
        );
7 ✔
4870
    }
4871

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

4890
        if ($this->offsetExists($key)) {
7 ✔
4891
            $tmpValue = $this->get($key);
7 ✔
4892
            unset($array[$key]);
7 ✔
4893
            $array += [$key => $tmpValue];
7 ✔
4894
        }
4895

4896
        return static::create(
7 ✔
4897
            $array,
7 ✔
4898
            $this->iteratorClass,
7 ✔
4899
            false
7 ✔
4900
        );
7 ✔
4901
    }
4902

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

4916
            return $this->generator->current() ?? false;
×
4917
        }
4918

4919
        return \next($this->array);
×
4920
    }
4921

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

4943
                yield $key => $value;
7 ✔
4944
            }
4945
        };
7 ✔
4946

4947
        return static::create(
7 ✔
4948
            $arrayFunction,
7 ✔
4949
            $this->iteratorClass,
7 ✔
4950
            false
7 ✔
4951
        );
7 ✔
4952
    }
4953

4954
    /**
4955
     * Get a subset of the items from the given array.
4956
     *
4957
     * @param int[]|string[] $keys
4958
     *
4959
     * @return static
4960
     *                <p>(Immutable)</p>
4961
     *
4962
     * @phpstan-param array-key[] $keys
4963
     * @phpstan-return static
4964
     * @psalm-mutation-free
4965
     */
4966
    public function only(array $keys): self
4967
    {
4968
        $keys = \array_flip($keys);
7 ✔
4969

4970
        $generator = function () use ($keys): \Generator {
7 ✔
4971
            foreach ($this->getGenerator() as $key => $value) {
7 ✔
4972
                if (isset($keys[$key])) {
7 ✔
4973
                    yield $key => $value;
7 ✔
4974
                }
4975
            }
4976
        };
7 ✔
4977

4978
        return static::create(
7 ✔
4979
            $generator,
7 ✔
4980
            $this->iteratorClass,
7 ✔
4981
            false
7 ✔
4982
        );
7 ✔
4983
    }
4984

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

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

5027
        foreach ($this->getGenerator() as $key => $value) {
7 ✔
5028
            if ($closure($value, $key)) {
7 ✔
5029
                $matches[$key] = $value;
7 ✔
5030
            } else {
5031
                $noMatches[$key] = $value;
7 ✔
5032
            }
5033
        }
5034

5035
        return [self::create($matches), self::create($noMatches)];
7 ✔
5036
    }
5037

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

5050
        return \array_pop($this->array);
35 ✔
5051
    }
5052

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

5074
        if ($this->properties !== []) {
84 ✔
5075
            $this->checkType($key, $value);
28 ✔
5076
        }
5077

5078
        if ($key === null) {
70 ✔
5079
            \array_unshift($this->array, $value);
56 ✔
5080
        } else {
5081
            $this->array = [$key => $value] + $this->array; // @phpstan-ignore assign.propertyType
21 ✔
5082
        }
5083

5084
        return $this;
70 ✔
5085
    }
5086

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

5112
            if ($key !== null) {
7 ✔
5113
                yield $key => $value;
×
5114
            } else {
5115
                yield $value;
7 ✔
5116
            }
5117

5118
            foreach ($this->getGenerator() as $keyOld => $itemOld) {
7 ✔
5119
                yield $keyOld => $itemOld;
7 ✔
5120
            }
5121
        };
7 ✔
5122

5123
        return static::create(
7 ✔
5124
            $generator,
7 ✔
5125
            $this->iteratorClass,
7 ✔
5126
            false
7 ✔
5127
        );
7 ✔
5128
    }
5129

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

5146
        foreach ($this->getGenerator() as $key => $item) {
70 ✔
5147
            if ($item instanceof self) {
63 ✔
5148
                $result[$key] = $item->prependToEachKey($suffix);
×
5149
            } elseif (\is_array($item)) {
63 ✔
5150
                $result[$key] = self::create(
×
5151
                    $item,
×
5152
                    $this->iteratorClass,
×
5153
                    false
×
5154
                )->prependToEachKey($suffix)
×
5155
                    ->toArray();
×
5156
            } else {
5157
                $result[$key . $suffix] = $item;
63 ✔
5158
            }
5159
        }
5160

5161
        return self::create(
70 ✔
5162
            $result,
70 ✔
5163
            $this->iteratorClass,
70 ✔
5164
            false
70 ✔
5165
        );
70 ✔
5166
    }
5167

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

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

5201
        return self::create(
70 ✔
5202
            $result,
70 ✔
5203
            $this->iteratorClass,
70 ✔
5204
            false
70 ✔
5205
        );
70 ✔
5206
    }
5207

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

5227
            return $array;
7 ✔
5228
        }
5229

5230
        if (\is_array($keyOrKeys)) {
35 ✔
5231
            $valueOrValues = [];
7 ✔
5232
            foreach ($keyOrKeys as $key) {
7 ✔
5233
                $valueOrValues[] = $this->get($key, $fallback);
7 ✔
5234
                $this->offsetUnset($key);
7 ✔
5235
            }
5236
        } else {
5237
            $valueOrValues = $this->get($keyOrKeys, $fallback);
35 ✔
5238
            $this->offsetUnset($keyOrKeys);
35 ✔
5239
        }
5240

5241
        /** @var T|T[]|TFallback $valueOrValues */
5242
        return $valueOrValues;
35 ✔
5243
    }
5244

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

5262
        if (
5263
            $this->checkPropertyTypes
63 ✔
5264
            &&
5265
            $this->properties !== []
63 ✔
5266
        ) {
5267
            foreach ($args as $key => $value) {
21 ✔
5268
                $this->checkType($key, $value);
21 ✔
5269
            }
5270
        }
5271

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

5274
        return $this;
56 ✔
5275
    }
5276

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

5295
        if ($this->count() === 0) {
133 ✔
5296
            return static::create(
7 ✔
5297
                [],
7 ✔
5298
                $this->iteratorClass,
7 ✔
5299
                false
7 ✔
5300
            );
7 ✔
5301
        }
5302

5303
        if ($number === null) {
126 ✔
5304
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
91 ✔
5305

5306
            return static::create(
91 ✔
5307
                $arrayRandValue,
91 ✔
5308
                $this->iteratorClass,
91 ✔
5309
                false
91 ✔
5310
            );
91 ✔
5311
        }
5312

5313
        $arrayTmp = $this->array;
42 ✔
5314
        \shuffle($arrayTmp);
42 ✔
5315

5316
        return static::create(
42 ✔
5317
            $arrayTmp,
42 ✔
5318
            $this->iteratorClass,
42 ✔
5319
            false
42 ✔
5320
        )->firstsImmutable($number);
42 ✔
5321
    }
5322

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

5342
        if (!isset($result[0])) {
28 ✔
5343
            $result[0] = null;
×
5344
        }
5345

5346
        return $result[0];
28 ✔
5347
    }
5348

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

5369
        $count = $this->count();
91 ✔
5370

5371
        if (
5372
            $number === 0
91 ✔
5373
            ||
5374
            $number > $count
91 ✔
5375
        ) {
5376
            throw new \RangeException(
14 ✔
5377
                \sprintf(
14 ✔
5378
                    'Number of requested keys (%s) must be equal or lower than number of elements in this array (%s)',
14 ✔
5379
                    $number,
14 ✔
5380
                    $count
14 ✔
5381
                )
14 ✔
5382
            );
14 ✔
5383
        }
5384

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

5387
        return static::create(
77 ✔
5388
            $result,
77 ✔
5389
            $this->iteratorClass,
77 ✔
5390
            false
77 ✔
5391
        );
77 ✔
5392
    }
5393

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

5412
        if ($this->count() === 0) {
119 ✔
5413
            return static::create(
×
5414
                [],
×
5415
                $this->iteratorClass,
×
5416
                false
×
5417
            );
×
5418
        }
5419

5420
        if ($number === null) {
119 ✔
5421
            $arrayRandValue = [$this->array[\array_rand($this->array)]];
49 ✔
5422
            $this->array = $arrayRandValue; // @phpstan-ignore assign.propertyType
49 ✔
5423

5424
            return $this;
49 ✔
5425
        }
5426

5427
        \shuffle($this->array);
77 ✔
5428

5429
        return $this->firstsMutable($number);
77 ✔
5430
    }
5431

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

5448
        if (!isset($result[0])) {
28 ✔
5449
            $result[0] = null;
×
5450
        }
5451

5452
        return $result[0];
28 ✔
5453
    }
5454

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

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

5495
        foreach ($array as $option => $weight) {
63 ✔
5496
            if ($this->searchIndex($option) !== false) {
63 ✔
5497
                for ($i = 0; $i < $weight; ++$i) {
14 ✔
5498
                    $options[] = $option;
7 ✔
5499
                }
5500
            }
5501
        }
5502

5503
        return $this->mergeAppendKeepIndex($options)->randomImmutable($number);
63 ✔
5504
    }
5505

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

5539
        /** @var static $return - help for phpstan */
5540
        $return = static::create(
126 ✔
5541
            $initial,
126 ✔
5542
            $this->iteratorClass,
126 ✔
5543
            false
126 ✔
5544
        );
126 ✔
5545

5546
        return $return;
126 ✔
5547
    }
5548

5549
    /**
5550
     * @param bool $unique
5551
     *
5552
     * @return static
5553
     *                <p>(Immutable)</p>
5554
     *
5555
     * @phpstan-return static
5556
     * @psalm-mutation-free
5557
     */
5558
    public function reduce_dimension(bool $unique = true): self
5559
    {
5560
        // init
5561
        $result = [];
98 ✔
5562

5563
        foreach ($this->getGenerator() as $val) {
98 ✔
5564
            if (\is_array($val)) {
84 ✔
5565
                $result[] = static::create($val)->reduce_dimension($unique)->toArray();
35 ✔
5566
            } else {
5567
                $result[] = [$val];
84 ✔
5568
            }
5569
        }
5570

5571
        $result = $result === [] ? [] : \array_merge(...$result);
98 ✔
5572

5573
        $resultArrayy = static::create($result);
98 ✔
5574

5575
        /**
5576
         * @psalm-suppress ImpureMethodCall - object is already re-created
5577
         * @psalm-suppress InvalidReturnStatement - why?
5578
         */
5579
        return $unique ? $resultArrayy->unique() : $resultArrayy;
98 ✔
5580
    }
5581

5582
    /**
5583
     * Create a numerically re-indexed Arrayy object.
5584
     *
5585
     * EXAMPLE: <code>
5586
     * a([2 => 1, 3 => 2])->reindex(); // Arrayy[0 => 1, 1 => 2]
5587
     * </code>
5588
     *
5589
     * @return $this
5590
     *               <p>(Mutable) Return this Arrayy object, with re-indexed array-elements.</p>
5591
     *
5592
     * @phpstan-return static
5593
     */
5594
    public function reindex(): self
5595
    {
5596
        $this->generatorToArray(false);
63 ✔
5597

5598
        $this->array = \array_values($this->array);
63 ✔
5599

5600
        return $this;
63 ✔
5601
    }
5602

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

5627
        foreach ($this->getGenerator() as $key => $value) {
7 ✔
5628
            if (!$closure($value, $key)) {
7 ✔
5629
                $filtered[$key] = $value;
7 ✔
5630
            }
5631
        }
5632

5633
        return static::create(
7 ✔
5634
            $filtered,
7 ✔
5635
            $this->iteratorClass,
7 ✔
5636
            false
7 ✔
5637
        );
7 ✔
5638
    }
5639

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

5663
            return static::create(
7 ✔
5664
                $this->toArray(),
7 ✔
5665
                $this->iteratorClass,
7 ✔
5666
                false
7 ✔
5667
            );
7 ✔
5668
        }
5669

5670
        $this->internalRemove($key);
147 ✔
5671

5672
        return static::create(
147 ✔
5673
            $this->toArray(),
147 ✔
5674
            $this->iteratorClass,
147 ✔
5675
            false
147 ✔
5676
        );
147 ✔
5677
    }
5678

5679
    /**
5680
     * alias: for "Arrayy->removeValue()"
5681
     *
5682
     * @param mixed $element
5683
     *
5684
     * @return static
5685
     *                <p>(Immutable)</p>
5686
     *
5687
     * @phpstan-param  T $element
5688
     * @phpstan-return static
5689
     * @psalm-mutation-free
5690
     */
5691
    public function removeElement($element)
5692
    {
5693
        return $this->removeValue($element);
56 ✔
5694
    }
5695

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

5713
        \array_shift($tmpArray);
49 ✔
5714

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

5722
    /**
5723
     * Remove the last value from the current array.
5724
     *
5725
     * EXAMPLE: <code>
5726
     * a([1 => 'bar', 'foo' => 'foo'])->removeLast(); // Arrayy[1 => 'bar']
5727
     * </code>
5728
     *
5729
     * @return static
5730
     *                <p>(Immutable)</p>
5731
     *
5732
     * @phpstan-return static
5733
     * @psalm-mutation-free
5734
     */
5735
    public function removeLast(): self
5736
    {
5737
        $tmpArray = $this->toArray();
49 ✔
5738

5739
        \array_pop($tmpArray);
49 ✔
5740

5741
        return static::create(
49 ✔
5742
            $tmpArray,
49 ✔
5743
            $this->iteratorClass,
49 ✔
5744
            false
49 ✔
5745
        );
49 ✔
5746
    }
5747

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

5768
        // init
5769
        $isSequentialArray = $this->isSequential();
56 ✔
5770

5771
        foreach ($this->array as $key => $item) {
56 ✔
5772
            if ($item === $value) {
49 ✔
5773
                unset($this->array[$key]);
49 ✔
5774
            }
5775
        }
5776

5777
        if ($isSequentialArray) {
56 ✔
5778
            $this->array = \array_values($this->array);
42 ✔
5779
        }
5780

5781
        return static::create(
56 ✔
5782
            $this->array,
56 ✔
5783
            $this->iteratorClass,
56 ✔
5784
            false
56 ✔
5785
        );
56 ✔
5786
    }
5787

5788
    /**
5789
     * Generate array of repeated arrays.
5790
     *
5791
     * @param int $times <p>How many times has to be repeated.</p>
5792
     *
5793
     * @return static
5794
     *                <p>(Immutable)</p>
5795
     *
5796
     * @phpstan-return static
5797
     * @psalm-mutation-free
5798
     */
5799
    public function repeat($times): self
5800
    {
5801
        if ($times === 0) {
7 ✔
5802
            return static::create([], $this->iteratorClass);
7 ✔
5803
        }
5804

5805
        return static::create(
7 ✔
5806
            \array_fill(0, (int) $times, $this->toArray()),
7 ✔
5807
            $this->iteratorClass,
7 ✔
5808
            false
7 ✔
5809
        );
7 ✔
5810
    }
5811

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

5837
        /**
5838
         * @psalm-suppress ImpureMethodCall - object is already cloned
5839
         */
5840
        return $that->remove($oldKey)
35 ✔
5841
            ->set($newKey, $newValue);
35 ✔
5842
    }
5843

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

5881
        return static::create(
14 ✔
5882
            $data,
14 ✔
5883
            $this->iteratorClass,
14 ✔
5884
            false
14 ✔
5885
        );
14 ✔
5886
    }
5887

5888
    /**
5889
     * Create an array using the current array as keys and the other array as values.
5890
     *
5891
     * EXAMPLE: <code>
5892
     * $firstArray = [
5893
     *     1 => 'one',
5894
     *     2 => 'two',
5895
     *     3 => 'three',
5896
     * ];
5897
     * $secondArray = [
5898
     *     'one' => 1,
5899
     *     1     => 'one',
5900
     *     2     => 2,
5901
     * ];
5902
     * $arrayy = a($firstArray);
5903
     * $arrayy->replaceAllValues($secondArray); // Arrayy['one' => 1, 'two' => 'one', 'three' => 2]
5904
     * </code>
5905
     *
5906
     * @param array $array <p>An array of values.</p>
5907
     *
5908
     * @return static
5909
     *                <p>(Immutable) Arrayy object with values from the other array, empty Arrayy object if the number of elements
5910
     *                for each array isn't equal or if the arrays are empty.
5911
     *                </p>
5912
     *
5913
     * @phpstan-param  array<T> $array
5914
     * @phpstan-return static
5915
     * @psalm-mutation-free
5916
     */
5917
    public function replaceAllValues(array $array): self
5918
    {
5919
        $data = \array_combine($this->toArray(), $array);
14 ✔
5920
        /* @phpstan-ignore identical.alwaysFalse */
5921
        if ($data === false) {
14 ✔
5922
            $data = [];
×
5923
        }
5924

5925
        return static::create(
14 ✔
5926
            $data,
14 ✔
5927
            $this->iteratorClass,
14 ✔
5928
            false
14 ✔
5929
        );
14 ✔
5930
    }
5931

5932
    /**
5933
     * Replace the keys in an array with another set.
5934
     *
5935
     * EXAMPLE: <code>
5936
     * a([1 => 'bar', 'foo' => 'foo'])->replaceKeys([1 => 2, 'foo' => 'replaced']); // Arrayy[2 => 'bar', 'replaced' => 'foo']
5937
     * </code>
5938
     *
5939
     * @param array $keys <p>An array of keys matching the array's size.</p>
5940
     *
5941
     * @return static
5942
     *                <p>(Immutable)</p>
5943
     *
5944
     * @phpstan-param  array<TKey> $keys
5945
     * @phpstan-return static
5946
     * @psalm-mutation-free
5947
     */
5948
    public function replaceKeys(array $keys): self
5949
    {
5950
        $values = \array_values($this->toArray());
7 ✔
5951
        $result = \array_combine($keys, $values);
7 ✔
5952
        /* @phpstan-ignore identical.alwaysFalse */
5953
        if ($result === false) {
7 ✔
5954
            $result = [];
×
5955
        }
5956

5957
        return static::create(
7 ✔
5958
            $result,
7 ✔
5959
            $this->iteratorClass,
7 ✔
5960
            false
7 ✔
5961
        );
7 ✔
5962
    }
5963

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

5988
        if ($key !== false) {
21 ✔
5989
            $array[$key] = $replacement;
21 ✔
5990
        }
5991

5992
        return static::create(
21 ✔
5993
            $array,
21 ✔
5994
            $this->iteratorClass,
21 ✔
5995
            false
21 ✔
5996
        );
21 ✔
5997
    }
5998

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

6022
        /* @phpstan-ignore argument.type */
6023
        return $this->each($callable);
7 ✔
6024
    }
6025

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

6045
        return static::create(
105 ✔
6046
            \array_splice($tmpArray, $from),
105 ✔
6047
            $this->iteratorClass,
105 ✔
6048
            false
105 ✔
6049
        );
105 ✔
6050
    }
6051

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

6068
        $this->array = \array_reverse($this->array);
63 ✔
6069

6070
        return $this;
63 ✔
6071
    }
6072

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

6089
        $this->array = \array_reverse($this->array, true);
35 ✔
6090

6091
        return $this;
35 ✔
6092
    }
6093

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

6112
        \rsort($this->array, $sort_flags);
28 ✔
6113

6114
        return $this;
28 ✔
6115
    }
6116

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

6136
        /**
6137
         * @psalm-suppress ImpureMethodCall - object is already cloned
6138
         */
6139
        $that->rsort($sort_flags);
28 ✔
6140

6141
        return $that;
28 ✔
6142
    }
6143

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

6169
        return false;
77 ✔
6170
    }
6171

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

6192
        // init
6193
        $return = [];
63 ✔
6194

6195
        if ($this->array === []) {
63 ✔
6196
            return static::create(
×
6197
                [],
×
6198
                $this->iteratorClass,
×
6199
                false
×
6200
            );
×
6201
        }
6202

6203
        // php cast "bool"-index into "int"-index
6204
        /* @phpstan-ignore identical.alwaysFalse */
6205
        if ((bool) $index === $index) {
63 ✔
6206
            $index = (int) $index;
7 ✔
6207
        }
6208

6209
        if ($this->offsetExists($index)) {
63 ✔
6210
            $return = [$this->array[$index]];
49 ✔
6211
        }
6212

6213
        return static::create(
63 ✔
6214
            $return,
63 ✔
6215
            $this->iteratorClass,
63 ✔
6216
            false
63 ✔
6217
        );
63 ✔
6218
    }
6219

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

6242
        return $this;
196 ✔
6243
    }
6244

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

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

6274
        return $this->get($key);
77 ✔
6275
    }
6276

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

6289
        return \array_shift($this->array);
35 ✔
6290
    }
6291

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

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

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

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

6345
        return static::create(
14 ✔
6346
            $array,
14 ✔
6347
            $this->iteratorClass,
14 ✔
6348
            false
14 ✔
6349
        );
14 ✔
6350
    }
6351

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

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

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

6387
        return $itemsTempCount === $size;
7 ✔
6388
    }
6389

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

6407
        // init
6408
        $itemsTempCount = 0;
7 ✔
6409

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

6418
        return $fromSize < $itemsTempCount && $itemsTempCount < $toSize;
7 ✔
6419
    }
6420

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

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

6441
        return $itemsTempCount > $size;
7 ✔
6442
    }
6443

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

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

6464
        return $itemsTempCount < $size;
7 ✔
6465
    }
6466

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

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

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

6554
        return $this->sorting(
140 ✔
6555
            $this->array,
140 ✔
6556
            $direction,
140 ✔
6557
            $strategy,
140 ✔
6558
            $keepKeys
140 ✔
6559
        );
140 ✔
6560
    }
6561

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

6582
        $that->generatorToArray();
84 ✔
6583

6584
        return $that->sorting(
84 ✔
6585
            $that->array,
84 ✔
6586
            $direction,
84 ✔
6587
            $strategy,
84 ✔
6588
            $keepKeys
84 ✔
6589
        );
84 ✔
6590
    }
6591

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

6617
        $this->sorterKeys($this->array, $direction, $strategy);
126 ✔
6618

6619
        return $this;
126 ✔
6620
    }
6621

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

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

6649
        return $that;
56 ✔
6650
    }
6651

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

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

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

6730
        // Transform all values into their results.
6731
        if ($sorter) {
7 ✔
6732
            $arrayy = static::create(
7 ✔
6733
                $array,
7 ✔
6734
                $this->iteratorClass,
7 ✔
6735
                false
7 ✔
6736
            );
7 ✔
6737

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

6748
                    return $sorter === $value;
7 ✔
6749
                }
7 ✔
6750
            );
7 ✔
6751

6752
            $results = $results->toArray();
7 ✔
6753
        } else {
6754
            $results = $array;
7 ✔
6755
        }
6756

6757
        // Sort by the results and replace by original values
6758
        \array_multisort($results, $direction, $strategy, $array);
7 ✔
6759

6760
        return static::create(
7 ✔
6761
            $array,
7 ✔
6762
            $this->iteratorClass,
7 ✔
6763
            false
7 ✔
6764
        );
7 ✔
6765
    }
6766

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

6783
        \array_splice(
7 ✔
6784
            $tmpArray,
7 ✔
6785
            $offset,
7 ✔
6786
            $length ?? $this->count(),
7 ✔
6787
            $replacement
7 ✔
6788
        );
7 ✔
6789

6790
        return static::create(
7 ✔
6791
            $tmpArray,
7 ✔
6792
            $this->iteratorClass,
7 ✔
6793
            false
7 ✔
6794
        );
7 ✔
6795
    }
6796

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

6822
                    if ($i % $numberOfPieces !== 0) {
7 ✔
6823
                        ++$i;
7 ✔
6824

6825
                        continue;
7 ✔
6826
                    }
6827

6828
                    yield $carry;
7 ✔
6829

6830
                    $carry = [];
7 ✔
6831
                    $i = 1;
7 ✔
6832
                }
6833

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

6845
                    if ($i % $numberOfPieces !== 0) {
7 ✔
6846
                        ++$i;
7 ✔
6847

6848
                        continue;
7 ✔
6849
                    }
6850

6851
                    yield $carry;
7 ✔
6852

6853
                    $carry = [];
7 ✔
6854
                    $i = 1;
7 ✔
6855
                }
6856

6857
                if ($carry !== []) {
7 ✔
6858
                    yield $carry;
7 ✔
6859
                }
6860
            };
7 ✔
6861
        }
6862

6863
        return static::create(
7 ✔
6864
            $generator,
7 ✔
6865
            $this->iteratorClass,
7 ✔
6866
            false
7 ✔
6867
        );
7 ✔
6868
    }
6869

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

6891
                if ((bool) \trim((string) $item)) {
7 ✔
6892
                    yield $key => $item;
7 ✔
6893
                }
6894
            }
6895
        };
7 ✔
6896

6897
        return static::create(
7 ✔
6898
            $generator(),
7 ✔
6899
            $this->iteratorClass,
7 ✔
6900
            false
7 ✔
6901
        );
7 ✔
6902
    }
6903

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

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

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

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

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

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

6973
            /* @phpstan-ignore return.type */
6974
            return $array;
21 ✔
6975
        }
6976

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

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

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

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

7024
        return $return;
91 ✔
7025
    }
7026

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

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

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

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

7069
        return $return;
7 ✔
7070
    }
7071

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

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

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

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

7113
        return $this;
91 ✔
7114
    }
7115

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

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

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

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

7152
        return $this;
77 ✔
7153
    }
7154

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

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

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

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

7197
        return $this;
35 ✔
7198
    }
7199

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

7218
        return true;
7 ✔
7219
    }
7220

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

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

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

7302
        return $this;
84 ✔
7303
    }
7304

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

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

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

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

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

7359
        return $object;
21 ✔
7360
    }
7361

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

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

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

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

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

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

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

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

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

7465
        $explodedPath = \explode($this->pathSeparator, $path);
70 ✔
7466
        /* @phpstan-ignore identical.alwaysFalse */
7467
        if ($explodedPath === false) {
70 ✔
7468
            return;
×
7469
        }
7470

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

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

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

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

7512
            return $return;
7 ✔
7513
        }
7514

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

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

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

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

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

7553
        return $data;
9,119 ✔
7554
    }
7555

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

7573
            return true;
21 ✔
7574
        }
7575

7576
        return false;
8,433 ✔
7577
    }
7578

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

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

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

7607
        return $direction;
301 ✔
7608
    }
7609

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

7621
        if (isset($PROPERTY_CACHE[$cacheKey])) {
523 ✔
7622
            $this->optionalProperties = $OPTIONAL_PROPERTY_CACHE[$cacheKey] ?? [];
467 ✔
7623

7624
            return $PROPERTY_CACHE[$cacheKey];
467 ✔
7625
        }
7626

7627
        $properties = $this->getPropertiesFromNativeDefinitions();
145 ✔
7628
        $optionalProperties = [];
145 ✔
7629
        $phpDocPropertyAnnotationStyle = null;
145 ✔
7630

7631
        $reflector = new \ReflectionClass($this);
145 ✔
7632
        $factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
145 ✔
7633
        $docComment = $reflector->getDocComment();
145 ✔
7634
        if ($docComment) {
145 ✔
7635
            $docblock = $factory->create($docComment);
138 ✔
7636
            $this->addPropertiesFromDocBlock($docblock, $properties, $optionalProperties, $phpDocPropertyAnnotationStyle);
138 ✔
7637
        }
7638

7639
        /** @noinspection PhpAssignmentInConditionInspection */
7640
        while ($reflector = $reflector->getParentClass()) {
138 ✔
7641
            $docComment = $reflector->getDocComment();
138 ✔
7642
            if ($docComment) {
138 ✔
7643
                $docblock = $factory->create($docComment);
138 ✔
7644
                $this->addPropertiesFromDocBlock($docblock, $properties, $optionalProperties, $phpDocPropertyAnnotationStyle);
138 ✔
7645
            }
7646
        }
7647

7648
        $this->optionalProperties = $optionalProperties;
131 ✔
7649
        $OPTIONAL_PROPERTY_CACHE[$cacheKey] = $optionalProperties;
131 ✔
7650

7651
        return $PROPERTY_CACHE[$cacheKey] = $properties;
131 ✔
7652
    }
7653

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

7669
        if ($propertyTags !== [] && $arrayShapeItems !== []) {
145 ✔
7670
            throw new \TypeError('Use either @property tags or array-shape annotations for Arrayy property definitions, not both.');
7 ✔
7671
        }
7672

7673
        $currentPhpDocPropertyAnnotationStyle = null;
138 ✔
7674
        if ($propertyTags !== []) {
138 ✔
7675
            $currentPhpDocPropertyAnnotationStyle = 'property';
49 ✔
7676
        } elseif ($arrayShapeItems !== []) {
138 ✔
7677
            $currentPhpDocPropertyAnnotationStyle = 'array-shape';
56 ✔
7678
        }
7679

7680
        if (
7681
            $currentPhpDocPropertyAnnotationStyle !== null
138 ✔
7682
            &&
7683
            $phpDocPropertyAnnotationStyle !== null
138 ✔
7684
            &&
7685
            $phpDocPropertyAnnotationStyle !== $currentPhpDocPropertyAnnotationStyle
138 ✔
7686
        ) {
7687
            throw new \TypeError('Use either @property tags or array-shape annotations for Arrayy property definitions, not both.');
7 ✔
7688
        }
7689

7690
        if ($currentPhpDocPropertyAnnotationStyle !== null) {
138 ✔
7691
            $phpDocPropertyAnnotationStyle = $currentPhpDocPropertyAnnotationStyle;
98 ✔
7692
        }
7693

7694
        /** @var \phpDocumentor\Reflection\DocBlock\Tags\Property $tag */
7695
        foreach ($propertyTags as $tag) {
138 ✔
7696
            $typeName = $tag->getVariableName();
42 ✔
7697
            /** @var string|null $typeName */
7698
            if (
7699
                $typeName !== null
42 ✔
7700
                &&
7701
                isset($properties[$typeName]) === false
42 ✔
7702
            ) {
7703
                $typeCheckPhpDoc = TypeCheckPhpDoc::fromPhpDocumentorProperty($tag, $typeName);
42 ✔
7704
                if ($typeCheckPhpDoc !== null) {
42 ✔
7705
                    $properties[$typeName] = $typeCheckPhpDoc;
42 ✔
7706
                    unset($optionalProperties[$typeName]);
42 ✔
7707
                }
7708
            }
7709
        }
7710

7711
        foreach ($arrayShapeItems as $item) {
138 ✔
7712
            $typeName = (string) $item->getKey();
56 ✔
7713
            if ($typeName === '') {
56 ✔
7714
                continue;
×
7715
            }
7716

7717
            $typeName = \trim($typeName, '\'"');
56 ✔
7718
            if (isset($properties[$typeName])) {
56 ✔
7719
                continue;
×
7720
            }
7721

7722
            $typeCheckPhpDoc = TypeCheckPhpDoc::fromDocTypeObject($typeName, $item->getValue());
56 ✔
7723
            $properties[$typeName] = $typeCheckPhpDoc;
56 ✔
7724
            if ($item->isOptional()) {
56 ✔
7725
                $optionalProperties[$typeName] = true;
35 ✔
7726
            }
7727
        }
7728
    }
7729

7730
    /**
7731
     * Extract array-shape items from supported @template and @extends annotations.
7732
     *
7733
     * @param \phpDocumentor\Reflection\DocBlock $docblock
7734
     *
7735
     * @return \phpDocumentor\Reflection\PseudoTypes\ArrayShapeItem[]
7736
     */
7737
    private function getArrayShapeItemsFromDocBlock($docblock): array
7738
    {
7739
        if (!\class_exists('\phpDocumentor\Reflection\PseudoTypes\ArrayShape')) {
145 ✔
7740
            return [];
×
7741
        }
7742

7743
        $items = [];
145 ✔
7744
        foreach ($docblock->getTagsByName('template') as $tag) {
145 ✔
7745
            if (
7746
                $tag instanceof \phpDocumentor\Reflection\DocBlock\Tags\Template
145 ✔
7747
                &&
7748
                $tag->getTemplateName() === 'T'
145 ✔
7749
                &&
7750
                $tag->getBound() instanceof \phpDocumentor\Reflection\PseudoTypes\ArrayShape
145 ✔
7751
            ) {
7752
                foreach ($tag->getBound()->getItems() as $item) {
49 ✔
7753
                    $items[] = $item;
49 ✔
7754
                }
7755
            }
7756
        }
7757

7758
        foreach ($docblock->getTagsByName('extends') as $tag) {
145 ✔
7759
            if (!$tag instanceof \phpDocumentor\Reflection\DocBlock\Tags\Extends_) {
145 ✔
7760
                continue;
×
7761
            }
7762

7763
            $type = $tag->getType();
145 ✔
7764
            if (
7765
                !$type instanceof \phpDocumentor\Reflection\PseudoTypes\Generic
145 ✔
7766
                ||
7767
                !$this->isArrayyGenericTarget((string) $type->getFqsen())
145 ✔
7768
            ) {
7769
                continue;
131 ✔
7770
            }
7771

7772
            foreach ($type->getTypes() as $genericType) {
138 ✔
7773
                if ($genericType instanceof \phpDocumentor\Reflection\PseudoTypes\ArrayShape) {
138 ✔
7774
                    foreach ($genericType->getItems() as $item) {
14 ✔
7775
                        $items[] = $item;
14 ✔
7776
                    }
7777
                }
7778
            }
7779
        }
7780

7781
        return $items;
145 ✔
7782
    }
7783

7784
    /**
7785
     * Check whether a generic annotation target is Arrayy, ArrayyStrict, or an Arrayy subclass.
7786
     *
7787
     * @param string $fqcn
7788
     *
7789
     * @return bool
7790
     */
7791
    private function isArrayyGenericTarget(string $fqcn): bool
7792
    {
7793
        $fqcn = \ltrim($fqcn, '\\');
145 ✔
7794
        if ($fqcn === '') {
145 ✔
7795
            return false;
×
7796
        }
7797

7798
        if (\in_array($fqcn, [self::class, ArrayyStrict::class], true)) {
145 ✔
7799
            return true;
138 ✔
7800
        }
7801

7802
        return \class_exists($fqcn) && \is_a($fqcn, self::class, true);
131 ✔
7803
    }
7804

7805
    /**
7806
     * @return TypeCheckInterface[]
7807
     */
7808
    protected function getPropertiesFromNativeDefinitions(): array
7809
    {
7810
        $properties = [];
145 ✔
7811
        $reflector = new \ReflectionClass($this);
145 ✔
7812
        $reservedProperties = self::getReservedPropertyNames();
145 ✔
7813

7814
        do {
7815
            if ($reflector->getName() === self::class) {
145 ✔
7816
                break;
145 ✔
7817
            }
7818

7819
            foreach ($reflector->getProperties() as $property) {
145 ✔
7820
                if (
7821
                    $property->getDeclaringClass()->getName() !== $reflector->getName()
145 ✔
7822
                    ||
7823
                    $property->isStatic()
124 ✔
7824
                    ||
7825
                    isset($reservedProperties[$property->getName()])
124 ✔
7826
                    ||
7827
                    isset($properties[$property->getName()])
145 ✔
7828
                ) {
7829
                    continue;
145 ✔
7830
                }
7831

7832
                $properties[$property->getName()] = TypeCheckPhpDoc::fromReflectionProperty($property);
19 ✔
7833
            }
7834
        } while ($reflector = $reflector->getParentClass());
145 ✔
7835

7836
        return $properties;
145 ✔
7837
    }
7838

7839
    /**
7840
     * @return array<string, true>
7841
     */
7842
    private static function getReservedPropertyNames(): array
7843
    {
7844
        static $reservedProperties = null;
145 ✔
7845

7846
        if ($reservedProperties !== null) {
145 ✔
7847
            return $reservedProperties;
138 ✔
7848
        }
7849

7850
        $reservedProperties = [];
7 ✔
7851
        $reflector = new \ReflectionClass(self::class);
7 ✔
7852
        foreach ($reflector->getProperties() as $property) {
7 ✔
7853
            if ($property->getDeclaringClass()->getName() !== self::class) {
7 ✔
7854
                continue;
×
7855
            }
7856

7857
            $reservedProperties[$property->getName()] = true;
7 ✔
7858
        }
7859

7860
        return $reservedProperties;
7 ✔
7861
    }
7862

7863
    /**
7864
     * @param string $glue
7865
     * @param mixed  $pieces
7866
     * @param bool   $useKeys
7867
     *
7868
     * @return string
7869
     *
7870
     * @phpstan-param scalar|object|self<TKey|T>|array<TKey,T>|array<T> $pieces
7871
     * @psalm-mutation-free
7872
     */
7873
    protected function implode_recursive(
7874
        $glue = '',
7875
        $pieces = [],
7876
        bool $useKeys = false
7877
    ): string {
7878
        if ($pieces instanceof self) {
259 ✔
7879
            $pieces = $pieces->toArray();
7 ✔
7880
        }
7881

7882
        if (\is_array($pieces)) {
259 ✔
7883
            /** @noinspection PhpSillyAssignmentInspection - hack for phpstan */
7884
            /** @phpstan-var array<TKey,T> $pieces */
7885
            $pieces = $pieces;
259 ✔
7886

7887
            $pieces_count = \count($pieces, \COUNT_NORMAL);
259 ✔
7888
            $pieces_count_not_zero = $pieces_count > 0;
259 ✔
7889

7890
            return \implode(
259 ✔
7891
                $glue,
259 ✔
7892
                \array_map(
259 ✔
7893
                    [$this, 'implode_recursive'],
259 ✔
7894
                    \array_fill(0, ($pieces_count_not_zero ? $pieces_count : 1), $glue),
259 ✔
7895
                    ($useKeys === true && $pieces_count_not_zero ? $this->array_keys_recursive($pieces) : $pieces)
259 ✔
7896
                )
259 ✔
7897
            );
259 ✔
7898
        }
7899

7900
        if (
7901
            \is_scalar($pieces) === true
259 ✔
7902
            ||
7903
            $pieces instanceof \Stringable
259 ✔
7904
        ) {
7905
            return (string) $pieces;
231 ✔
7906
        }
7907

7908
        return '';
56 ✔
7909
    }
7910

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

7942
        foreach ($haystack as $item) {
128 ✔
7943
            if (\is_array($item)) {
100 ✔
7944
                $returnTmp = $this->in_array_recursive($needle, $item, $strict);
23 ✔
7945
            } else {
7946
                /** @noinspection NestedPositiveIfStatementsInspection */
7947
                if ($strict === true) {
100 ✔
7948
                    $returnTmp = $item === $needle;
100 ✔
7949
                } else {
7950
                    $returnTmp = $item == $needle;
×
7951
                }
7952
            }
7953

7954
            if ($returnTmp === true) {
100 ✔
7955
                return true;
72 ✔
7956
            }
7957
        }
7958

7959
        return false;
56 ✔
7960
    }
7961

7962
    /**
7963
     * @param mixed $data
7964
     *
7965
     * @return array<mixed>|null
7966
     */
7967
    protected function internalGetArray(&$data)
7968
    {
7969
        if (\is_array($data)) {
9,133 ✔
7970
            return $data;
9,091 ✔
7971
        }
7972

7973
        if (!$data) {
791 ✔
7974
            return [];
49 ✔
7975
        }
7976

7977
        if (\is_object($data) === true) {
784 ✔
7978
            if ($data instanceof \ArrayObject) {
735 ✔
7979
                return $data->getArrayCopy();
35 ✔
7980
            }
7981

7982
            if ($data instanceof \Generator) {
707 ✔
7983
                return static::createFromGeneratorImmutable($data)->toArray();
7 ✔
7984
            }
7985

7986
            if ($data instanceof \Traversable) {
700 ✔
7987
                return static::createFromObject($data)->toArray();
×
7988
            }
7989

7990
            if ($data instanceof \JsonSerializable) {
700 ✔
7991
                return (array) $data->jsonSerialize();
×
7992
            }
7993

7994
            if (\method_exists($data, '__toArray')) {
700 ✔
7995
                return (array) $data->__toArray();
×
7996
            }
7997

7998
            if (\method_exists($data, '__toString')) {
700 ✔
7999
                return [(string) $data];
×
8000
            }
8001
        }
8002

8003
        if (\is_callable($data)) {
749 ✔
8004
            /**
8005
             * @psalm-suppress InvalidPropertyAssignmentValue - why?
8006
             */
8007
            $this->generator = new ArrayyRewindableGenerator($data);
686 ✔
8008

8009
            return [];
686 ✔
8010
        }
8011

8012
        if (\is_scalar($data)) {
77 ✔
8013
            return [$data];
63 ✔
8014
        }
8015

8016
        return null;
14 ✔
8017
    }
8018

8019
    /**
8020
     * Internal mechanics of remove method.
8021
     *
8022
     * @param float|int|string $key
8023
     *
8024
     * @return bool
8025
     */
8026
    protected function internalRemove($key): bool
8027
    {
8028
        $this->generatorToArray();
154 ✔
8029

8030
        if (
8031
            $this->pathSeparator
154 ✔
8032
            &&
8033
            (string) $key === $key
154 ✔
8034
            &&
8035
            \strpos($key, $this->pathSeparator) !== false
154 ✔
8036
        ) {
8037
            $path = \explode($this->pathSeparator, (string) $key);
×
8038
            // crawl though the keys
8039
            while (\count($path, \COUNT_NORMAL) > 1) {
×
8040
                $key = \array_shift($path);
×
8041

8042
                if (!$this->has($key)) {
×
8043
                    return false;
×
8044
                }
8045

8046
                $this->array = &$this->array[$key];
×
8047
            }
8048

8049
            $key = \array_shift($path);
×
8050
        }
8051

8052
        unset($this->array[$key]);
154 ✔
8053

8054
        return true;
154 ✔
8055
    }
8056

8057
    /**
8058
     * Internal mechanic of set method.
8059
     *
8060
     * @param int|string|null $key
8061
     * @param mixed           $value
8062
     * @param bool            $checkProperties
8063
     *
8064
     * @return bool
8065
     *
8066
     * @phpstan-param TKey|null $key
8067
     * @phpstan-param T $value
8068
     */
8069
    protected function internalSet(
8070
        $key,
8071
        &$value,
8072
        bool $checkProperties = true
8073
    ): bool {
8074
        if (
8075
            $checkProperties === true
8,034 ✔
8076
            &&
8077
            $this->properties !== []
8,034 ✔
8078
        ) {
8079
            $this->checkType($key, $value);
1,190 ✔
8080
        }
8081

8082
        if ($key === null) {
7,992 ✔
8083
            return false;
×
8084
        }
8085

8086
        $this->generatorToArray();
7,992 ✔
8087

8088
        $array = &$this->array;
7,992 ✔
8089

8090
        /**
8091
         * https://github.com/vimeo/psalm/issues/2536
8092
         *
8093
         * @psalm-suppress PossiblyInvalidArgument
8094
         * @psalm-suppress InvalidScalarArgument
8095
         */
8096
        if (
8097
            $this->pathSeparator
7,992 ✔
8098
            &&
8099
            (string) $key === $key
7,992 ✔
8100
            &&
8101
            \strpos($key, $this->pathSeparator) !== false
7,992 ✔
8102
        ) {
8103
            $path = \explode($this->pathSeparator, (string) $key);
63 ✔
8104
            // crawl through the keys
8105
            while (\count($path, \COUNT_NORMAL) > 1) {
63 ✔
8106
                $key = \array_shift($path);
63 ✔
8107

8108
                $array = &$array[$key];
63 ✔
8109
            }
8110

8111
            $key = \array_shift($path);
63 ✔
8112
        }
8113

8114
        if ($array === null) {
7,992 ✔
8115
            $array = [];
28 ✔
8116
        } elseif (!\is_array($array)) {
7,971 ✔
8117
            throw new \RuntimeException('Can not set value at this path "' . $key . '" because (' . \gettype($array) . ')"' . \print_r($array, true) . '" is not an array.');
7 ✔
8118
        }
8119

8120
        $array[$key] = $value;
7,992 ✔
8121

8122
        return true;
7,992 ✔
8123
    }
8124

8125
    /**
8126
     * Convert a object into an array.
8127
     *
8128
     * @param mixed|object $object
8129
     *
8130
     * @return array|mixed
8131
     *
8132
     * @psalm-mutation-free
8133
     */
8134
    protected static function objectToArray($object)
8135
    {
8136
        if (!\is_object($object)) {
42 ✔
8137
            return $object;
35 ✔
8138
        }
8139

8140
        $object = \get_object_vars($object);
42 ✔
8141

8142
        /**
8143
         * @psalm-suppress PossiblyInvalidArgument - the parameter is always some kind of array - false-positive from psalm?
8144
         */
8145
        return \array_map([static::class, 'objectToArray'], $object);
42 ✔
8146
    }
8147

8148
    /**
8149
     * @param array $data
8150
     * @param bool  $checkPropertiesInConstructor
8151
     *
8152
     * @return void
8153
     *
8154
     * @phpstan-param array<mixed,T> $data
8155
     */
8156
    protected function setInitialValuesAndProperties(array &$data, bool $checkPropertiesInConstructor)
8157
    {
8158
        $checkPropertiesInConstructor = $this->checkForMissingPropertiesInConstructor === true
9,119 ✔
8159
                                        &&
9,119 ✔
8160
                                        $checkPropertiesInConstructor === true;
9,119 ✔
8161

8162
        if ($this->properties === []) {
9,119 ✔
8163
            if (
8164
                $this->checkPropertyTypes === true
8,426 ✔
8165
                ||
8166
                $checkPropertiesInConstructor === true
8,426 ✔
8167
            ) {
8168
                $this->properties = $this->getPropertiesFromPhpDoc();
495 ✔
8169
            }
8170

8171
            /** @var TypeCheckInterface[] $properties */
8172
            $properties = $this->properties;
8,412 ✔
8173
            $requiredProperties = \array_diff_key($properties, $this->optionalProperties);
8,412 ✔
8174

8175
            if (
8176
                $this->checkPropertiesMismatchInConstructor === true
8,412 ✔
8177
                &&
8178
                \count($data) !== 0
8,412 ✔
8179
                &&
8180
                \count(\array_diff_key($requiredProperties, $data)) > 0
8,412 ✔
8181
            ) {
8182
                throw new \TypeError('Property mismatch - input: ' . \print_r(\array_keys($data), true) . ' | expected: ' . \print_r(\array_keys($requiredProperties), true));
14 ✔
8183
            }
8184
        }
8185

8186
        foreach ($data as $key => &$valueInner) {
9,091 ✔
8187
            $this->internalSet(
7,908 ✔
8188
                $key,
7,908 ✔
8189
                $valueInner,
7,908 ✔
8190
                $checkPropertiesInConstructor
7,908 ✔
8191
            );
7,908 ✔
8192
        }
8193
    }
8194

8195
    /**
8196
     * sorting keys
8197
     *
8198
     * @param array      $elements
8199
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
8200
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
8201
     *                              <strong>SORT_NATURAL</strong></p>
8202
     *
8203
     * @return $this
8204
     *               <p>(Mutable) Return this Arrayy object.</p>
8205
     *
8206
     * @phpstan-param  array<mixed|TKey,T> $elements
8207
     * @phpstan-return static
8208
     */
8209
    protected function sorterKeys(
8210
        array &$elements,
8211
        $direction = \SORT_ASC,
8212
        int $strategy = \SORT_REGULAR
8213
    ): self {
8214
        $direction = $this->getDirection($direction);
126 ✔
8215

8216
        switch ($direction) {
8217
            case 'desc':
126 ✔
8218
            case \SORT_DESC:
8219
                \krsort($elements, $strategy);
42 ✔
8220

8221
                break;
42 ✔
8222
            case 'asc':
91 ✔
8223
            case \SORT_ASC:
91 ✔
8224
            default:
8225
                \ksort($elements, $strategy);
91 ✔
8226
        }
8227

8228
        return $this;
126 ✔
8229
    }
8230

8231
    /**
8232
     * @param array      $elements  <p>Warning: used as reference</p>
8233
     * @param int|string $direction <p>use <strong>SORT_ASC</strong> (default) or <strong>SORT_DESC</strong></p>
8234
     * @param int        $strategy  <p>use e.g.: <strong>SORT_REGULAR</strong> (default) or
8235
     *                              <strong>SORT_NATURAL</strong></p>
8236
     * @param bool       $keepKeys
8237
     *
8238
     * @return $this
8239
     *               <p>(Mutable) Return this Arrayy object.</p>
8240
     *
8241
     * @phpstan-param array<mixed|TKey,T> $elements
8242
     * @phpstan-return static
8243
     */
8244
    protected function sorting(
8245
        array &$elements,
8246
        $direction = \SORT_ASC,
8247
        int $strategy = \SORT_REGULAR,
8248
        bool $keepKeys = false
8249
    ): self {
8250
        $direction = $this->getDirection($direction);
168 ✔
8251

8252
        if (!$strategy) {
168 ✔
8253
            $strategy = \SORT_REGULAR;
168 ✔
8254
        }
8255

8256
        switch ($direction) {
8257
            case 'desc':
168 ✔
8258
            case \SORT_DESC:
8259
                if ($keepKeys) {
91 ✔
8260
                    \arsort($elements, $strategy);
63 ✔
8261
                } else {
8262
                    \rsort($elements, $strategy);
28 ✔
8263
                }
8264

8265
                break;
91 ✔
8266
            case 'asc':
77 ✔
8267
            case \SORT_ASC:
77 ✔
8268
            default:
8269
                if ($keepKeys) {
77 ✔
8270
                    \asort($elements, $strategy);
28 ✔
8271
                } else {
8272
                    \sort($elements, $strategy);
49 ✔
8273
                }
8274
        }
8275

8276
        return $this;
168 ✔
8277
    }
8278

8279
    /**
8280
     * @param array $array
8281
     *
8282
     * @return array
8283
     *
8284
     * @phpstan-param array<array-key, mixed> $array
8285
     * @phpstan-return array<array-key, mixed>
8286
     *
8287
     * @psalm-mutation-free
8288
     */
8289
    private function getArrayRecursiveHelperArrayy(array $array)
8290
    {
8291
        if ($array === []) {
175 ✔
8292
            return [];
×
8293
        }
8294

8295
        \array_walk_recursive(
175 ✔
8296
            $array,
175 ✔
8297
            /**
8298
             * @param array|self $item
8299
             *
8300
             * @return void
8301
             */
8302
            static function (&$item) {
175 ✔
8303
                if ($item instanceof self) {
175 ✔
8304
                    $item = $item->getArray();
7 ✔
8305
                }
8306
            }
175 ✔
8307
        );
175 ✔
8308

8309
        return $array;
175 ✔
8310
    }
8311

8312
    /**
8313
     * @param int|string|null $key
8314
     * @param mixed           $value
8315
     *
8316
     * @return void
8317
     */
8318
    private function checkType($key, $value)
8319
    {
8320
        if (
8321
            $key !== null
1,190 ✔
8322
            &&
8323
            isset($this->properties[$key]) === false
1,190 ✔
8324
            &&
8325
            $this->checkPropertiesMismatch === true
1,190 ✔
8326
        ) {
8327
            throw new \TypeError('The key "' . $key . '" does not exist as a property definition. (' . \get_class($this) . ').');
28 ✔
8328
        }
8329

8330
        if (isset($this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES])) {
1,190 ✔
8331
            $this->properties[self::ARRAYY_HELPER_TYPES_FOR_ALL_PROPERTIES]->checkType($value);
833 ✔
8332
        } elseif ($key !== null && isset($this->properties[$key])) {
434 ✔
8333
            $this->properties[$key]->checkType($value);
434 ✔
8334
        }
8335
    }
8336
}
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