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

aimeos / map / 79611145-a9a7-4bf2-892e-d6654472af64

06 Jul 2026 03:25PM UTC coverage: 87.508% (+0.1%) from 87.408%
79611145-a9a7-4bf2-892e-d6654472af64

push

circleci

aimeos
Performance improvements

 Method                        Before       After     Change
━━━━━━━━━━━━━━━━━━━━━━━━━━  ━━━━━━━━━━  ━━━━━━━━━━  ━━━━━━━━━
 find() (reverse=true)        417.330      47.152    -88.70%
──────────────────────────  ──────────  ──────────  ─────────
 findKey() (reverse=true)     416.939      47.737    -88.55%
──────────────────────────  ──────────  ──────────  ─────────
 grep() (all scalars)        3646.658    2689.883    -26.24%
──────────────────────────  ──────────  ──────────  ─────────
 isList()                     857.993       0.643    -99.93%
──────────────────────────  ──────────  ──────────  ─────────
 join() (all scalars)        2996.890    1979.318    -33.95%
──────────────────────────  ──────────  ──────────  ─────────
 random(1)                    124.317     121.963     -1.89%
──────────────────────────  ──────────  ──────────  ─────────
 skip(0)                       63.995       0.824    -98.71%
──────────────────────────  ──────────  ──────────  ─────────
 take(0)                        1.476       0.665    -54.94%

51 of 53 new or added lines in 1 file covered. (96.23%)

1338 of 1529 relevant lines covered (87.51%)

5.13 hits per line

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

87.48
/src/Map.php
1
<?php
2

3
/**
4
 * @license MIT, http://opensource.org/licenses/MIT
5
 * @author Taylor Otwell, Aimeos.org developers
6
 */
7

8

9
namespace Aimeos;
10

11

12
/**
13
 * Handling and operating on a list of elements easily
14
 * Inspired by Laravel Collection class, PHP map data structure and Javascript
15
 *
16
 * @template TKey of int|string
17
 * @template TValue
18
 * @implements \ArrayAccess<TKey,TValue>
19
 * @implements \IteratorAggregate<TKey,TValue>
20
 * @phpstan-consistent-constructor
21
 */
22
class Map implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable
23
{
24
        /**
25
         * @var array<string,\Closure>
26
         */
27
        protected static array $methods = [];
28

29
        /**
30
         * @var non-empty-string
31
         */
32
        protected static string $delim = '/';
33

34
        protected const RECURSION_LIMIT = 512;
35

36
        /**
37
         * @var array<int|string,mixed>|\Closure|iterable|mixed
38
         */
39
        protected $list;
40

41
        /**
42
         * @var non-empty-string
43
         */
44
        protected string $sep = '/';
45

46

47
        /**
48
         * Creates a new map.
49
         *
50
         * Returns a new map instance containing the list of elements. In case of
51
         * an empty array or null, the map object will contain an empty list.
52
         *
53
         * @param array<TKey,TValue>|\Closure|iterable<TKey,TValue>|TValue|null $elements List of elements or single value
54
         */
55
        public function __construct( mixed $elements = [] )
56
        {
57
                $this->sep = self::$delim;
503 ✔
58
                $this->list = $elements;
503 ✔
59
        }
60

61

62
        /**
63
         * Handles static calls to custom methods for the class.
64
         *
65
         * Calls a custom method added by Map::method() statically. The called method
66
         * has no access to the internal array because no object is available.
67
         *
68
         * Examples:
69
         *  Map::method( 'foo', function( $arg1, $arg2 ) {} );
70
         *  Map::foo( $arg1, $arg2 );
71
         *
72
         * @param string $name Method name
73
         * @param array<mixed> $params List of parameters
74
         * @return mixed Result from called function or new map with results from the element methods
75
         * @throws \BadMethodCallException
76
         */
77
        public static function __callStatic( string $name, array $params ) : mixed
78
        {
79
                if( !isset( static::$methods[$name] ) ) {
2 ✔
80
                        throw new \BadMethodCallException( sprintf( 'Method %s::%s does not exist.', static::class, $name ) );
1 ✔
81
                }
82

83
                return call_user_func_array( \Closure::bind( static::$methods[$name], null, static::class ), $params );
1 ✔
84
        }
85

86

87
        /**
88
         * Handles dynamic calls to custom methods for the class.
89
         *
90
         * Calls a custom method added by Map::method(). The called method
91
         * has access to the internal array by using $this->list().
92
         *
93
         * Examples:
94
         *  Map::method( 'case', function( $case = CASE_LOWER ) {
95
         *      return new static( array_change_key_case( $this->list(), $case ) );
96
         *  } );
97
         *  Map::from( ['a' => 'bar'] )->case( CASE_UPPER );
98
         *
99
         *  $item = new MyClass(); // with method setId() and getCode()
100
         *  Map::from( [$item, $item] )->setId( null )->getCode();
101
         *
102
         * Results:
103
         * The first example will return ['A' => 'bar'].
104
         *
105
         * The second one will call the setId() method of each element in the map and use
106
         * their return values to create a new map. On the new map, the getCode() method
107
         * is called for every element and its return values are also stored in a new map.
108
         * This last map is then returned.
109
         * If the elements are not objects or the method isn't callable, they are
110
         * skipped. If this applies to all elements, an empty map is returned. The map
111
         * keys from the original map are preserved in the returned map.
112
         *
113
         * @param string $name Method name
114
         * @param array<mixed> $params List of parameters
115
         * @return mixed|self Result from called function or new map with results from the element methods
116
         */
117
        public function __call( string $name, array $params ) : mixed
118
        {
119
                if( isset( static::$methods[$name] ) ) {
5 ✔
120
                        return call_user_func_array( static::$methods[$name]->bindTo( $this, static::class ), $params );
2 ✔
121
                }
122

123
                $result = [];
3 ✔
124

125
                foreach( $this->list() as $key => $item )
3 ✔
126
                {
127
                        if( is_object( $item ) && is_callable( [$item, $name] ) ) {
2 ✔
128
                                $result[$key] = $item->{$name}( ...$params );
2 ✔
129
                        }
130
                }
131

132
                return new static( $result );
3 ✔
133
        }
134

135

136
        /**
137
         * Returns the elements as a plain array.
138
         *
139
         * @return array<int|string,mixed> Plain array
140
         */
141
        public function __toArray() : array
142
        {
143
                return $this->list = $this->array( $this->list );
1 ✔
144
        }
145

146

147
        /**
148
         * Sets or returns the separator for paths to values in multi-dimensional arrays or objects.
149
         *
150
         * The static method only changes the separator for new maps created afterwards.
151
         * Already existing maps will continue to use the previous separator. To change
152
         * the separator of an existing map, use the sep() method instead.
153
         *
154
         * Examples:
155
         *  Map::delimiter( '.' );
156
         *  Map::from( ['foo' => ['bar' => 'baz']] )->get( 'foo.bar' );
157
         *
158
         * Results:
159
         *  '/'
160
         *  'baz'
161
         *
162
         * @param string|null $char Separator character, e.g. "." for "key.to.value" instead of "key/to/value"
163
         * @return string Separator used up to now
164
         * @throws \InvalidArgumentException If the separator is empty
165
         */
166
        public static function delimiter( ?string $char = null ) : string
167
        {
168
                $old = self::$delim;
2 ✔
169

170
                if( $char !== null )
2 ✔
171
                {
172
                        if( $char === '' ) {
2 ✔
173
                                throw new \InvalidArgumentException( 'Separator must not be empty' );
1 ✔
174
                        }
175

176
                        self::$delim = $char;
1 ✔
177
                }
178

179
                return $old;
1 ✔
180
        }
181

182

183
        /**
184
         * Creates a new map with the string splitted by the delimiter.
185
         *
186
         * The string is split immediately and the returned map contains the parts.
187
         *
188
         * Examples:
189
         *  Map::explode( ',', 'a,b,c' );
190
         *  Map::explode( '<-->', 'a a<-->b b<-->c c' );
191
         *  Map::explode( '', 'string' );
192
         *  Map::explode( '|', 'a|b|c', 2 );
193
         *  Map::explode( '', 'string', 2 );
194
         *  Map::explode( '|', 'a|b|c|d', -2 );
195
         *  Map::explode( '', 'string', -3 );
196
         *
197
         * Results:
198
         *  ['a', 'b', 'c']
199
         *  ['a a', 'b b', 'c c']
200
         *  ['s', 't', 'r', 'i', 'n', 'g']
201
         *  ['a', 'b|c']
202
         *  ['s', 't', 'ring']
203
         *  ['a', 'b']
204
         *  ['s', 't', 'r']
205
         *
206
         * A limit of "0" is treated the same as "1". If limit is negative, the rest of
207
         * the string is dropped and not part of the returned map.
208
         *
209
         * @param string $delimiter Delimiter character, string or empty string
210
         * @param string $string String to split
211
         * @param int $limit Maximum number of element with the last element containing the rest of the string
212
         * @return self<int|string,mixed> New map with splitted parts
213
         */
214
        public static function explode( string $delimiter, string $string, int $limit = PHP_INT_MAX ) : self
215
        {
216
                if( $delimiter !== '' ) {
8 ✔
217
                        return new static( explode( $delimiter, $string, $limit ) );
4 ✔
218
                }
219

220
                $limit = $limit ?: 1;
4 ✔
221
                $parts = mb_str_split( $string, 1, 'UTF-8' );
4 ✔
222

223
                if( $limit < 1 ) {
4 ✔
224
                        return new static( array_slice( $parts, 0, $limit ) );
1 ✔
225
                }
226

227
                if( $limit < count( $parts ) )
3 ✔
228
                {
229
                        $result = array_slice( $parts, 0, $limit );
1 ✔
230
                        $result[] = join( '', array_slice( $parts, $limit ) );
1 ✔
231

232
                        return new static( $result );
1 ✔
233
                }
234

235
                return new static( $parts );
2 ✔
236
        }
237

238

239
        /**
240
         * Creates a new map filled with given value.
241
         *
242
         * Examples:
243
         *  Map::fill( 3, 'a' );
244
         *  Map::fill( 3, 'a', 2 );
245
         *  Map::fill( 3, 'a', -2 );
246
         *
247
         * Results:
248
         * The first example will return [0 => 'a', 1 => 'a', 2 => 'a']. The second
249
         * example will return [2 => 'a', 3 => 'a', 4 => 'a'] and the last one
250
         * [-2 => 'a', -1 => 'a', 0 => 'a'] (PHP 8) or [-2 => 'a', 0 => 'a', 1 => 'a'] (PHP 7).
251
         *
252
         * @param int $num Number of elements to create
253
         * @param mixed $value Value to fill the map with
254
         * @param int $start Start index for the elements
255
         * @return self<int|string,mixed> New map with filled elements
256
         * @throws \InvalidArgumentException If the number of elements is less than 0
257
         */
258
        public static function fill( int $num, mixed $value, int $start = 0 ) : self
259
        {
260
                if( $num < 0 ) {
3 ✔
261
                        throw new \InvalidArgumentException( 'Number of elements must be greater or equal than 0' );
1 ✔
262
                }
263

264
                return new static( array_fill( $start, $num, $value ) );
2 ✔
265
        }
266

267

268
        /**
269
         * Creates a new map instance if the value isn't one already.
270
         *
271
         * Examples:
272
         *  Map::from( [] );
273
         *  Map::from( null );
274
         *  Map::from( 'a' );
275
         *  Map::from( new Map() );
276
         *  Map::from( new ArrayObject() );
277
         *
278
         * Results:
279
         * A new map instance containing the list of elements. In case of an empty
280
         * array or null, the map object will contain an empty list. If a map object
281
         * is passed, it will be returned instead of creating a new instance.
282
         *
283
         * @param mixed $elements List of elements or single element
284
         * @return self<int|string,mixed> New map object
285
         */
286
        public static function from( mixed $elements = [] ) : self
287
        {
288
                if( $elements instanceof self ) {
272 ✔
289
                        return $elements;
3 ✔
290
                }
291

292
                return new static( $elements );
272 ✔
293
        }
294

295

296
        /**
297
         * Creates a new map instance from a JSON string.
298
         *
299
         * The JSON string is decoded immediately and invalid JSON strings throw an
300
         * exception while the map is created.
301
         *
302
         * Examples:
303
         *  Map::fromJson( '["a", "b"]' );
304
         *  Map::fromJson( '{"a": "b"}' );
305
         *  Map::fromJson( '""' );
306
         *
307
         * Results:
308
         *  ['a', 'b']
309
         *  ['a' => 'b']
310
         *  ['']
311
         *
312
         * There are several options available for decoding the JSON string:
313
         * {@link https://www.php.net/manual/en/function.json-decode.php}
314
         * The parameter can be a single JSON_* constant or a bitmask of several
315
         * constants combine by bitwise OR (|), e.g.:
316
         *
317
         *  JSON_BIGINT_AS_STRING|JSON_INVALID_UTF8_IGNORE
318
         *
319
         * @param string $json JSON string to decode
320
         * @param int $options Combination of JSON_* constants
321
         * @return self<int|string,mixed> New map from decoded JSON string
322
         * @throws \RuntimeException If the passed JSON string is invalid
323
         * @throws \JsonException If JSON_THROW_ON_ERROR is part of the passed options and the JSON string is invalid
324
         */
325
        public static function fromJson( string $json, int $options = JSON_BIGINT_AS_STRING ) : self
326
        {
327
                $result = json_decode( $json, true, 512, $options );
5 ✔
328

329
                if( json_last_error() === JSON_ERROR_NONE ) {
5 ✔
330
                        return new static( $result );
4 ✔
331
                }
332

333
                throw new \RuntimeException( 'Not a valid JSON string: ' . json_last_error_msg() );
1 ✔
334
        }
335

336

337
        /**
338
         * Registers a custom method or returns the existing one.
339
         *
340
         * The registered method has access to the class properties if called non-static.
341
         *
342
         * Examples:
343
         *  Map::method( 'foo', function( $arg1, $arg2 ) {
344
         *      return $this->list();
345
         *  } );
346
         *
347
         * Dynamic calls have access to the class properties:
348
         *  Map::from( ['bar'] )->foo( $arg1, $arg2 );
349
         *
350
         * Static calls yield an error because $this->elements isn't available:
351
         *  Map::foo( $arg1, $arg2 );
352
         *
353
         * @param string $method Method name
354
         * @param \Closure|null $fcn Anonymous function or NULL to return the closure if available
355
         * @return \Closure|null Registered anonymous function or NULL if none has been registered
356
         */
357
        public static function method( string $method, ?\Closure $fcn = null ) : ?\Closure
358
        {
359
                if( $fcn ) {
3 ✔
360
                        self::$methods[$method] = $fcn;
3 ✔
361
                }
362

363
                return self::$methods[$method] ?? null;
3 ✔
364
        }
365

366

367
        /**
368
         * Creates a new map by invoking the closure the given number of times.
369
         *
370
         * The entries are generated immediately, so the passed callback is called
371
         * while the map is created.
372
         *
373
         * Examples:
374
         *  Map::times( 3, function( $num ) {
375
         *    return $num * 10;
376
         *  } );
377
         *  Map::times( 3, function( $num, &$key ) {
378
         *    $key = $num * 2;
379
         *    return $num * 5;
380
         *  } );
381
         *  Map::times( 2, function( $num ) {
382
         *    return new \stdClass();
383
         *  } );
384
         *
385
         * Results:
386
         *  [0 => 0, 1 => 10, 2 => 20]
387
         *  [0 => 0, 2 => 5, 4 => 10]
388
         *  [0 => new \stdClass(), 1 => new \stdClass()]
389
         *
390
         * @param int $num Number of times the function is called
391
         * @param callable $callback Function with (value, key) parameters and returns new value
392
         * @return self<int|string,mixed> New map with the generated elements
393
         */
394
        public static function times( int $num, callable $callback ) : self
395
        {
396
                $list = [];
4 ✔
397

398
                for( $i = 0; $i < $num; $i++ ) {
4 ✔
399
                        $key = $i;
4 ✔
400
                        $list[$key] = $callback( $i, $key );
4 ✔
401
                }
402

403
                return new static( $list );
4 ✔
404
        }
405

406

407
        /**
408
         * Returns the elements after the given one.
409
         *
410
         * Examples:
411
         *  Map::from( ['a' => 1, 'b' => 0] )->after( 1 );
412
         *  Map::from( [0 => 'b', 1 => 'a'] )->after( 'b' );
413
         *  Map::from( [0 => 'b', 1 => 'a'] )->after( 'c' );
414
         *  Map::from( ['a', 'c', 'b'] )->after( function( $item, $key ) {
415
         *      return $item >= 'c';
416
         *  } );
417
         *
418
         * Results:
419
         *  ['b' => 0]
420
         *  [1 => 'a']
421
         *  []
422
         *  [2 => 'b']
423
         *
424
         * The keys are preserved using this method.
425
         *
426
         * @param \Closure|int|string $value Value or function with (item, key) parameters
427
         * @return self<int|string,mixed> New map with the elements after the given one
428
         */
429
        public function after( \Closure|int|string $value ) : self
430
        {
431
                if( ( $pos = $this->pos( $value ) ) === null ) {
4 ✔
432
                        return new static();
1 ✔
433
                }
434

435
                return new static( array_slice( $this->list(), $pos + 1, null, true ) );
3 ✔
436
        }
437

438

439
        /**
440
         * Returns the elements as a plain array.
441
         *
442
         * @return array<int|string,mixed> Plain array
443
         */
444
        public function all() : array
445
        {
446
                return $this->list = $this->array( $this->list );
×
447
        }
448

449

450
        /**
451
         * Tests if at least one element satisfies the callback function.
452
         *
453
         * Examples:
454
         *  Map::from( ['a', 'b'] )->any( function( $item, $key ) {
455
         *    return $item === 'a';
456
         *  } );
457
         *  Map::from( ['a', 'b'] )->any( function( $item, $key ) {
458
         *    return !is_string( $item );
459
         *  } );
460
         *
461
         * Results:
462
         * The first example will return TRUE while the last one will return FALSE
463
         *
464
         * @param callable $callback Function with (item, key) parameter
465
         * @return bool TRUE if at least one element satisfies the callback function, FALSE if not
466
         */
467
        public function any( callable $callback ) : bool
468
        {
469
                if( function_exists( 'array_any' ) ) {
2 ✔
470
                        return array_any( $this->list(), $callback );
2 ✔
471
                }
472

473
                foreach( $this->list() as $key => $item )
×
474
                {
475
                        if( $callback( $item, $key ) ) {
×
476
                                return true;
×
477
                        }
478
                }
479

480
                return false;
×
481
        }
482

483

484
        /**
485
         * Sorts all elements in reverse order and maintains the key association.
486
         *
487
         * Examples:
488
         *  Map::from( ['b' => 0, 'a' => 1] )->arsort();
489
         *  Map::from( ['a', 'b'] )->arsort();
490
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsort();
491
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsort( SORT_STRING|SORT_FLAG_CASE );
492
         *
493
         * Results:
494
         *  ['a' => 1, 'b' => 0]
495
         *  ['b', 'a']
496
         *  [1 => 'b', 0 => 'C']
497
         *  [0 => 'C', 1 => 'b'] // because 'C' -> 'c' and 'c' > 'b'
498
         *
499
         * The parameter modifies how the values are compared. Possible parameter values are:
500
         * - SORT_REGULAR : compare elements normally (don't change types)
501
         * - SORT_NUMERIC : compare elements numerically
502
         * - SORT_STRING : compare elements as strings
503
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
504
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
505
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
506
         *
507
         * The keys are preserved using this method and no new map is created.
508
         *
509
         * @param int $options Sort options for arsort()
510
         * @return self<int|string,mixed> Updated map for fluid interface
511
         */
512
        public function arsort( int $options = SORT_REGULAR ) : self
513
        {
514
                arsort( $this->list(), $options );
4 ✔
515
                return $this;
4 ✔
516
        }
517

518

519
        /**
520
         * Sorts a copy of all elements in reverse order and maintains the key association.
521
         *
522
         * Examples:
523
         *  Map::from( ['b' => 0, 'a' => 1] )->arsorted();
524
         *  Map::from( ['a', 'b'] )->arsorted();
525
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsorted();
526
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsorted( SORT_STRING|SORT_FLAG_CASE );
527
         *
528
         * Results:
529
         *  ['a' => 1, 'b' => 0]
530
         *  ['b', 'a']
531
         *  [1 => 'b', 0 => 'C']
532
         *  [0 => 'C', 1 => 'b'] // because 'C' -> 'c' and 'c' > 'b'
533
         *
534
         * The parameter modifies how the values are compared. Possible parameter values are:
535
         * - SORT_REGULAR : compare elements normally (don't change types)
536
         * - SORT_NUMERIC : compare elements numerically
537
         * - SORT_STRING : compare elements as strings
538
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
539
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
540
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
541
         *
542
         * The keys are preserved using this method and a new map is created.
543
         *
544
         * @param int $options Sort options for arsort()
545
         * @return self<int|string,mixed> New map with sorted elements
546
         */
547
        public function arsorted( int $options = SORT_REGULAR ) : self
548
        {
549
                return ( clone $this )->arsort( $options );
1 ✔
550
        }
551

552

553
        /**
554
         * Sorts all elements and maintains the key association.
555
         *
556
         * Examples:
557
         *  Map::from( ['a' => 1, 'b' => 0] )->asort();
558
         *  Map::from( [0 => 'b', 1 => 'a'] )->asort();
559
         *  Map::from( [0 => 'C', 1 => 'b'] )->asort();
560
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsort( SORT_STRING|SORT_FLAG_CASE );
561
         *
562
         * Results:
563
         *  ['b' => 0, 'a' => 1]
564
         *  [1 => 'a', 0 => 'b']
565
         *  [0 => 'C', 1 => 'b'] // because 'C' < 'b'
566
         *  [1 => 'b', 0 => 'C'] // because 'C' -> 'c' and 'c' > 'b'
567
         *
568
         * The parameter modifies how the values are compared. Possible parameter values are:
569
         * - SORT_REGULAR : compare elements normally (don't change types)
570
         * - SORT_NUMERIC : compare elements numerically
571
         * - SORT_STRING : compare elements as strings
572
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
573
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
574
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
575
         *
576
         * The keys are preserved using this method and no new map is created.
577
         *
578
         * @param int $options Sort options for asort()
579
         * @return self<int|string,mixed> Updated map for fluid interface
580
         */
581
        public function asort( int $options = SORT_REGULAR ) : self
582
        {
583
                asort( $this->list(), $options );
4 ✔
584
                return $this;
4 ✔
585
        }
586

587

588
        /**
589
         * Sorts a copy of all elements and maintains the key association.
590
         *
591
         * Examples:
592
         *  Map::from( ['a' => 1, 'b' => 0] )->asorted();
593
         *  Map::from( [0 => 'b', 1 => 'a'] )->asorted();
594
         *  Map::from( [0 => 'C', 1 => 'b'] )->asorted();
595
         *  Map::from( [0 => 'C', 1 => 'b'] )->asorted( SORT_STRING|SORT_FLAG_CASE );
596
         *
597
         * Results:
598
         *  ['b' => 0, 'a' => 1]
599
         *  [1 => 'a', 0 => 'b']
600
         *  [0 => 'C', 1 => 'b'] // because 'C' < 'b'
601
         *  [1 => 'b', 0 => 'C'] // because 'C' -> 'c' and 'c' > 'b'
602
         *
603
         * The parameter modifies how the values are compared. Possible parameter values are:
604
         * - SORT_REGULAR : compare elements normally (don't change types)
605
         * - SORT_NUMERIC : compare elements numerically
606
         * - SORT_STRING : compare elements as strings
607
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
608
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
609
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
610
         *
611
         * The keys are preserved using this method and a new map is created.
612
         *
613
         * @param int $options Sort options for asort()
614
         * @return self<int|string,mixed> New map with sorted elements
615
         */
616
        public function asorted( int $options = SORT_REGULAR ) : self
617
        {
618
                return ( clone $this )->asort( $options );
1 ✔
619
        }
620

621

622
        /**
623
         * Returns the value at the given position.
624
         *
625
         * Examples:
626
         *  Map::from( [1, 3, 5] )->at( 0 );
627
         *  Map::from( [1, 3, 5] )->at( 1 );
628
         *  Map::from( [1, 3, 5] )->at( -1 );
629
         *  Map::from( [1, 3, 5] )->at( 3 );
630
         *
631
         * Results:
632
         * The first line will return "1", the second one "3", the third one "5" and
633
         * the last one NULL.
634
         *
635
         * The position starts from zero and a position of "0" returns the first element
636
         * of the map, "1" the second and so on. If the position is negative, the
637
         * sequence will start from the end of the map.
638
         *
639
         * @param int $pos Position of the value in the map
640
         * @return mixed|null Value at the given position or NULL if no value is available
641
         */
642
        public function at( int $pos ) : mixed
643
        {
644
                $list = $this->list();
1 ✔
645

646
                if( $pos === 0 ) {
1 ✔
647
                        $key = array_key_first( $list );
1 ✔
648
                        return $key !== null ? $list[$key] : null;
1 ✔
649
                }
650

651
                if( $pos === -1 ) {
1 ✔
652
                        $key = array_key_last( $list );
1 ✔
653
                        return $key !== null ? $list[$key] : null;
1 ✔
654
                }
655

656
                $pair = array_slice( $list, $pos, 1 );
1 ✔
657
                return !empty( $pair ) ? current( $pair ) : null;
1 ✔
658
        }
659

660

661
        /**
662
         * Returns the average of all integer and float values in the map.
663
         *
664
         * Examples:
665
         *  Map::from( [1, 3, 5] )->avg();
666
         *  Map::from( [1, null, 5] )->avg();
667
         *  Map::from( [1, 'sum', 5] )->avg();
668
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( 'p' );
669
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->avg( 'i/p' );
670
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->avg( fn( $val, $key ) => $val['i']['p'] ?? null );
671
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( fn( $val, $key ) => $key < 1 ? $val : null );
672
         *
673
         * Results:
674
         * The first and second line will return "3", the third one "2", the forth
675
         * one "30", the fifth and sixth one "40" and the last one "30".
676
         *
677
         * Non-numeric values will be removed before calculation.
678
         *
679
         * This does also work for multi-dimensional arrays by passing the keys
680
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
681
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
682
         * public properties of objects or objects implementing __isset() and __get() methods.
683
         *
684
         * @param \Closure|string|null $col Closure, key or path to the values in the nested array or object to compute the average for
685
         * @return float Average of all elements or 0 if there are no elements in the map
686
         */
687
        public function avg( \Closure|string|null $col = null ) : float
688
        {
689
                $sum = 0;
3 ✔
690
                $cnt = 0;
3 ✔
691

692
                if( $col instanceof \Closure )
3 ✔
693
                {
694
                        foreach( $this->list() as $key => $item )
1 ✔
695
                        {
696
                                if( is_numeric( $val = $col( $item, $key ) ) )
1 ✔
697
                                {
698
                                        $sum += $val;
1 ✔
699
                                        $cnt++;
1 ✔
700
                                }
701
                        }
702
                }
703
                else
704
                {
705
                        $parts = $col ? explode( $this->sep, (string) $col ) : [];
2 ✔
706

707
                        foreach( $this->list() as $item )
2 ✔
708
                        {
709
                                if( $parts === [] ) {
2 ✔
710
                                        $val = $item;
1 ✔
711
                                } elseif( is_array( $item ) ) {
1 ✔
712
                                        $val = $this->arrayVal( $item, $parts );
1 ✔
713
                                } else {
714
                                        $val = $this->val( $item, $parts );
×
715
                                }
716

717
                                if( is_numeric( $val ) )
2 ✔
718
                                {
719
                                        $sum += $val;
2 ✔
720
                                        $cnt++;
2 ✔
721
                                }
722
                        }
723
                }
724

725
                return $cnt > 0 ? $sum / $cnt : 0;
3 ✔
726
        }
727

728

729
        /**
730
         * Returns the elements before the given one.
731
         *
732
         * Examples:
733
         *  Map::from( ['a' => 1, 'b' => 0] )->before( 0 );
734
         *  Map::from( [0 => 'b', 1 => 'a'] )->before( 'a' );
735
         *  Map::from( [0 => 'b', 1 => 'a'] )->before( 'b' );
736
         *  Map::from( ['a', 'c', 'b'] )->before( function( $item, $key ) {
737
         *      return $key >= 1;
738
         *  } );
739
         *
740
         * Results:
741
         *  ['a' => 1]
742
         *  [0 => 'b']
743
         *  []
744
         *  [0 => 'a']
745
         *
746
         * The keys are preserved using this method.
747
         *
748
         * @param \Closure|int|string $value Value or function with (item, key) parameters
749
         * @return self<int|string,mixed> New map with the elements before the given one
750
         */
751
        public function before( \Closure|int|string $value ) : self
752
        {
753
                if( ( $pos = $this->pos( $value ) ) === null ) {
4 ✔
754
                        return new static();
×
755
                }
756

757
                return new static( array_slice( $this->list(), 0, $pos, true ) );
4 ✔
758
        }
759

760

761
        /**
762
         * Returns an element by key and casts it to boolean if possible.
763
         *
764
         * Examples:
765
         *  Map::from( ['a' => true] )->bool( 'a' );
766
         *  Map::from( ['a' => '1'] )->bool( 'a' );
767
         *  Map::from( ['a' => 1.1] )->bool( 'a' );
768
         *  Map::from( ['a' => '10'] )->bool( 'a' );
769
         *  Map::from( ['a' => 'abc'] )->bool( 'a' );
770
         *  Map::from( ['a' => ['b' => ['c' => true]]] )->bool( 'a/b/c' );
771
         *  Map::from( [] )->bool( 'c', function( $val ) { return rand( 1, 2 ); } );
772
         *  Map::from( [] )->bool( 'a', true );
773
         *
774
         *  Map::from( [] )->bool( 'b' );
775
         *  Map::from( ['b' => ''] )->bool( 'b' );
776
         *  Map::from( ['b' => null] )->bool( 'b' );
777
         *  Map::from( ['b' => [true]] )->bool( 'b' );
778
         *  Map::from( ['b' => resource] )->bool( 'b' );
779
         *  Map::from( ['b' => new \stdClass] )->bool( 'b' );
780
         *
781
         *  Map::from( [] )->bool( 'c', new \Exception( 'error' ) );
782
         *
783
         * Results:
784
         * The first eight examples will return TRUE while the 9th to 14th example
785
         * returns FALSE. The last example will throw an exception.
786
         *
787
         * This does also work for multi-dimensional arrays by passing the keys
788
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
789
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
790
         * public properties of objects or objects implementing __isset() and __get() methods.
791
         *
792
         * @param int|string $key Key or path to the requested item
793
         * @param \Closure|\Throwable|bool $default Default value if key isn't found
794
         * @return bool Value from map or default value
795
         */
796
        public function bool( int|string $key, \Closure|\Throwable|bool $default = false ) : bool
797
        {
798
                if( $this->item( $key, $val ) && ( is_scalar( $val ) || $val === null ) ) {
4 ✔
799
                        return (bool) $val;
2 ✔
800
                }
801

802
                return (bool) $this->fallback( $default, isset( $val ), $val ?? null );
4 ✔
803
        }
804

805

806
        /**
807
         * Calls the given method on all items and returns the result.
808
         *
809
         * This method can call methods on the map entries that are also implemented
810
         * by the map object itself and are therefore not reachable when using the
811
         * magic __call() method.
812
         *
813
         * Examples:
814
         *  $item = new MyClass(); // implements methods get() and toArray()
815
         *  Map::from( [$item, $item] )->call( 'get', ['myprop'] );
816
         *  Map::from( [$item, $item] )->call( 'toArray' );
817
         *
818
         * Results:
819
         * The first example will return ['...', '...'] while the second one returns [[...], [...]].
820
         *
821
         * If some entries are not objects or the method isn't callable, they will be
822
         * skipped. The map keys from the original map are preserved in the returned map.
823
         *
824
         * @param string $name Method name
825
         * @param array<mixed> $params List of parameters
826
         * @return self<int|string,mixed> New map with results from all elements
827
         */
828
        public function call( string $name, array $params = [] ) : self
829
        {
830
                $result = [];
2 ✔
831

832
                foreach( $this->list() as $key => $item )
2 ✔
833
                {
834
                        if( is_object( $item ) && is_callable( [$item, $name] ) ) {
2 ✔
835
                                $result[$key] = $item->{$name}( ...$params );
2 ✔
836
                        }
837
                }
838

839
                return new static( $result );
2 ✔
840
        }
841

842

843
        /**
844
         * Casts all entries to the passed type.
845
         *
846
         * Examples:
847
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast();
848
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast( 'bool' );
849
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast( 'int' );
850
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast( 'float' );
851
         *  Map::from( [new stdClass, new stdClass] )->cast( 'array' );
852
         *  Map::from( [[], []] )->cast( 'object' );
853
         *
854
         * Results:
855
         * The examples will return (in this order):
856
         * ['1', '1', '1.0', 'yes']
857
         * [true, true, true, true]
858
         * [1, 1, 1, 0]
859
         * [1.0, 1.0, 1.0, 0.0]
860
         * [[], []]
861
         * [new stdClass, new stdClass]
862
         *
863
         * Casting arrays and objects to scalar values won't return anything useful!
864
         * Casting values to strings which are neither scalar values nor stringable
865
         * objects will return an empty string instead.
866
         *
867
         * @param string $type Type to cast the values to ("string", "bool", "int", "float", "array", "object")
868
         * @return self<int|string,mixed> Updated map with casted elements
869
         */
870
        public function cast( string $type = 'string' ) : self
871
        {
872
                foreach( $this->list() as &$item )
2 ✔
873
                {
874
                        switch( $type )
875
                        {
876
                                case 'bool': $item = (bool) $item; break;
2 ✔
877
                                case 'int': $item = (int) $item; break;
2 ✔
878
                                case 'float': $item = (float) $item; break;
2 ✔
879
                                case 'string': $item = is_scalar( $item ) || $item instanceof \Stringable ? (string) $item : ''; break;
2 ✔
880
                                case 'array': $item = (array) $item; break;
1 ✔
881
                                case 'object': $item = (object) $item; break;
1 ✔
882
                        }
883
                }
884

885
                return $this;
2 ✔
886
        }
887

888

889
        /**
890
         * Chunks the map into arrays with the given number of elements.
891
         *
892
         * Examples:
893
         *  Map::from( [0, 1, 2, 3, 4] )->chunk( 3 );
894
         *  Map::from( ['a' => 0, 'b' => 1, 'c' => 2] )->chunk( 2 );
895
         *
896
         * Results:
897
         *  [[0, 1, 2], [3, 4]]
898
         *  [['a' => 0, 'b' => 1], ['c' => 2]]
899
         *
900
         * The last chunk may contain less elements than the given number.
901
         *
902
         * The sub-arrays of the returned map are plain PHP arrays. If you need Map
903
         * objects, then wrap them with Map::from() when you iterate over the map.
904
         *
905
         * @param int $size Maximum size of the sub-arrays
906
         * @param bool $preserve Preserve keys in new map
907
         * @return self<int|string,mixed> New map with elements chunked in sub-arrays
908
         * @throws \InvalidArgumentException If size is smaller than 1
909
         */
910
        public function chunk( int $size, bool $preserve = false ) : self
911
        {
912
                if( $size < 1 ) {
3 ✔
913
                        throw new \InvalidArgumentException( 'Chunk size must be greater or equal than 1' );
1 ✔
914
                }
915

916
                return new static( array_chunk( $this->list(), $size, $preserve ) );
2 ✔
917
        }
918

919

920
        /**
921
         * Removes all elements from the current map.
922
         *
923
         * @return self<int|string,mixed> Updated map for fluid interface
924
         */
925
        public function clear() : self
926
        {
927
                $this->list = [];
4 ✔
928
                return $this;
4 ✔
929
        }
930

931

932
        /**
933
         * Clones the map and all objects within.
934
         *
935
         * Examples:
936
         *  Map::from( [new \stdClass, new \stdClass] )->clone();
937
         *
938
         * Results:
939
         *   [new \stdClass, new \stdClass]
940
         *
941
         * The objects within the Map are NOT the same as before but new cloned objects.
942
         * This is different to copy(), which doesn't clone the objects within.
943
         *
944
         * The keys are preserved using this method.
945
         *
946
         * @return self<int|string,mixed> New map with cloned objects
947
         */
948
        public function clone() : self
949
        {
950
                $list = [];
1 ✔
951

952
                foreach( $this->list() as $key => $item ) {
1 ✔
953
                        $list[$key] = is_object( $item ) ? clone $item : $item;
1 ✔
954
                }
955

956
                return new static( $list );
1 ✔
957
        }
958

959

960
        /**
961
         * Returns the values of a single column/property from an array of arrays or objects in a new map.
962
         *
963
         * Examples:
964
         *  Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( 'val' );
965
         *  Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( 'val', 'id' );
966
         *  Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( null, 'id' );
967
         *  Map::from( [['id' => 'ix', 'val' => 'v1'], ['id' => 'ix', 'val' => 'v2']] )->col( null, 'id' );
968
         *  Map::from( [['foo' => ['bar' => 'one', 'baz' => 'two']]] )->col( 'foo/baz', 'foo/bar' );
969
         *  Map::from( [['foo' => ['bar' => 'one']]] )->col( 'foo/baz', 'foo/bar' );
970
         *  Map::from( [['foo' => ['baz' => 'two']]] )->col( 'foo/baz', 'foo/bar' );
971
         *
972
         * Results:
973
         *  ['v1', 'v2']
974
         *  ['i1' => 'v1', 'i2' => 'v2']
975
         *  ['i1' => ['id' => 'i1', 'val' => 'v1'], 'i2' => ['id' => 'i2', 'val' => 'v2']]
976
         *  ['ix' => ['id' => 'ix', 'val' => 'v2']]
977
         *  ['one' => 'two']
978
         *  ['one' => null]
979
         *  ['two']
980
         *
981
         * If $indexcol is omitted, it's value is NULL or not set, the result will be indexed from 0-n.
982
         * Items with the same value for $indexcol will overwrite previous items and only the last
983
         * one will be part of the resulting map.
984
         *
985
         * This does also work to map values from multi-dimensional arrays by passing the keys
986
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
987
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
988
         * public properties of objects or objects implementing __isset() and __get() methods.
989
         *
990
         * If the index value is not a scalar value or a stringable object, the
991
         * original key of the entry is used instead.
992
         *
993
         * @param string|null $valuecol Name or path of the value property
994
         * @param string|null $indexcol Name or path of the index property
995
         * @return self<int|string,mixed> New map with mapped entries
996
         */
997
        public function col( ?string $valuecol = null, ?string $indexcol = null ) : self
998
        {
999
                $vparts = explode( $this->sep, (string) $valuecol );
14 ✔
1000
                $iparts = explode( $this->sep, (string) $indexcol );
14 ✔
1001

1002
                if( ( $valuecol === null || count( $vparts ) === 1 )
14 ✔
1003
                        && ( $indexcol === null || count( $iparts ) === 1 )
14 ✔
1004
                ) {
1005
                        try {
1006
                                $list = $this->list();
9 ✔
1007

1008
                                foreach( $list as $key => $item )
9 ✔
1009
                                {
1010
                                        if( $item instanceof \Aimeos\Map ) {
9 ✔
1011
                                                $list[$key] = $item->toArray();
1 ✔
1012
                                        } elseif( $item instanceof \Traversable ) {
8 ✔
1013
                                                $list[$key] = iterator_to_array( $item, true );
1 ✔
1014
                                        }
1015
                                }
1016

1017
                                return new static( array_column( $list, $valuecol, $indexcol ) );
9 ✔
1018
                        } catch( \TypeError $e ) {
1 ✔
1019
                                ; // use the loop below if the index values can't be used as keys
1020
                        }
1021
                }
1022

1023
                $list = [];
6 ✔
1024

1025
                foreach( $this->list() as $key => $item )
6 ✔
1026
                {
1027
                        if( $valuecol )
6 ✔
1028
                        {
1029
                                if( is_array( $item ) ) {
6 ✔
1030
                                        $v = $this->arrayVal( $item, $vparts );
6 ✔
1031
                                } else {
1032
                                        $v = $this->val( $item, $vparts );
×
1033
                                }
1034
                        }
1035
                        else
1036
                        {
1037
                                $v = $item;
×
1038
                        }
1039

1040
                        $idx = null;
6 ✔
1041
                        $hasIndex = $indexcol && ( is_array( $item )
6 ✔
1042
                                ? $this->arrayPath( $item, $iparts, $idx )
6 ✔
1043
                                : $this->value( $item, $iparts, $idx )
6 ✔
1044
                        );
6 ✔
1045

1046
                        if( $hasIndex && ( is_scalar( $idx ) || $idx instanceof \Stringable ) ) {
6 ✔
1047
                                $list[$this->arrayKey( $idx )] = $v;
4 ✔
1048
                        } else {
1049
                                $list[$key] = $v;
2 ✔
1050
                        }
1051
                }
1052

1053
                return new static( $list );
6 ✔
1054
        }
1055

1056

1057
        /**
1058
         * Collapses all sub-array elements recursively to a new map overwriting existing keys.
1059
         *
1060
         * Examples:
1061
         *  Map::from( [0 => ['a' => 0, 'b' => 1], 1 => ['c' => 2, 'd' => 3]] )->collapse();
1062
         *  Map::from( [0 => ['a' => 0, 'b' => 1], 1 => ['a' => 2]] )->collapse();
1063
         *  Map::from( [0 => [0 => 0, 1 => 1], 1 => [0 => ['a' => 2, 0 => 3], 1 => 4]] )->collapse();
1064
         *  Map::from( [0 => [0 => 0, 'a' => 1], 1 => [0 => ['b' => 2, 0 => 3], 1 => 4]] )->collapse( 1 );
1065
         *  Map::from( [0 => [0 => 0, 'a' => 1], 1 => Map::from( [0 => ['b' => 2, 0 => 3], 1 => 4] )] )->collapse();
1066
         *
1067
         * Results:
1068
         *  ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3]
1069
         *  ['a' => 2, 'b' => 1]
1070
         *  [0 => 3, 1 => 4, 'a' => 2]
1071
         *  [0 => ['b' => 2, 0 => 3], 1 => 4, 'a' => 1]
1072
         *  [0 => 3, 'a' => 1, 'b' => 2, 1 => 4]
1073
         *
1074
         * The keys are preserved and already existing elements will be overwritten.
1075
         * This is also true for numeric keys! A value smaller than 1 for depth will
1076
         * return the same map elements. Collapsing does also work if elements
1077
         * implement the "Traversable" interface (which the Map object does).
1078
         *
1079
         * This method is similar than flat() but replaces already existing elements.
1080
         *
1081
         * @param int|null $depth Number of levels to collapse for multi-dimensional arrays or NULL for all
1082
         * @return self<int|string,mixed> New map with all sub-array elements added into it recursively, up to the specified depth
1083
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
1084
         */
1085
        public function collapse( ?int $depth = null ) : self
1086
        {
1087
                if( $depth < 0 ) {
6 ✔
1088
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
1 ✔
1089
                }
1090

1091
                $result = [];
5 ✔
1092
                $this->kflatten( $this->list(), $result, $depth ?? 0x7fffffff );
5 ✔
1093
                return new static( $result );
5 ✔
1094
        }
1095

1096

1097
        /**
1098
         * Combines the values of the map as keys with the passed elements as values.
1099
         *
1100
         * Examples:
1101
         *  Map::from( ['name', 'age'] )->combine( ['Tom', 29] );
1102
         *
1103
         * Results:
1104
         *  ['name' => 'Tom', 'age' => 29]
1105
         *
1106
         * @param iterable<int|string,mixed> $values Values of the new map
1107
         * @return self<int|string,mixed> New map
1108
         * @throws \InvalidArgumentException If the number of elements doesn't match or a key isn't a scalar value or stringable object
1109
         */
1110
        public function combine( iterable $values ) : self
1111
        {
1112
                $keys = $this->list();
4 ✔
1113
                $values = $this->array( $values );
4 ✔
1114

1115
                if( count( $keys ) !== count( $values ) ) {
4 ✔
1116
                        throw new \InvalidArgumentException( 'Number of keys and values must be the same' );
1 ✔
1117
                }
1118

1119
                $result = [];
3 ✔
1120
                $value = reset( $values );
3 ✔
1121

1122
                foreach( $keys as $key )
3 ✔
1123
                {
1124
                        $result[$this->arrayKey( $key )] = $value;
3 ✔
1125
                        $value = next( $values );
2 ✔
1126
                }
1127

1128
                return new static( $result );
2 ✔
1129
        }
1130

1131

1132
        /**
1133
         * Compares the value against all map elements.
1134
         *
1135
         * This method is an alias for strCompare().
1136
         *
1137
         * @param string $value Value to compare map elements to
1138
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
1139
         * @return bool TRUE If at least one element matches, FALSE if value is not in map
1140
         * @deprecated Use strCompare() method instead
1141
         */
1142
        public function compare( string $value, bool $case = true ) : bool
1143
        {
1144
                return $this->strCompare( $value, $case );
1 ✔
1145
        }
1146

1147

1148
        /**
1149
         * Pushs all of the given elements onto the map with new keys without creating a new map.
1150
         *
1151
         * Examples:
1152
         *  Map::from( ['foo'] )->concat( new Map( ['bar'] ));
1153
         *
1154
         * Results:
1155
         *  ['foo', 'bar']
1156
         *
1157
         * The keys of the passed elements are NOT preserved!
1158
         *
1159
         * @param iterable<int|string,mixed> $elements List of elements
1160
         * @return self<int|string,mixed> Updated map for fluid interface
1161
         */
1162
        public function concat( iterable $elements ) : self
1163
        {
1164
                $this->list();
2 ✔
1165

1166
                foreach( $elements as $item ) {
2 ✔
1167
                        $this->list[] = $item;
2 ✔
1168
                }
1169

1170
                return $this;
2 ✔
1171
        }
1172

1173

1174
        /**
1175
         * Determines if an item exists in the map.
1176
         *
1177
         * This method combines the power of the where() method with some() to check
1178
         * if the map contains at least one of the passed values or conditions.
1179
         *
1180
         * Examples:
1181
         *  Map::from( ['a', 'b'] )->contains( 'a' );
1182
         *  Map::from( ['a', 'b'] )->contains( ['a', 'c'] );
1183
         *  Map::from( ['a', 'b'] )->contains( function( $item, $key ) {
1184
         *    return $item === 'a'
1185
         *  } );
1186
         *  Map::from( [['type' => 'name']] )->contains( 'type', 'name' );
1187
         *  Map::from( [['type' => 'name']] )->contains( 'type', '==', 'name' );
1188
         *
1189
         * Results:
1190
         * All method calls will return TRUE because at least "a" is included in the
1191
         * map or there's a "type" key with a value "name" like in the last two
1192
         * examples.
1193
         *
1194
         * Check the where() method for available operators.
1195
         *
1196
         * @param \Closure|iterable<mixed>|string|int $key Anonymous function with (item, key) parameter, element or list of elements to test against
1197
         * @param string|null $operator Operator used for comparison
1198
         * @param mixed $value Value used for comparison
1199
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
1200
         */
1201
        public function contains( \Closure|iterable|string|int $key, ?string $operator = null, mixed $value = null ) : bool
1202
        {
1203
                if( $operator === null ) {
4 ✔
1204
                        return $this->some( $key );
2 ✔
1205
                }
1206

1207
                if( !is_string( $key ) ) {
2 ✔
1208
                        throw new \InvalidArgumentException( 'Key must be a string' );
×
1209
                }
1210

1211
                if( func_num_args() < 3 ) {
2 ✔
1212
                        $filter = $this->whereFilter( $key, '==', $operator );
1 ✔
1213
                } else {
1214
                        $filter = $this->whereFilter( $key, $operator, $value );
2 ✔
1215
                }
1216

1217
                foreach( $this->list() as $item )
2 ✔
1218
                {
1219
                        if( $filter( $item ) ) {
2 ✔
1220
                                return true;
2 ✔
1221
                        }
1222
                }
1223

1224
                return false;
1 ✔
1225
        }
1226

1227

1228
        /**
1229
         * Creates a new map with the same elements.
1230
         *
1231
         * Both maps share the same array until one of the map objects modifies the
1232
         * array. Then, the array is copied and the copy is modfied (copy on write).
1233
         *
1234
         * @return self<int|string,mixed> New map
1235
         */
1236
        public function copy() : self
1237
        {
1238
                return clone $this;
3 ✔
1239
        }
1240

1241

1242
        /**
1243
         * Counts the total number of elements in the map.
1244
         *
1245
         * @return int Number of elements
1246
         */
1247
        public function count() : int
1248
        {
1249
                return count( $this->list() );
10 ✔
1250
        }
1251

1252

1253
        /**
1254
         * Counts how often the same values are in the map.
1255
         *
1256
         * Examples:
1257
         *  Map::from( [1, 'foo', 2, 'foo', 1] )->countBy();
1258
         *  Map::from( [1.11, 3.33, 3.33, 9.99] )->countBy();
1259
         *  Map::from( [['i' => ['p' => 1.11]], ['i' => ['p' => 3.33]], ['i' => ['p' => 3.33]]] )->countBy( 'i/p' );
1260
         *  Map::from( ['a@gmail.com', 'b@yahoo.com', 'c@gmail.com'] )->countBy( function( $email ) {
1261
         *    return substr( strrchr( $email, '@' ), 1 );
1262
         *  } );
1263
         *
1264
         * Results:
1265
         *  [1 => 2, 'foo' => 2, 2 => 1]
1266
         *  ['1.11' => 1, '3.33' => 2, '9.99' => 1]
1267
         *  ['1.11' => 1, '3.33' => 2]
1268
         *  ['gmail.com' => 2, 'yahoo.com' => 1]
1269
         *
1270
         * Counting values does only work for values that can be converted to array
1271
         * keys. All elements are casted to strings if no callback is passed. Custom
1272
         * callback results are normalized to array keys, too.
1273
         *
1274
         * This does also work for multi-dimensional arrays by passing the keys
1275
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1276
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1277
         * public properties of objects or objects implementing __isset() and __get() methods.
1278
         *
1279
         * @param \Closure|string|null $col Key as "key1/key2/key3" or function with (value) parameter returning the values for counting
1280
         * @return self<int|string,mixed> New map with values as keys and their count as value
1281
         * @throws \InvalidArgumentException If one of the returned values can't be used as key
1282
         */
1283
        public function countBy( \Closure|string|null $col = null ) : self
1284
        {
1285
                $result = [];
7 ✔
1286

1287
                if( $col instanceof \Closure )
7 ✔
1288
                {
1289
                        foreach( $this->list() as $item )
3 ✔
1290
                        {
1291
                                $key = $this->arrayKey( $col( $item ) );
3 ✔
1292
                                $result[$key] = ( $result[$key] ?? 0 ) + 1;
2 ✔
1293
                        }
1294

1295
                        return new static( $result );
2 ✔
1296
                }
1297

1298
                $parts = $col ? explode( $this->sep, (string) $col ) : [];
4 ✔
1299
                $part = count( $parts ) === 1 ? current( $parts ) : null;
4 ✔
1300

1301
                foreach( $this->list() as $item )
4 ✔
1302
                {
1303
                        if( $part !== null && is_array( $item ) ) {
4 ✔
1304
                                $key = $this->groupKey( $item[$part] ?? null );
1 ✔
1305
                        } elseif( $parts !== [] ) {
3 ✔
1306
                                if( is_array( $item ) ) {
1 ✔
1307
                                        $val = $this->arrayVal( $item, $parts );
1 ✔
1308
                                } else {
1309
                                        $val = $this->val( $item, $parts );
×
1310
                                }
1311

1312
                                $key = $this->groupKey( $val );
1 ✔
1313
                        } else {
1314
                                $key = $this->groupKey( $item );
2 ✔
1315
                        }
1316

1317
                        $result[$key] = ( $result[$key] ?? 0 ) + 1;
4 ✔
1318
                }
1319

1320
                return new static( $result );
4 ✔
1321
        }
1322

1323

1324
        /**
1325
         * Dumps the map content and terminates the script.
1326
         *
1327
         * The dd() method is very helpful to see what are the map elements passed
1328
         * between two map methods in a method call chain. It stops execution of the
1329
         * script afterwards to avoid further output.
1330
         *
1331
         * Examples:
1332
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->sort()->dd();
1333
         *
1334
         * Results:
1335
         *  Array
1336
         *  (
1337
         *      [0] => bar
1338
         *      [1] => foo
1339
         *  )
1340
         *
1341
         * @param callable|null $callback Function receiving the map elements as parameter (optional)
1342
         */
1343
        public function dd( ?callable $callback = null ) : void
1344
        {
1345
                $this->dump( $callback );
×
1346
                exit( 1 );
×
1347
        }
1348

1349

1350
        /**
1351
         * Returns the keys/values in the map whose values are not present in the passed elements in a new map.
1352
         *
1353
         * Examples:
1354
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->diff( ['bar'] );
1355
         *
1356
         * Results:
1357
         *  ['a' => 'foo']
1358
         *
1359
         * If a callback is passed, the given function will be used to compare the values.
1360
         * The function must accept two parameters (value A and B) and must return
1361
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
1362
         * greater than value B. Both, a method name and an anonymous function can be passed:
1363
         *
1364
         *  Map::from( [0 => 'a'] )->diff( [0 => 'A'], 'strcasecmp' );
1365
         *  Map::from( ['b' => 'a'] )->diff( ['B' => 'A'], 'strcasecmp' );
1366
         *  Map::from( ['b' => 'a'] )->diff( ['c' => 'A'], function( $valA, $valB ) {
1367
         *      return strtolower( $valA ) <=> strtolower( $valB );
1368
         *  } );
1369
         *
1370
         * All examples will return an empty map because both contain the same values
1371
         * when compared case insensitive.
1372
         *
1373
         * The keys are preserved using this method.
1374
         *
1375
         * @param iterable<int|string,mixed> $elements List of elements
1376
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
1377
         * @return self<int|string,mixed> New map
1378
         */
1379
        public function diff( iterable $elements, ?callable $callback = null ) : self
1380
        {
1381
                $list = $this->list();
5 ✔
1382
                $elements = $this->array( $elements );
5 ✔
1383

1384
                if( $callback ) {
5 ✔
1385
                        return new static( array_udiff( $list, $elements, $callback ) );
1 ✔
1386
                }
1387

1388
                return new static( (array) $this->native(
5 ✔
1389
                        static fn() => array_diff( $list, $elements ),
5 ✔
1390
                        fn() => $this->filterByValues( $list, $elements, false )
5 ✔
1391
                ) );
5 ✔
1392
        }
1393

1394

1395
        /**
1396
         * Returns the keys/values in the map whose keys AND values are not present in the passed elements in a new map.
1397
         *
1398
         * Examples:
1399
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->diffAssoc( new Map( ['foo', 'b' => 'bar'] ) );
1400
         *
1401
         * Results:
1402
         *  ['a' => 'foo']
1403
         *
1404
         * If a callback is passed, the given function will be used to compare the values.
1405
         * The function must accept two parameters (value A and B) and must return
1406
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
1407
         * greater than value B. Both, a method name and an anonymous function can be passed:
1408
         *
1409
         *  Map::from( [0 => 'a'] )->diffAssoc( [0 => 'A'], 'strcasecmp' );
1410
         *  Map::from( ['b' => 'a'] )->diffAssoc( ['B' => 'A'], 'strcasecmp' );
1411
         *  Map::from( ['b' => 'a'] )->diffAssoc( ['c' => 'A'], function( $valA, $valB ) {
1412
         *      return strtolower( $valA ) <=> strtolower( $valB );
1413
         *  } );
1414
         *
1415
         * The first example will return an empty map because both contain the same
1416
         * values when compared case insensitive. The second and third example will return
1417
         * an empty map because 'A' is part of the passed array but the keys doesn't match
1418
         * ("b" vs. "B" and "b" vs. "c").
1419
         *
1420
         * The keys are preserved using this method.
1421
         *
1422
         * @param iterable<int|string,mixed> $elements List of elements
1423
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
1424
         * @return self<int|string,mixed> New map
1425
         */
1426
        public function diffAssoc( iterable $elements, ?callable $callback = null ) : self
1427
        {
1428
                $list = $this->list();
3 ✔
1429
                $elements = $this->array( $elements );
3 ✔
1430

1431
                if( $callback ) {
3 ✔
1432
                        return new static( array_udiff_assoc( $list, $elements, $callback ) );
1 ✔
1433
                }
1434

1435
                return new static( (array) $this->native(
3 ✔
1436
                        static fn() => array_diff_assoc( $list, $elements ),
3 ✔
1437
                        fn() => array_udiff_assoc( $list, $elements, $this->comparator() )
3 ✔
1438
                ) );
3 ✔
1439
        }
1440

1441

1442
        /**
1443
         * Returns the key/value pairs from the map whose keys are not present in the passed elements in a new map.
1444
         *
1445
         * Examples:
1446
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->diffKeys( new Map( ['foo', 'b' => 'baz'] ) );
1447
         *
1448
         * Results:
1449
         *  ['a' => 'foo']
1450
         *
1451
         * If a callback is passed, the given function will be used to compare the keys.
1452
         * The function must accept two parameters (key A and B) and must return
1453
         * -1 if key A is smaller than key B, 0 if both are equal and 1 if key A is
1454
         * greater than key B. Both, a method name and an anonymous function can be passed:
1455
         *
1456
         *  Map::from( [0 => 'a'] )->diffKeys( [0 => 'A'], 'strcasecmp' );
1457
         *  Map::from( ['b' => 'a'] )->diffKeys( ['B' => 'X'], 'strcasecmp' );
1458
         *  Map::from( ['b' => 'a'] )->diffKeys( ['c' => 'a'], function( $keyA, $keyB ) {
1459
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
1460
         *  } );
1461
         *
1462
         * The first and second example will return an empty map because both contain
1463
         * the same keys when compared case insensitive. The third example will return
1464
         * ['b' => 'a'] because the keys doesn't match ("b" vs. "c").
1465
         *
1466
         * The keys are preserved using this method.
1467
         *
1468
         * @param iterable<int|string,mixed> $elements List of elements
1469
         * @param  callable|null $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
1470
         * @return self<int|string,mixed> New map
1471
         */
1472
        public function diffKeys( iterable $elements, ?callable $callback = null ) : self
1473
        {
1474
                if( $callback ) {
2 ✔
1475
                        return new static( array_diff_ukey( $this->list(), $this->array( $elements ), $callback ) );
1 ✔
1476
                }
1477

1478
                return new static( array_diff_key( $this->list(), $this->array( $elements ) ) );
2 ✔
1479
        }
1480

1481

1482
        /**
1483
         * Dumps the map content using the given function (print_r by default).
1484
         *
1485
         * The dump() method is very helpful to see what are the map elements passed
1486
         * between two map methods in a method call chain.
1487
         *
1488
         * Examples:
1489
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->dump()->asort()->dump( 'var_dump' );
1490
         *
1491
         * Results:
1492
         *  Array
1493
         *  (
1494
         *      [a] => foo
1495
         *      [b] => bar
1496
         *  )
1497
         *  array(1) {
1498
         *    ["b"]=>
1499
         *    string(3) "bar"
1500
         *    ["a"]=>
1501
         *    string(3) "foo"
1502
         *  }
1503
         *
1504
         * @param callable|null $callback Function receiving the map elements as parameter (optional)
1505
         * @return self<int|string,mixed> Same map for fluid interface
1506
         */
1507
        public function dump( ?callable $callback = null ) : self
1508
        {
1509
                $callback ? $callback( $this->list() ) : print_r( $this->list() );
1 ✔
1510
                return $this;
1 ✔
1511
        }
1512

1513

1514
        /**
1515
         * Returns the duplicate values from the map.
1516
         *
1517
         * For nested arrays, you have to pass the name of the column of the nested
1518
         * array which should be used to check for duplicates.
1519
         *
1520
         * Examples:
1521
         *  Map::from( [1, 2, '1', 3] )->duplicates()
1522
         *  Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->duplicates( 'p' )
1523
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->duplicates( 'i/p' )
1524
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->duplicates( fn( $item, $key ) => $item['i']['p'] )
1525
         *
1526
         * Results:
1527
         *  [2 => '1']
1528
         *  [1 => ['p' => 1]]
1529
         *  [1 => ['i' => ['p' => 1]]]
1530
         *  [1 => ['i' => ['p' => 1]]]
1531
         *
1532
         * This does also work for multi-dimensional arrays by passing the keys
1533
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1534
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1535
         * public properties of objects or objects implementing __isset() and __get() methods.
1536
         *
1537
         * The keys are preserved using this method.
1538
         *
1539
         * @param \Closure|string|null $col Key, path of the nested array or anonymous function with ($item, $key) parameters returning the value for comparison
1540
         * @return self<int|string,mixed> New map
1541
         */
1542
        public function duplicates( \Closure|string|null $col = null ) : self
1543
        {
1544
                $list = $this->list();
5 ✔
1545

1546
                if( $col === null ) {
5 ✔
1547
                        return new static( array_diff_key( $list, $this->dedup( $list ) ) );
2 ✔
1548
                }
1549

1550
                return new static( array_diff_key( $list, $this->dedupMappedKeys( $list, $col ) ) );
3 ✔
1551
        }
1552

1553

1554
        /**
1555
         * Executes a callback over each entry until FALSE is returned.
1556
         *
1557
         * Examples:
1558
         *  $result = [];
1559
         *  Map::from( [0 => 'a', 1 => 'b'] )->each( function( $value, $key ) use ( &$result ) {
1560
         *      $result[$key] = strtoupper( $value );
1561
         *      return false;
1562
         *  } );
1563
         *
1564
         * The $result array will contain [0 => 'A'] because FALSE is returned
1565
         * after the first entry and all other entries are then skipped.
1566
         *
1567
         * @param callable $callback Function with (value, key) parameters and returns TRUE/FALSE
1568
         * @return self<int|string,mixed> Same map for fluid interface
1569
         */
1570
        public function each( callable $callback ) : self
1571
        {
1572
                foreach( $this->list() as $key => $item )
3 ✔
1573
                {
1574
                        if( $callback( $item, $key ) === false ) {
3 ✔
1575
                                break;
1 ✔
1576
                        }
1577
                }
1578

1579
                return $this;
3 ✔
1580
        }
1581

1582

1583
        /**
1584
         * Determines if the map is empty or not.
1585
         *
1586
         * Examples:
1587
         *  Map::from( [] )->empty();
1588
         *  Map::from( ['a'] )->empty();
1589
         *
1590
         * Results:
1591
         *  The first example returns TRUE while the second returns FALSE
1592
         *
1593
         * The method is equivalent to isEmpty().
1594
         *
1595
         * @return bool TRUE if map is empty, FALSE if not
1596
         */
1597
        public function empty() : bool
1598
        {
1599
                return empty( $this->list() );
2 ✔
1600
        }
1601

1602

1603
        /**
1604
         * Tests if the passed elements are equal to the elements in the map.
1605
         *
1606
         * Examples:
1607
         *  Map::from( ['a'] )->equals( ['a', 'b'] );
1608
         *  Map::from( ['a', 'b'] )->equals( ['b'] );
1609
         *  Map::from( ['a', 'b'] )->equals( ['b', 'a'] );
1610
         *
1611
         * Results:
1612
         * The first and second example will return FALSE, the third example will return TRUE
1613
         *
1614
         * The method differs to is() in the fact that it doesn't care about the keys
1615
         * by default. The elements are only loosely compared and the keys are ignored.
1616
         *
1617
         * Scalar values are compared by their string values:
1618
         * (string) $item1 === (string) $item2
1619
         *
1620
         * Non-scalar values like arrays and objects that can't be cast to strings
1621
         * are compared by their type and structure instead.
1622
         *
1623
         * @param iterable<int|string,mixed> $elements List of elements to test against
1624
         * @return bool TRUE if both are equal, FALSE if not
1625
         */
1626
        public function equals( iterable $elements ) : bool
1627
        {
1628
                $list = $this->list();
6 ✔
1629
                $elements = $this->array( $elements );
6 ✔
1630

1631
                return (bool) $this->native(
6 ✔
1632
                        static fn() => array_diff( $list, $elements ) === [] && array_diff( $elements, $list ) === [],
6 ✔
1633
                        function() use ( $list, $elements ) {
6 ✔
1634
                                return $this->filterByValues( $list, $elements, false ) === []
×
1635
                                        && $this->filterByValues( $elements, $list, false ) === [];
×
1636
                        }
6 ✔
1637
                );
6 ✔
1638
        }
1639

1640

1641
        /**
1642
         * Verifies that all elements pass the test of the given callback.
1643
         *
1644
         * Examples:
1645
         *  Map::from( [0 => 'a', 1 => 'b'] )->every( function( $value, $key ) {
1646
         *      return is_string( $value );
1647
         *  } );
1648
         *
1649
         *  Map::from( [0 => 'a', 1 => 100] )->every( function( $value, $key ) {
1650
         *      return is_string( $value );
1651
         *  } );
1652
         *
1653
         * The first example will return TRUE because all values are a string while
1654
         * the second example will return FALSE.
1655
         *
1656
         * @param callable $callback Function with (value, key) parameters and returns TRUE/FALSE
1657
         * @return bool True if all elements pass the test, false if if fails for at least one element
1658
         */
1659
        public function every( callable $callback ) : bool
1660
        {
1661
                foreach( $this->list() as $key => $item )
2 ✔
1662
                {
1663
                        if( !$callback( $item, $key ) ) {
2 ✔
1664
                                return false;
2 ✔
1665
                        }
1666
                }
1667

1668
                return true;
1 ✔
1669
        }
1670

1671

1672
        /**
1673
         * Returns a new map without the passed element keys.
1674
         *
1675
         * Examples:
1676
         *  Map::from( ['a' => 1, 'b' => 2, 'c' => 3] )->except( 'b' );
1677
         *  Map::from( [1 => 'a', 2 => 'b', 3 => 'c'] )->except( [1, 3] );
1678
         *
1679
         * Results:
1680
         *  ['a' => 1, 'c' => 3]
1681
         *  [2 => 'b']
1682
         *
1683
         * The keys in the result map are preserved.
1684
         *
1685
         * @param iterable<mixed>|array<mixed>|string|int $keys List of keys to remove
1686
         * @return self<int|string,mixed> New map
1687
         * @throws \InvalidArgumentException If one of the keys can't be used as key
1688
         */
1689
        public function except( iterable|string|int $keys ) : self
1690
        {
1691
                return ( clone $this )->remove( $keys );
2 ✔
1692
        }
1693

1694

1695
        /**
1696
         * Applies a filter to all elements of the map and returns a new map.
1697
         *
1698
         * Examples:
1699
         *  Map::from( [null, 0, 1, '', '0', 'a'] )->filter();
1700
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->filter( function( $value, $key ) {
1701
         *      return $key < 10 && $value < 'n';
1702
         *  } );
1703
         *
1704
         * Results:
1705
         *  [1, 'a']
1706
         *  ['a', 'b']
1707
         *
1708
         * If no callback is passed, all values which are empty, null or false will be
1709
         * removed if their value converted to boolean is FALSE:
1710
         *  (bool) $value === false
1711
         *
1712
         * The keys in the result map are preserved.
1713
         *
1714
         * @param callable|null $callback Function with (item, key) parameters and returns TRUE/FALSE
1715
         * @phpstan-param (callable(TValue,TKey):bool)|null $callback
1716
         * @phpstan-return self<TKey,TValue>
1717
         * @return self<int|string,mixed> New map
1718
         */
1719
        public function filter( ?callable $callback = null ) : self
1720
        {
1721
                if( $callback )
10 ✔
1722
                {
1723
                        $result = [];
9 ✔
1724

1725
                        foreach( $this->list() as $key => $value )
9 ✔
1726
                        {
1727
                                if( $callback( $value, $key ) ) {
9 ✔
1728
                                        $result[$key] = $value;
8 ✔
1729
                                }
1730
                        }
1731

1732
                        return new static( $result );
9 ✔
1733
                }
1734

1735
                return new static( array_filter( $this->list() ) );
1 ✔
1736
        }
1737

1738

1739
        /**
1740
         * Returns the first/last matching element where the callback returns TRUE.
1741
         *
1742
         * Examples:
1743
         *  Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
1744
         *      return $value >= 'b';
1745
         *  } );
1746
         *  Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
1747
         *      return $value >= 'b';
1748
         *  }, null, true );
1749
         *  Map::from( [] )->find( function( $value, $key ) {
1750
         *      return $value >= 'b';
1751
         *  }, fn() => 'none' );
1752
         *  Map::from( [] )->find( function( $value, $key ) {
1753
         *      return $value >= 'b';
1754
         *  }, new \Exception( 'error' ) );
1755
         *
1756
         * Results:
1757
         * The first example will return 'c' while the second will return 'e' (last element).
1758
         * The third and forth one will return "none" and the last one will throw the exception.
1759
         *
1760
         * @param callable $callback Function with (value, key) parameters and returns TRUE/FALSE
1761
         * @param mixed $default Default value, closure or exception if the callback only returns FALSE
1762
         * @param bool $reverse TRUE to test elements from back to front, FALSE for front to back (default)
1763
         * @return mixed First matching value, passed default value or an exception
1764
         */
1765
        public function find( callable $callback, mixed $default = null, bool $reverse = false ) : mixed
1766
        {
1767
                $list = $this->list();
7 ✔
1768

1769
                if( $reverse )
7 ✔
1770
                {
1771
                        $keys = array_keys( $list );
3 ✔
1772

1773
                        for( $i = count( $keys ) - 1; $i >= 0; $i-- )
3 ✔
1774
                        {
1775
                                $key = $keys[$i];
3 ✔
1776
                                $value = $list[$key];
3 ✔
1777

1778
                                if( $callback( $value, $key ) ) {
3 ✔
1779
                                        return $value;
2 ✔
1780
                                }
1781
                        }
1782
                }
1783
                else
1784
                {
1785
                        foreach( $list as $key => $value )
4 ✔
1786
                        {
1787
                                if( $callback( $value, $key ) ) {
4 ✔
1788
                                        return $value;
2 ✔
1789
                                }
1790
                        }
1791
                }
1792

1793
                return $this->fallback( $default );
3 ✔
1794
        }
1795

1796

1797
        /**
1798
         * Returns the first/last key where the callback returns TRUE.
1799
         *
1800
         * Examples:
1801
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1802
         *      return $value >= 'b';
1803
         *  } );
1804
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1805
         *      return $value >= 'b';
1806
         *  }, null, true );
1807
         *  Map::from( [] )->findKey( function( $value, $key ) {
1808
         *      return $value >= 'b';
1809
         *  }, 'none' );
1810
         *  Map::from( [] )->findKey( function( $value, $key ) {
1811
         *      return $value >= 'b';
1812
         *  }, fn() => 'none' );
1813
         *  Map::from( [] )->findKey( function( $value, $key ) {
1814
         *      return $value >= 'b';
1815
         *  }, new \Exception( 'error' ) );
1816
         *
1817
         * Results:
1818
         * The first example will return '1' while the second will return '2' (last element).
1819
         * The third and forth one will return "none" and the last one will throw the exception.
1820
         *
1821
         * @param callable $callback Function with (value, key) parameters and returns TRUE/FALSE
1822
         * @param mixed $default Default value, closure or exception if the callback only returns FALSE
1823
         * @param bool $reverse TRUE to test elements from back to front, FALSE for front to back (default)
1824
         * @return mixed Key of first matching element, passed default value or an exception
1825
         */
1826
        public function findKey( callable $callback, mixed $default = null, bool $reverse = false ) : mixed
1827
        {
1828
                $list = $this->list();
6 ✔
1829

1830
                if( $reverse )
6 ✔
1831
                {
1832
                        $keys = array_keys( $list );
1 ✔
1833

1834
                        for( $i = count( $keys ) - 1; $i >= 0; $i-- )
1 ✔
1835
                        {
1836
                                $key = $keys[$i];
1 ✔
1837
                                $value = $list[$key];
1 ✔
1838

1839
                                if( $callback( $value, $key ) ) {
1 ✔
1840
                                        return $key;
1 ✔
1841
                                }
1842
                        }
1843
                }
1844
                else
1845
                {
1846
                        foreach( $list as $key => $value )
5 ✔
1847
                        {
1848
                                if( $callback( $value, $key ) ) {
2 ✔
1849
                                        return $key;
2 ✔
1850
                                }
1851
                        }
1852
                }
1853

1854
                return $this->fallback( $default );
3 ✔
1855
        }
1856

1857

1858
        /**
1859
         * Returns the first element from the map.
1860
         *
1861
         * Examples:
1862
         *  Map::from( ['a', 'b'] )->first();
1863
         *  Map::from( [] )->first( 'x' );
1864
         *  Map::from( [] )->first( new \Exception( 'error' ) );
1865
         *  Map::from( [] )->first( function() { return rand(); } );
1866
         *
1867
         * Results:
1868
         * The first example will return 'b' and the second one 'x'. The third example
1869
         * will throw the exception passed if the map contains no elements. In the
1870
         * fourth example, a random value generated by the closure function will be
1871
         * returned.
1872
         *
1873
         * Using this method doesn't affect the internal array pointer.
1874
         *
1875
         * @template TDefault
1876
         * @param mixed $default Default value, closure or exception if the map contains no elements
1877
         * @phpstan-param TDefault|\Closure():TDefault|\Throwable $default
1878
         * @phpstan-return TValue|TDefault
1879
         * @return mixed First value of map, (generated) default value or an exception
1880
         */
1881
        public function first( mixed $default = null ) : mixed
1882
        {
1883
                $list = $this->list();
8 ✔
1884
                $key = array_key_first( $list );
8 ✔
1885

1886
                if( $key !== null ) {
8 ✔
1887
                        return $list[$key];
4 ✔
1888
                }
1889

1890
                return $this->fallback( $default );
5 ✔
1891
        }
1892

1893

1894
        /**
1895
         * Returns the first key from the map.
1896
         *
1897
         * Examples:
1898
         *  Map::from( ['a' => 1, 'b' => 2] )->firstKey();
1899
         *  Map::from( [] )->firstKey( 'x' );
1900
         *  Map::from( [] )->firstKey( new \Exception( 'error' ) );
1901
         *  Map::from( [] )->firstKey( function() { return rand(); } );
1902
         *
1903
         * Results:
1904
         * The first example will return 'a' and the second one 'x', the third one will throw
1905
         * an exception and the last one will return a random value.
1906
         *
1907
         * Using this method doesn't affect the internal array pointer.
1908
         *
1909
         * @template TDefault
1910
         * @param mixed $default Default value, closure or exception if the map contains no elements
1911
         * @phpstan-param TDefault|\Closure():TDefault|\Throwable $default
1912
         * @phpstan-return TKey|TDefault
1913
         * @return mixed First key of map, (generated) default value or an exception
1914
         */
1915
        public function firstKey( mixed $default = null ) : mixed
1916
        {
1917
                $list = $this->list();
5 ✔
1918
                $key = array_key_first( $list );
5 ✔
1919

1920
                if( $key !== null ) {
5 ✔
1921
                        return $key;
1 ✔
1922
                }
1923

1924
                return $this->fallback( $default );
4 ✔
1925
        }
1926

1927

1928
        /**
1929
         * Creates a new map with all sub-array elements added recursively without overwriting existing keys.
1930
         *
1931
         * Examples:
1932
         *  Map::from( [[0, 1], [2, 3]] )->flat();
1933
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat();
1934
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat( 1 );
1935
         *  Map::from( [[0, 1], Map::from( [[2, 3], 4] )] )->flat();
1936
         *
1937
         * Results:
1938
         *  [0, 1, 2, 3]
1939
         *  [0, 1, 2, 3, 4]
1940
         *  [0, 1, [2, 3], 4]
1941
         *  [0, 1, 2, 3, 4]
1942
         *
1943
         * The keys are not preserved and the new map elements will be numbered from
1944
         * 0-n. A value smaller than 1 for depth will return the same map elements
1945
         * indexed from 0-n. Flattening does also work if elements implement the
1946
         * "Traversable" interface (which the Map object does).
1947
         *
1948
         * This method is similar than collapse() but doesn't replace existing elements.
1949
         * Keys are NOT preserved using this method!
1950
         *
1951
         * @param int|null $depth Number of levels to flatten multi-dimensional arrays or NULL for all
1952
         * @return self<int|string,mixed> New map with all sub-array elements added into it recursively, up to the specified depth
1953
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
1954
         */
1955
        public function flat( ?int $depth = null ) : self
1956
        {
1957
                if( $depth < 0 ) {
6 ✔
1958
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
1 ✔
1959
                }
1960

1961
                $result = [];
5 ✔
1962
                $this->nflatten( $this->list(), $result, $depth ?? 0x7fffffff );
5 ✔
1963
                return new static( $result );
5 ✔
1964
        }
1965

1966

1967
        /**
1968
         * Creates a new map with keys joined recursively.
1969
         *
1970
         * Examples:
1971
         *  Map::from( ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]] )->flatten();
1972
         *  Map::from( ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]] )->flatten( 1 );
1973
         *  Map::from( ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]] )->sep( '.' )->flatten();
1974
         *
1975
         * Results:
1976
         *  ['a/b/c' => 1, 'a/b/d' => 2, 'b/e' => 3]
1977
         *  ['a/b' => ['c' => 1, 'd' => 2], 'b/e' => 3]
1978
         *  ['a.b.c' => 1, 'a.b.d' => 2, 'b.e' => 3]
1979
         *
1980
         * To create the original multi-dimensional array again, use the unflatten() method.
1981
         *
1982
         * @param int|null $depth Number of levels to flatten multi-dimensional arrays or NULL for all
1983
         * @return self<int|string,mixed> New map with keys joined recursively, up to the specified depth
1984
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
1985
         */
1986
        public function flatten( ?int $depth = null ) : self
1987
        {
1988
                if( $depth < 0 ) {
2 ✔
1989
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
1 ✔
1990
                }
1991

1992
                $result = [];
1 ✔
1993
                $this->rflatten( $this->list(), $result, $depth ?? 0x7fffffff );
1 ✔
1994

1995
                return new static( $result );
1 ✔
1996
        }
1997

1998

1999
        /**
2000
         * Exchanges the keys with their values and vice versa.
2001
         *
2002
         * Examples:
2003
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->flip();
2004
         *
2005
         * Results:
2006
         *  ['X' => 'a', 'Y' => 'b']
2007
         *
2008
         * @return self<int|string,mixed> New map with keys as values and values as keys
2009
         * @throws \InvalidArgumentException If one of the values can't be used as key
2010
         */
2011
        public function flip() : self
2012
        {
2013
                $result = [];
2 ✔
2014

2015
                foreach( $this->list() as $key => $value ) {
2 ✔
2016
                        $result[$this->arrayKey( $value )] = $key;
2 ✔
2017
                }
2018

2019
                return new static( $result );
1 ✔
2020
        }
2021

2022

2023
        /**
2024
         * Returns an element by key and casts it to float if possible.
2025
         *
2026
         * Examples:
2027
         *  Map::from( ['a' => true] )->float( 'a' );
2028
         *  Map::from( ['a' => 1] )->float( 'a' );
2029
         *  Map::from( ['a' => '1.1'] )->float( 'a' );
2030
         *  Map::from( ['a' => '10'] )->float( 'a' );
2031
         *  Map::from( ['a' => ['b' => ['c' => 1.1]]] )->float( 'a/b/c' );
2032
         *  Map::from( [] )->float( 'c', function( $val ) { return 1.1; } );
2033
         *  Map::from( [] )->float( 'a', 1.1 );
2034
         *
2035
         *  Map::from( [] )->float( 'b' );
2036
         *  Map::from( ['b' => ''] )->float( 'b' );
2037
         *  Map::from( ['b' => null] )->float( 'b' );
2038
         *  Map::from( ['b' => 'abc'] )->float( 'b' );
2039
         *  Map::from( ['b' => [1]] )->float( 'b' );
2040
         *  Map::from( ['b' => #resource] )->float( 'b' );
2041
         *  Map::from( ['b' => new \stdClass] )->float( 'b' );
2042
         *
2043
         *  Map::from( [] )->float( 'c', new \Exception( 'error' ) );
2044
         *
2045
         * Results:
2046
         * The first eight examples will return the float values for the passed keys
2047
         * while the 9th to 14th example returns 0. The last example will throw an exception.
2048
         *
2049
         * This does also work for multi-dimensional arrays by passing the keys
2050
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2051
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2052
         * public properties of objects or objects implementing __isset() and __get() methods.
2053
         *
2054
         * @param int|string $key Key or path to the requested item
2055
         * @param \Closure|\Throwable|float $default Default value if key isn't found
2056
         * @return float Value from map or default value
2057
         */
2058
        public function float( int|string $key, \Closure|\Throwable|float $default = 0.0 ) : float
2059
        {
2060
                if( $this->item( $key, $val ) && ( is_scalar( $val ) || $val === null ) ) {
4 ✔
2061
                        return (float) $val;
2 ✔
2062
                }
2063

2064
                return (float) $this->fallback( $default, isset( $val ), $val ?? null );
4 ✔
2065
        }
2066

2067

2068
        /**
2069
         * Returns an element from the map by key.
2070
         *
2071
         * Examples:
2072
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'a' );
2073
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'c', 'Z' );
2074
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->get( 'a/b/c' );
2075
         *  Map::from( [] )->get( 'Y', new \Exception( 'error' ) );
2076
         *  Map::from( [] )->get( 'Y', function() { return rand(); } );
2077
         *
2078
         * Results:
2079
         * The first example will return 'X', the second 'Z' and the third 'Y'. The forth
2080
         * example will throw the exception passed if the map contains no elements. In
2081
         * the fifth example, a random value generated by the closure function will be
2082
         * returned.
2083
         *
2084
         * This does also work for multi-dimensional arrays by passing the keys
2085
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2086
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2087
         * public properties of objects or objects implementing __isset() and __get() methods.
2088
         *
2089
         * @param int|string $key Key or path to the requested item
2090
         * @template TDefault
2091
         * @param mixed $default Default value if no element matches
2092
         * @phpstan-param TDefault|\Closure():TDefault|\Throwable $default
2093
         * @phpstan-return TValue|TDefault
2094
         * @return mixed Value from map or default value
2095
         */
2096
        public function get( int|string $key, mixed $default = null ) : mixed
2097
        {
2098
                if( $this->item( $key, $v ) ) {
9 ✔
2099
                        return $v;
6 ✔
2100
                }
2101

2102
                return $this->fallback( $default );
4 ✔
2103
        }
2104

2105

2106
        /**
2107
         * Returns an iterator for the elements.
2108
         *
2109
         * This method will be used by e.g. foreach() to loop over all entries:
2110
         *  foreach( Map::from( ['a', 'b'] ) as $value )
2111
         *
2112
         * @return \ArrayIterator<int|string,mixed> Iterator for map elements
2113
         */
2114
        public function getIterator() : \ArrayIterator
2115
        {
2116
                return new \ArrayIterator( $this->list() );
5 ✔
2117
        }
2118

2119

2120
        /**
2121
         * Returns only items which matches the regular expression.
2122
         *
2123
         * All items are converted to string first before they are compared to the
2124
         * regular expression. Thus, fractions of ".0" will be removed in float numbers
2125
         * which may result in unexpected results.
2126
         *
2127
         * Examples:
2128
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/b/' );
2129
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/a/', PREG_GREP_INVERT );
2130
         *  Map::from( [1.5, 0, 1.0, 'a'] )->grep( '/^(\d+)?\.\d+$/' );
2131
         *
2132
         * Results:
2133
         *  ['ab', 'bc']
2134
         *  ['bc', 'cd']
2135
         *  [1.5] // float 1.0 is converted to string "1"
2136
         *
2137
         * The keys are preserved using this method. Entries that are neither scalar
2138
         * values nor stringable objects are skipped and never part of the result.
2139
         *
2140
         * @param string $pattern Regular expression pattern, e.g. "/ab/"
2141
         * @param int $flags PREG_GREP_INVERT to return elements not matching the pattern
2142
         * @return self<int|string,mixed> New map containing only the matched elements
2143
         */
2144
        public function grep( string $pattern, int $flags = 0 ) : self
2145
        {
2146
                $filtered = [];
5 ✔
2147
                $list = $this->list();
5 ✔
2148

2149
                foreach( $list as $key => $entry )
5 ✔
2150
                {
2151
                        if( is_scalar( $entry ) || $entry === null || $entry instanceof \Stringable ) {
4 ✔
2152
                                $filtered[$key] = $entry;
4 ✔
2153
                        }
2154
                }
2155

2156
                if( ( $result = preg_grep( $pattern, $filtered, $flags ) ) === false )
5 ✔
2157
                {
2158
                        switch( preg_last_error() )
1 ✔
2159
                        {
2160
                                case PREG_INTERNAL_ERROR: $msg = 'Internal error'; break;
1 ✔
2161
                                case PREG_BACKTRACK_LIMIT_ERROR: $msg = 'Backtrack limit error'; break;
×
2162
                                case PREG_RECURSION_LIMIT_ERROR: $msg = 'Recursion limit error'; break;
×
2163
                                case PREG_BAD_UTF8_ERROR: $msg = 'Bad UTF8 error'; break;
×
2164
                                case PREG_BAD_UTF8_OFFSET_ERROR: $msg = 'Bad UTF8 offset error'; break;
×
2165
                                case PREG_JIT_STACKLIMIT_ERROR: $msg = 'JIT stack limit error'; break;
×
2166
                                default: $msg = 'Unknown error';
×
2167
                        }
2168

2169
                        throw new \RuntimeException( 'Regular expression error: ' . $msg );
1 ✔
2170
                }
2171

2172
                return new static( $result );
4 ✔
2173
        }
2174

2175

2176
        /**
2177
         * Groups associative array elements or objects by the passed key or closure.
2178
         *
2179
         * Instead of overwriting items with the same keys like to the col() method
2180
         * does, groupBy() keeps all entries in sub-arrays. It's preserves the keys
2181
         * of the orignal map entries too.
2182
         *
2183
         * Examples:
2184
         *  $list = [
2185
         *    10 => ['aid' => 123, 'code' => 'x-abc'],
2186
         *    20 => ['aid' => 123, 'code' => 'x-def'],
2187
         *    30 => ['aid' => 456, 'code' => 'x-def']
2188
         *  ];
2189
         *  Map::from( $list )->groupBy( 'aid' );
2190
         *  Map::from( $list )->groupBy( function( $item, $key ) {
2191
         *    return substr( $item['code'], -3 );
2192
         *  } );
2193
         *  Map::from( $list )->groupBy( 'xid' );
2194
         *
2195
         * Results:
2196
         *  [
2197
         *    123 => [10 => ['aid' => 123, 'code' => 'x-abc'], 20 => ['aid' => 123, 'code' => 'x-def']],
2198
         *    456 => [30 => ['aid' => 456, 'code' => 'x-def']]
2199
         *  ]
2200
         *  [
2201
         *    'abc' => [10 => ['aid' => 123, 'code' => 'x-abc']],
2202
         *    'def' => [20 => ['aid' => 123, 'code' => 'x-def'], 30 => ['aid' => 456, 'code' => 'x-def']]
2203
         *  ]
2204
         *  [
2205
         *    '' => [
2206
         *      10 => ['aid' => 123, 'code' => 'x-abc'],
2207
         *      20 => ['aid' => 123, 'code' => 'x-def'],
2208
         *      30 => ['aid' => 456, 'code' => 'x-def']
2209
         *    ]
2210
         *  ]
2211
         *
2212
         * In case the passed key doesn't exist in one or more items or its value
2213
         * is not a scalar value or stringable object, these items are stored in
2214
         * a sub-array using an empty string as key.
2215
         *
2216
         * This does also work for multi-dimensional arrays by passing the keys
2217
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2218
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2219
         * public properties of objects or objects implementing __isset() and __get() methods.
2220
         *
2221
         * @param  \Closure|string|int $key Closure function with (item, idx) parameters returning the key or the key itself to group by
2222
         * @return self<int|string,mixed> New map with elements grouped by the given key
2223
         */
2224
        public function groupBy( \Closure|string|int $key ) : self
2225
        {
2226
                $result = [];
4 ✔
2227

2228
                if( $key instanceof \Closure )
4 ✔
2229
                {
2230
                        foreach( $this->list() as $idx => $item )
1 ✔
2231
                        {
2232
                                $val = $key( $item, $idx );
1 ✔
2233
                                $keyval = is_scalar( $val ) || $val instanceof \Stringable ? (string) $val : '';
1 ✔
2234
                                $result[$keyval][$idx] = $item;
1 ✔
2235
                        }
2236
                }
2237
                else
2238
                {
2239
                        $parts = explode( $this->sep, (string) $key );
3 ✔
2240
                        $part = count( $parts ) === 1 ? current( $parts ) : null;
3 ✔
2241

2242
                        foreach( $this->list() as $idx => $item )
3 ✔
2243
                        {
2244
                                if( $part !== null && is_array( $item ) )
3 ✔
2245
                                {
2246
                                        $keyval = $this->groupKey( $item[$part] ?? null );
2 ✔
2247
                                }
2248
                                else
2249
                                {
2250
                                        if( is_array( $item ) ) {
1 ✔
2251
                                                $val = $this->arrayVal( $item, $parts );
×
2252
                                        } else {
2253
                                                $val = $this->val( $item, $parts );
1 ✔
2254
                                        }
2255

2256
                                        $keyval = $this->groupKey( $val );
1 ✔
2257
                                }
2258

2259
                                $result[$keyval][$idx] = $item;
3 ✔
2260
                        }
2261
                }
2262

2263
                return new static( $result );
4 ✔
2264
        }
2265

2266

2267
        /**
2268
         * Determines if a key or several keys exists in the map.
2269
         *
2270
         * If several keys are passed as array, all keys must exist in the map for
2271
         * TRUE to be returned.
2272
         *
2273
         * Examples:
2274
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'a' );
2275
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'b'] );
2276
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->has( 'a/b/c' );
2277
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'c' );
2278
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'c'] );
2279
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'X' );
2280
         *
2281
         * Results:
2282
         * The first three examples will return TRUE while the other ones will return FALSE
2283
         *
2284
         * This does also work for multi-dimensional arrays by passing the keys
2285
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2286
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2287
         * public properties of objects or objects implementing __isset() and __get() methods.
2288
         *
2289
         * @param array<mixed>|int|string $key Key of the requested item or list of keys
2290
         * @return bool TRUE if key or keys are available in map, FALSE if not
2291
         * @throws \InvalidArgumentException If one of the keys can't be used as key
2292
         */
2293
        public function has( array|int|string $key ) : bool
2294
        {
2295
                $list = $this->list();
5 ✔
2296

2297
                foreach( (array) $key as $entry )
5 ✔
2298
                {
2299
                        $entry = $this->arrayKey( $entry );
5 ✔
2300

2301
                        if( array_key_exists( $entry, $list ) ) {
4 ✔
2302
                                continue;
3 ✔
2303
                        }
2304

2305
                        if( !str_contains( (string) $entry, $this->sep )
4 ✔
2306
                                || !$this->value( $list, explode( $this->sep, (string) $entry ), $value )
4 ✔
2307
                        ) {
2308
                                return false;
4 ✔
2309
                        }
2310
                }
2311

2312
                return true;
4 ✔
2313
        }
2314

2315

2316
        /**
2317
         * Determines if a top-level key exists in the map.
2318
         *
2319
         * Unlike offsetExists(), this method returns TRUE for keys whose value is NULL.
2320
         * Unlike has(), this method doesn't check paths into nested arrays or objects.
2321
         *
2322
         * Examples:
2323
         *  Map::from( ['a' => null] )->keyExists( 'a' );
2324
         *  Map::from( ['a' => ['b' => 1]] )->keyExists( 'a/b' );
2325
         *
2326
         * Results:
2327
         * The first example will return TRUE while the second one will return FALSE.
2328
         *
2329
         * @param int|string $key Top-level key to check for
2330
         * @return bool TRUE if key is available in map, FALSE if not
2331
         */
2332
        public function keyExists( int|string $key ) : bool
2333
        {
2334
                return array_key_exists( $key, $this->list() );
1 ✔
2335
        }
2336

2337

2338
        /**
2339
         * Executes callbacks depending on the condition.
2340
         *
2341
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2342
         * executed and their returned value is passed back within a Map object. In
2343
         * case no "then" or "else" closure is given, the method will return the same
2344
         * map object.
2345
         *
2346
         * Examples:
2347
         *  Map::from( [] )->if( strpos( 'abc', 'b' ) !== false, function( $map ) {
2348
         *    echo 'found';
2349
         *  } );
2350
         *
2351
         *  Map::from( [] )->if( function( $map ) {
2352
         *    return $map->empty();
2353
         *  }, function( $map ) {
2354
         *    echo 'then';
2355
         *  } );
2356
         *
2357
         *  Map::from( ['a'] )->if( function( $map ) {
2358
         *    return $map->empty();
2359
         *  }, function( $map ) {
2360
         *    echo 'then';
2361
         *  }, function( $map ) {
2362
         *    echo 'else';
2363
         *  } );
2364
         *
2365
         *  Map::from( ['a', 'b'] )->if( true, function( $map ) {
2366
         *    return $map->push( 'c' );
2367
         *  } );
2368
         *
2369
         *  Map::from( ['a', 'b'] )->if( false, null, function( $map ) {
2370
         *    return $map->pop();
2371
         *  } );
2372
         *
2373
         * Results:
2374
         * The first example returns "found" while the second one returns "then" and
2375
         * the third one "else". The forth one will return ['a', 'b', 'c'] while the
2376
         * fifth one will return 'b', which is turned into a map of ['b'] again.
2377
         *
2378
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2379
         * (a short form for anonymous closures) as parameters. They automatically have access
2380
         * to previously defined variables but can not modify them. Also, they can not have
2381
         * a void return type and must/will always return something. Details about
2382
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2383
         *
2384
         * @param callable|bool $condition Boolean or function with (map) parameter returning a boolean
2385
         * @param callable|null $then Function with (map, condition) parameter (optional)
2386
         * @param callable|null $else Function with (map, condition) parameter (optional)
2387
         * @return self<int|string,mixed> New map
2388
         */
2389
        public function if( callable|bool $condition, ?callable $then = null, ?callable $else = null ) : self
2390
        {
2391
                if( is_callable( $condition ) ) {
9 ✔
2392
                        $condition = $condition( $this );
3 ✔
2393
                }
2394

2395
                if( $condition ) {
9 ✔
2396
                        return $then ? static::from( $then( $this, $condition ) ) : $this;
6 ✔
2397
                } elseif( $else ) {
3 ✔
2398
                        return static::from( $else( $this, $condition ) );
3 ✔
2399
                }
2400

2401
                return $this;
×
2402
        }
2403

2404

2405
        /**
2406
         * Executes callbacks depending if the map contains elements or not.
2407
         *
2408
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2409
         * executed and their returned value is passed back within a Map object. In
2410
         * case no "then" or "else" closure is given, the method will return the same
2411
         * map object.
2412
         *
2413
         * Examples:
2414
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2415
         *    $map->push( 'b' );
2416
         *  } );
2417
         *
2418
         *  Map::from( [] )->ifAny( null, function( $map ) {
2419
         *    return $map->push( 'b' );
2420
         *  } );
2421
         *
2422
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2423
         *    return 'c';
2424
         *  } );
2425
         *
2426
         * Results:
2427
         * The first example returns a Map containing ['a', 'b'] because the initial
2428
         * Map is not empty. The second one returns a Map with ['b'] because the initial
2429
         * Map is empty and the "else" closure is used. The last example returns ['c']
2430
         * as new map content.
2431
         *
2432
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2433
         * (a short form for anonymous closures) as parameters. They automatically have access
2434
         * to previously defined variables but can not modify them. Also, they can not have
2435
         * a void return type and must/will always return something. Details about
2436
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2437
         *
2438
         * @param callable|null $then Function with (map, condition) parameter (optional)
2439
         * @param callable|null $else Function with (map, condition) parameter (optional)
2440
         * @return self<int|string,mixed> New map
2441
         */
2442
        public function ifAny( ?callable $then = null, ?callable $else = null ) : self
2443
        {
2444
                return $this->if( !empty( $this->list() ), $then, $else );
4 ✔
2445
        }
2446

2447

2448
        /**
2449
         * Executes callbacks depending if the map is empty or not.
2450
         *
2451
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2452
         * executed and their returned value is passed back within a Map object. In
2453
         * case no "then" or "else" closure is given, the method will return the same
2454
         * map object.
2455
         *
2456
         * Examples:
2457
         *  Map::from( [] )->ifEmpty( function( $map ) {
2458
         *    $map->push( 'a' );
2459
         *  } );
2460
         *
2461
         *  Map::from( ['a'] )->ifEmpty( null, function( $map ) {
2462
         *    return $map->push( 'b' );
2463
         *  } );
2464
         *
2465
         * Results:
2466
         * The first example returns a Map containing ['a'] because the initial Map
2467
         * is empty. The second one returns a Map with ['a', 'b'] because the initial
2468
         * Map is not empty and the "else" closure is used.
2469
         *
2470
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2471
         * (a short form for anonymous closures) as parameters. They automatically have access
2472
         * to previously defined variables but can not modify them. Also, they can not have
2473
         * a void return type and must/will always return something. Details about
2474
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2475
         *
2476
         * @param callable|null $then Function with (map, condition) parameter (optional)
2477
         * @param callable|null $else Function with (map, condition) parameter (optional)
2478
         * @return self<int|string,mixed> New map
2479
         */
2480
        public function ifEmpty( ?callable $then = null, ?callable $else = null ) : self
2481
        {
2482
                return $this->if( empty( $this->list() ), $then, $else );
1 ✔
2483
        }
2484

2485

2486
        /**
2487
         * Tests if all entries in the map are objects implementing the given interface.
2488
         *
2489
         * Examples:
2490
         *  Map::from( [new Map(), new Map()] )->implements( '\Countable' );
2491
         *  Map::from( [new Map(), new stdClass()] )->implements( '\Countable' );
2492
         *  Map::from( [new Map(), 123] )->implements( '\Countable' );
2493
         *  Map::from( [new Map(), 123] )->implements( '\Countable', true );
2494
         *  Map::from( [new Map(), 123] )->implements( '\Countable', '\RuntimeException' );
2495
         *
2496
         * Results:
2497
         *  The first example returns TRUE while the second and third one return FALSE.
2498
         *  The forth example will throw an UnexpectedValueException while the last one
2499
         *  throws a RuntimeException.
2500
         *
2501
         * @param string $interface Name of the interface that must be implemented
2502
         * @param bool $throw Passing TRUE will throw an exception instead of returning FALSE
2503
         * @return bool TRUE if all entries implement the interface or FALSE if at least one doesn't
2504
         * @throws \UnexpectedValueException If one entry doesn't implement the interface if $throw is TRUE
2505
         */
2506
        public function implements( string $interface, bool $throw = false ) : bool
2507
        {
2508
                foreach( $this->list() as $entry )
3 ✔
2509
                {
2510
                        if( !( $entry instanceof $interface ) )
3 ✔
2511
                        {
2512
                                if( $throw ) {
3 ✔
2513
                                        throw new \UnexpectedValueException( "Does not implement $interface: " . get_debug_type( $entry ) );
2 ✔
2514
                                }
2515

2516
                                return false;
1 ✔
2517
                        }
2518
                }
2519

2520
                return true;
1 ✔
2521
        }
2522

2523

2524
        /**
2525
         * Tests if the passed element or elements are part of the map.
2526
         *
2527
         * Examples:
2528
         *  Map::from( ['a', 'b'] )->in( 'a' );
2529
         *  Map::from( ['a', 'b'] )->in( ['a', 'b'] );
2530
         *  Map::from( ['a', 'b'] )->in( 'x' );
2531
         *  Map::from( ['a', 'b'] )->in( ['a', 'x'] );
2532
         *  Map::from( ['1', '2'] )->in( 2, true );
2533
         *
2534
         * Results:
2535
         * The first and second example will return TRUE while the other ones will return FALSE
2536
         *
2537
         * @param iterable<mixed>|mixed $element Element or elements to search for in the map
2538
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2539
         * @return bool TRUE if all elements are available in map, FALSE if not
2540
         */
2541
        public function in( mixed $element, bool $strict = false ) : bool
2542
        {
2543
                $list = $this->list();
4 ✔
2544

2545
                if( !is_iterable( $element ) ) {
4 ✔
2546
                        return in_array( $element, $list, $strict );
4 ✔
2547
                };
2548

2549
                $elements = $this->array( $element );
1 ✔
2550

2551
                if( $strict && count( $elements ) > 128 && ( $keys = $this->lookupKeys( $elements ) ) !== null )
1 ✔
2552
                {
2553
                        $lookup = $this->lookupSet( $list );
×
2554

2555
                        foreach( $keys as $key )
×
2556
                        {
2557
                                if( !isset( $lookup[$key] ) ) {
×
2558
                                        return false;
×
2559
                                }
2560
                        }
2561

2562
                        return true;
×
2563
                }
2564

2565
                foreach( $elements as $entry )
1 ✔
2566
                {
2567
                        if( in_array( $entry, $list, $strict ) === false ) {
1 ✔
2568
                                return false;
1 ✔
2569
                        }
2570
                }
2571

2572
                return true;
1 ✔
2573
        }
2574

2575

2576
        /**
2577
         * Tests if the passed element or elements are part of the map.
2578
         *
2579
         * This method is an alias for in(). For performance reasons, in() should be
2580
         * preferred because it uses one method call less than includes().
2581
         *
2582
         * @param mixed|array $element Element or elements to search for in the map
2583
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2584
         * @return bool TRUE if all elements are available in map, FALSE if not
2585
         * @see in() - Underlying method with same parameters and return value but better performance
2586
         */
2587
        public function includes( mixed $element, bool $strict = false ) : bool
2588
        {
2589
                return $this->in( $element, $strict );
1 ✔
2590
        }
2591

2592

2593
        /**
2594
         * Returns the numerical index of the given key.
2595
         *
2596
         * Examples:
2597
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( '8' );
2598
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( function( $key ) {
2599
         *      return $key == '8';
2600
         *  } );
2601
         *
2602
         * Results:
2603
         * Both examples will return "1" because the value "b" is at the second position
2604
         * and the returned index is zero based so the first item has the index "0".
2605
         *
2606
         * @param \Closure|string|int $value Key to search for or function with (key) parameters return TRUE if key is found
2607
         * @return int|null Position of the found value (zero based) or NULL if not found
2608
         */
2609
        public function index( \Closure|string|int $value ) : ?int
2610
        {
2611
                if( $value instanceof \Closure )
4 ✔
2612
                {
2613
                        $pos = 0;
2 ✔
2614

2615
                        foreach( $this->list() as $key => $item )
2 ✔
2616
                        {
2617
                                if( $value( $key ) ) {
1 ✔
2618
                                        return $pos;
1 ✔
2619
                                }
2620

2621
                                ++$pos;
1 ✔
2622
                        }
2623

2624
                        return null;
1 ✔
2625
                }
2626

2627
                $list = $this->list();
2 ✔
2628

2629
                if( is_string( $value ) && !is_numeric( $value ) && !array_key_exists( $value, $list ) ) {
2 ✔
2630
                        return null;
1 ✔
2631
                }
2632

2633
                $pos = array_search( $value, array_keys( $list ) );
1 ✔
2634
                return $pos !== false ? $pos : null;
1 ✔
2635
        }
2636

2637

2638
        /**
2639
         * Inserts the value or values after the given element.
2640
         *
2641
         * Examples:
2642
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAfter( 'foo', 'baz' );
2643
         *  Map::from( ['foo', 'bar'] )->insertAfter( 'foo', ['baz', 'boo'] );
2644
         *  Map::from( ['foo', 'bar'] )->insertAfter( null, 'baz' );
2645
         *
2646
         * Results:
2647
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2648
         *  ['foo', 'baz', 'boo', 'bar']
2649
         *  ['foo', 'bar', 'baz']
2650
         *
2651
         * Numerical array indexes are not preserved.
2652
         *
2653
         * @param mixed $element Element after the value is inserted
2654
         * @param mixed $value Element or list of elements to insert
2655
         * @return self<int|string,mixed> Updated map for fluid interface
2656
         */
2657
        public function insertAfter( mixed $element, mixed $value ) : self
2658
        {
2659
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
3 ✔
2660
                array_splice( $this->list(), $position + 1, 0, $this->array( $value ) );
3 ✔
2661

2662
                return $this;
3 ✔
2663
        }
2664

2665

2666
        /**
2667
         * Inserts the item at the given position in the map.
2668
         *
2669
         * Examples:
2670
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 0, 'baz' );
2671
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 1, 'baz', 'c' );
2672
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 4, 'baz' );
2673
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( -1, 'baz', 'c' );
2674
         *
2675
         * Results:
2676
         *  [0 => 'baz', 'a' => 'foo', 'b' => 'bar']
2677
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2678
         *  ['a' => 'foo', 'b' => 'bar', 0 => 'baz']
2679
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2680
         *
2681
         * @param int $pos Position the value should be inserted at
2682
         * @param mixed $value Value to be inserted
2683
         * @param string|int|null $key Value key or NULL to assign an integer key automatically
2684
         * @return self<int|string,mixed> Updated map for fluid interface
2685
         */
2686
        public function insertAt( int $pos, mixed $value, string|int|null $key = null ) : self
2687
        {
2688
                if( $key !== null )
5 ✔
2689
                {
2690
                        $list = $this->list();
2 ✔
2691

2692
                        $this->list = array_merge(
2 ✔
2693
                                array_slice( $list, 0, $pos, true ),
2 ✔
2694
                                [$key => $value],
2 ✔
2695
                                array_slice( $list, $pos, null, true )
2 ✔
2696
                        );
2 ✔
2697
                }
2698
                else
2699
                {
2700
                        array_splice( $this->list(), $pos, 0, [$value] );
3 ✔
2701
                }
2702

2703
                return $this;
5 ✔
2704
        }
2705

2706

2707
        /**
2708
         * Inserts the value or values before the given element.
2709
         *
2710
         * Examples:
2711
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertBefore( 'bar', 'baz' );
2712
         *  Map::from( ['foo', 'bar'] )->insertBefore( 'bar', ['baz', 'boo'] );
2713
         *  Map::from( ['foo', 'bar'] )->insertBefore( null, 'baz' );
2714
         *
2715
         * Results:
2716
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2717
         *  ['foo', 'baz', 'boo', 'bar']
2718
         *  ['foo', 'bar', 'baz']
2719
         *
2720
         * Numerical array indexes are not preserved.
2721
         *
2722
         * @param mixed $element Element before the value is inserted
2723
         * @param mixed $value Element or list of elements to insert
2724
         * @return self<int|string,mixed> Updated map for fluid interface
2725
         */
2726
        public function insertBefore( mixed $element, mixed $value ) : self
2727
        {
2728
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
3 ✔
2729
                array_splice( $this->list(), $position, 0, $this->array( $value ) );
3 ✔
2730

2731
                return $this;
3 ✔
2732
        }
2733

2734

2735
        /**
2736
         * Returns an element by key and casts it to integer if possible.
2737
         *
2738
         * Examples:
2739
         *  Map::from( ['a' => true] )->int( 'a' );
2740
         *  Map::from( ['a' => '1'] )->int( 'a' );
2741
         *  Map::from( ['a' => 1.1] )->int( 'a' );
2742
         *  Map::from( ['a' => '10'] )->int( 'a' );
2743
         *  Map::from( ['a' => ['b' => ['c' => 1]]] )->int( 'a/b/c' );
2744
         *  Map::from( [] )->int( 'c', function( $val ) { return rand( 1, 1 ); } );
2745
         *  Map::from( [] )->int( 'a', 1 );
2746
         *
2747
         *  Map::from( [] )->int( 'b' );
2748
         *  Map::from( ['b' => ''] )->int( 'b' );
2749
         *  Map::from( ['b' => 'abc'] )->int( 'b' );
2750
         *  Map::from( ['b' => null] )->int( 'b' );
2751
         *  Map::from( ['b' => [1]] )->int( 'b' );
2752
         *  Map::from( ['b' => #resource] )->int( 'b' );
2753
         *  Map::from( ['b' => new \stdClass] )->int( 'b' );
2754
         *
2755
         *  Map::from( [] )->int( 'c', new \Exception( 'error' ) );
2756
         *
2757
         * Results:
2758
         * The first seven examples will return 1 while the 8th to 14th example
2759
         * returns 0. The last example will throw an exception.
2760
         *
2761
         * This does also work for multi-dimensional arrays by passing the keys
2762
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2763
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2764
         * public properties of objects or objects implementing __isset() and __get() methods.
2765
         *
2766
         * @param int|string $key Key or path to the requested item
2767
         * @param \Closure|\Throwable|int $default Default value if key isn't found
2768
         * @return int Value from map or default value
2769
         */
2770
        public function int( int|string $key, \Closure|\Throwable|int $default = 0 ) : int
2771
        {
2772
                if( $this->item( $key, $val ) && ( is_scalar( $val ) || $val === null ) ) {
4 ✔
2773
                        return (int) $val;
2 ✔
2774
                }
2775

2776
                return (int) $this->fallback( $default, isset( $val ), $val ?? null );
4 ✔
2777
        }
2778

2779

2780
        /**
2781
         * Returns all values in a new map that are available in both, the map and the given elements.
2782
         *
2783
         * Examples:
2784
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersect( ['bar'] );
2785
         *
2786
         * Results:
2787
         *  ['b' => 'bar']
2788
         *
2789
         * If a callback is passed, the given function will be used to compare the values.
2790
         * The function must accept two parameters (value A and B) and must return
2791
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2792
         * greater than value B. Both, a method name and an anonymous function can be passed:
2793
         *
2794
         *  Map::from( [0 => 'a'] )->intersect( [0 => 'A'], 'strcasecmp' );
2795
         *  Map::from( ['b' => 'a'] )->intersect( ['B' => 'A'], 'strcasecmp' );
2796
         *  Map::from( ['b' => 'a'] )->intersect( ['c' => 'A'], function( $valA, $valB ) {
2797
         *      return strtolower( $valA ) <=> strtolower( $valB );
2798
         *  } );
2799
         *
2800
         * All examples will return a map containing ['a'] because both contain the same
2801
         * values when compared case insensitive.
2802
         *
2803
         * The keys are preserved using this method.
2804
         *
2805
         * @param iterable<int|string,mixed> $elements List of elements
2806
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2807
         * @return self<int|string,mixed> New map
2808
         */
2809
        public function intersect( iterable $elements, ?callable $callback = null ) : self
2810
        {
2811
                $list = $this->list();
4 ✔
2812
                $elements = $this->array( $elements );
4 ✔
2813

2814
                if( $callback ) {
4 ✔
2815
                        return new static( array_uintersect( $list, $elements, $callback ) );
1 ✔
2816
                }
2817

2818
                return new static( (array) $this->native(
3 ✔
2819
                        static fn() => array_intersect( $list, $elements ),
3 ✔
2820
                        fn() => $this->filterByValues( $list, $elements, true )
3 ✔
2821
                ) );
3 ✔
2822
        }
2823

2824

2825
        /**
2826
         * Returns all values in a new map that are available in both, the map and the given elements while comparing the keys too.
2827
         *
2828
         * Examples:
2829
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectAssoc( new Map( ['foo', 'b' => 'bar'] ) );
2830
         *
2831
         * Results:
2832
         *  ['a' => 'foo']
2833
         *
2834
         * If a callback is passed, the given function will be used to compare the values.
2835
         * The function must accept two parameters (value A and B) and must return
2836
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2837
         * greater than value B. Both, a method name and an anonymous function can be passed:
2838
         *
2839
         *  Map::from( [0 => 'a'] )->intersectAssoc( [0 => 'A'], 'strcasecmp' );
2840
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['B' => 'A'], 'strcasecmp' );
2841
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['c' => 'A'], function( $valA, $valB ) {
2842
         *      return strtolower( $valA ) <=> strtolower( $valB );
2843
         *  } );
2844
         *
2845
         * The first example will return [0 => 'a'] because both contain the same
2846
         * values when compared case insensitive. The second and third example will return
2847
         * an empty map because the keys doesn't match ("b" vs. "B" and "b" vs. "c").
2848
         *
2849
         * The keys are preserved using this method.
2850
         *
2851
         * @param iterable<int|string,mixed> $elements List of elements
2852
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2853
         * @return self<int|string,mixed> New map
2854
         */
2855
        public function intersectAssoc( iterable $elements, ?callable $callback = null ) : self
2856
        {
2857
                $list = $this->list();
6 ✔
2858
                $elements = $this->array( $elements );
6 ✔
2859

2860
                if( $callback ) {
6 ✔
2861
                        return new static( array_uintersect_assoc( $list, $elements, $callback ) );
1 ✔
2862
                }
2863

2864
                return new static( (array) $this->native(
5 ✔
2865
                        static fn() => array_intersect_assoc( $list, $elements ),
5 ✔
2866
                        fn() => array_uintersect_assoc( $list, $elements, $this->comparator() )
5 ✔
2867
                ) );
5 ✔
2868
        }
2869

2870

2871
        /**
2872
         * Returns all values in a new map that are available in both, the map and the given elements by comparing the keys only.
2873
         *
2874
         * Examples:
2875
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectKeys( new Map( ['foo', 'b' => 'baz'] ) );
2876
         *
2877
         * Results:
2878
         *  ['b' => 'bar']
2879
         *
2880
         * If a callback is passed, the given function will be used to compare the keys.
2881
         * The function must accept two parameters (key A and B) and must return
2882
         * -1 if key A is smaller than key B, 0 if both are equal and 1 if key A is
2883
         * greater than key B. Both, a method name and an anonymous function can be passed:
2884
         *
2885
         *  Map::from( [0 => 'a'] )->intersectKeys( [0 => 'A'], 'strcasecmp' );
2886
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['B' => 'X'], 'strcasecmp' );
2887
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['c' => 'a'], function( $keyA, $keyB ) {
2888
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
2889
         *  } );
2890
         *
2891
         * The first example will return a map with [0 => 'a'] and the second one will
2892
         * return a map with ['b' => 'a'] because both contain the same keys when compared
2893
         * case insensitive. The third example will return an empty map because the keys
2894
         * doesn't match ("b" vs. "c").
2895
         *
2896
         * The keys are preserved using this method.
2897
         *
2898
         * @param iterable<int|string,mixed> $elements List of elements
2899
         * @param  callable|null $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
2900
         * @return self<int|string,mixed> New map
2901
         */
2902
        public function intersectKeys( iterable $elements, ?callable $callback = null ) : self
2903
        {
2904
                $elements = $this->array( $elements );
2 ✔
2905

2906
                if( $callback ) {
2 ✔
2907
                        return new static( array_intersect_ukey( $this->list(), $elements, $callback ) );
1 ✔
2908
                }
2909

2910
                return new static( array_intersect_key( $this->list(), $elements ) );
1 ✔
2911
        }
2912

2913

2914
        /**
2915
         * Tests if the map consists of the same keys and values
2916
         *
2917
         * Examples:
2918
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'] );
2919
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'], true );
2920
         *  Map::from( [1, 2] )->is( ['1', '2'] );
2921
         *
2922
         * Results:
2923
         *  The first example returns TRUE while the second and third one returns FALSE
2924
         *
2925
         * @param iterable<int|string,mixed> $list List of key/value pairs to compare with
2926
         * @param bool $strict TRUE for comparing order of elements too, FALSE for key/values only
2927
         * @return bool TRUE if given list is equal, FALSE if not
2928
         */
2929
        public function is( iterable $list, bool $strict = false ) : bool
2930
        {
2931
                $list = $this->array( $list );
3 ✔
2932

2933
                if( $strict ) {
3 ✔
2934
                        return $this->list() === $list;
2 ✔
2935
                }
2936

2937
                return $this->list() == $list;
1 ✔
2938
        }
2939

2940

2941
        /**
2942
         * Determines if the map is empty or not.
2943
         *
2944
         * Examples:
2945
         *  Map::from( [] )->isEmpty();
2946
         *  Map::from( ['a'] )->isEmpty();
2947
         *
2948
         * Results:
2949
         *  The first example returns TRUE while the second returns FALSE
2950
         *
2951
         * The method is equivalent to empty().
2952
         *
2953
         * @return bool TRUE if map is empty, FALSE if not
2954
         */
2955
        public function isEmpty() : bool
2956
        {
2957
                return empty( $this->list() );
3 ✔
2958
        }
2959

2960

2961
        /**
2962
         * Checks if the map contains a list of subsequentially numbered keys.
2963
         *
2964
         * Examples:
2965
         * Map::from( [] )->isList();
2966
         * Map::from( [1, 3, 2] )->isList();
2967
         * Map::from( [0 => 1, 1 => 2, 2 => 3] )->isList();
2968
         * Map::from( [1 => 1, 2 => 2, 3 => 3] )->isList();
2969
         * Map::from( [0 => 1, 2 => 2, 3 => 3] )->isList();
2970
         * Map::from( ['a' => 1, 1 => 2, 'c' => 3] )->isList();
2971
         *
2972
         * Results:
2973
         * The first three examples return TRUE while the last three return FALSE
2974
         *
2975
         * @return bool TRUE if the map is a list, FALSE if not
2976
         */
2977
        public function isList() : bool
2978
        {
2979
                return array_is_list( $this->list() );
1 ✔
2980
        }
2981

2982

2983
        /**
2984
         * Determines if all entries are numeric values.
2985
         *
2986
         * Examples:
2987
         *  Map::from( [] )->isNumeric();
2988
         *  Map::from( [1] )->isNumeric();
2989
         *  Map::from( [1.1] )->isNumeric();
2990
         *  Map::from( [010] )->isNumeric();
2991
         *  Map::from( [0x10] )->isNumeric();
2992
         *  Map::from( [0b10] )->isNumeric();
2993
         *  Map::from( ['010'] )->isNumeric();
2994
         *  Map::from( ['10'] )->isNumeric();
2995
         *  Map::from( ['10.1'] )->isNumeric();
2996
         *  Map::from( [' 10 '] )->isNumeric();
2997
         *  Map::from( ['10e2'] )->isNumeric();
2998
         *  Map::from( ['0b10'] )->isNumeric();
2999
         *  Map::from( ['0x10'] )->isNumeric();
3000
         *  Map::from( ['null'] )->isNumeric();
3001
         *  Map::from( [null] )->isNumeric();
3002
         *  Map::from( [true] )->isNumeric();
3003
         *  Map::from( [[]] )->isNumeric();
3004
         *  Map::from( [''] )->isNumeric();
3005
         *
3006
         * Results:
3007
         *  The first eleven examples return TRUE while the last seven return FALSE
3008
         *
3009
         * @return bool TRUE if all map entries are numeric values, FALSE if not
3010
         */
3011
        public function isNumeric() : bool
3012
        {
3013
                foreach( $this->list() as $val )
1 ✔
3014
                {
3015
                        if( !is_numeric( $val ) ) {
1 ✔
3016
                                return false;
1 ✔
3017
                        }
3018
                }
3019

3020
                return true;
1 ✔
3021
        }
3022

3023

3024
        /**
3025
         * Determines if all entries are objects.
3026
         *
3027
         * Examples:
3028
         *  Map::from( [] )->isObject();
3029
         *  Map::from( [new stdClass] )->isObject();
3030
         *  Map::from( [1] )->isObject();
3031
         *
3032
         * Results:
3033
         *  The first two examples return TRUE while the last one return FALSE
3034
         *
3035
         * @return bool TRUE if all map entries are objects, FALSE if not
3036
         */
3037
        public function isObject() : bool
3038
        {
3039
                foreach( $this->list() as $val )
1 ✔
3040
                {
3041
                        if( !is_object( $val ) ) {
1 ✔
3042
                                return false;
1 ✔
3043
                        }
3044
                }
3045

3046
                return true;
1 ✔
3047
        }
3048

3049

3050
        /**
3051
         * Determines if all entries are scalar values.
3052
         *
3053
         * Examples:
3054
         *  Map::from( [] )->isScalar();
3055
         *  Map::from( [1] )->isScalar();
3056
         *  Map::from( [1.1] )->isScalar();
3057
         *  Map::from( ['abc'] )->isScalar();
3058
         *  Map::from( [true, false] )->isScalar();
3059
         *  Map::from( [new stdClass] )->isScalar();
3060
         *  Map::from( [#resource] )->isScalar();
3061
         *  Map::from( [null] )->isScalar();
3062
         *  Map::from( [[1]] )->isScalar();
3063
         *
3064
         * Results:
3065
         *  The first five examples return TRUE while the others return FALSE
3066
         *
3067
         * @return bool TRUE if all map entries are scalar values, FALSE if not
3068
         */
3069
        public function isScalar() : bool
3070
        {
3071
                foreach( $this->list() as $val )
1 ✔
3072
                {
3073
                        if( !is_scalar( $val ) ) {
1 ✔
3074
                                return false;
1 ✔
3075
                        }
3076
                }
3077

3078
                return true;
1 ✔
3079
        }
3080

3081

3082
        /**
3083
         * Tests for the matching item, but is true only if exactly one item is matching.
3084
         *
3085
         * Examples:
3086
         *  Map::from( ['a', 'b'] )->isSole( 'a' );
3087
         *  Map::from( ['a', 'b', 'a'] )->isSole( fn( $v, $k ) => $v === 'a' && $k < 2 );
3088
         *  Map::from( [['name' => 'test'], ['name' => 'user']] )->isSole( fn( $v, $k ) => $v['name'] === 'user' );
3089
         *  Map::from( ['b', 'c'] )->isSole( 'a' );
3090
         *  Map::from( ['a', 'b', 'a'] )->isSole( 'a' );
3091
         *  Map::from( [['name' => 'test'], ['name' => 'user'], ['name' => 'test']] )->isSole( 'test', 'name' );
3092
         *
3093
         * Results:
3094
         * The first three examples will return TRUE while all others will return FALSE.
3095
         *
3096
         * @param \Closure|mixed $value Closure with (item, key) parameter or element to test against
3097
         * @param string|int|null $key Key to compare the value for if $values is not a closure
3098
         * @return bool TRUE if exactly one item matches, FALSE if no or more than one item matches
3099
         */
3100
        public function isSole( mixed $value = null, string|int|null $key = null ) : bool
3101
        {
3102
                $cnt = 0;
3 ✔
3103

3104
                foreach( $this->list() as $mapkey => $item )
3 ✔
3105
                {
3106
                        if( $this->matches( $item, $mapkey, $value, $key ) && ++$cnt > 1 ) {
3 ✔
3107
                                return false;
1 ✔
3108
                        }
3109
                }
3110

3111
                return $cnt === 1;
2 ✔
3112
        }
3113

3114

3115
        /**
3116
         * Determines if all entries are string values.
3117
         *
3118
         * Examples:
3119
         *  Map::from( ['abc'] )->isString();
3120
         *  Map::from( [] )->isString();
3121
         *  Map::from( [1] )->isString();
3122
         *  Map::from( [1.1] )->isString();
3123
         *  Map::from( [true, false] )->isString();
3124
         *  Map::from( [new stdClass] )->isString();
3125
         *  Map::from( [#resource] )->isString();
3126
         *  Map::from( [null] )->isString();
3127
         *  Map::from( [[1]] )->isString();
3128
         *
3129
         * Results:
3130
         *  The first two examples return TRUE while the others return FALSE
3131
         *
3132
         * @return bool TRUE if all map entries are string values, FALSE if not
3133
         */
3134
        public function isString() : bool
3135
        {
3136
                foreach( $this->list() as $val )
1 ✔
3137
                {
3138
                        if( !is_string( $val ) ) {
1 ✔
3139
                                return false;
1 ✔
3140
                        }
3141
                }
3142

3143
                return true;
1 ✔
3144
        }
3145

3146

3147
        /**
3148
         * Concatenates the string representation of all elements.
3149
         *
3150
         * Objects that implement __toString() does also work, otherwise (and in case
3151
         * of arrays) a PHP notice is generated. NULL and FALSE values are treated as
3152
         * empty strings.
3153
         *
3154
         * Examples:
3155
         *  Map::from( ['a', 'b', false] )->join();
3156
         *  Map::from( ['a', 'b', null, false] )->join( '-' );
3157
         *
3158
         * Results:
3159
         * The first example will return "ab" while the second one will return "a-b--"
3160
         *
3161
         * Entries that are neither scalar values nor stringable objects are skipped
3162
         * and never part of the result.
3163
         *
3164
         * @param string $glue Character or string added between elements
3165
         * @return string String of concatenated map elements
3166
         */
3167
        public function join( string $glue = '' ) : string
3168
        {
3169
                $list = $this->list();
3 ✔
3170
                $all = true;
3 ✔
3171

3172
                foreach( $list as $entry )
3 ✔
3173
                {
3174
                        if( !is_scalar( $entry ) && $entry !== null && !( $entry instanceof \Stringable ) ) {
3 ✔
3175
                                $all = false;
1 ✔
3176
                                break;
1 ✔
3177
                        }
3178
                }
3179

3180
                if( $all ) {
3 ✔
3181
                        return implode( $glue, $list );
2 ✔
3182
                }
3183

3184
                $filter = [];
1 ✔
3185

3186
                foreach( $list as $entry )
1 ✔
3187
                {
3188
                        if( is_scalar( $entry ) || $entry === null || $entry instanceof \Stringable ) {
1 ✔
3189
                                $filter[] = $entry;
1 ✔
3190
                        }
3191
                }
3192

3193
                return implode( $glue, $filter );
1 ✔
3194
        }
3195

3196

3197
        /**
3198
         * Specifies the data which should be serialized to JSON by json_encode().
3199
         *
3200
         * Examples:
3201
         *   json_encode( Map::from( ['a', 'b'] ) );
3202
         *   json_encode( Map::from( ['a' => 0, 'b' => 1] ) );
3203
         *
3204
         * Results:
3205
         *   ["a", "b"]
3206
         *   {"a":0,"b":1}
3207
         *
3208
         * @phpstan-return array<TKey,TValue>
3209
         * @return array<int|string,mixed> Data to serialize to JSON
3210
         */
3211
        public function jsonSerialize() : mixed
3212
        {
3213
                return $this->list();
1 ✔
3214
        }
3215

3216

3217
        /**
3218
         * Returns the keys of the all elements in a new map object.
3219
         *
3220
         * Examples:
3221
         *  Map::from( ['a', 'b'] );
3222
         *  Map::from( ['a' => 0, 'b' => 1] );
3223
         *
3224
         * Results:
3225
         * The first example returns a map containing [0, 1] while the second one will
3226
         * return a map with ['a', 'b'].
3227
         *
3228
         * @phpstan-return self<int,TKey>
3229
         * @return self<int|string,mixed> New map
3230
         */
3231
        public function keys() : self
3232
        {
3233
                return new static( array_keys( $this->list() ) );
1 ✔
3234
        }
3235

3236

3237
        /**
3238
         * Sorts the elements by their keys in reverse order.
3239
         *
3240
         * Examples:
3241
         *  Map::from( ['b' => 0, 'a' => 1] )->krsort();
3242
         *  Map::from( [1 => 'a', 0 => 'b'] )->krsort();
3243
         *
3244
         * Results:
3245
         *  ['a' => 1, 'b' => 0]
3246
         *  [0 => 'b', 1 => 'a']
3247
         *
3248
         * The parameter modifies how the keys are compared. Possible values are:
3249
         * - SORT_REGULAR : compare elements normally (don't change types)
3250
         * - SORT_NUMERIC : compare elements numerically
3251
         * - SORT_STRING : compare elements as strings
3252
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3253
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3254
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3255
         *
3256
         * The keys are preserved using this method and no new map is created.
3257
         *
3258
         * @param int $options Sort options for krsort()
3259
         * @return self<int|string,mixed> Updated map for fluid interface
3260
         */
3261
        public function krsort( int $options = SORT_REGULAR ) : self
3262
        {
3263
                krsort( $this->list(), $options );
3 ✔
3264
                return $this;
3 ✔
3265
        }
3266

3267

3268
        /**
3269
         * Sorts a copy of the elements by their keys in reverse order.
3270
         *
3271
         * Examples:
3272
         *  Map::from( ['b' => 0, 'a' => 1] )->krsorted();
3273
         *  Map::from( [1 => 'a', 0 => 'b'] )->krsorted();
3274
         *
3275
         * Results:
3276
         *  ['a' => 1, 'b' => 0]
3277
         *  [0 => 'b', 1 => 'a']
3278
         *
3279
         * The parameter modifies how the keys are compared. Possible values are:
3280
         * - SORT_REGULAR : compare elements normally (don't change types)
3281
         * - SORT_NUMERIC : compare elements numerically
3282
         * - SORT_STRING : compare elements as strings
3283
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3284
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3285
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3286
         *
3287
         * The keys are preserved using this method and a new map is created.
3288
         *
3289
         * @param int $options Sort options for krsort()
3290
         * @return self<int|string,mixed> New map with sorted elements
3291
         */
3292
        public function krsorted( int $options = SORT_REGULAR ) : self
3293
        {
3294
                return ( clone $this )->krsort( $options );
1 ✔
3295
        }
3296

3297

3298
        /**
3299
         * Sorts the elements by their keys.
3300
         *
3301
         * Examples:
3302
         *  Map::from( ['b' => 0, 'a' => 1] )->ksort();
3303
         *  Map::from( [1 => 'a', 0 => 'b'] )->ksort();
3304
         *
3305
         * Results:
3306
         *  ['a' => 1, 'b' => 0]
3307
         *  [0 => 'b', 1 => 'a']
3308
         *
3309
         * The parameter modifies how the keys are compared. Possible values are:
3310
         * - SORT_REGULAR : compare elements normally (don't change types)
3311
         * - SORT_NUMERIC : compare elements numerically
3312
         * - SORT_STRING : compare elements as strings
3313
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3314
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3315
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3316
         *
3317
         * The keys are preserved using this method and no new map is created.
3318
         *
3319
         * @param int $options Sort options for ksort()
3320
         * @return self<int|string,mixed> Updated map for fluid interface
3321
         */
3322
        public function ksort( int $options = SORT_REGULAR ) : self
3323
        {
3324
                ksort( $this->list(), $options );
3 ✔
3325
                return $this;
3 ✔
3326
        }
3327

3328

3329
        /**
3330
         * Sorts a copy of the elements by their keys.
3331
         *
3332
         * Examples:
3333
         *  Map::from( ['b' => 0, 'a' => 1] )->ksorted();
3334
         *  Map::from( [1 => 'a', 0 => 'b'] )->ksorted();
3335
         *
3336
         * Results:
3337
         *  ['a' => 1, 'b' => 0]
3338
         *  [0 => 'b', 1 => 'a']
3339
         *
3340
         * The parameter modifies how the keys are compared. Possible values are:
3341
         * - SORT_REGULAR : compare elements normally (don't change types)
3342
         * - SORT_NUMERIC : compare elements numerically
3343
         * - SORT_STRING : compare elements as strings
3344
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3345
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3346
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3347
         *
3348
         * The keys are preserved using this method and a new map is created.
3349
         *
3350
         * @param int $options Sort options for ksort()
3351
         * @return self<int|string,mixed> New map with sorted elements
3352
         */
3353
        public function ksorted( int $options = SORT_REGULAR ) : self
3354
        {
3355
                return ( clone $this )->ksort( $options );
1 ✔
3356
        }
3357

3358

3359
        /**
3360
         * Returns the last element from the map.
3361
         *
3362
         * Examples:
3363
         *  Map::from( ['a', 'b'] )->last();
3364
         *  Map::from( [] )->last( 'x' );
3365
         *  Map::from( [] )->last( new \Exception( 'error' ) );
3366
         *  Map::from( [] )->last( function() { return rand(); } );
3367
         *
3368
         * Results:
3369
         * The first example will return 'b' and the second one 'x'. The third example
3370
         * will throw the exception passed if the map contains no elements. In the
3371
         * fourth example, a random value generated by the closure function will be
3372
         * returned.
3373
         *
3374
         * Using this method doesn't affect the internal array pointer.
3375
         *
3376
         * @template TDefault
3377
         * @param mixed $default Default value or exception if the map contains no elements
3378
         * @phpstan-param TDefault|\Closure():TDefault|\Throwable $default
3379
         * @phpstan-return TValue|TDefault
3380
         * @return mixed Last value of map, (generated) default value or an exception
3381
         */
3382
        public function last( mixed $default = null ) : mixed
3383
        {
3384
                $list = $this->list();
6 ✔
3385
                $key = array_key_last( $list );
6 ✔
3386

3387
                if( $key !== null ) {
6 ✔
3388
                        return $list[$key];
2 ✔
3389
                }
3390

3391
                return $this->fallback( $default );
4 ✔
3392
        }
3393

3394

3395
        /**
3396
         * Returns the last key from the map.
3397
         *
3398
         * Examples:
3399
         *  Map::from( ['a' => 1, 'b' => 2] )->lastKey();
3400
         *  Map::from( [] )->lastKey( 'x' );
3401
         *  Map::from( [] )->lastKey( new \Exception( 'error' ) );
3402
         *  Map::from( [] )->lastKey( function() { return rand(); } );
3403
         *
3404
         * Results:
3405
         * The first example will return 'a' and the second one 'x', the third one will throw
3406
         * an exception and the last one will return a random value.
3407
         *
3408
         * Using this method doesn't affect the internal array pointer.
3409
         *
3410
         * @template TDefault
3411
         * @param mixed $default Default value, closure or exception if the map contains no elements
3412
         * @phpstan-param TDefault|\Closure():TDefault|\Throwable $default
3413
         * @phpstan-return TKey|TDefault
3414
         * @return mixed Last key of map, (generated) default value or an exception
3415
         */
3416
        public function lastKey( mixed $default = null ) : mixed
3417
        {
3418
                $list = $this->list();
5 ✔
3419
                $key = array_key_last( $list );
5 ✔
3420

3421
                if( $key !== null ) {
5 ✔
3422
                        return $key;
1 ✔
3423
                }
3424

3425
                return $this->fallback( $default );
4 ✔
3426
        }
3427

3428

3429
        /**
3430
         * Removes the passed characters from the left of all strings.
3431
         *
3432
         * Examples:
3433
         *  Map::from( [" abc\n", "\tcde\r\n"] )->ltrim();
3434
         *  Map::from( ["a b c", "cbxa"] )->ltrim( 'abc' );
3435
         *
3436
         * Results:
3437
         * The first example will return ["abc\n", "cde\r\n"] while the second one will return [" b c", "xa"].
3438
         *
3439
         * @param string $chars List of characters to trim
3440
         * @return self<int|string,mixed> Updated map for fluid interface
3441
         */
3442
        public function ltrim( string $chars = " \n\r\t\v\x00" ) : self
3443
        {
3444
                foreach( $this->list() as &$entry )
1 ✔
3445
                {
3446
                        if( is_string( $entry ) ) {
1 ✔
3447
                                $entry = ltrim( $entry, $chars );
1 ✔
3448
                        }
3449
                }
3450

3451
                return $this;
1 ✔
3452
        }
3453

3454

3455
        /**
3456
         * Maps new values to the existing keys using the passed function and returns a new map for the result.
3457
         *
3458
         * Examples:
3459
         *  Map::from( ['a' => 2, 'b' => 4] )->map( function( $value, $key ) {
3460
         *      return $value * 2;
3461
         *  } );
3462
         *
3463
         * Results:
3464
         *  ['a' => 4, 'b' => 8]
3465
         *
3466
         * The keys are preserved using this method.
3467
         *
3468
         * @template TNewValue
3469
         * @param callable $callback Function with (value, key) parameters and returns computed result
3470
         * @phpstan-param callable(TValue,TKey):TNewValue $callback
3471
         * @phpstan-return self<TKey,TNewValue>
3472
         * @return self<int|string,mixed> New map with the original keys and the computed values
3473
         * @see rekey() - Changes the keys according to the passed function
3474
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
3475
         */
3476
        public function map( callable $callback ) : self
3477
        {
3478
                $result = [];
1 ✔
3479

3480
                foreach( $this->list() as $key => $value ) {
1 ✔
3481
                        $result[$key] = $callback( $value, $key );
1 ✔
3482
                }
3483

3484
                return new static( $result );
1 ✔
3485
        }
3486

3487

3488
        /**
3489
         * Returns the maximum value of all elements.
3490
         *
3491
         * Examples:
3492
         *  Map::from( [1, 3, 2, 5, 4] )->max()
3493
         *  Map::from( ['bar', 'foo', 'baz'] )->max()
3494
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->max( 'p' )
3495
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( 'i/p' )
3496
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( fn( $val, $key ) => $val['i']['p'] ?? null )
3497
         *  Map::from( [50, 10, 30] )->max( fn( $val, $key ) => $key > 0 ? $val : null )
3498
         *
3499
         * Results:
3500
         * The first line will return "5", the second one "foo" and the third to fifth
3501
         * one return 50 while the last one will return 30.
3502
         *
3503
         * NULL values are removed before the comparison. If there are no values or all
3504
         * values are NULL, NULL is returned.
3505
         *
3506
         * This does also work for multi-dimensional arrays by passing the keys
3507
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3508
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3509
         * public properties of objects or objects implementing __isset() and __get() methods.
3510
         *
3511
         * Be careful comparing elements of different types because this can have
3512
         * unpredictable results due to the PHP comparison rules:
3513
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3514
         *
3515
         * @param \Closure|string|null $col Closure, key or path to the value of the nested array or object
3516
         * @return mixed Maximum value or NULL if there are no elements in the map
3517
         */
3518
        public function max( \Closure|string|null $col = null ) : mixed
3519
        {
3520
                $found = false;
4 ✔
3521
                $max = null;
4 ✔
3522

3523
                if( $col instanceof \Closure )
4 ✔
3524
                {
3525
                        foreach( $this->list() as $key => $item )
1 ✔
3526
                        {
3527
                                if( ( $val = $col( $item, $key ) ) !== null && ( !$found || $val > $max ) )
1 ✔
3528
                                {
3529
                                        $max = $val;
1 ✔
3530
                                        $found = true;
1 ✔
3531
                                }
3532
                        }
3533
                }
3534
                else
3535
                {
3536
                        $parts = $col ? explode( $this->sep, (string) $col ) : [];
3 ✔
3537

3538
                        foreach( $this->list() as $item )
3 ✔
3539
                        {
3540
                                if( $parts === [] ) {
2 ✔
3541
                                        $val = $item;
1 ✔
3542
                                } elseif( is_array( $item ) ) {
1 ✔
3543
                                        $val = $this->arrayVal( $item, $parts );
1 ✔
3544
                                } else {
3545
                                        $val = $this->val( $item, $parts );
×
3546
                                }
3547

3548
                                if( $val !== null && ( !$found || $val > $max ) )
2 ✔
3549
                                {
3550
                                        $max = $val;
2 ✔
3551
                                        $found = true;
2 ✔
3552
                                }
3553
                        }
3554
                }
3555

3556
                return $found ? $max : null;
4 ✔
3557
        }
3558

3559

3560
        /**
3561
         * Merges the map with the given elements without returning a new map.
3562
         *
3563
         * Elements with the same non-numeric keys will be overwritten, elements
3564
         * with the same numeric keys will be added.
3565
         *
3566
         * Examples:
3567
         *  Map::from( ['a', 'b'] )->merge( ['b', 'c'] );
3568
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6] );
3569
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6], true );
3570
         *
3571
         * Results:
3572
         *  ['a', 'b', 'b', 'c']
3573
         *  ['a' => 1, 'b' => 4, 'c' => 6]
3574
         *  ['a' => 1, 'b' => [2, 4], 'c' => 6]
3575
         *
3576
         * The method is similar to replace() but doesn't replace elements with
3577
         * the same numeric keys. If you want to be sure that all passed elements
3578
         * are added without replacing existing ones, use concat() instead.
3579
         *
3580
         * The keys are preserved using this method.
3581
         *
3582
         * @param iterable<int|string,mixed> $elements List of elements
3583
         * @param bool $recursive TRUE to merge nested arrays too, FALSE for first level elements only
3584
         * @return self<int|string,mixed> Updated map for fluid interface
3585
         */
3586
        public function merge( iterable $elements, bool $recursive = false ) : self
3587
        {
3588
                if( $recursive ) {
3 ✔
3589
                        $this->list = array_merge_recursive( $this->list(), $this->array( $elements ) );
1 ✔
3590
                } else {
3591
                        $this->list = array_merge( $this->list(), $this->array( $elements ) );
2 ✔
3592
                }
3593

3594
                return $this;
3 ✔
3595
        }
3596

3597

3598
        /**
3599
         * Returns the minimum value of all elements.
3600
         *
3601
         * Examples:
3602
         *  Map::from( [2, 3, 1, 5, 4] )->min()
3603
         *  Map::from( ['baz', 'foo', 'bar'] )->min()
3604
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->min( 'p' )
3605
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->min( 'i/p' )
3606
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->min( fn( $val, $key ) => $val['i']['p'] ?? null )
3607
         *  Map::from( [10, 50, 30] )->min( fn( $val, $key ) => $key > 0 ? $val : null )
3608
         *
3609
         * Results:
3610
         * The first line will return "1", the second one "bar", the third one
3611
         * 10, and the forth to the last one 30.
3612
         *
3613
         * NULL values are removed before the comparison. If there are no values or all
3614
         * values are NULL, NULL is returned.
3615
         *
3616
         * This does also work for multi-dimensional arrays by passing the keys
3617
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3618
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3619
         * public properties of objects or objects implementing __isset() and __get() methods.
3620
         *
3621
         * Be careful comparing elements of different types because this can have
3622
         * unpredictable results due to the PHP comparison rules:
3623
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3624
         *
3625
         * @param \Closure|string|null $col Closure, key or path to the value of the nested array or object
3626
         * @return mixed Minimum value or NULL if there are no elements in the map
3627
         */
3628
        public function min( \Closure|string|null $col = null ) : mixed
3629
        {
3630
                $found = false;
4 ✔
3631
                $min = null;
4 ✔
3632

3633
                if( $col instanceof \Closure )
4 ✔
3634
                {
3635
                        foreach( $this->list() as $key => $item )
1 ✔
3636
                        {
3637
                                if( ( $val = $col( $item, $key ) ) !== null && ( !$found || $val < $min ) )
1 ✔
3638
                                {
3639
                                        $min = $val;
1 ✔
3640
                                        $found = true;
1 ✔
3641
                                }
3642
                        }
3643
                }
3644
                else
3645
                {
3646
                        $parts = $col ? explode( $this->sep, (string) $col ) : [];
3 ✔
3647

3648
                        foreach( $this->list() as $item )
3 ✔
3649
                        {
3650
                                if( $parts === [] ) {
2 ✔
3651
                                        $val = $item;
1 ✔
3652
                                } elseif( is_array( $item ) ) {
1 ✔
3653
                                        $val = $this->arrayVal( $item, $parts );
1 ✔
3654
                                } else {
3655
                                        $val = $this->val( $item, $parts );
×
3656
                                }
3657

3658
                                if( $val !== null && ( !$found || $val < $min ) )
2 ✔
3659
                                {
3660
                                        $min = $val;
2 ✔
3661
                                        $found = true;
2 ✔
3662
                                }
3663
                        }
3664
                }
3665

3666
                return $found ? $min : null;
4 ✔
3667
        }
3668

3669

3670
        /**
3671
         * Tests if none of the elements are part of the map.
3672
         *
3673
         * Examples:
3674
         *  Map::from( ['a', 'b'] )->none( 'x' );
3675
         *  Map::from( ['a', 'b'] )->none( ['x', 'y'] );
3676
         *  Map::from( ['1', '2'] )->none( 2, true );
3677
         *  Map::from( ['a', 'b'] )->none( 'a' );
3678
         *  Map::from( ['a', 'b'] )->none( ['a', 'b'] );
3679
         *  Map::from( ['a', 'b'] )->none( ['a', 'x'] );
3680
         *
3681
         * Results:
3682
         * The first three examples will return TRUE while the other ones will return FALSE
3683
         *
3684
         * @param iterable<mixed>|mixed $element Element or elements to search for in the map
3685
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
3686
         * @return bool TRUE if none of the elements is part of the map, FALSE if at least one is
3687
         */
3688
        public function none( mixed $element, bool $strict = false ) : bool
3689
        {
3690
                $list = $this->list();
1 ✔
3691

3692
                if( !is_iterable( $element ) ) {
1 ✔
3693
                        return !in_array( $element, $list, $strict );
1 ✔
3694
                };
3695

3696
                $elements = $this->array( $element );
1 ✔
3697

3698
                if( $strict && count( $elements ) > 128 && ( $keys = $this->lookupKeys( $elements ) ) !== null )
1 ✔
3699
                {
3700
                        $lookup = $this->lookupSet( $list );
×
3701

3702
                        foreach( $keys as $key )
×
3703
                        {
3704
                                if( isset( $lookup[$key] ) ) {
×
3705
                                        return false;
×
3706
                                }
3707
                        }
3708

3709
                        return true;
×
3710
                }
3711

3712
                foreach( $elements as $entry )
1 ✔
3713
                {
3714
                        if( in_array( $entry, $list, $strict ) === true ) {
1 ✔
3715
                                return false;
1 ✔
3716
                        }
3717
                }
3718

3719
                return true;
1 ✔
3720
        }
3721

3722

3723
        /**
3724
         * Returns every nth element from the map.
3725
         *
3726
         * Examples:
3727
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2 );
3728
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2, 1 );
3729
         *
3730
         * Results:
3731
         *  ['a', 'c', 'e']
3732
         *  ['b', 'd', 'f']
3733
         *
3734
         * @param int $step Step width
3735
         * @param int $offset Non-negative number of element to start from (0-based)
3736
         * @return self<int|string,mixed> New map
3737
         * @throws \InvalidArgumentException If the step is less than 1 or the offset is negative
3738
         */
3739
        public function nth( int $step, int $offset = 0 ) : self
3740
        {
3741
                if( $step < 1 ) {
4 ✔
3742
                        throw new \InvalidArgumentException( 'Step width must be greater than zero' );
1 ✔
3743
                }
3744

3745
                if( $offset < 0 ) {
3 ✔
3746
                        throw new \InvalidArgumentException( 'Offset must be greater than or equal to zero' );
1 ✔
3747
                }
3748

3749
                if( $step === 1 ) {
2 ✔
3750
                        return clone $this;
1 ✔
3751
                }
3752

3753
                $result = [];
1 ✔
3754
                $pos = 0;
1 ✔
3755

3756
                foreach( $this->list() as $key => $item )
1 ✔
3757
                {
3758
                        if( $pos++ === $offset )
1 ✔
3759
                        {
3760
                                $result[$key] = $item;
1 ✔
3761
                                $offset += $step;
1 ✔
3762
                        }
3763
                }
3764

3765
                return new static( $result );
1 ✔
3766
        }
3767

3768

3769
        /**
3770
         * Determines if an element exists at an offset.
3771
         *
3772
         * Examples:
3773
         *  $map = Map::from( ['a' => 1, 'b' => 3, 'c' => null] );
3774
         *  isset( $map['b'] );
3775
         *  isset( $map['c'] );
3776
         *  isset( $map['d'] );
3777
         *
3778
         * Results:
3779
         *  The first isset() will return TRUE while the second and third one will return FALSE
3780
         *
3781
         * @param mixed $key Key to check for
3782
         * @return bool TRUE if key exists, FALSE if not
3783
         * @throws \InvalidArgumentException If the key can't be used as key
3784
         */
3785
        public function offsetExists( mixed $key ) : bool
3786
        {
3787
                return isset( $this->list()[$this->arrayKey( $key )] );
8 ✔
3788
        }
3789

3790

3791
        /**
3792
         * Returns an element at a given offset.
3793
         *
3794
         * Examples:
3795
         *  $map = Map::from( ['a' => 1, 'b' => 3] );
3796
         *  $map['b'];
3797
         *
3798
         * Results:
3799
         *  $map['b'] will return 3
3800
         *
3801
         * @param mixed $key Key to return the element for
3802
         * @return mixed Value associated to the given key
3803
         * @throws \InvalidArgumentException If the key can't be used as key
3804
         */
3805
        public function offsetGet( mixed $key ) : mixed
3806
        {
3807
                return $this->list()[$this->arrayKey( $key )] ?? null;
6 ✔
3808
        }
3809

3810

3811
        /**
3812
         * Sets the element at a given offset.
3813
         *
3814
         * Examples:
3815
         *  $map = Map::from( ['a' => 1] );
3816
         *  $map['b'] = 2;
3817
         *  $map[0] = 4;
3818
         *
3819
         * Results:
3820
         *  ['a' => 1, 'b' => 2, 0 => 4]
3821
         *
3822
         * @param mixed $key Key to set the element for or NULL to append value
3823
         * @param mixed $value New value set for the key
3824
         * @throws \InvalidArgumentException If the key can't be used as key
3825
         */
3826
        public function offsetSet( mixed $key, mixed $value ) : void
3827
        {
3828
                if( $key !== null ) {
4 ✔
3829
                        $this->list()[$this->arrayKey( $key )] = $value;
3 ✔
3830
                } else {
3831
                        $this->list()[] = $value;
2 ✔
3832
                }
3833
        }
3834

3835

3836
        /**
3837
         * Unsets the element at a given offset.
3838
         *
3839
         * Examples:
3840
         *  $map = Map::from( ['a' => 1] );
3841
         *  unset( $map['a'] );
3842
         *
3843
         * Results:
3844
         *  The map will be empty
3845
         *
3846
         * @param mixed $key Key for unsetting the item
3847
         * @throws \InvalidArgumentException If the key can't be used as key
3848
         */
3849
        public function offsetUnset( mixed $key ) : void
3850
        {
3851
                unset( $this->list()[$this->arrayKey( $key )] );
3 ✔
3852
        }
3853

3854

3855
        /**
3856
         * Returns a new map with only those elements specified by the given keys.
3857
         *
3858
         * Examples:
3859
         *  Map::from( ['a' => 1, 0 => 'b'] )->only( 'a' );
3860
         *  Map::from( ['a' => 1, 0 => 'b', 1 => 'c'] )->only( [0, 1] );
3861
         *
3862
         * Results:
3863
         *  ['a' => 1]
3864
         *  [0 => 'b', 1 => 'c']
3865
         *
3866
         * The keys are preserved using this method.
3867
         *
3868
         * @param iterable<mixed>|array<mixed>|string|int $keys Keys of the elements that should be returned
3869
         * @return self<int|string,mixed> New map with only the elements specified by the keys
3870
         * @throws \InvalidArgumentException If one of the keys can't be used as key
3871
         */
3872
        public function only( iterable|string|int $keys ) : self
3873
        {
3874
                $list = [];
2 ✔
3875

3876
                foreach( $this->array( $keys ) as $key ) {
2 ✔
3877
                        $list[$this->arrayKey( $key )] = true;
2 ✔
3878
                }
3879

3880
                return new static( array_intersect_key( $this->list(), $list ) );
1 ✔
3881
        }
3882

3883

3884
        /**
3885
         * Returns a new map with elements ordered by the passed keys.
3886
         *
3887
         * If there are less keys passed than available in the map, the remaining
3888
         * elements are removed. Otherwise, if keys are passed that are not in the
3889
         * map, they will be also available in the returned map but their value is
3890
         * NULL.
3891
         *
3892
         * Examples:
3893
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 'a'] );
3894
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 2] );
3895
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1] );
3896
         *
3897
         * Results:
3898
         *  [0 => 'b', 1 => 'c', 'a' => 1]
3899
         *  [0 => 'b', 1 => 'c', 2 => null]
3900
         *  [0 => 'b', 1 => 'c']
3901
         *
3902
         * The keys are preserved using this method.
3903
         *
3904
         * @param iterable<mixed> $keys Keys of the elements in the required order
3905
         * @return self<int|string,mixed> New map with elements ordered by the passed keys
3906
         * @throws \InvalidArgumentException If one of the keys can't be used as key
3907
         */
3908
        public function order( iterable $keys ) : self
3909
        {
3910
                $result = [];
3 ✔
3911
                $list = $this->list();
3 ✔
3912

3913
                foreach( $keys as $key )
3 ✔
3914
                {
3915
                        $key = $this->arrayKey( $key );
3 ✔
3916
                        $result[$key] = $list[$key] ?? null;
2 ✔
3917
                }
3918

3919
                return new static( $result );
2 ✔
3920
        }
3921

3922

3923
        /**
3924
         * Fill up to the specified length with the given value
3925
         *
3926
         * In case the given number is smaller than the number of element that are
3927
         * already in the list, the map is unchanged. If the size is positive, the
3928
         * new elements are padded on the right, if it's negative then the elements
3929
         * are padded on the left.
3930
         *
3931
         * Examples:
3932
         *  Map::from( [1, 2, 3] )->pad( 5 );
3933
         *  Map::from( [1, 2, 3] )->pad( -5 );
3934
         *  Map::from( [1, 2, 3] )->pad( 5, '0' );
3935
         *  Map::from( [1, 2, 3] )->pad( 2 );
3936
         *  Map::from( [10 => 1, 20 => 2] )->pad( 3 );
3937
         *  Map::from( ['a' => 1, 'b' => 2] )->pad( 3, 3 );
3938
         *
3939
         * Results:
3940
         *  [1, 2, 3, null, null]
3941
         *  [null, null, 1, 2, 3]
3942
         *  [1, 2, 3, '0', '0']
3943
         *  [1, 2, 3]
3944
         *  [0 => 1, 1 => 2, 2 => null]
3945
         *  ['a' => 1, 'b' => 2, 0 => 3]
3946
         *
3947
         * Associative keys are preserved, numerical keys are replaced and numerical
3948
         * keys are used for the new elements.
3949
         *
3950
         * @param int $size Total number of elements that should be in the list
3951
         * @param mixed $value Value to fill up with if the map length is smaller than the given size
3952
         * @return self<int|string,mixed> New map
3953
         */
3954
        public function pad( int $size, mixed $value = null ) : self
3955
        {
3956
                return new static( array_pad( $this->list(), $size, $value ) );
1 ✔
3957
        }
3958

3959

3960
        /**
3961
         * Breaks the list of elements into the given number of groups.
3962
         *
3963
         * Examples:
3964
         *  Map::from( [1, 2, 3, 4, 5] )->partition( 3 );
3965
         *  Map::from( [1, 2, 3, 4, 5] )->partition( function( $val, $idx ) {
3966
         *                return $idx % 3;
3967
         *        } );
3968
         *
3969
         * Results:
3970
         *  [[0 => 1, 1 => 2], [2 => 3, 3 => 4], [4 => 5]]
3971
         *  [0 => [0 => 1, 3 => 4], 1 => [1 => 2, 4 => 5], 2 => [2 => 3]]
3972
         *
3973
         * The keys of the original map are preserved in the returned map.
3974
         *
3975
         * @param \Closure|int $number Function with (value, index) as arguments returning the bucket key or number of groups
3976
         * @return self<int|string,mixed> New map
3977
         * @throws \InvalidArgumentException If the number of groups is less than 1 or a bucket key can't be used as key
3978
         */
3979
        public function partition( \Closure|int $number ) : self
3980
        {
3981
                if( !$number instanceof \Closure && $number < 1 ) {
4 ✔
3982
                        throw new \InvalidArgumentException( 'Number of groups must be greater than 0' );
×
3983
                }
3984

3985
                $list = $this->list();
4 ✔
3986

3987
                if( empty( $list ) ) {
4 ✔
3988
                        return new static();
1 ✔
3989
                }
3990

3991
                $result = [];
3 ✔
3992

3993
                if( $number instanceof \Closure )
3 ✔
3994
                {
3995
                        foreach( $list as $idx => $item ) {
2 ✔
3996
                                $result[$this->arrayKey( $number( $item, $idx ) )][$idx] = $item;
2 ✔
3997
                        }
3998

3999
                        return new static( $result );
1 ✔
4000
                }
4001

4002
                $start = 0;
1 ✔
4003
                $size = (int) ceil( count( $list ) / $number );
1 ✔
4004

4005
                for( $i = 0; $i < $number; $i++ )
1 ✔
4006
                {
4007
                        $result[] = array_slice( $list, $start, $size, true );
1 ✔
4008
                        $start += $size;
1 ✔
4009
                }
4010

4011
                return new static( $result );
1 ✔
4012
        }
4013

4014

4015
        /**
4016
         * Returns the percentage of all elements passing the test in the map.
4017
         *
4018
         * Examples:
4019
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50 );
4020
         *  Map::from( [] )->percentage( fn( $val, $key ) => true );
4021
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 100 );
4022
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 3 );
4023
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 0 );
4024
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50, -1 );
4025
         *
4026
         * Results:
4027
         * The first line will return "66.67", the second and third one "0.0", the forth
4028
         * one "33.333", the fifth one "33.0" and the last one "70.0" (66 rounded up).
4029
         *
4030
         * @param callable $fcn Function to filter the values in the nested array or object to compute the percentage
4031
         * @param int $precision Number of decimal digits use by the result value
4032
         * @return float Percentage of all elements passing the test in the map
4033
         */
4034
        public function percentage( callable $fcn, int $precision = 2 ) : float
4035
        {
4036
                $total = 0;
2 ✔
4037
                $match = 0;
2 ✔
4038

4039
                foreach( $this->list() as $key => $value )
2 ✔
4040
                {
4041
                        $total++;
2 ✔
4042

4043
                        if( $fcn( $value, $key ) ) {
2 ✔
4044
                                $match++;
2 ✔
4045
                        }
4046
                }
4047

4048
                return $total > 0 ? round( $match * 100 / $total, $precision ) : 0;
2 ✔
4049
        }
4050

4051

4052
        /**
4053
         * Passes the map to the given callback and return the result.
4054
         *
4055
         * Examples:
4056
         *  Map::from( ['a', 'b'] )->pipe( function( $map ) {
4057
         *      return join( '-', $map->toArray() );
4058
         *  } );
4059
         *
4060
         * Results:
4061
         *  "a-b" will be returned
4062
         *
4063
         * @param callable $callback Function with map as parameter which returns arbitrary result
4064
         * @return mixed Result returned by the callback
4065
         */
4066
        public function pipe( callable $callback ) : mixed
4067
        {
4068
                return $callback( $this );
2 ✔
4069
        }
4070

4071

4072
        /**
4073
         * Returns the values of a single column/property from an array of arrays or objects in a new map.
4074
         *
4075
         * This method is an alias for col(). For performance reasons, col() should
4076
         * be preferred because it uses one method call less than pluck().
4077
         *
4078
         * @param string|null $valuecol Name or path of the value property
4079
         * @param string|null $indexcol Name or path of the index property
4080
         * @return self<int|string,mixed> New map with mapped entries
4081
         * @see col() - Underlying method with same parameters and return value but better performance
4082
         */
4083
        public function pluck( ?string $valuecol = null, ?string $indexcol = null ) : self
4084
        {
4085
                return $this->col( $valuecol, $indexcol );
1 ✔
4086
        }
4087

4088

4089
        /**
4090
         * Returns and removes the last element from the map.
4091
         *
4092
         * Examples:
4093
         *  Map::from( ['a', 'b'] )->pop();
4094
         *
4095
         * Results:
4096
         *  "b" will be returned and the map only contains ['a'] afterwards
4097
         *
4098
         * @return mixed Last element of the map or null if empty
4099
         */
4100
        public function pop() : mixed
4101
        {
4102
                return array_pop( $this->list() );
2 ✔
4103
        }
4104

4105

4106
        /**
4107
         * Returns the numerical index of the value.
4108
         *
4109
         * Examples:
4110
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( 'b' );
4111
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( function( $item, $key ) {
4112
         *      return $item === 'b';
4113
         *  } );
4114
         *
4115
         * Results:
4116
         * Both examples will return "1" because the value "b" is at the second position
4117
         * and the returned index is zero based so the first item has the index "0".
4118
         *
4119
         * @param \Closure|mixed $value Value to search for or function with (item, key) parameters return TRUE if value is found
4120
         * @return int|null Position of the found value (zero based) or NULL if not found
4121
         */
4122
        public function pos( mixed $value ) : ?int
4123
        {
4124
                $pos = 0;
15 ✔
4125
                $list = $this->list();
15 ✔
4126

4127
                if( $value instanceof \Closure )
15 ✔
4128
                {
4129
                        foreach( $list as $key => $item )
3 ✔
4130
                        {
4131
                                if( $value( $item, $key ) ) {
3 ✔
4132
                                        return $pos;
3 ✔
4133
                                }
4134

4135
                                ++$pos;
3 ✔
4136
                        }
4137

4138
                        return null;
×
4139
                }
4140

4141
                foreach( $list as $key => $item )
12 ✔
4142
                {
4143
                        if( $item === $value ) {
11 ✔
4144
                                return $pos;
10 ✔
4145
                        }
4146

4147
                        ++$pos;
6 ✔
4148
                }
4149

4150
                return null;
2 ✔
4151
        }
4152

4153

4154
        /**
4155
         * Adds a prefix in front of each map entry.
4156
         *
4157
         * By default, nested arrays are walked recursively so all entries at all levels are prefixed.
4158
         *
4159
         * Examples:
4160
         *  Map::from( ['a', 'b'] )->prefix( '1-' );
4161
         *  Map::from( ['a', ['b']] )->prefix( '1-' );
4162
         *  Map::from( ['a', ['b']] )->prefix( '1-', 1 );
4163
         *  Map::from( ['a', 'b'] )->prefix( function( $item, $key ) {
4164
         *      return ( ord( $item ) + ord( $key ) ) . '-';
4165
         *  } );
4166
         *
4167
         * Results:
4168
         *  The first example returns ['1-a', '1-b'] while the second one will return
4169
         *  ['1-a', ['1-b']]. In the third example, the depth is limited to the first
4170
         *  level only so it will return ['1-a', ['b']]. The forth example passing
4171
         *  the closure will return ['145-a', '147-b'].
4172
         *
4173
         * The keys of the original map are preserved in the returned map.
4174
         *
4175
         * @param \Closure|string $prefix Prefix string or anonymous function with ($item, $key) as parameters
4176
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
4177
         * @return self<int|string,mixed> Updated map for fluid interface
4178
         */
4179
        public function prefix( \Closure|string $prefix, ?int $depth = null ) : self
4180
        {
4181
                $list = &$this->list();
1 ✔
4182
                $this->prefixRecursive( $list, $prefix, $depth ?? 0x7fffffff );
1 ✔
4183
                return $this;
1 ✔
4184
        }
4185

4186

4187
        /**
4188
         * Pushes an element onto the beginning of the map without returning a new map.
4189
         *
4190
         * This method is an alias for unshift().
4191
         *
4192
         * @param mixed $value Item to add at the beginning
4193
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
4194
         * @return self<int|string,mixed> Updated map for fluid interface
4195
         * @see unshift() - Underlying method with same parameters and return value but better performance
4196
         */
4197
        public function prepend( mixed $value, int|string|null $key = null ) : self
4198
        {
4199
                return $this->unshift( $value, $key );
1 ✔
4200
        }
4201

4202

4203
        /**
4204
         * Returns and removes an element from the map by its key.
4205
         *
4206
         * Examples:
4207
         *  Map::from( ['a', 'b', 'c'] )->pull( 1 );
4208
         *  Map::from( ['a' => ['b' => 'c']] )->pull( 'a/b' );
4209
         *  Map::from( ['a', 'b', 'c'] )->pull( 'x', 'none' );
4210
         *  Map::from( [] )->pull( 'Y', new \Exception( 'error' ) );
4211
         *  Map::from( [] )->pull( 'Z', function() { return rand(); } );
4212
         *
4213
         * Results:
4214
         * The first example will return "b" and the map contains ['a', 'c'] afterwards.
4215
         * The second example will return "c" and the map contains ['a' => []] afterwards.
4216
         * The third one will return "none" and the map content stays untouched. If you
4217
         * pass an exception as default value, it will throw that exception if the map
4218
         * contains no elements. In the fifth example, a random value generated by the
4219
         * closure function will be returned.
4220
         *
4221
         * @param int|string $key Key or path to retrieve the value for
4222
         * @param mixed $default Default value if key isn't available
4223
         * @return mixed Value from map or default value
4224
         */
4225
        public function pull( int|string $key, mixed $default = null ) : mixed
4226
        {
4227
                if( !$this->item( $key, $value ) ) {
7 ✔
4228
                        return $this->fallback( $default );
3 ✔
4229
                }
4230

4231
                $this->forget( $key );
4 ✔
4232
                return $value;
4 ✔
4233
        }
4234

4235

4236
        /**
4237
         * Pushes an element onto the end of the map without returning a new map.
4238
         *
4239
         * Examples:
4240
         *  Map::from( ['a', 'b'] )->push( 'aa' );
4241
         *
4242
         * Results:
4243
         *  ['a', 'b', 'aa']
4244
         *
4245
         * @param mixed $value Value to add to the end
4246
         * @return self<int|string,mixed> Updated map for fluid interface
4247
         */
4248
        public function push( mixed $value ) : self
4249
        {
4250
                $this->list()[] = $value;
3 ✔
4251
                return $this;
3 ✔
4252
        }
4253

4254

4255
        /**
4256
         * Sets the given key and value in the map without returning a new map.
4257
         *
4258
         * This method is an alias for set(). For performance reasons, set() should be
4259
         * preferred because it uses one method call less than put().
4260
         *
4261
         * @param int|string $key Key to set the new value for
4262
         * @param mixed $value New element that should be set
4263
         * @return self<int|string,mixed> Updated map for fluid interface
4264
         * @see set() - Underlying method with same parameters and return value but better performance
4265
         */
4266
        public function put( int|string $key, mixed $value ) : self
4267
        {
4268
                return $this->set( $key, $value );
1 ✔
4269
        }
4270

4271

4272
        /**
4273
         * Returns one or more random element from the map incl. their keys.
4274
         *
4275
         * Examples:
4276
         *  Map::from( [2, 4, 8, 16] )->random();
4277
         *  Map::from( [2, 4, 8, 16] )->random( 2 );
4278
         *  Map::from( [2, 4, 8, 16] )->random( 5 );
4279
         *
4280
         * Results:
4281
         * The first example will return a map including [0 => 8] or any other value,
4282
         * the second one will return a map with [0 => 16, 1 => 2] or any other values
4283
         * and the third example will return a map of the whole list in random order. The
4284
         * less elements are in the map, the less random the order will be, especially if
4285
         * the maximum number of values is high or close to the number of elements.
4286
         *
4287
         * The keys of the original map are preserved in the returned map.
4288
         *
4289
         * @param int $max Maximum number of elements that should be returned
4290
         * @return self<int|string,mixed> New map with key/element pairs from original map in random order
4291
         * @throws \InvalidArgumentException If requested number of elements is less than 1
4292
         */
4293
        public function random( int $max = 1 ) : self
4294
        {
4295
                if( $max < 1 ) {
5 ✔
4296
                        throw new \InvalidArgumentException( 'Requested number of elements must be greater or equal than 1' );
1 ✔
4297
                }
4298

4299
                $list = $this->list();
4 ✔
4300

4301
                if( empty( $list ) ) {
4 ✔
4302
                        return new static();
1 ✔
4303
                }
4304

4305
                if( ( $num = count( $list ) ) < $max ) {
3 ✔
4306
                        $max = $num;
1 ✔
4307
                }
4308

4309
                $buf = [];
3 ✔
4310
                $pos = 0;
3 ✔
4311

4312
                if( $max === 1 )
3 ✔
4313
                {
4314
                        $keys = array_keys( $list );
1 ✔
4315
                        $idx = $this->rand( $num - 1, $buf, $pos );
1 ✔
4316

4317
                        return new static( [ $keys[$idx] => $list[$keys[$idx]] ] );
1 ✔
4318
                }
4319

4320
                $keys = array_keys( $list );
2 ✔
4321
                $min = $num - $max;
2 ✔
4322

4323
                for( $i = $num - 1; $i > 0 && $i >= $min; $i-- )
2 ✔
4324
                {
4325
                        $idx = $this->rand( $i, $buf, $pos );
2 ✔
4326
                        [$keys[$i], $keys[$idx]] = [$keys[$idx], $keys[$i]];
2 ✔
4327
                }
4328

4329
                $result = [];
2 ✔
4330

4331
                foreach( array_slice( $keys, $min ) as $key ) {
2 ✔
4332
                        $result[$key] = $list[$key];
2 ✔
4333
                }
4334

4335
                return new static( $result );
2 ✔
4336
        }
4337

4338

4339
        /**
4340
         * Iteratively reduces the array to a single value using a callback function.
4341
         * Afterwards, the map will be empty.
4342
         *
4343
         * Examples:
4344
         *  Map::from( [2, 8] )->reduce( function( $result, $value ) {
4345
         *      return $result += $value;
4346
         *  }, 10 );
4347
         *
4348
         * Results:
4349
         *  "20" will be returned because the sum is computed by 10 (initial value) + 2 + 8
4350
         *
4351
         * @param callable $callback Function with (result, value) parameters and returns result
4352
         * @param mixed $initial Initial value when computing the result
4353
         * @return mixed Value computed by the callback function
4354
         */
4355
        public function reduce( callable $callback, mixed $initial = null ) : mixed
4356
        {
4357
                return array_reduce( $this->list(), $callback, $initial );
1 ✔
4358
        }
4359

4360

4361
        /**
4362
         * Removes all matched elements and returns a new map.
4363
         *
4364
         * Examples:
4365
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->reject( function( $value, $key ) {
4366
         *      return $value < 'm';
4367
         *  } );
4368
         *  Map::from( [2 => 'a', 13 => 'm', 30 => 'z'] )->reject( 'm' );
4369
         *  Map::from( [2 => 'a', 6 => null, 13 => 'm'] )->reject();
4370
         *
4371
         * Results:
4372
         *  [13 => 'm', 30 => 'z']
4373
         *  [2 => 'a', 30 => 'z']
4374
         *  [6 => null]
4375
         *
4376
         * This method is the inverse of the filter() and should return TRUE if the
4377
         * item should be removed from the returned map.
4378
         *
4379
         * If no callback is passed, all values which are NOT empty, null or false will be
4380
         * removed. The keys of the original map are preserved in the returned map.
4381
         *
4382
         * @param Closure|mixed $callback Function with (item, key) parameter which returns TRUE/FALSE
4383
         * @return self<int|string,mixed> New map
4384
         */
4385
        public function reject( mixed $callback = true ) : self
4386
        {
4387
                $result = [];
3 ✔
4388

4389
                if( $callback instanceof \Closure )
3 ✔
4390
                {
4391
                        foreach( $this->list() as $key => $value )
1 ✔
4392
                        {
4393
                                if( !$callback( $value, $key ) ) {
1 ✔
4394
                                        $result[$key] = $value;
1 ✔
4395
                                }
4396
                        }
4397
                }
4398
                else
4399
                {
4400
                        foreach( $this->list() as $key => $value )
2 ✔
4401
                        {
4402
                                if( $value != $callback ) {
2 ✔
4403
                                        $result[$key] = $value;
2 ✔
4404
                                }
4405
                        }
4406
                }
4407

4408
                return new static( $result );
3 ✔
4409
        }
4410

4411

4412
        /**
4413
         * Changes the keys according to the passed function.
4414
         *
4415
         * Examples:
4416
         *  Map::from( ['a' => 2, 'b' => 4] )->rekey( function( $value, $key ) {
4417
         *      return 'key-' . $key;
4418
         *  } );
4419
         *
4420
         * Results:
4421
         *  ['key-a' => 2, 'key-b' => 4]
4422
         *
4423
         * @param callable $callback Function with (value, key) parameters and returns new key
4424
         * @return self<int|string,mixed> New map with new keys and original values
4425
         * @throws \InvalidArgumentException If one of the returned keys can't be used as key
4426
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
4427
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
4428
         */
4429
        public function rekey( callable $callback ) : self
4430
        {
4431
                $result = [];
2 ✔
4432

4433
                foreach( $this->list() as $key => $value ) {
2 ✔
4434
                        $result[$this->arrayKey( $callback( $value, $key ) )] = $value;
2 ✔
4435
                }
4436

4437
                return new static( $result );
1 ✔
4438
        }
4439

4440

4441
        /**
4442
         * Removes one or more elements from the map by its keys without returning a new map.
4443
         *
4444
         * Examples:
4445
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( 'a' );
4446
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( [2, 'a'] );
4447
         *
4448
         * Results:
4449
         * The first example will result in [2 => 'b'] while the second one resulting
4450
         * in an empty list
4451
         *
4452
         * @param iterable<mixed>|array<mixed>|string|int $keys List of keys to remove
4453
         * @return self<int|string,mixed> Updated map for fluid interface
4454
         * @throws \InvalidArgumentException If one of the keys can't be used as key
4455
         */
4456
        public function remove( iterable|string|int $keys ) : self
4457
        {
4458
                $list = &$this->list();
7 ✔
4459

4460
                foreach( $this->array( $keys ) as $key ) {
7 ✔
4461
                        unset( $list[$this->arrayKey( $key )] );
7 ✔
4462
                }
4463

4464
                return $this;
5 ✔
4465
        }
4466

4467

4468
        /**
4469
         * Replaces elements in the map with the given elements without returning a new map.
4470
         *
4471
         * Examples:
4472
         *  Map::from( ['a' => 1, 2 => 'b'] )->replace( ['a' => 2] );
4473
         *  Map::from( ['a' => 1, 'b' => ['c' => 3, 'd' => 4]] )->replace( ['b' => ['c' => 9]] );
4474
         *
4475
         * Results:
4476
         *  ['a' => 2, 2 => 'b']
4477
         *  ['a' => 1, 'b' => ['c' => 9, 'd' => 4]]
4478
         *
4479
         * The method is similar to merge() but it also replaces elements with numeric
4480
         * keys. These would be added by merge() with a new numeric key.
4481
         *
4482
         * The keys are preserved using this method.
4483
         *
4484
         * @param iterable<int|string,mixed> $elements List of elements
4485
         * @param bool $recursive TRUE to replace recursively (default), FALSE to replace elements only
4486
         * @return self<int|string,mixed> Updated map for fluid interface
4487
         */
4488
        public function replace( iterable $elements, bool $recursive = true ) : self
4489
        {
4490
                if( $recursive ) {
5 ✔
4491
                        $this->list = array_replace_recursive( $this->list(), $this->array( $elements ) );
4 ✔
4492
                } else {
4493
                        $this->list = array_replace( $this->list(), $this->array( $elements ) );
1 ✔
4494
                }
4495

4496
                return $this;
5 ✔
4497
        }
4498

4499

4500
        /**
4501
         * Returns only the items matching the value (and key) from the map.
4502
         *
4503
         * Examples:
4504
         *  Map::from( ['a', 'b', 'a'] )->restrict( 'a' );
4505
         *  Map::from( [['name' => 'test'], ['name' => 'user'], ['name' => 'test']] )->restrict( 'test', 'name' );
4506
         *  Map::from( [['name' => 'test'], ['name' => 'user']] )->restrict( fn( $v, $k ) => $v['name'] === 'user' );
4507
         *  Map::from( ['a', 'b', 'a'] )->restrict( fn( $v, $k ) => $v === 'a' && $k < 2 );
4508
         *
4509
         * Results:
4510
         *  [0 => 'a', 2 => 'a']
4511
         *  [0 => ['name' => 'test'], 2 => ['name' => 'test']]
4512
         *  [1 => ['name' => 'user']]
4513
         *  [0 => 'a']
4514
         *
4515
         * The keys are preserved in the returned map.
4516
         *
4517
         * @param \Closure|mixed $value Closure with (item, key) parameter or element to test against
4518
         * @param string|int|null $key Key to compare the value to if $value is not a closure
4519
         * @return self<int|string,mixed> New map with matching items only
4520
         */
4521
        public function restrict( mixed $value = null, string|int|null $key = null ) : self
4522
        {
4523
                $result = [];
6 ✔
4524

4525
                foreach( $this->list() as $mapkey => $item )
6 ✔
4526
                {
4527
                        if( $this->matches( $item, $mapkey, $value, $key ) ) {
6 ✔
4528
                                $result[$mapkey] = $item;
6 ✔
4529
                        }
4530
                }
4531

4532
                return new static( $result );
6 ✔
4533
        }
4534

4535

4536
        /**
4537
         * Reverses the element order with keys without returning a new map.
4538
         *
4539
         * Examples:
4540
         *  Map::from( ['a', 'b'] )->reverse();
4541
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reverse();
4542
         *
4543
         * Results:
4544
         *  ['b', 'a']
4545
         *  ['last' => 'user', 'name' => 'test']
4546
         *
4547
         * The keys are preserved using this method.
4548
         *
4549
         * @return self<int|string,mixed> Updated map for fluid interface
4550
         * @see reversed() - Reverses the element order in a copy of the map
4551
         */
4552
        public function reverse() : self
4553
        {
4554
                $this->list = array_reverse( $this->list(), true );
4 ✔
4555
                return $this;
4 ✔
4556
        }
4557

4558

4559
        /**
4560
         * Reverses the element order in a copy of the map.
4561
         *
4562
         * Examples:
4563
         *  Map::from( ['a', 'b'] )->reversed();
4564
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reversed();
4565
         *
4566
         * Results:
4567
         *  ['b', 'a']
4568
         *  ['last' => 'user', 'name' => 'test']
4569
         *
4570
         * The keys are preserved using this method and a new map is created before reversing the elements.
4571
         * Thus, reverse() should be preferred for performance reasons if possible.
4572
         *
4573
         * @return self<int|string,mixed> New map with a reversed copy of the elements
4574
         * @see reverse() - Reverses the element order with keys without returning a new map
4575
         */
4576
        public function reversed() : self
4577
        {
4578
                return ( clone $this )->reverse();
2 ✔
4579
        }
4580

4581

4582
        /**
4583
         * Sorts all elements in reverse order using new keys.
4584
         *
4585
         * Examples:
4586
         *  Map::from( ['a' => 1, 'b' => 0] )->rsort();
4587
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsort();
4588
         *
4589
         * Results:
4590
         *  [0 => 1, 1 => 0]
4591
         *  [0 => 'b', 1 => 'a']
4592
         *
4593
         * The parameter modifies how the values are compared. Possible parameter values are:
4594
         * - SORT_REGULAR : compare elements normally (don't change types)
4595
         * - SORT_NUMERIC : compare elements numerically
4596
         * - SORT_STRING : compare elements as strings
4597
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4598
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4599
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4600
         *
4601
         * The keys aren't preserved and elements get a new index. No new map is created
4602
         *
4603
         * @param int $options Sort options for rsort()
4604
         * @return self<int|string,mixed> Updated map for fluid interface
4605
         */
4606
        public function rsort( int $options = SORT_REGULAR ) : self
4607
        {
4608
                rsort( $this->list(), $options );
3 ✔
4609
                return $this;
3 ✔
4610
        }
4611

4612

4613
        /**
4614
         * Sorts a copy of all elements in reverse order using new keys.
4615
         *
4616
         * Examples:
4617
         *  Map::from( ['a' => 1, 'b' => 0] )->rsorted();
4618
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsorted();
4619
         *
4620
         * Results:
4621
         *  [0 => 1, 1 => 0]
4622
         *  [0 => 'b', 1 => 'a']
4623
         *
4624
         * The parameter modifies how the values are compared. Possible parameter values are:
4625
         * - SORT_REGULAR : compare elements normally (don't change types)
4626
         * - SORT_NUMERIC : compare elements numerically
4627
         * - SORT_STRING : compare elements as strings
4628
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4629
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4630
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4631
         *
4632
         * The keys aren't preserved, elements get a new index and a new map is created.
4633
         *
4634
         * @param int $options Sort options for rsort()
4635
         * @return self<int|string,mixed> New map with sorted elements
4636
         */
4637
        public function rsorted( int $options = SORT_REGULAR ) : self
4638
        {
4639
                return ( clone $this )->rsort( $options );
1 ✔
4640
        }
4641

4642

4643
        /**
4644
         * Removes the passed characters from the right of all strings.
4645
         *
4646
         * Examples:
4647
         *  Map::from( [" abc\n", "\tcde\r\n"] )->rtrim();
4648
         *  Map::from( ["a b c", "cbxa"] )->rtrim( 'abc' );
4649
         *
4650
         * Results:
4651
         * The first example will return [" abc", "\tcde"] while the second one will return ["a b ", "cbx"].
4652
         *
4653
         * @param string $chars List of characters to trim
4654
         * @return self<int|string,mixed> Updated map for fluid interface
4655
         */
4656
        public function rtrim( string $chars = " \n\r\t\v\x00" ) : self
4657
        {
4658
                foreach( $this->list() as &$entry )
1 ✔
4659
                {
4660
                        if( is_string( $entry ) ) {
1 ✔
4661
                                $entry = rtrim( $entry, $chars );
1 ✔
4662
                        }
4663
                }
4664

4665
                return $this;
1 ✔
4666
        }
4667

4668

4669
        /**
4670
         * Searches the map for a given value and return the corresponding key if successful.
4671
         *
4672
         * Examples:
4673
         *  Map::from( ['a', 'b', 'c'] )->search( 'b' );
4674
         *  Map::from( [1, 2, 3] )->search( '2' );
4675
         *  Map::from( [1, 2, 3] )->search( '2', true );
4676
         *
4677
         * Results:
4678
         * The first example will return 1 (array index), the second will also return 1
4679
         * (loose comparison) while the third one will return NULL because the types
4680
         * doesn't match (int vs. string)
4681
         *
4682
         * @param mixed $value Item to search for
4683
         * @param bool $strict TRUE if type of the element should be checked too
4684
         * @return int|string|null Key associated to the value or null if not found
4685
         */
4686
        public function search( mixed $value, bool $strict = false ) : int|string|null
4687
        {
4688
                if( ( $result = array_search( $value, $this->list(), $strict ) ) !== false ) {
1 ✔
4689
                        return $result;
1 ✔
4690
                }
4691

4692
                return null;
1 ✔
4693
        }
4694

4695

4696
        /**
4697
         * Sets the separator for paths to values in multi-dimensional arrays or objects.
4698
         *
4699
         * This method only changes the separator for the current map instance. To
4700
         * change the separator for all maps created afterwards, use the static
4701
         * delimiter() method instead.
4702
         *
4703
         * Examples:
4704
         *  Map::from( ['foo' => ['bar' => 'baz']] )->sep( '.' )->get( 'foo.bar' );
4705
         *
4706
         * Results:
4707
         *  'baz'
4708
         *
4709
         * @param string $char Separator character, e.g. "." for "key.to.value" instead of "key/to/value"
4710
         * @return self<int|string,mixed> Same map for fluid interface
4711
         * @throws \InvalidArgumentException If the separator is empty
4712
         */
4713
        public function sep( string $char ) : self
4714
        {
4715
                if( $char === '' ) {
4 ✔
4716
                        throw new \InvalidArgumentException( 'Separator must not be empty' );
1 ✔
4717
                }
4718

4719
                $this->sep = $char;
3 ✔
4720
                return $this;
3 ✔
4721
        }
4722

4723

4724
        /**
4725
         * Sets an element in the map by key without returning a new map.
4726
         *
4727
         * Examples:
4728
         *  Map::from( ['a'] )->set( 1, 'b' );
4729
         *  Map::from( ['a'] )->set( 0, 'b' );
4730
         *
4731
         * Results:
4732
         *  ['a', 'b']
4733
         *  ['b']
4734
         *
4735
         * @param int|string $key Key to set the new value for
4736
         * @param mixed $value New element that should be set
4737
         * @return self<int|string,mixed> Updated map for fluid interface
4738
         */
4739
        public function set( int|string $key, mixed $value ) : self
4740
        {
4741
                $this->list()[(string) $key] = $value;
5 ✔
4742
                return $this;
5 ✔
4743
        }
4744

4745

4746
        /**
4747
         * Returns and removes the first element from the map.
4748
         *
4749
         * Examples:
4750
         *  Map::from( ['a', 'b'] )->shift();
4751
         *  Map::from( [] )->shift();
4752
         *
4753
         * Results:
4754
         * The first example returns "a" and shortens the map to ['b'] only while the
4755
         * second example will return NULL
4756
         *
4757
         * Performance note:
4758
         * The bigger the list, the higher the performance impact because shift()
4759
         * reindexes all existing elements. Usually, it's better to reverse() the list
4760
         * and pop() entries from the list afterwards if a significant number of elements
4761
         * should be removed from the list:
4762
         *
4763
         *  $map->reverse()->pop();
4764
         * instead of
4765
         *  $map->shift( 'a' );
4766
         *
4767
         * @return mixed|null Value from map or null if not found
4768
         */
4769
        public function shift() : mixed
4770
        {
4771
                return array_shift( $this->list() );
1 ✔
4772
        }
4773

4774

4775
        /**
4776
         * Shuffles the elements in the map without returning a new map.
4777
         *
4778
         * Examples:
4779
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle();
4780
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle( true );
4781
         *
4782
         * Results:
4783
         * The map in the first example will contain "a" and "b" in random order and
4784
         * with new keys assigned. The second call will also return all values in
4785
         * random order but preserves the keys of the original list.
4786
         *
4787
         * @param bool $assoc True to preserve keys, false to assign new keys
4788
         * @return self<int|string,mixed> Updated map for fluid interface
4789
         * @see shuffled() - Shuffles the elements in a copy of the map
4790
         */
4791
        public function shuffle( bool $assoc = false ) : self
4792
        {
4793
                $list = $this->list();
3 ✔
4794
                $keys = array_keys( $list );
3 ✔
4795
                $buf = [];
3 ✔
4796
                $pos = 0;
3 ✔
4797

4798
                for( $i = count( $keys ) - 1; $i > 0; $i-- )
3 ✔
4799
                {
4800
                        $idx = $this->rand( $i, $buf, $pos );
3 ✔
4801
                        [$keys[$i], $keys[$idx]] = [$keys[$idx], $keys[$i]];
3 ✔
4802
                }
4803

4804
                $items = [];
3 ✔
4805

4806
                if( $assoc )
3 ✔
4807
                {
4808
                        foreach( $keys as $key ) {
1 ✔
4809
                                $items[$key] = $list[$key];
1 ✔
4810
                        }
4811
                }
4812
                else
4813
                {
4814
                        foreach( $keys as $key ) {
2 ✔
4815
                                $items[] = $list[$key];
2 ✔
4816
                        }
4817
                }
4818

4819
                $this->list = $items;
3 ✔
4820

4821
                return $this;
3 ✔
4822
        }
4823

4824

4825
        /**
4826
         * Shuffles the elements in a copy of the map.
4827
         *
4828
         * Examples:
4829
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled();
4830
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled( true );
4831
         *
4832
         * Results:
4833
         * The map in the first example will contain "a" and "b" in random order and
4834
         * with new keys assigned. The second call will also return all values in
4835
         * random order but preserves the keys of the original list.
4836
         *
4837
         * @param bool $assoc True to preserve keys, false to assign new keys
4838
         * @return self<int|string,mixed> New map with a shuffled copy of the elements
4839
         * @see shuffle() - Shuffles the elements in the map without returning a new map
4840
         */
4841
        public function shuffled( bool $assoc = false ) : self
4842
        {
4843
                return ( clone $this )->shuffle( $assoc );
1 ✔
4844
        }
4845

4846

4847
        /**
4848
         * Returns a new map with the given number of items skipped.
4849
         *
4850
         * Examples:
4851
         *  Map::from( [1, 2, 3, 4] )->skip( 2 );
4852
         *  Map::from( [1, 2, 3, 4] )->skip( function( $item, $key ) {
4853
         *      return $item < 4;
4854
         *  } );
4855
         *
4856
         * Results:
4857
         *  [2 => 3, 3 => 4]
4858
         *  [3 => 4]
4859
         *
4860
         * The keys of the items returned in the new map are the same as in the original one.
4861
         *
4862
         * @param \Closure|int $offset Non-negative number of items to skip or function($item, $key) returning true for skipped items
4863
         * @return self<int|string,mixed> New map
4864
         * @throws \InvalidArgumentException If the offset is negative
4865
         */
4866
        public function skip( \Closure|int $offset ) : self
4867
        {
4868
                $list = $this->list();
3 ✔
4869

4870
                if( is_int( $offset ) )
3 ✔
4871
                {
4872
                        if( $offset === 0 ) {
2 ✔
NEW
4873
                                return clone $this;
×
4874
                        }
4875

4876
                        if( $offset < 0 ) {
2 ✔
4877
                                throw new \InvalidArgumentException( 'Offset must be greater than or equal to zero' );
1 ✔
4878
                        }
4879
                }
4880

4881
                if( $offset instanceof \Closure ) {
2 ✔
4882
                        return new static( array_slice( $list, $this->until( $list, $offset ), null, true ) );
1 ✔
4883
                }
4884

4885
                return new static( array_slice( $list, (int) $offset, null, true ) );
1 ✔
4886
        }
4887

4888

4889
        /**
4890
         * Returns a map with the slice from the original map.
4891
         *
4892
         * Examples:
4893
         *  Map::from( ['a', 'b', 'c'] )->slice( 1 );
4894
         *  Map::from( ['a', 'b', 'c'] )->slice( 1, 1 );
4895
         *  Map::from( ['a', 'b', 'c', 'd'] )->slice( -2, -1 );
4896
         *
4897
         * Results:
4898
         * The first example will return ['b', 'c'] and the second one ['b'] only.
4899
         * The third example returns ['c'] because the slice starts at the second
4900
         * last value and ends before the last value.
4901
         *
4902
         * The rules for offsets are:
4903
         * - If offset is non-negative, the sequence will start at that offset
4904
         * - If offset is negative, the sequence will start that far from the end
4905
         *
4906
         * Similar for the length:
4907
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4908
         * - If the array is shorter than the length, then only the available array elements will be present
4909
         * - If length is given and is negative then the sequence will stop that many elements from the end
4910
         * - If it is omitted, then the sequence will have everything from offset up until the end
4911
         *
4912
         * The keys of the items returned in the new map are the same as in the original one.
4913
         *
4914
         * @param int $offset Number of elements to start from
4915
         * @param int|null $length Number of elements to return or NULL for no limit
4916
         * @return self<int|string,mixed> New map
4917
         */
4918
        public function slice( int $offset, ?int $length = null ) : self
4919
        {
4920
                return new static( array_slice( $this->list(), $offset, $length, true ) );
6 ✔
4921
        }
4922

4923

4924
        /**
4925
         * Returns a new map containing sliding windows of the original map.
4926
         *
4927
         * Examples:
4928
         *  Map::from( [1, 2, 3, 4, 5] )->sliding( 2 );
4929
         *  Map::from( [1, 2, 3, 4, 5] )->sliding( 3, 2 );
4930
         *
4931
         * Results:
4932
         * The first example will return [[0 => 1, 1 => 2], [1 => 2, 2 => 3], [2 => 3, 3 => 4], [3 => 4, 4 => 5]]
4933
         * while the second one will return [[0 => 1, 1 => 2, 2 => 3], [2 => 3, 3 => 4, 4 => 5]]
4934
         *
4935
         * @param int $size Size of each window
4936
         * @param int $step Step size to move the window
4937
         * @return self<int,array<int|string,mixed>> New map containing arrays for each window
4938
         * @throws \InvalidArgumentException If size or step is smaller than 1
4939
         */
4940
        public function sliding( int $size = 2, int $step = 1 ) : self
4941
        {
4942
                if( $size < 1 ) {
4 ✔
4943
                        throw new \InvalidArgumentException( 'Window size must be greater or equal than 1' );
1 ✔
4944
                }
4945

4946
                if( $step < 1 ) {
3 ✔
4947
                        throw new \InvalidArgumentException( 'Step width must be greater or equal than 1' );
1 ✔
4948
                }
4949

4950
                $result = [];
2 ✔
4951
                $list = $this->list();
2 ✔
4952
                $chunks = floor( ( count( $list ) - $size ) / $step ) + 1;
2 ✔
4953

4954
                for( $i = 0; $i < $chunks; $i++ ) {
2 ✔
4955
                        $result[] = array_slice( $list, $i * $step, $size, true );
2 ✔
4956
                }
4957

4958
                return new static( $result );
2 ✔
4959
        }
4960

4961

4962
        /**
4963
         * Returns the matching item, but only if one matching item exists.
4964
         *
4965
         * Examples:
4966
         *  Map::from( ['a', 'b'] )->sole( 'a' );
4967
         *  Map::from( ['a', 'b', 'a'] )->restrict( fn( $v, $k ) => $v === 'a' && $k < 2 );
4968
         *  Map::from( [['name' => 'test'], ['name' => 'user']] )->restrict( fn( $v, $k ) => $v['name'] === 'user' );
4969
         *  Map::from( ['b', 'c'] )->sole( 'a' );
4970
         *  Map::from( ['a', 'b', 'a'] )->sole( 'a' );
4971
         *  Map::from( [['name' => 'test'], ['name' => 'user'], ['name' => 'test']] )->restrict( 'test', 'name' );
4972
         *
4973
         * Results:
4974
         * The first two examples will return "a" while the third one will return [1 => ['name' => 'user']].
4975
         * All other examples throw a LengthException because more than one item matches the test.
4976
         *
4977
         * @param \Closure|mixed $value Closure with (item, key) parameter or element to test against
4978
         * @param string|int|null $key Key to compare the value for if $value is not a closure
4979
         * @return mixed Value from map if exactly one matching item exists
4980
         * @throws \LengthException If no items or more than one item is found
4981
         */
4982
        public function sole( mixed $value = null, string|int|null $key = null ) : mixed
4983
        {
4984
                $found = false;
3 ✔
4985
                $result = null;
3 ✔
4986

4987
                foreach( $this->list() as $mapkey => $item )
3 ✔
4988
                {
4989
                        if( $this->matches( $item, $mapkey, $value, $key ) )
3 ✔
4990
                        {
4991
                                if( $found ) {
2 ✔
4992
                                        throw new \LengthException( 'Multiple items found' );
1 ✔
4993
                                }
4994

4995
                                $found = true;
2 ✔
4996
                                $result = $item;
2 ✔
4997
                        }
4998
                }
4999

5000
                if( !$found ) {
2 ✔
5001
                        throw new \LengthException( 'No items found' );
1 ✔
5002
                }
5003

5004
                return $result;
1 ✔
5005
        }
5006

5007

5008
        /**
5009
         * Tests if at least one element passes the test or is part of the map.
5010
         *
5011
         * Examples:
5012
         *  Map::from( ['a', 'b'] )->some( 'a' );
5013
         *  Map::from( ['a', 'b'] )->some( ['a', 'c'] );
5014
         *  Map::from( ['a', 'b'] )->some( function( $item, $key ) {
5015
         *    return $item === 'a';
5016
         *  } );
5017
         *  Map::from( ['a', 'b'] )->some( ['c', 'd'] );
5018
         *  Map::from( ['1', '2'] )->some( [2], true );
5019
         *
5020
         * Results:
5021
         * The first three examples will return TRUE while the fourth and fifth will return FALSE
5022
         *
5023
         * @param \Closure|iterable|mixed $values Closure with (item, key) parameter, element or list of elements to test against
5024
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
5025
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
5026
         */
5027
        public function some( mixed $values, bool $strict = false ) : bool
5028
        {
5029
                $list = $this->list();
8 ✔
5030

5031
                if( is_iterable( $values ) )
8 ✔
5032
                {
5033
                        if( $strict && ( is_array( $values ) || $values instanceof \Aimeos\Map ) )
3 ✔
5034
                        {
5035
                                $values = $this->array( $values );
1 ✔
5036

5037
                                if( count( $values ) > 128 && ( $keys = $this->lookupKeys( $values ) ) !== null )
1 ✔
5038
                                {
5039
                                        $lookup = $this->lookupSet( $list );
×
5040

5041
                                        foreach( $keys as $key )
×
5042
                                        {
5043
                                                if( isset( $lookup[$key] ) ) {
×
5044
                                                        return true;
×
5045
                                                }
5046
                                        }
5047

5048
                                        return false;
×
5049
                                }
5050
                        }
5051

5052
                        foreach( $values as $entry )
3 ✔
5053
                        {
5054
                                if( in_array( $entry, $list, $strict ) === true ) {
3 ✔
5055
                                        return true;
3 ✔
5056
                                }
5057
                        }
5058

5059
                        return false;
2 ✔
5060
                }
5061

5062
                if( $values instanceof \Closure )
6 ✔
5063
                {
5064
                        foreach( $list as $key => $item )
4 ✔
5065
                        {
5066
                                if( $values( $item, $key ) ) {
4 ✔
5067
                                        return true;
2 ✔
5068
                                }
5069
                        }
5070

5071
                        return false;
3 ✔
5072
                }
5073

5074
                return in_array( $values, $list, $strict );
3 ✔
5075
        }
5076

5077

5078
        /**
5079
         * Sorts all elements in-place using new keys.
5080
         *
5081
         * Examples:
5082
         *  Map::from( ['a' => 1, 'b' => 0] )->sort();
5083
         *  Map::from( [0 => 'b', 1 => 'a'] )->sort();
5084
         *
5085
         * Results:
5086
         *  [0 => 0, 1 => 1]
5087
         *  [0 => 'a', 1 => 'b']
5088
         *
5089
         * The parameter modifies how the values are compared. Possible parameter values are:
5090
         * - SORT_REGULAR : compare elements normally (don't change types)
5091
         * - SORT_NUMERIC : compare elements numerically
5092
         * - SORT_STRING : compare elements as strings
5093
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
5094
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
5095
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
5096
         *
5097
         * The keys aren't preserved and elements get a new index. No new map is created.
5098
         *
5099
         * @param int $options Sort options for PHP sort()
5100
         * @return self<int|string,mixed> Updated map for fluid interface
5101
         * @see sorted() - Sorts elements in a copy of the map
5102
         */
5103
        public function sort( int $options = SORT_REGULAR ) : self
5104
        {
5105
                sort( $this->list(), $options );
5 ✔
5106
                return $this;
5 ✔
5107
        }
5108

5109

5110
        /**
5111
         * Sorts the elements in a copy of the map using new keys.
5112
         *
5113
         * Examples:
5114
         *  Map::from( ['a' => 1, 'b' => 0] )->sorted();
5115
         *  Map::from( [0 => 'b', 1 => 'a'] )->sorted();
5116
         *
5117
         * Results:
5118
         *  [0 => 0, 1 => 1]
5119
         *  [0 => 'a', 1 => 'b']
5120
         *
5121
         * The parameter modifies how the values are compared. Possible parameter values are:
5122
         * - SORT_REGULAR : compare elements normally (don't change types)
5123
         * - SORT_NUMERIC : compare elements numerically
5124
         * - SORT_STRING : compare elements as strings
5125
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
5126
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
5127
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
5128
         *
5129
         * The keys aren't preserved and elements get a new index and a new map is created before sorting the elements.
5130
         * Thus, sort() should be preferred for performance reasons if possible. A new map is created by calling this method.
5131
         *
5132
         * @param int $options Sort options for PHP sort()
5133
         * @return self<int|string,mixed> New map with a sorted copy of the elements
5134
         * @see sort() - Sorts elements in-place in the original map
5135
         */
5136
        public function sorted( int $options = SORT_REGULAR ) : self
5137
        {
5138
                return ( clone $this )->sort( $options );
2 ✔
5139
        }
5140

5141

5142
        /**
5143
         * Removes a portion of the map and replace it with the given replacement, then return the updated map.
5144
         *
5145
         * Examples:
5146
         *  Map::from( ['a', 'b', 'c'] )->splice( 1 );
5147
         *  Map::from( ['a', 'b', 'c'] )->splice( 1, 1, ['x', 'y'] );
5148
         *
5149
         * Results:
5150
         * The first example removes all entries after "a", so only ['a'] will be left
5151
         * in the map and ['b', 'c'] is returned. The second example replaces/returns "b"
5152
         * (start at 1, length 1) with ['x', 'y'] so the new map will contain
5153
         * ['a', 'x', 'y', 'c'] afterwards.
5154
         *
5155
         * The rules for offsets are:
5156
         * - If offset is non-negative, the sequence will start at that offset
5157
         * - If offset is negative, the sequence will start that far from the end
5158
         *
5159
         * Similar for the length:
5160
         * - If length is given and is positive, then the sequence will have up to that many elements in it
5161
         * - If the array is shorter than the length, then only the available array elements will be present
5162
         * - If length is given and is negative then the sequence will stop that many elements from the end
5163
         * - If it is omitted, then the sequence will have everything from offset up until the end
5164
         *
5165
         * Numerical array indexes are NOT preserved.
5166
         *
5167
         * @param int $offset Number of elements to start from
5168
         * @param int|null $length Number of elements to remove, NULL for all
5169
         * @param mixed $replacement List of elements to insert
5170
         * @return self<int|string,mixed> New map
5171
         */
5172
        public function splice( int $offset, ?int $length = null, mixed $replacement = [] ) : self
5173
        {
5174
                return new static( array_splice( $this->list(), $offset, $length, $this->array( $replacement ) ) );
7 ✔
5175
        }
5176

5177

5178
        /**
5179
         * Returns the strings after the passed value.
5180
         *
5181
         * Examples:
5182
         *  Map::from( ['äöüß'] )->strAfter( 'ö' );
5183
         *  Map::from( ['abc'] )->strAfter( '' );
5184
         *  Map::from( ['abc'] )->strAfter( 'b' );
5185
         *  Map::from( ['abc'] )->strAfter( 'c' );
5186
         *  Map::from( ['abc'] )->strAfter( 'x' );
5187
         *  Map::from( [''] )->strAfter( '' );
5188
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
5189
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
5190
         *  Map::from( ['abc'] )->strAfter( 'B' );
5191
         *  Map::from( ['abc'] )->strAfter( 'B', false );
5192
         *
5193
         * Results:
5194
         *  ['üß']
5195
         *  ['abc']
5196
         *  ['c']
5197
         *  ['']
5198
         *  []
5199
         *  []
5200
         *  ['1', '1', '1']
5201
         *  ['0', '0']
5202
         *  []
5203
         *  ['c']
5204
         *
5205
         * All scalar values (bool, int, float, string) will be converted to strings.
5206
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
5207
         *
5208
         * @param string $value Character or string to search for
5209
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5210
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5211
         * @return self<int|string,mixed> New map
5212
         */
5213
        public function strAfter( string $value, bool $case = true, string $encoding = 'UTF-8' ) : self
5214
        {
5215
                $list = [];
1 ✔
5216

5217
                if( $case && $encoding === 'UTF-8' )
1 ✔
5218
                {
5219
                        $len = strlen( $value );
1 ✔
5220

5221
                        foreach( $this->list() as $key => $entry )
1 ✔
5222
                        {
5223
                                if( is_scalar( $entry ) )
1 ✔
5224
                                {
5225
                                        $pos = null;
1 ✔
5226
                                        $str = (string) $entry;
1 ✔
5227

5228
                                        if( $str !== '' && $value !== '' && ( $pos = strpos( $str, $value ) ) !== false ) {
1 ✔
5229
                                                $list[$key] = substr( $str, $pos + $len );
1 ✔
5230
                                        } elseif( $str !== '' && $pos !== false ) {
1 ✔
5231
                                                $list[$key] = $str;
1 ✔
5232
                                        }
5233
                                }
5234
                        }
5235

5236
                        return new static( $list );
1 ✔
5237
                }
5238

5239
                $len = mb_strlen( $value, $encoding );
1 ✔
5240
                $fcn = $case ? 'mb_strpos' : 'mb_stripos';
1 ✔
5241

5242
                foreach( $this->list() as $key => $entry )
1 ✔
5243
                {
5244
                        if( is_scalar( $entry ) )
1 ✔
5245
                        {
5246
                                $pos = null;
1 ✔
5247
                                $str = (string) $entry;
1 ✔
5248

5249
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
1 ✔
5250
                                        $list[$key] = mb_substr( $str, $pos + $len, null, $encoding );
1 ✔
5251
                                } elseif( $str !== '' && $pos !== false ) {
×
5252
                                        $list[$key] = $str;
×
5253
                                }
5254
                        }
5255
                }
5256

5257
                return new static( $list );
1 ✔
5258
        }
5259

5260

5261
        /**
5262
         * Returns the strings before the passed value.
5263
         *
5264
         * Examples:
5265
         *  Map::from( ['äöüß'] )->strBefore( 'ü' );
5266
         *  Map::from( ['abc'] )->strBefore( '' );
5267
         *  Map::from( ['abc'] )->strBefore( 'b' );
5268
         *  Map::from( ['abc'] )->strBefore( 'a' );
5269
         *  Map::from( ['abc'] )->strBefore( 'x' );
5270
         *  Map::from( [''] )->strBefore( '' );
5271
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strBefore( '' );
5272
         *  Map::from( [0, 0.0, false, []] )->strBefore( '' );
5273
         *  Map::from( ['abc'] )->strBefore( 'B' );
5274
         *  Map::from( ['abc'] )->strBefore( 'B', false );
5275
         *
5276
         * Results:
5277
         *  ['äö']
5278
         *  ['abc']
5279
         *  ['a']
5280
         *  ['']
5281
         *  []
5282
         *  []
5283
         *  ['1', '1', '1']
5284
         *  ['0', '0']
5285
         *  []
5286
         *  ['a']
5287
         *
5288
         * All scalar values (bool, int, float, string) will be converted to strings.
5289
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
5290
         *
5291
         * @param string $value Character or string to search for
5292
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5293
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5294
         * @return self<int|string,mixed> New map
5295
         */
5296
        public function strBefore( string $value, bool $case = true, string $encoding = 'UTF-8' ) : self
5297
        {
5298
                $list = [];
1 ✔
5299

5300
                if( $case && $encoding === 'UTF-8' )
1 ✔
5301
                {
5302
                        foreach( $this->list() as $key => $entry )
1 ✔
5303
                        {
5304
                                if( is_scalar( $entry ) )
1 ✔
5305
                                {
5306
                                        $pos = null;
1 ✔
5307
                                        $str = (string) $entry;
1 ✔
5308

5309
                                        if( $str !== '' && $value !== '' && ( $pos = strrpos( $str, $value ) ) !== false ) {
1 ✔
5310
                                                $list[$key] = substr( $str, 0, $pos );
1 ✔
5311
                                        } elseif( $str !== '' && $pos !== false ) {
1 ✔
5312
                                                $list[$key] = $str;
1 ✔
5313
                                        }
5314
                                }
5315
                        }
5316

5317
                        return new static( $list );
1 ✔
5318
                }
5319

5320
                $fcn = $case ? 'mb_strrpos' : 'mb_strripos';
1 ✔
5321

5322
                foreach( $this->list() as $key => $entry )
1 ✔
5323
                {
5324
                        if( is_scalar( $entry ) )
1 ✔
5325
                        {
5326
                                $pos = null;
1 ✔
5327
                                $str = (string) $entry;
1 ✔
5328

5329
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
1 ✔
5330
                                        $list[$key] = mb_substr( $str, 0, $pos, $encoding );
1 ✔
5331
                                } elseif( $str !== '' && $pos !== false ) {
×
5332
                                        $list[$key] = $str;
×
5333
                                }
5334
                        }
5335
                }
5336

5337
                return new static( $list );
1 ✔
5338
        }
5339

5340

5341
        /**
5342
         * Compares the value against all map elements.
5343
         *
5344
         * Examples:
5345
         *  Map::from( ['foo', 'bar'] )->compare( 'foo' );
5346
         *  Map::from( ['foo', 'bar'] )->strCompare( 'Foo', false );
5347
         *  Map::from( [123, 12.3] )->strCompare( '12.3' );
5348
         *  Map::from( [false, true] )->strCompare( '1' );
5349
         *  Map::from( ['foo', 'bar'] )->strCompare( 'Foo' );
5350
         *  Map::from( ['foo', 'bar'] )->strCompare( 'baz' );
5351
         *  Map::from( [new \stdClass(), 'bar'] )->strCompare( 'foo' );
5352
         *
5353
         * Results:
5354
         * The first four examples return TRUE, the last three examples will return FALSE.
5355
         *
5356
         * All scalar values (bool, float, int and string) are casted to string values before
5357
         * comparing to the given value. Non-scalar values in the map are ignored.
5358
         *
5359
         * @param string $value Value to compare map elements to
5360
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5361
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5362
         * @return bool TRUE If at least one element matches, FALSE if value is not in map
5363
         */
5364
        public function strCompare( string $value, bool $case = true, string $encoding = 'UTF-8' ) : bool
5365
        {
5366
                $val = $case ? $value : mb_strtolower( $value, $encoding );
2 ✔
5367

5368
                foreach( $this->list() as $item )
2 ✔
5369
                {
5370
                        if( is_scalar( $item ) )
2 ✔
5371
                        {
5372
                                if( ( $case ? (string) $item : mb_strtolower( (string) $item, $encoding ) ) === $val ) {
2 ✔
5373
                                        return true;
2 ✔
5374
                                }
5375
                        }
5376
                }
5377

5378
                return false;
2 ✔
5379
        }
5380

5381

5382
        /**
5383
         * Tests if at least one of the passed strings is part of at least one entry.
5384
         *
5385
         * Examples:
5386
         *  Map::from( ['abc'] )->strContains( '' );
5387
         *  Map::from( ['abc'] )->strContains( 'a' );
5388
         *  Map::from( ['abc'] )->strContains( 'bc' );
5389
         *  Map::from( [12345] )->strContains( '23' );
5390
         *  Map::from( [123.4] )->strContains( 23.4 );
5391
         *  Map::from( [12345] )->strContains( false );
5392
         *  Map::from( [12345] )->strContains( true );
5393
         *  Map::from( [false] )->strContains( false );
5394
         *  Map::from( [''] )->strContains( false );
5395
         *  Map::from( ['abc'] )->strContains( ['b', 'd'] );
5396
         *  Map::from( ['abc'] )->strContains( 'c', true, 'ASCII' );
5397
         *  Map::from( ['abc'] )->strContains( 'B', false );
5398
         *
5399
         *  Map::from( ['abc'] )->strContains( 'd' );
5400
         *  Map::from( ['abc'] )->strContains( 'cb' );
5401
         *  Map::from( [23456] )->strContains( true );
5402
         *  Map::from( [false] )->strContains( 0 );
5403
         *  Map::from( ['abc'] )->strContains( ['d', 'e'] );
5404
         *  Map::from( ['abc'] )->strContains( 'cb', true, 'ASCII' );
5405
         *  Map::from( ['abc'] )->strContains( 'B' );
5406
         *
5407
         * Results:
5408
         * The first twelve examples will return TRUE while the last seven will return FALSE.
5409
         *
5410
         * @param array<string>|string $value The string or list of strings to search for in each entry
5411
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5412
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5413
         * @return bool TRUE if one of the entries contains one of the strings, FALSE if not
5414
         */
5415
        public function strContains( array|string $value, bool $case = true, string $encoding = 'UTF-8' ) : bool
5416
        {
5417
                $native = $case && $encoding === 'UTF-8';
1 ✔
5418
                $fcn = $case ? 'mb_strpos' : 'mb_stripos';
1 ✔
5419
                $needles = [];
1 ✔
5420

5421
                foreach( (array) $value as $str ) {
1 ✔
5422
                        $needles[] = (string) $str;
1 ✔
5423
                }
5424

5425
                foreach( $this->list() as $entry )
1 ✔
5426
                {
5427
                        if( !is_scalar( $entry ) && !$entry instanceof \Stringable ) {
1 ✔
5428
                                continue;
×
5429
                        }
5430

5431
                        $entry = (string) $entry;
1 ✔
5432

5433
                        foreach( $needles as $str )
1 ✔
5434
                        {
5435
                                if( $native ? str_contains( $entry, $str ) : ( $str === '' || $fcn( $entry, $str, 0, $encoding ) !== false ) ) {
1 ✔
5436
                                        return true;
1 ✔
5437
                                }
5438
                        }
5439
                }
5440

5441
                return false;
1 ✔
5442
        }
5443

5444

5445
        /**
5446
         * Tests if all of the entries contains one of the passed strings.
5447
         *
5448
         * Examples:
5449
         *  Map::from( ['abc', 'def'] )->strContainsAll( '' );
5450
         *  Map::from( ['abc', 'cba'] )->strContainsAll( 'a' );
5451
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'bc' );
5452
         *  Map::from( [12345, '230'] )->strContainsAll( '23' );
5453
         *  Map::from( [123.4, 23.42] )->strContainsAll( 23.4 );
5454
         *  Map::from( [12345, '234'] )->strContainsAll( [true, false] );
5455
         *  Map::from( ['', false] )->strContainsAll( false );
5456
         *  Map::from( ['abc', 'def'] )->strContainsAll( ['b', 'd'] );
5457
         *  Map::from( ['abc', 'ecf'] )->strContainsAll( 'c', true, 'ASCII' );
5458
         *  Map::from( ['abc', 'Abc'] )->strContainsAll( 'A', false );
5459
         *
5460
         *  Map::from( ['abc', 'def'] )->strContainsAll( 'd' );
5461
         *  Map::from( ['abc', 'cab'] )->strContainsAll( 'cb' );
5462
         *  Map::from( [23456, '123'] )->strContainsAll( true );
5463
         *  Map::from( [false, '000'] )->strContainsAll( 0 );
5464
         *  Map::from( ['abc', 'acf'] )->strContainsAll( ['d', 'e'] );
5465
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'cb', true, 'ASCII' );
5466
         *  Map::from( ['abc', 'def'] )->strContainsAll( 'A' );
5467
         *
5468
         * Results:
5469
         * The first ten examples will return TRUE while the last seven will return FALSE.
5470
         *
5471
         * @param array<string>|string $value The string or list of strings to search for in each entry
5472
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5473
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5474
         * @return bool TRUE if all of the entries contains at least one of the strings, FALSE if not
5475
         */
5476
        public function strContainsAll( array|string $value, bool $case = true, string $encoding = 'UTF-8' ) : bool
5477
        {
5478
                $native = $case && $encoding === 'UTF-8';
1 ✔
5479
                $fcn = $case ? 'mb_strpos' : 'mb_stripos';
1 ✔
5480
                $needles = [];
1 ✔
5481

5482
                foreach( (array) $value as $str ) {
1 ✔
5483
                        $needles[] = (string) $str;
1 ✔
5484
                }
5485

5486
                foreach( $this->list() as $entry )
1 ✔
5487
                {
5488
                        if( !is_scalar( $entry ) && !$entry instanceof \Stringable ) {
1 ✔
5489
                                return false;
×
5490
                        }
5491

5492
                        $entry = (string) $entry;
1 ✔
5493
                        $match = false;
1 ✔
5494

5495
                        foreach( $needles as $str )
1 ✔
5496
                        {
5497
                                if( $native ? str_contains( $entry, $str ) : ( $str === '' || $fcn( $entry, $str, 0, $encoding ) !== false ) ) {
1 ✔
5498
                                        $match = true; break;
1 ✔
5499
                                }
5500
                        }
5501

5502
                        if( !$match ) {
1 ✔
5503
                                return false;
1 ✔
5504
                        }
5505
                }
5506

5507
                return true;
1 ✔
5508
        }
5509

5510

5511
        /**
5512
         * Tests if at least one of the entries ends with one of the passed strings.
5513
         *
5514
         * Examples:
5515
         *  Map::from( ['abc'] )->strEnds( '' );
5516
         *  Map::from( ['abc'] )->strEnds( 'c' );
5517
         *  Map::from( ['abc'] )->strEnds( 'bc' );
5518
         *  Map::from( ['abc'] )->strEnds( ['b', 'c'] );
5519
         *  Map::from( ['abc'] )->strEnds( 'c', true, 'ASCII' );
5520
         *  Map::from( ['abc'] )->strEnds( 'C', false );
5521
         *  Map::from( ['abc'] )->strEnds( 'a' );
5522
         *  Map::from( ['abc'] )->strEnds( 'cb' );
5523
         *  Map::from( ['abc'] )->strEnds( ['d', 'b'] );
5524
         *  Map::from( ['abc'] )->strEnds( 'cb', true, 'ASCII' );
5525
         *  Map::from( ['abc'] )->strEnds( 'C' );
5526
         *
5527
         * Results:
5528
         * The first six examples will return TRUE while the last five will return FALSE.
5529
         *
5530
         * @param array<string>|string $value The string or strings to search for in each entry
5531
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5532
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5533
         * @return bool TRUE if one of the entries ends with one of the strings, FALSE if not
5534
         */
5535
        public function strEnds( array|string $value, bool $case = true, string $encoding = 'UTF-8' ) : bool
5536
        {
5537
                $native = $case && $encoding === 'UTF-8';
1 ✔
5538
                $fcn = $case ? 'mb_strpos' : 'mb_stripos';
1 ✔
5539
                $needles = $lengths = [];
1 ✔
5540

5541
                foreach( (array) $value as $str )
1 ✔
5542
                {
5543
                        $needles[] = $str = (string) $str;
1 ✔
5544
                        $lengths[] = $native ? 0 : mb_strlen( $str, $encoding );
1 ✔
5545
                }
5546

5547
                foreach( $this->list() as $entry )
1 ✔
5548
                {
5549
                        if( !is_scalar( $entry ) && !$entry instanceof \Stringable ) {
1 ✔
5550
                                continue;
×
5551
                        }
5552

5553
                        $entry = (string) $entry;
1 ✔
5554

5555
                        if( $native )
1 ✔
5556
                        {
5557
                                foreach( $needles as $str )
1 ✔
5558
                                {
5559
                                        if( str_ends_with( $entry, $str ) ) {
1 ✔
5560
                                                return true;
1 ✔
5561
                                        }
5562
                                }
5563

5564
                                continue;
1 ✔
5565
                        }
5566

5567
                        $len = mb_strlen( $entry, $encoding );
1 ✔
5568
                        $i = 0;
1 ✔
5569

5570
                        foreach( $needles as $str )
1 ✔
5571
                        {
5572
                                if( $str === '' || ( $lengths[$i] <= $len && $fcn( $entry, $str, -$lengths[$i], $encoding ) !== false ) ) {
1 ✔
5573
                                        return true;
1 ✔
5574
                                }
5575

5576
                                $i++;
1 ✔
5577
                        }
5578
                }
5579

5580
                return false;
1 ✔
5581
        }
5582

5583

5584
        /**
5585
         * Tests if all of the entries ends with at least one of the passed strings.
5586
         *
5587
         * Examples:
5588
         *  Map::from( ['abc', 'def'] )->strEndsAll( '' );
5589
         *  Map::from( ['abc', 'bac'] )->strEndsAll( 'c' );
5590
         *  Map::from( ['abc', 'cbc'] )->strEndsAll( 'bc' );
5591
         *  Map::from( ['abc', 'def'] )->strEndsAll( ['c', 'f'] );
5592
         *  Map::from( ['abc', 'efc'] )->strEndsAll( 'c', true, 'ASCII' );
5593
         *  Map::from( ['abc', 'deC'] )->strEndsAll( 'c', false );
5594
         *  Map::from( ['abc', 'fed'] )->strEndsAll( 'd' );
5595
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca' );
5596
         *  Map::from( ['abc', 'acf'] )->strEndsAll( ['a', 'c'] );
5597
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca', true, 'ASCII' );
5598
         *  Map::from( ['abc', 'deC'] )->strEndsAll( 'c' );
5599
         *
5600
         * Results:
5601
         * The first six examples will return TRUE while the last five will return FALSE.
5602
         *
5603
         * @param array<string>|string $value The string or strings to search for in each entry
5604
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5605
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5606
         * @return bool TRUE if all of the entries ends with at least one of the strings, FALSE if not
5607
         */
5608
        public function strEndsAll( array|string $value, bool $case = true, string $encoding = 'UTF-8' ) : bool
5609
        {
5610
                $native = $case && $encoding === 'UTF-8';
1 ✔
5611
                $fcn = $case ? 'mb_strpos' : 'mb_stripos';
1 ✔
5612
                $needles = $lengths = [];
1 ✔
5613

5614
                foreach( (array) $value as $str )
1 ✔
5615
                {
5616
                        $needles[] = $str = (string) $str;
1 ✔
5617
                        $lengths[] = $native ? 0 : mb_strlen( $str, $encoding );
1 ✔
5618
                }
5619

5620
                foreach( $this->list() as $entry )
1 ✔
5621
                {
5622
                        if( !is_scalar( $entry ) && !$entry instanceof \Stringable ) {
1 ✔
5623
                                return false;
×
5624
                        }
5625

5626
                        $entry = (string) $entry;
1 ✔
5627
                        $match = false;
1 ✔
5628

5629
                        if( $native )
1 ✔
5630
                        {
5631
                                foreach( $needles as $str )
1 ✔
5632
                                {
5633
                                        if( str_ends_with( $entry, $str ) ) {
1 ✔
5634
                                                $match = true; break;
1 ✔
5635
                                        }
5636
                                }
5637

5638
                                if( !$match ) {
1 ✔
5639
                                        return false;
1 ✔
5640
                                }
5641

5642
                                continue;
1 ✔
5643
                        }
5644

5645
                        $len = mb_strlen( $entry, $encoding );
1 ✔
5646
                        $i = 0;
1 ✔
5647

5648
                        foreach( $needles as $str )
1 ✔
5649
                        {
5650
                                if( $str === '' || ( $lengths[$i] <= $len && $fcn( $entry, $str, -$lengths[$i], $encoding ) !== false ) ) {
1 ✔
5651
                                        $match = true; break;
1 ✔
5652
                                }
5653

5654
                                $i++;
1 ✔
5655
                        }
5656

5657
                        if( !$match ) {
1 ✔
5658
                                return false;
1 ✔
5659
                        }
5660
                }
5661

5662
                return true;
1 ✔
5663
        }
5664

5665

5666
        /**
5667
         * Returns an element by key and casts it to string if possible.
5668
         *
5669
         * Examples:
5670
         *  Map::from( ['a' => true] )->string( 'a' );
5671
         *  Map::from( ['a' => 1] )->string( 'a' );
5672
         *  Map::from( ['a' => 1.1] )->string( 'a' );
5673
         *  Map::from( ['a' => 'abc'] )->string( 'a' );
5674
         *  Map::from( ['a' => ['b' => ['c' => 'yes']]] )->string( 'a/b/c' );
5675
         *  Map::from( [] )->string( 'a', function( $val ) { return 'no'; } );
5676
         *
5677
         *  Map::from( [] )->string( 'b' );
5678
         *  Map::from( ['b' => ''] )->string( 'b' );
5679
         *  Map::from( ['b' => null] )->string( 'b' );
5680
         *  Map::from( ['b' => [true]] )->string( 'b' );
5681
         *  Map::from( ['b' => resource] )->string( 'b' );
5682
         *  Map::from( ['b' => new \stdClass] )->string( 'b' );
5683
         *
5684
         *  Map::from( [] )->string( 'c', new \Exception( 'error' ) );
5685
         *
5686
         * Results:
5687
         * The first six examples will return the value as string while the 9th to 12th
5688
         * example returns an empty string. The last example will throw an exception.
5689
         *
5690
         * This does also work for multi-dimensional arrays by passing the keys
5691
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5692
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5693
         * public properties of objects or objects implementing __isset() and __get() methods.
5694
         *
5695
         * @param int|string $key Key or path to the requested item
5696
         * @param \Closure|\Throwable|string $default Default value if key isn't found
5697
         * @return string Value from map or default value
5698
         */
5699
        public function string( int|string $key, \Closure|\Throwable|string $default = '' ) : string
5700
        {
5701
                if( $this->item( $key, $val ) && ( is_scalar( $val ) || $val === null ) ) {
4 ✔
5702
                        return (string) $val;
2 ✔
5703
                }
5704

5705
                return (string) $this->fallback( $default, isset( $val ), $val ?? null );
4 ✔
5706
        }
5707

5708

5709
        /**
5710
         * Converts all alphabetic characters in strings to lower case.
5711
         *
5712
         * Examples:
5713
         *  Map::from( ['My String'] )->strLower();
5714
         *  Map::from( ['Τάχιστη'] )->strLower();
5715
         *  Map::from( ['Äpfel', 'Birnen'] )->strLower( 'ISO-8859-1' );
5716
         *  Map::from( [123] )->strLower();
5717
         *  Map::from( [new stdClass] )->strLower();
5718
         *
5719
         * Results:
5720
         * The first example will return ["my string"], the second one ["τάχιστη"] and
5721
         * the third one ["äpfel", "birnen"]. The last two strings will be unchanged.
5722
         *
5723
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5724
         * @return self<int|string,mixed> Updated map for fluid interface
5725
         */
5726
        public function strLower( string $encoding = 'UTF-8' ) : self
5727
        {
5728
                foreach( $this->list() as &$entry )
1 ✔
5729
                {
5730
                        if( is_string( $entry ) ) {
1 ✔
5731
                                $entry = mb_strtolower( $entry, $encoding );
1 ✔
5732
                        }
5733
                }
5734

5735
                return $this;
1 ✔
5736
        }
5737

5738

5739
        /**
5740
         * Replaces all occurrences of the search string with the replacement string.
5741
         *
5742
         * Examples:
5743
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( '.com', '.de' );
5744
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], '.de' );
5745
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.de'] );
5746
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.fr', '.de'] );
5747
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( ['.com', '.co'], ['.co', '.de', '.fr'] );
5748
         * Map::from( ['google.com', 'aimeos.com', 123] )->strReplace( '.com', '.de' );
5749
         * Map::from( ['GOOGLE.COM', 'AIMEOS.COM'] )->strReplace( '.com', '.de', false );
5750
         *
5751
         * Restults:
5752
         * ['google.de', 'aimeos.de']
5753
         * ['google.de', 'aimeos.de']
5754
         * ['google.de', 'aimeos']
5755
         * ['google.fr', 'aimeos.de']
5756
         * ['google.de', 'aimeos.de']
5757
         * ['google.de', 'aimeos.de', 123]
5758
         * ['GOOGLE.de', 'AIMEOS.de']
5759
         *
5760
         * If you use an array of strings for search or search/replacement, the order of
5761
         * the strings matters! Each search string found is replaced by the corresponding
5762
         * replacement string at the same position.
5763
         *
5764
         * In case of array parameters and if the number of replacement strings is less
5765
         * than the number of search strings, the search strings with no corresponding
5766
         * replacement string are replaced with empty strings. Replacement strings with
5767
         * no corresponding search string are ignored.
5768
         *
5769
         * An array parameter for the replacements is only allowed if the search parameter
5770
         * is an array of strings too!
5771
         *
5772
         * Because the method replaces from left to right, it might replace a previously
5773
         * inserted value when doing multiple replacements. Entries which are non-string
5774
         * values are left untouched.
5775
         *
5776
         * @param array<string>|string $search String or list of strings to search for
5777
         * @param array<string>|string $replace String or list of strings of replacement strings
5778
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5779
         * @return self<int|string,mixed> Updated map for fluid interface
5780
         */
5781
        public function strReplace( array|string $search, array|string $replace, bool $case = true ) : self
5782
        {
5783
                $fcn = $case ? 'str_replace' : 'str_ireplace';
1 ✔
5784

5785
                foreach( $this->list() as &$entry )
1 ✔
5786
                {
5787
                        if( is_string( $entry ) ) {
1 ✔
5788
                                $entry = $fcn( $search, $replace, $entry );
1 ✔
5789
                        }
5790
                }
5791

5792
                return $this;
1 ✔
5793
        }
5794

5795

5796
        /**
5797
         * Tests if at least one of the entries starts with at least one of the passed strings.
5798
         *
5799
         * Examples:
5800
         *  Map::from( ['abc'] )->strStarts( '' );
5801
         *  Map::from( ['abc'] )->strStarts( 'a' );
5802
         *  Map::from( ['abc'] )->strStarts( 'ab' );
5803
         *  Map::from( ['abc'] )->strStarts( ['a', 'b'] );
5804
         *  Map::from( ['abc'] )->strStarts( 'ab', true, 'ASCII' );
5805
         *  Map::from( ['abc'] )->strStarts( 'A', false );
5806
         *  Map::from( ['abc'] )->strStarts( 'b' );
5807
         *  Map::from( ['abc'] )->strStarts( 'bc' );
5808
         *  Map::from( ['abc'] )->strStarts( ['b', 'c'] );
5809
         *  Map::from( ['abc'] )->strStarts( 'bc', true, 'ASCII' );
5810
         *  Map::from( ['abc'] )->strStarts( 'A' );
5811
         *
5812
         * Results:
5813
         * The first six examples will return TRUE while the last five will return FALSE.
5814
         *
5815
         * @param array<string>|string $value The string or strings to search for in each entry
5816
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5817
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5818
         * @return bool TRUE if at least one of the entries starts with one of the strings, FALSE if not
5819
         */
5820
        public function strStarts( array|string $value, bool $case = true, string $encoding = 'UTF-8' ) : bool
5821
        {
5822
                $native = $case && $encoding === 'UTF-8';
1 ✔
5823
                $fcn = $case ? 'mb_strpos' : 'mb_stripos';
1 ✔
5824
                $needles = [];
1 ✔
5825

5826
                foreach( (array) $value as $str ) {
1 ✔
5827
                        $needles[] = (string) $str;
1 ✔
5828
                }
5829

5830
                foreach( $this->list() as $entry )
1 ✔
5831
                {
5832
                        if( !is_scalar( $entry ) && !$entry instanceof \Stringable ) {
1 ✔
5833
                                continue;
×
5834
                        }
5835

5836
                        $entry = (string) $entry;
1 ✔
5837

5838
                        foreach( $needles as $str )
1 ✔
5839
                        {
5840
                                if( $native ? str_starts_with( $entry, $str ) : ( $str === '' || $fcn( $entry, $str, 0, $encoding ) === 0 ) ) {
1 ✔
5841
                                        return true;
1 ✔
5842
                                }
5843
                        }
5844
                }
5845

5846
                return false;
1 ✔
5847
        }
5848

5849

5850
        /**
5851
         * Tests if all of the entries starts with one of the passed strings.
5852
         *
5853
         * Examples:
5854
         *  Map::from( ['abc', 'def'] )->strStartsAll( '' );
5855
         *  Map::from( ['abc', 'acb'] )->strStartsAll( 'a' );
5856
         *  Map::from( ['abc', 'aba'] )->strStartsAll( 'ab' );
5857
         *  Map::from( ['abc', 'def'] )->strStartsAll( ['a', 'd'] );
5858
         *  Map::from( ['abc', 'acf'] )->strStartsAll( 'a', true, 'ASCII' );
5859
         *  Map::from( ['abc', 'Acf'] )->strStartsAll( 'a', false );
5860
         *  Map::from( ['abc', 'def'] )->strStartsAll( 'd' );
5861
         *  Map::from( ['abc', 'bca'] )->strStartsAll( 'ab' );
5862
         *  Map::from( ['abc', 'bac'] )->strStartsAll( ['a', 'c'] );
5863
         *  Map::from( ['abc', 'cab'] )->strStartsAll( 'ab', true, 'ASCII' );
5864
         *  Map::from( ['abc', 'Acf'] )->strStartsAll( 'a' );
5865
         *
5866
         * Results:
5867
         * The first six examples will return TRUE while the last five will return FALSE.
5868
         *
5869
         * @param array<string>|string $value The string or strings to search for in each entry
5870
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
5871
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5872
         * @return bool TRUE if all of the entries start with at least one of the strings, FALSE if not
5873
         */
5874
        public function strStartsAll( array|string $value, bool $case = true, string $encoding = 'UTF-8' ) : bool
5875
        {
5876
                $native = $case && $encoding === 'UTF-8';
1 ✔
5877
                $fcn = $case ? 'mb_strpos' : 'mb_stripos';
1 ✔
5878
                $needles = [];
1 ✔
5879

5880
                foreach( (array) $value as $str ) {
1 ✔
5881
                        $needles[] = (string) $str;
1 ✔
5882
                }
5883

5884
                foreach( $this->list() as $entry )
1 ✔
5885
                {
5886
                        if( !is_scalar( $entry ) && !$entry instanceof \Stringable ) {
1 ✔
5887
                                return false;
×
5888
                        }
5889

5890
                        $entry = (string) $entry;
1 ✔
5891
                        $match = false;
1 ✔
5892

5893
                        foreach( $needles as $str )
1 ✔
5894
                        {
5895
                                if( $native ? str_starts_with( $entry, $str ) : ( $str === '' || $fcn( $entry, $str, 0, $encoding ) === 0 ) ) {
1 ✔
5896
                                        $match = true; break;
1 ✔
5897
                                }
5898
                        }
5899

5900
                        if( !$match ) {
1 ✔
5901
                                return false;
1 ✔
5902
                        }
5903
                }
5904

5905
                return true;
1 ✔
5906
        }
5907

5908

5909
        /**
5910
         * Converts all alphabetic characters in strings to upper case.
5911
         *
5912
         * Examples:
5913
         *  Map::from( ['My String'] )->strUpper();
5914
         *  Map::from( ['τάχιστη'] )->strUpper();
5915
         *  Map::from( ['äpfel', 'birnen'] )->strUpper( 'ISO-8859-1' );
5916
         *  Map::from( [123] )->strUpper();
5917
         *  Map::from( [new stdClass] )->strUpper();
5918
         *
5919
         * Results:
5920
         * The first example will return ["MY STRING"], the second one ["ΤΆΧΙΣΤΗ"] and
5921
         * the third one ["ÄPFEL", "BIRNEN"]. The last two strings will be unchanged.
5922
         *
5923
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5924
         * @return self<int|string,mixed> Updated map for fluid interface
5925
         */
5926
        public function strUpper( string $encoding = 'UTF-8' ) :self
5927
        {
5928
                foreach( $this->list() as &$entry )
1 ✔
5929
                {
5930
                        if( is_string( $entry ) ) {
1 ✔
5931
                                $entry = mb_strtoupper( $entry, $encoding );
1 ✔
5932
                        }
5933
                }
5934

5935
                return $this;
1 ✔
5936
        }
5937

5938

5939
        /**
5940
         * Adds a suffix at the end of each map entry.
5941
         *
5942
         * By default, nested arrays are walked recursively so all entries at all levels are suffixed.
5943
         *
5944
         * Examples:
5945
         *  Map::from( ['a', 'b'] )->suffix( '-1' );
5946
         *  Map::from( ['a', ['b']] )->suffix( '-1' );
5947
         *  Map::from( ['a', ['b']] )->suffix( '-1', 1 );
5948
         *  Map::from( ['a', 'b'] )->suffix( function( $item, $key ) {
5949
         *      return '-' . ( ord( $item ) + ord( $key ) );
5950
         *  } );
5951
         *
5952
         * Results:
5953
         *  The first example returns ['a-1', 'b-1'] while the second one will return
5954
         *  ['a-1', ['b-1']]. In the third example, the depth is limited to the first
5955
         *  level only so it will return ['a-1', ['b']]. The forth example passing
5956
         *  the closure will return ['a-145', 'b-147'].
5957
         *
5958
         * The keys are preserved using this method.
5959
         *
5960
         * @param \Closure|string $suffix Suffix string or anonymous function with ($item, $key) as parameters
5961
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
5962
         * @return self<int|string,mixed> Updated map for fluid interface
5963
         */
5964
        public function suffix( \Closure|string $suffix, ?int $depth = null ) : self
5965
        {
5966
                $list = &$this->list();
1 ✔
5967
                $this->suffixRecursive( $list, $suffix, $depth ?? 0x7fffffff );
1 ✔
5968
                return $this;
1 ✔
5969
        }
5970

5971

5972
        /**
5973
         * Returns the sum of all integer and float values in the map.
5974
         *
5975
         * Examples:
5976
         *  Map::from( [1, 3, 5] )->sum();
5977
         *  Map::from( [1, 'sum', 5] )->sum();
5978
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->sum( 'p' );
5979
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( 'i/p' );
5980
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( fn( $val, $key ) => $val['i']['p'] ?? null )
5981
         *  Map::from( [30, 50, 10] )->sum( fn( $val, $key ) => $val < 50 ? $val : null )
5982
         *
5983
         * Results:
5984
         * The first line will return "9", the second one "6", the third one "90"
5985
         * the forth/fifth "80" and the last one "40".
5986
         *
5987
         * Non-numeric values will be removed before calculation.
5988
         *
5989
         * This does also work for multi-dimensional arrays by passing the keys
5990
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5991
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5992
         * public properties of objects or objects implementing __isset() and __get() methods.
5993
         *
5994
         * @param \Closure|string|null $col Closure, key or path to the values in the nested array or object to sum up
5995
         * @return float Sum of all elements or 0 if there are no elements in the map
5996
         */
5997
        public function sum( \Closure|string|null $col = null ) : float
5998
        {
5999
                $sum = 0;
3 ✔
6000

6001
                if( $col instanceof \Closure )
3 ✔
6002
                {
6003
                        foreach( $this->list() as $key => $item )
1 ✔
6004
                        {
6005
                                if( is_numeric( $val = $col( $item, $key ) ) ) {
1 ✔
6006
                                        $sum += $val;
1 ✔
6007
                                }
6008
                        }
6009
                }
6010
                else
6011
                {
6012
                        $parts = $col ? explode( $this->sep, (string) $col ) : [];
2 ✔
6013

6014
                        foreach( $this->list() as $item )
2 ✔
6015
                        {
6016
                                if( $parts === [] ) {
2 ✔
6017
                                        $val = $item;
1 ✔
6018
                                } elseif( is_array( $item ) ) {
1 ✔
6019
                                        $val = $this->arrayVal( $item, $parts );
1 ✔
6020
                                } else {
6021
                                        $val = $this->val( $item, $parts );
×
6022
                                }
6023

6024
                                if( is_numeric( $val ) ) {
2 ✔
6025
                                        $sum += $val;
2 ✔
6026
                                }
6027
                        }
6028
                }
6029

6030
                return $sum;
3 ✔
6031
        }
6032

6033

6034
        /**
6035
         * Returns a new map with the given number of items.
6036
         *
6037
         * The keys of the items returned in the new map are the same as in the original one.
6038
         *
6039
         * Examples:
6040
         *  Map::from( [1, 2, 3, 4] )->take( 2 );
6041
         *  Map::from( [1, 2, 3, 4] )->take( 2, 1 );
6042
         *  Map::from( [1, 2, 3, 4] )->take( 2, 2 );
6043
         *  Map::from( [1, 2, 3, 4] )->take( 2, function( $item, $key ) {
6044
         *      return $item < 2;
6045
         *  } );
6046
         *
6047
         * Results:
6048
         *  [0 => 1, 1 => 2]
6049
         *  [1 => 2, 2 => 3]
6050
         *  [2 => 3, 3 => 4]
6051
         *  [1 => 2, 2 => 3]
6052
         *
6053
         * The keys of the items returned in the new map are the same as in the original one.
6054
         *
6055
         * @param int $size Non-negative number of items to return
6056
         * @param \Closure|int $offset Non-negative number of items to skip or function($item, $key) returning true for skipped items
6057
         * @return self<int|string,mixed> New map
6058
         * @throws \InvalidArgumentException If the size or offset is negative
6059
         */
6060
        public function take( int $size, \Closure|int $offset = 0 ) : self
6061
        {
6062
                if( $size < 0 ) {
5 ✔
6063
                        throw new \InvalidArgumentException( 'Size must be greater than or equal to zero' );
1 ✔
6064
                }
6065

6066
                if( $size === 0 ) {
4 ✔
NEW
6067
                        return new static();
×
6068
                }
6069

6070
                $list = $this->list();
4 ✔
6071

6072
                if( $offset instanceof \Closure ) {
4 ✔
6073
                        return new static( array_slice( $list, $this->until( $list, $offset ), $size, true ) );
1 ✔
6074
                }
6075

6076
                if( $offset < 0 ) {
3 ✔
6077
                        throw new \InvalidArgumentException( 'Offset must be greater than or equal to zero' );
1 ✔
6078
                }
6079

6080
                return new static( array_slice( $list, (int) $offset, $size, true ) );
2 ✔
6081
        }
6082

6083

6084
        /**
6085
         * Passes a clone of the map to the given callback.
6086
         *
6087
         * Use it to "tap" into a chain of methods to check the state between two
6088
         * method calls. The original map is not altered by anything done in the
6089
         * callback.
6090
         *
6091
         * Examples:
6092
         *  Map::from( [3, 2, 1] )->rsort()->tap( function( $map ) {
6093
         *    print_r( $map->remove( 0 )->toArray() );
6094
         *  } )->first();
6095
         *
6096
         * Results:
6097
         * It will sort the list in reverse order (`[1, 2, 3]`) while keeping the keys,
6098
         * then prints the items without the first (`[2, 3]`) in the function passed
6099
         * to `tap()` and returns the first item ("1") at the end.
6100
         *
6101
         * @param callable $callback Function receiving ($map) parameter
6102
         * @return self<int|string,mixed> Same map for fluid interface
6103
         */
6104
        public function tap( callable $callback ) : self
6105
        {
6106
                $callback( clone $this );
1 ✔
6107
                return $this;
1 ✔
6108
        }
6109

6110

6111
        /**
6112
         * Returns the elements as a plain array.
6113
         *
6114
         * @return array<int|string,mixed> Plain array
6115
         */
6116
        public function to() : array
6117
        {
6118
                return $this->list = $this->array( $this->list );
1 ✔
6119
        }
6120

6121

6122
        /**
6123
         * Returns the elements as a plain array.
6124
         *
6125
         * @return array<int|string,mixed> Plain array
6126
         */
6127
        public function toArray() : array
6128
        {
6129
                return $this->list = $this->array( $this->list );
290 ✔
6130
        }
6131

6132

6133
        /**
6134
         * Returns the elements encoded as JSON string.
6135
         *
6136
         * There are several options available to modify the JSON output:
6137
         * {@link https://www.php.net/manual/en/function.json-encode.php}
6138
         * The parameter can be a single JSON_* constant or a bitmask of several
6139
         * constants combine by bitwise OR (|), e.g.:
6140
         *
6141
         *  JSON_FORCE_OBJECT|JSON_HEX_QUOT
6142
         *
6143
         * @param int $options Combination of JSON_* constants
6144
         * @return string|null Array encoded as JSON string or NULL on failure
6145
         * @throws \JsonException If JSON_THROW_ON_ERROR is part of the passed options and the map contains unsupported values
6146
         */
6147
        public function toJson( int $options = 0 ) : ?string
6148
        {
6149
                $result = json_encode( $this->list(), $options );
3 ✔
6150
                return $result !== false ? $result : null;
2 ✔
6151
        }
6152

6153

6154
        /**
6155
         * Reverses the element order in a copy of the map (alias).
6156
         *
6157
         * This method is an alias for reversed(). For performance reasons, reversed() should be
6158
         * preferred because it uses one method call less than toReversed().
6159
         *
6160
         * @return self<int|string,mixed> New map with a reversed copy of the elements
6161
         * @see reversed() - Underlying method with same parameters and return value but better performance
6162
         */
6163
        public function toReversed() : self
6164
        {
6165
                return $this->reversed();
1 ✔
6166
        }
6167

6168

6169
        /**
6170
         * Sorts the elements in a copy of the map using new keys (alias).
6171
         *
6172
         * This method is an alias for sorted(). For performance reasons, sorted() should be
6173
         * preferred because it uses one method call less than toSorted().
6174
         *
6175
         * @param int $options Sort options for PHP sort()
6176
         * @return self<int|string,mixed> New map with a sorted copy of the elements
6177
         * @see sorted() - Underlying method with same parameters and return value but better performance
6178
         */
6179
        public function toSorted( int $options = SORT_REGULAR ) : self
6180
        {
6181
                return $this->sorted( $options );
1 ✔
6182
        }
6183

6184

6185
        /**
6186
         * Creates a HTTP query string from the map elements.
6187
         *
6188
         * Examples:
6189
         *  Map::from( ['a' => 1, 'b' => 2] )->toUrl();
6190
         *  Map::from( ['a' => ['b' => 'abc', 'c' => 'def'], 'd' => 123] )->toUrl();
6191
         *
6192
         * Results:
6193
         *  a=1&b=2
6194
         *  a%5Bb%5D=abc&a%5Bc%5D=def&d=123
6195
         *
6196
         * @return string Parameter string for GET requests
6197
         */
6198
        public function toUrl() : string
6199
        {
6200
                return http_build_query( $this->list(), '', '&', PHP_QUERY_RFC3986 );
2 ✔
6201
        }
6202

6203

6204
        /**
6205
         * Creates new key/value pairs using the passed function and returns a new map for the result.
6206
         *
6207
         * Examples:
6208
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
6209
         *      return [$key . '-2' => $value * 2];
6210
         *  } );
6211
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
6212
         *      return [$key => $value * 2, $key . $key => $value * 4];
6213
         *  } );
6214
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
6215
         *      return $key < 'b' ? [$key => $value * 2] : null;
6216
         *  } );
6217
         *  Map::from( ['la' => 2, 'le' => 4, 'li' => 6] )->transform( function( $value, $key ) {
6218
         *      return [$key[0] => $value * 2];
6219
         *  } );
6220
         *
6221
         * Results:
6222
         *  ['a-2' => 4, 'b-2' => 8]
6223
         *  ['a' => 4, 'aa' => 8, 'b' => 8, 'bb' => 16]
6224
         *  ['a' => 4]
6225
         *  ['l' => 12]
6226
         *
6227
         * If a key is returned twice, the last value will overwrite previous values.
6228
         *
6229
         * @param callable $callback Function with (value, key) parameters and returns an array of new key/value pair(s)
6230
         * @return self<int|string,mixed> New map with the new key/value pairs
6231
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
6232
         * @see rekey() - Changes the keys according to the passed function
6233
         */
6234
        public function transform( callable $callback ) : self
6235
        {
6236
                $result = [];
7 ✔
6237

6238
                foreach( $this->list() as $key => $value )
7 ✔
6239
                {
6240
                        foreach( $this->array( $callback( $value, $key ) ) as $newkey => $newval ) {
7 ✔
6241
                                $result[$newkey] = $newval;
7 ✔
6242
                        }
6243
                }
6244

6245
                return new static( $result );
7 ✔
6246
        }
6247

6248

6249
        /**
6250
         * Exchanges rows and columns for a two dimensional map.
6251
         *
6252
         * Examples:
6253
         *  Map::from( [
6254
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
6255
         *    ['name' => 'B', 2020 => 300, 2021 => 200, 2022 => 100],
6256
         *    ['name' => 'C', 2020 => 400, 2021 => 300, 2022 => 200],
6257
         *  ] )->transpose();
6258
         *
6259
         *  Map::from( [
6260
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
6261
         *    ['name' => 'B', 2020 => 300, 2021 => 200],
6262
         *    ['name' => 'C', 2020 => 400]
6263
         *  ] );
6264
         *
6265
         * Results:
6266
         *  [
6267
         *    'name' => ['A', 'B', 'C'],
6268
         *    2020 => [200, 300, 400],
6269
         *    2021 => [100, 200, 300],
6270
         *    2022 => [50, 100, 200]
6271
         *  ]
6272
         *
6273
         *  [
6274
         *    'name' => ['A', 'B', 'C'],
6275
         *    2020 => [200, 300, 400],
6276
         *    2021 => [100, 200],
6277
         *    2022 => [50]
6278
         *  ]
6279
         *
6280
         * Column keys are collected from all rows. If a row doesn't contain a
6281
         * column, the value is skipped in the transposed result.
6282
         *
6283
         * @return self<int|string,mixed> New map
6284
         */
6285
        public function transpose() : self
6286
        {
6287
                $result = [];
5 ✔
6288

6289
                foreach( $this->list() as $row )
5 ✔
6290
                {
6291
                        if( $row instanceof \Aimeos\Map ) {
5 ✔
6292
                                $row = $row->toArray();
1 ✔
6293
                        } elseif( $row instanceof \Traversable ) {
4 ✔
6294
                                $row = iterator_to_array( $row, true );
1 ✔
6295
                        } elseif( !is_array( $row ) ) {
3 ✔
6296
                                $row = is_object( $row ) ? get_object_vars( $row ) : (array) $row;
×
6297
                        }
6298

6299
                        foreach( $row as $key => $col ) {
5 ✔
6300
                                $result[$key][] = $col;
5 ✔
6301
                        }
6302
                }
6303

6304
                return new static( $result );
5 ✔
6305
        }
6306

6307

6308
        /**
6309
         * Traverses trees of nested items passing each item to the callback.
6310
         *
6311
         * This does work for nested arrays and objects with public properties or
6312
         * objects implementing __isset() and __get() methods. To build trees
6313
         * of nested items, use the tree() method.
6314
         *
6315
         * Examples:
6316
         *   Map::from( [[
6317
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
6318
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
6319
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
6320
         *     ]
6321
         *   ]] )->traverse();
6322
         *
6323
         *   Map::from( [[
6324
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
6325
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
6326
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
6327
         *     ]
6328
         *   ]] )->traverse( function( $entry, $key, $level, $parent ) {
6329
         *     return str_repeat( '-', $level ) . '- ' . $entry['name'];
6330
         *   } );
6331
         *
6332
         *   Map::from( [[
6333
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
6334
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
6335
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
6336
         *     ]
6337
         *   ]] )->traverse( function( &$entry, $key, $level, $parent ) {
6338
         *     $entry['path'] = isset( $parent['path'] ) ? $parent['path'] . '/' . $entry['name'] : $entry['name'];
6339
         *     return $entry;
6340
         *   } );
6341
         *
6342
         *   Map::from( [[
6343
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [
6344
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []]
6345
         *     ]
6346
         *   ]] )->traverse( null, 'nodes' );
6347
         *
6348
         * Results:
6349
         *   [
6350
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...]],
6351
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
6352
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []],
6353
         *   ]
6354
         *
6355
         *   ['- n1', '-- n2', '-- n3']
6356
         *
6357
         *   [
6358
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...], 'path' => 'n1'],
6359
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => [], 'path' => 'n1/n2'],
6360
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => [], 'path' => 'n1/n3'],
6361
         *   ]
6362
         *
6363
         *   [
6364
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [...]],
6365
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []],
6366
         *   ]
6367
         *
6368
         * @param callable|null $callback Callback with (entry, key, level, $parent) arguments, returns the entry added to result
6369
         * @param string $nestKey Key to the children of each item
6370
         * @return self<int|string,mixed> New map with all items as flat list
6371
         */
6372
        public function traverse( ?callable $callback = null, string $nestKey = 'children' ) : self
6373
        {
6374
                $result = [];
5 ✔
6375
                $this->visit( $this->list(), $result, 0, $callback, $nestKey );
5 ✔
6376

6377
                return map( $result );
5 ✔
6378
        }
6379

6380

6381
        /**
6382
         * Creates a tree structure from the list items.
6383
         *
6384
         * Use this method to rebuild trees e.g. from database records. To traverse
6385
         * trees, use the traverse() method.
6386
         *
6387
         * Examples:
6388
         *  Map::from( [
6389
         *    ['id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1'],
6390
         *    ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2'],
6391
         *    ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3'],
6392
         *    ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4'],
6393
         *    ['id' => 5, 'pid' => 4, 'lvl' => 2, 'name' => 'n5'],
6394
         *    ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6'],
6395
         *  ] )->tree( 'id', 'pid' );
6396
         *
6397
         * Results:
6398
         *   [1 => [
6399
         *     'id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1', 'children' => [
6400
         *       2 => ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2', 'children' => [
6401
         *         3 => ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3', 'children' => []]
6402
         *       ]],
6403
         *       4 => ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4', 'children' => [
6404
         *         5 => ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5', 'children' => []]
6405
         *       ]],
6406
         *       6 => ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6', 'children' => []]
6407
         *     ]
6408
         *   ]]
6409
         *
6410
         * Items can be in any order as long as all parent nodes are part of the map.
6411
         *
6412
         * @param string $idKey Name of the key with the unique ID of the node
6413
         * @param string $parentKey Name of the key with the ID of the parent node
6414
         * @param string $nestKey Name of the key with will contain the children of the node
6415
         * @return self<int|string,mixed> New map with one or more root tree nodes
6416
         * @throws \UnexpectedValueException If a node isn't an array, an ID isn't a scalar value, an ID is used twice, a parent is missing or nodes reference themselves as parent
6417
         */
6418
        public function tree( string $idKey, string $parentKey, string $nestKey = 'children' ) : self
6419
        {
6420
                $this->list();
8 ✔
6421
                $trees = $refs = $parents = [];
8 ✔
6422

6423
                foreach( $this->list as &$node )
8 ✔
6424
                {
6425
                        if( !is_array( $node ) && !$node instanceof \ArrayAccess ) {
8 ✔
6426
                                throw new \UnexpectedValueException( 'Nodes must be arrays or objects implementing ArrayAccess but "' . get_debug_type( $node ) . '" given' );
1 ✔
6427
                        }
6428

6429
                        $id = $node[$idKey] ?? null;
7 ✔
6430
                        $parent = $node[$parentKey] ?? null;
7 ✔
6431

6432
                        if( !is_scalar( $id ) && $id !== null || !is_scalar( $parent ) && $parent !== null ) {
7 ✔
6433
                                throw new \UnexpectedValueException( 'Node IDs and parent IDs must be scalar values or NULL' );
1 ✔
6434
                        }
6435

6436
                        $id = $this->treeId( $id );
6 ✔
6437
                        $parent = $this->treeId( $parent );
6 ✔
6438

6439
                        if( $parent && (string) $parent === (string) $id ) {
6 ✔
6440
                                throw new \UnexpectedValueException( 'Node with ID "' . $id . '" references itself as parent' );
1 ✔
6441
                        }
6442

6443
                        if( array_key_exists( $id, $refs ) ) {
5 ✔
6444
                                throw new \UnexpectedValueException( 'Node with ID "' . $id . '" is used more than once' );
1 ✔
6445
                        }
6446

6447
                        $node[$nestKey] = [];
5 ✔
6448
                        $refs[$id] = &$node;
5 ✔
6449
                        $parents[$id] = $parent;
5 ✔
6450
                }
6451
                unset( $node );
4 ✔
6452

6453
                foreach( $parents as $id => $parent )
4 ✔
6454
                {
6455
                        if( $parent && !array_key_exists( $parent, $refs ) ) {
4 ✔
6456
                                throw new \UnexpectedValueException( 'Parent node with ID "' . $parent . '" for node "' . $id . '" is missing' );
1 ✔
6457
                        }
6458
                }
6459

6460
                $checked = [];
3 ✔
6461

6462
                foreach( $parents as $id => $parent )
3 ✔
6463
                {
6464
                        if( isset( $checked[$id] ) ) {
3 ✔
6465
                                continue;
1 ✔
6466
                        }
6467

6468
                        $seen = [$id => true];
3 ✔
6469
                        $path = [$id];
3 ✔
6470

6471
                        while( $parent )
3 ✔
6472
                        {
6473
                                if( isset( $seen[$parent] ) ) {
3 ✔
6474
                                        throw new \UnexpectedValueException( 'Node with ID "' . $id . '" has a cyclic parent reference' );
1 ✔
6475
                                }
6476

6477
                                if( isset( $checked[$parent] ) ) {
3 ✔
6478
                                        break;
1 ✔
6479
                                }
6480

6481
                                $seen[$parent] = true;
2 ✔
6482
                                $path[] = $parent;
2 ✔
6483
                                $parent = $parents[$parent];
2 ✔
6484
                        }
6485

6486
                        foreach( $path as $nodeid ) {
2 ✔
6487
                                $checked[$nodeid] = true;
2 ✔
6488
                        }
6489
                }
6490

6491
                foreach( $parents as $id => $parent )
2 ✔
6492
                {
6493
                        if( $parent ) {
2 ✔
6494
                                $refs[$parent][$nestKey][$id] = &$refs[$id];
2 ✔
6495
                        } else {
6496
                                $trees[$id] = &$refs[$id];
2 ✔
6497
                        }
6498
                }
6499

6500
                return map( $trees );
2 ✔
6501
        }
6502

6503

6504
        /**
6505
         * Removes the passed characters from the left/right of all strings.
6506
         *
6507
         * Examples:
6508
         *  Map::from( [" abc\n", "\tcde\r\n"] )->trim();
6509
         *  Map::from( ["a b c", "cbax"] )->trim( 'abc' );
6510
         *
6511
         * Results:
6512
         * The first example will return ["abc", "cde"] while the second one will return [" b ", "x"].
6513
         *
6514
         * @param string $chars List of characters to trim
6515
         * @return self<int|string,mixed> Updated map for fluid interface
6516
         */
6517
        public function trim( string $chars = " \n\r\t\v\x00" ) : self
6518
        {
6519
                foreach( $this->list() as &$entry )
1 ✔
6520
                {
6521
                        if( is_string( $entry ) ) {
1 ✔
6522
                                $entry = trim( $entry, $chars );
1 ✔
6523
                        }
6524
                }
6525

6526
                return $this;
1 ✔
6527
        }
6528

6529

6530
        /**
6531
         * Sorts all elements using a callback and maintains the key association.
6532
         *
6533
         * The given callback will be used to compare the values. The callback must accept
6534
         * two parameters (item A and B) and must return -1 if item A is smaller than
6535
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
6536
         * method name and an anonymous function can be passed.
6537
         *
6538
         * Examples:
6539
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( 'strcasecmp' );
6540
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( function( $itemA, $itemB ) {
6541
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
6542
         *  } );
6543
         *
6544
         * Results:
6545
         *  ['b' => 'a', 'a' => 'B']
6546
         *  ['b' => 'a', 'a' => 'B']
6547
         *
6548
         * The keys are preserved using this method and no new map is created.
6549
         *
6550
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
6551
         * @return self<int|string,mixed> Updated map for fluid interface
6552
         */
6553
        public function uasort( callable $callback ) : self
6554
        {
6555
                uasort( $this->list(), $callback );
2 ✔
6556
                return $this;
2 ✔
6557
        }
6558

6559

6560
        /**
6561
         * Sorts all elements using a callback and maintains the key association.
6562
         *
6563
         * The given callback will be used to compare the values. The callback must accept
6564
         * two parameters (item A and B) and must return -1 if item A is smaller than
6565
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
6566
         * method name and an anonymous function can be passed.
6567
         *
6568
         * Examples:
6569
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( 'strcasecmp' );
6570
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( function( $itemA, $itemB ) {
6571
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
6572
         *  } );
6573
         *
6574
         * Results:
6575
         *  ['b' => 'a', 'a' => 'B']
6576
         *  ['b' => 'a', 'a' => 'B']
6577
         *
6578
         * The keys are preserved using this method and a new map is created.
6579
         *
6580
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
6581
         * @return self<int|string,mixed> New map with sorted elements
6582
         */
6583
        public function uasorted( callable $callback ) : self
6584
        {
6585
                return ( clone $this )->uasort( $callback );
1 ✔
6586
        }
6587

6588

6589
        /**
6590
         * Sorts the map elements by their keys using a callback.
6591
         *
6592
         * The given callback will be used to compare the keys. The callback must accept
6593
         * two parameters (key A and B) and must return -1 if key A is smaller than
6594
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
6595
         * method name and an anonymous function can be passed.
6596
         *
6597
         * Examples:
6598
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( 'strcasecmp' );
6599
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( function( $keyA, $keyB ) {
6600
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
6601
         *  } );
6602
         *
6603
         * Results:
6604
         *  ['a' => 'b', 'B' => 'a']
6605
         *  ['a' => 'b', 'B' => 'a']
6606
         *
6607
         * The keys are preserved using this method and no new map is created.
6608
         *
6609
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
6610
         * @return self<int|string,mixed> Updated map for fluid interface
6611
         */
6612
        public function uksort( callable $callback ) : self
6613
        {
6614
                uksort( $this->list(), $callback );
2 ✔
6615
                return $this;
2 ✔
6616
        }
6617

6618

6619
        /**
6620
         * Sorts a copy of the map elements by their keys using a callback.
6621
         *
6622
         * The given callback will be used to compare the keys. The callback must accept
6623
         * two parameters (key A and B) and must return -1 if key A is smaller than
6624
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
6625
         * method name and an anonymous function can be passed.
6626
         *
6627
         * Examples:
6628
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( 'strcasecmp' );
6629
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( function( $keyA, $keyB ) {
6630
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
6631
         *  } );
6632
         *
6633
         * Results:
6634
         *  ['a' => 'b', 'B' => 'a']
6635
         *  ['a' => 'b', 'B' => 'a']
6636
         *
6637
         * The keys are preserved using this method and a new map is created.
6638
         *
6639
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
6640
         * @return self<int|string,mixed> New map with sorted elements
6641
         */
6642
        public function uksorted( callable $callback ) : self
6643
        {
6644
                return ( clone $this )->uksort( $callback );
1 ✔
6645
        }
6646

6647

6648
        /**
6649
         * Unflattens the key path/value pairs into a multi-dimensional array.
6650
         *
6651
         * Examples:
6652
         *  Map::from( ['a/b/c' => 1, 'a/b/d' => 2, 'b/e' => 3] )->unflatten();
6653
         *  Map::from( ['a.b.c' => 1, 'a.b.d' => 2, 'b.e' => 3] )->sep( '.' )->unflatten();
6654
         *
6655
         * Results:
6656
         * ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]]
6657
         *
6658
         * This is the inverse method for flatten().
6659
         * If a scalar value and a nested path target the same key, later entries
6660
         * overwrite earlier entries.
6661
         *
6662
         * @return self<int|string,mixed> New map with multi-dimensional arrays
6663
         */
6664
        public function unflatten() : self
6665
        {
6666
                $result = [];
3 ✔
6667

6668
                foreach( $this->list() as $key => $value )
3 ✔
6669
                {
6670
                        $nested = &$result;
3 ✔
6671
                        $parts = explode( $this->sep, (string) $key );
3 ✔
6672
                        $last = count( $parts ) - 1;
3 ✔
6673

6674
                        for( $i = 0; $i < $last; $i++ )
3 ✔
6675
                        {
6676
                                $part = (string) $parts[$i];
3 ✔
6677

6678
                                if( !isset( $nested[$part] ) || !is_array( $nested[$part] ) ) {
3 ✔
6679
                                        $nested[$part] = [];
3 ✔
6680
                                }
6681

6682
                                $nested = &$nested[$part];
3 ✔
6683
                        }
6684

6685
                        $nested[(string) $parts[$last]] = $value;
3 ✔
6686
                        unset( $nested );
3 ✔
6687
                }
6688

6689
                return new static( $result );
3 ✔
6690
        }
6691

6692

6693
        /**
6694
         * Builds a union of the elements and the given elements without overwriting existing ones.
6695
         * Existing keys in the map will not be overwritten
6696
         *
6697
         * Examples:
6698
         *  Map::from( [0 => 'a', 1 => 'b'] )->union( [0 => 'c'] );
6699
         *  Map::from( ['a' => 1, 'b' => 2] )->union( ['c' => 1] );
6700
         *
6701
         * Results:
6702
         * The first example will result in [0 => 'a', 1 => 'b'] because the key 0
6703
         * isn't overwritten. In the second example, the result will be a combined
6704
         * list: ['a' => 1, 'b' => 2, 'c' => 1].
6705
         *
6706
         * If list entries should be overwritten,  please use merge() instead!
6707
         * The keys are preserved using this method and no new map is created.
6708
         *
6709
         * @param iterable<int|string,mixed> $elements List of elements
6710
         * @return self<int|string,mixed> Updated map for fluid interface
6711
         */
6712
        public function union( iterable $elements ) : self
6713
        {
6714
                $this->list = $this->list() + $this->array( $elements );
2 ✔
6715
                return $this;
2 ✔
6716
        }
6717

6718

6719
        /**
6720
         * Returns only unique elements from the map incl. their keys.
6721
         *
6722
         * Examples:
6723
         *  Map::from( [0 => 'a', 1 => 'b', 2 => 'b', 3 => 'c'] )->unique();
6724
         *  Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->unique( 'p' )
6725
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( 'i/p' )
6726
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( fn( $item, $key ) => $item['i']['p'] )
6727
         *
6728
         * Results:
6729
         * [0 => 'a', 1 => 'b', 3 => 'c']
6730
         * [['p' => 1], ['p' => 2]]
6731
         * [['i' => ['p' => '1']]]
6732
         * [['i' => ['p' => '1']]]
6733
         *
6734
         * Two elements are considered equal if comparing their string representions returns TRUE:
6735
         * (string) $elem1 === (string) $elem2
6736
         *
6737
         * Elements which are neither scalar values nor stringable objects are
6738
         * compared by their type and structure instead.
6739
         *
6740
         * The keys of the elements are only preserved in the new map if no key is passed.
6741
         *
6742
         * @param \Closure|string|null $col Key, path of the nested array or anonymous function with ($item, $key) parameters returning the value for comparison
6743
         * @return self<int|string,mixed> New map
6744
         */
6745
        public function unique( \Closure|string|null $col = null ) : self
6746
        {
6747
                if( $col === null ) {
6 ✔
6748
                        return new static( $this->dedup( $this->list() ) );
3 ✔
6749
                }
6750

6751
                $list = $this->list();
3 ✔
6752

6753
                return new static( array_intersect_key( $list, $this->dedupMappedKeys( $list, $col ) ) );
3 ✔
6754
        }
6755

6756

6757
        /**
6758
         * Pushes an element onto the beginning of the map without returning a new map.
6759
         *
6760
         * Examples:
6761
         *  Map::from( ['a', 'b'] )->unshift( 'd' );
6762
         *  Map::from( ['a', 'b'] )->unshift( 'd', 'first' );
6763
         *
6764
         * Results:
6765
         *  ['d', 'a', 'b']
6766
         *  ['first' => 'd', 0 => 'a', 1 => 'b']
6767
         *
6768
         * The keys of the elements are only preserved in the new map if no key is passed.
6769
         *
6770
         * Performance note:
6771
         * The bigger the list, the higher the performance impact because unshift()
6772
         * needs to create a new list and copies all existing elements to the new
6773
         * array. Usually, it's better to push() new entries at the end and reverse()
6774
         * the list afterwards:
6775
         *
6776
         *  $map->push( 'a' )->push( 'b' )->reverse();
6777
         * instead of
6778
         *  $map->unshift( 'a' )->unshift( 'b' );
6779
         *
6780
         * @param mixed $value Item to add at the beginning
6781
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
6782
         * @return self<int|string,mixed> Updated map for fluid interface
6783
         */
6784
        public function unshift( mixed $value, int|string|null $key = null ) : self
6785
        {
6786
                if( $key === null ) {
3 ✔
6787
                        array_unshift( $this->list(), $value );
2 ✔
6788
                } else {
6789
                        $this->list = [$key => $value] + $this->list();
1 ✔
6790
                }
6791

6792
                return $this;
3 ✔
6793
        }
6794

6795

6796
        /**
6797
         * Sorts all elements using a callback using new keys.
6798
         *
6799
         * The given callback will be used to compare the values. The callback must accept
6800
         * two parameters (item A and B) and must return -1 if item A is smaller than
6801
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
6802
         * method name and an anonymous function can be passed.
6803
         *
6804
         * Examples:
6805
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usort( 'strcasecmp' );
6806
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usort( function( $itemA, $itemB ) {
6807
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
6808
         *  } );
6809
         *
6810
         * Results:
6811
         *  [0 => 'a', 1 => 'B']
6812
         *  [0 => 'a', 1 => 'B']
6813
         *
6814
         * The keys aren't preserved and elements get a new index. No new map is created.
6815
         *
6816
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
6817
         * @return self<int|string,mixed> Updated map for fluid interface
6818
         */
6819
        public function usort( callable $callback ) : self
6820
        {
6821
                usort( $this->list(), $callback );
2 ✔
6822
                return $this;
2 ✔
6823
        }
6824

6825

6826
        /**
6827
         * Sorts a copy of all elements using a callback using new keys.
6828
         *
6829
         * The given callback will be used to compare the values. The callback must accept
6830
         * two parameters (item A and B) and must return -1 if item A is smaller than
6831
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
6832
         * method name and an anonymous function can be passed.
6833
         *
6834
         * Examples:
6835
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usorted( 'strcasecmp' );
6836
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usorted( function( $itemA, $itemB ) {
6837
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
6838
         *  } );
6839
         *
6840
         * Results:
6841
         *  [0 => 'a', 1 => 'B']
6842
         *  [0 => 'a', 1 => 'B']
6843
         *
6844
         * The keys aren't preserved, elements get a new index and a new map is created.
6845
         *
6846
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
6847
         * @return self<int|string,mixed> New map with sorted elements
6848
         */
6849
        public function usorted( callable $callback ) : self
6850
        {
6851
                return ( clone $this )->usort( $callback );
1 ✔
6852
        }
6853

6854

6855
        /**
6856
         * Resets the keys and return the values in a new map.
6857
         *
6858
         * Examples:
6859
         *  Map::from( ['x' => 'b', 2 => 'a', 'c'] )->values();
6860
         *
6861
         * Results:
6862
         * A new map with [0 => 'b', 1 => 'a', 2 => 'c'] as content
6863
         *
6864
         * @phpstan-return self<int,TValue>
6865
         * @return self<int|string,mixed> New map of the values
6866
         */
6867
        public function values() : self
6868
        {
6869
                return new static( array_values( $this->list() ) );
10 ✔
6870
        }
6871

6872

6873
        /**
6874
         * Applies the given callback to all elements.
6875
         *
6876
         * To change the values of the Map, specify the value parameter as reference
6877
         * (&$value). You can only change the values but not the keys nor the array
6878
         * structure.
6879
         *
6880
         * Examples:
6881
         *  Map::from( ['a', 'B', ['c', 'd'], 'e'] )->walk( function( &$value ) {
6882
         *    $value = strtoupper( $value );
6883
         *  } );
6884
         *  Map::from( [66 => 'B', 97 => 'a'] )->walk( function( $value, $key ) {
6885
         *    echo 'ASCII ' . $key . ' is ' . $value . "\n";
6886
         *  } );
6887
         *  Map::from( [1, 2, 3] )->walk( function( &$value, $key, $data ) {
6888
         *    $value = $data[$value] ?? $value;
6889
         *  }, [1 => 'one', 2 => 'two'] );
6890
         *
6891
         * Results:
6892
         * The first example will change the Map elements to:
6893
         *   ['A', 'B', ['C', 'D'], 'E']
6894
         * The output of the second one will be:
6895
         *  ASCII 66 is B
6896
         *  ASCII 97 is a
6897
         * The last example changes the Map elements to:
6898
         *  ['one', 'two', 3]
6899
         *
6900
         * By default, Map elements which are arrays will be traversed recursively.
6901
         * To iterate over the Map elements only, pass FALSE as third parameter.
6902
         *
6903
         * @param callable $callback Function with (item, key, data) parameters
6904
         * @param mixed $data Arbitrary data that will be passed to the callback as third parameter
6905
         * @param bool $recursive TRUE to traverse sub-arrays recursively (default), FALSE to iterate Map elements only
6906
         * @return self<int|string,mixed> Updated map for fluid interface
6907
         */
6908
        public function walk( callable $callback, mixed $data = null, bool $recursive = true ) : self
6909
        {
6910
                if( $recursive )
4 ✔
6911
                {
6912
                        $list = &$this->list();
3 ✔
6913
                        $this->walkRecursive( $list, $callback, $data );
3 ✔
6914
                }
6915
                else
6916
                {
6917
                        array_walk( $this->list(), $callback, $data );
1 ✔
6918
                }
6919

6920
                return $this;
4 ✔
6921
        }
6922

6923

6924
        /**
6925
         * Filters the list of elements by a given condition.
6926
         *
6927
         * Examples:
6928
         *  Map::from( [
6929
         *    ['id' => 1, 'type' => 'name'],
6930
         *    ['id' => 2, 'type' => 'short'],
6931
         *  ] )->where( 'type', '==', 'name' );
6932
         *
6933
         *  Map::from( [
6934
         *    ['id' => 3, 'price' => 10],
6935
         *    ['id' => 4, 'price' => 50],
6936
         *  ] )->where( 'price', '>', 20 );
6937
         *
6938
         *  Map::from( [
6939
         *    ['id' => 3, 'price' => 10],
6940
         *    ['id' => 4, 'price' => 50],
6941
         *  ] )->where( 'price', 'in', [10, 25] );
6942
         *
6943
         *  Map::from( [
6944
         *    ['id' => 3, 'price' => 10],
6945
         *    ['id' => 4, 'price' => 50],
6946
         *  ] )->where( 'price', '-', [10, 100] );
6947
         *
6948
         *  Map::from( [
6949
         *    ['item' => ['id' => 3, 'price' => 10]],
6950
         *    ['item' => ['id' => 4, 'price' => 50]],
6951
         *  ] )->where( 'item/price', '>', 30 );
6952
         *
6953
         * Results:
6954
         *  [0 => ['id' => 1, 'type' => 'name']]
6955
         *  [1 => ['id' => 4, 'price' => 50]]
6956
         *  [0 => ['id' => 3, 'price' => 10]]
6957
         *  [0 => ['id' => 3, 'price' => 10], ['id' => 4, 'price' => 50]]
6958
         *  [1 => ['item' => ['id' => 4, 'price' => 50]]]
6959
         *
6960
         * Available operators are:
6961
         * * '==' : Equal
6962
         * * '===' : Equal and same type
6963
         * * '!=' : Not equal
6964
         * * '!==' : Not equal and same type
6965
         * * '<=' : Smaller than an equal
6966
         * * '>=' : Greater than an equal
6967
         * * '<' : Smaller
6968
         * * '>' : Greater
6969
         * 'in' : Array of value which are in the list of values
6970
         * '-' : Values between array of start and end value, e.g. [10, 100] (inclusive)
6971
         *
6972
         * This does also work for multi-dimensional arrays by passing the keys
6973
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
6974
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
6975
         * public properties of objects or objects implementing __isset() and __get() methods.
6976
         *
6977
         * The keys of the original map are preserved in the returned map.
6978
         *
6979
         * @param string $key Key or path of the value in the array or object used for comparison
6980
         * @param string $op Operator used for comparison
6981
         * @param mixed $value Value used for comparison
6982
         * @return self<int|string,mixed> New map for fluid interface
6983
         * @throws \InvalidArgumentException If the operator isn't supported
6984
         */
6985
        public function where( string $key, string $op, mixed $value ) : self
6986
        {
6987
                return $this->filter( $this->whereFilter( $key, $op, $value ) );
7 ✔
6988
        }
6989

6990

6991
        /**
6992
         * Returns a copy of the map with the element at the given index replaced with the given value.
6993
         *
6994
         * Examples:
6995
         *  $m = Map::from( ['a' => 1] );
6996
         *  $m->with( 2, 'b' );
6997
         *  $m->with( 'a', 2 );
6998
         *
6999
         * Results:
7000
         *  ['a' => 1, 2 => 'b']
7001
         *  ['a' => 2]
7002
         *
7003
         * The original map ($m) stays untouched!
7004
         * This method is a shortcut for calling the copy() and set() methods.
7005
         *
7006
         * @param int|string $key Array key to set or replace
7007
         * @param mixed $value New value for the given key
7008
         * @return self<int|string,mixed> New map
7009
         */
7010
        public function with( int|string $key, mixed $value ) : self
7011
        {
7012
                return ( clone $this )->set( $key, $value );
1 ✔
7013
        }
7014

7015

7016
        /**
7017
         * Merges the values of all arrays at the corresponding index.
7018
         *
7019
         * Examples:
7020
         *  $en = ['one', 'two', 'three'];
7021
         *  $es = ['uno', 'dos', 'tres'];
7022
         *  $m = Map::from( [1, 2, 3] )->zip( $en, $es );
7023
         *
7024
         * Results:
7025
         *  [
7026
         *    [1, 'one', 'uno'],
7027
         *    [2, 'two', 'dos'],
7028
         *    [3, 'three', 'tres'],
7029
         *  ]
7030
         *
7031
         * @param array<int|string,mixed>|\Traversable<int|string,mixed>|\Iterator<int|string,mixed> $arrays List of arrays to merge with at the same position
7032
         * @return self<int|string,mixed> New map of arrays
7033
         */
7034
        public function zip( ...$arrays ) : self
7035
        {
7036
                $args = array_map( function( $items ) {
1 ✔
7037
                        return $this->array( $items );
1 ✔
7038
                }, $arrays );
1 ✔
7039

7040
                return new static( array_map( null, $this->list(), ...$args ) );
1 ✔
7041
        }
7042

7043

7044
        /**
7045
         * Returns a plain array of the given elements.
7046
         *
7047
         * @param mixed $elements List of elements or single value
7048
         * @return array<int|string,mixed> Plain array
7049
         */
7050
        protected function array( mixed $elements ) : array
7051
        {
7052
                if( is_array( $elements ) ) {
310 ✔
7053
                        return $elements;
298 ✔
7054
                }
7055

7056
                if( $elements instanceof \Closure ) {
53 ✔
7057
                        return $this->array( $elements() );
2 ✔
7058
                }
7059

7060
                if( $elements instanceof \Aimeos\Map ) {
53 ✔
7061
                        return $elements->toArray();
29 ✔
7062
                }
7063

7064
                if( is_iterable( $elements ) ) {
28 ✔
7065
                        return iterator_to_array( $elements, true );
9 ✔
7066
                }
7067

7068
                return $elements !== null ? [$elements] : [];
20 ✔
7069
        }
7070

7071

7072
        /**
7073
         * Returns a nested value from a plain PHP array.
7074
         *
7075
         * @param array<mixed> $entry Array to look at
7076
         * @param array<int|string> $parts Path parts to look for
7077
         * @return mixed Found value or NULL if the path doesn't exist
7078
         */
7079
        protected function arrayVal( array $entry, array $parts ) : mixed
7080
        {
7081
                $current = $entry;
13 ✔
7082

7083
                foreach( $parts as $part )
13 ✔
7084
                {
7085
                        if( !is_array( $current ) ) {
13 ✔
7086
                                return null;
×
7087
                        }
7088

7089
                        if( isset( $current[$part] ) )
13 ✔
7090
                        {
7091
                                $current = $current[$part];
13 ✔
7092
                                continue;
13 ✔
7093
                        }
7094

7095
                        if( !array_key_exists( $part, $current ) ) {
1 ✔
7096
                                return null;
1 ✔
7097
                        }
7098

7099
                        $current = $current[$part];
×
7100
                }
7101

7102
                return $current;
12 ✔
7103
        }
7104

7105

7106
        /**
7107
         * Returns a nested value from a plain PHP array and tells if the path exists.
7108
         *
7109
         * @param array<mixed> $entry Array to look at
7110
         * @param array<int|string> $parts Path parts to look for
7111
         * @param mixed $value Found value
7112
         * @return bool TRUE if the path exists, FALSE if not
7113
         */
7114
        protected function arrayPath( array $entry, array $parts, mixed &$value ) : bool
7115
        {
7116
                $current = $entry;
14 ✔
7117

7118
                foreach( $parts as $part )
14 ✔
7119
                {
7120
                        if( !is_array( $current ) ) {
14 ✔
7121
                                return false;
×
7122
                        }
7123

7124
                        if( isset( $current[$part] ) )
14 ✔
7125
                        {
7126
                                $current = $current[$part];
13 ✔
7127
                                continue;
13 ✔
7128
                        }
7129

7130
                        if( !array_key_exists( $part, $current ) ) {
4 ✔
7131
                                return false;
3 ✔
7132
                        }
7133

7134
                        $current = $current[$part];
2 ✔
7135
                }
7136

7137
                $value = $current;
12 ✔
7138
                return true;
12 ✔
7139
        }
7140

7141

7142
        /**
7143
         * Normalizes a value to a PHP array key.
7144
         *
7145
         * @param mixed $key Key candidate
7146
         * @return int|string Normalized key
7147
         * @throws \InvalidArgumentException If the key isn't scalar, NULL or stringable
7148
         */
7149
        protected function arrayKey( mixed $key ) : int|string
7150
        {
7151
                if( !is_scalar( $key ) && $key !== null && !$key instanceof \Stringable ) {
44 ✔
7152
                        throw new \InvalidArgumentException( 'Keys must be scalar values or stringable objects but "' . get_debug_type( $key ) . '" given' );
14 ✔
7153
                }
7154

7155
                return is_int( $key ) || is_string( $key ) ? $key : (string) $key;
30 ✔
7156
        }
7157

7158

7159
        /**
7160
         * Normalizes a value to the grouping/counting key used by countBy() and groupBy().
7161
         *
7162
         * @param mixed $value Value to normalize
7163
         * @return string Normalized grouping key
7164
         */
7165
        protected function groupKey( mixed $value ) : string
7166
        {
7167
                return is_scalar( $value ) || $value instanceof \Stringable ? (string) $value : '';
7 ✔
7168
        }
7169

7170

7171
        /**
7172
         * Returns a function for comparing two values without throwing errors.
7173
         *
7174
         * Scalar values, NULL and stringable objects are compared by their string
7175
         * values, all other values are compared by their type and structure.
7176
         *
7177
         * @return \Closure Function with ($a, $b) parameters returning -1, 0 or 1
7178
         */
7179
        protected function comparator() : \Closure
7180
        {
7181
                return function( $a, $b ) {
3 ✔
7182
                        $stra = is_scalar( $a ) || $a === null || $a instanceof \Stringable;
3 ✔
7183
                        $strb = is_scalar( $b ) || $b === null || $b instanceof \Stringable;
3 ✔
7184

7185
                        if( $stra && $strb ) {
3 ✔
7186
                                return (string) $a <=> (string) $b;
1 ✔
7187
                        }
7188

7189
                        if( $stra !== $strb ) {
3 ✔
7190
                                return $stra ? -1 : 1;
2 ✔
7191
                        }
7192

7193
                        if( is_array( $a ) !== is_array( $b ) ) {
1 ✔
7194
                                return is_array( $a ) ? -1 : 1;
×
7195
                        }
7196

7197
                        return $a <=> $b;
1 ✔
7198
                };
3 ✔
7199
        }
7200

7201

7202
        /**
7203
         * Returns a canonical key for values that can be compared safely by lookup.
7204
         *
7205
         * @param mixed $value Value to normalize
7206
         * @return string|null Canonical key or NULL if comparator fallback is required
7207
         */
7208
        protected function comparisonKey( mixed $value ) : ?string
7209
        {
7210
                if( is_scalar( $value ) || $value === null || $value instanceof \Stringable ) {
4 ✔
7211
                        return 's:' . (string) $value;
2 ✔
7212
                }
7213

7214
                return is_array( $value ) ? $this->arrayComparisonKey( $value ) : null;
4 ✔
7215
        }
7216

7217

7218
        /**
7219
         * Returns a canonical key for plain arrays where PHP loose comparison is safe to model.
7220
         *
7221
         * @param array<mixed> $value Array value to normalize
7222
         * @return string|null Canonical key or NULL if comparator fallback is required
7223
         */
7224
        protected function arrayComparisonKey( array $value ) : ?string
7225
        {
7226
                $entries = [];
2 ✔
7227

7228
                foreach( $value as $key => $entry )
2 ✔
7229
                {
7230
                        if( is_int( $entry ) ) {
2 ✔
7231
                                $entry = 'i:' . $entry;
2 ✔
7232
                        } elseif( is_string( $entry ) && !is_numeric( $entry ) ) {
×
7233
                                $entry = 's:' . $entry;
×
7234
                        } elseif( is_array( $entry ) ) {
×
7235
                                $entry = $this->arrayComparisonKey( $entry );
×
7236
                        } else {
7237
                                return null;
×
7238
                        }
7239

7240
                        if( $entry === null ) {
2 ✔
7241
                                return null;
×
7242
                        }
7243

7244
                        $entries[is_int( $key ) ? 'i:' . $key : 's:' . $key] = $entry;
2 ✔
7245
                }
7246

7247
                ksort( $entries, SORT_STRING );
2 ✔
7248
                return 'a:' . serialize( $entries );
2 ✔
7249
        }
7250

7251

7252
        /**
7253
         * Tests if the list contains the value using the comparison callback.
7254
         *
7255
         * @param array<int|string,mixed> $list List of values to check
7256
         * @param mixed $value Value to search for
7257
         * @param callable $compare Function with ($a, $b) parameters returning -1, 0 or 1
7258
         * @return bool TRUE if the value is found, FALSE if not
7259
         */
7260
        protected function containsValue( array $list, mixed $value, callable $compare ) : bool
7261
        {
7262
                foreach( $list as $entry )
2 ✔
7263
                {
7264
                        if( $compare( $value, $entry ) === 0 ) {
2 ✔
7265
                                return true;
×
7266
                        }
7267
                }
7268

7269
                return false;
2 ✔
7270
        }
7271

7272

7273
        /**
7274
         * Filters the list by values contained in the comparison list.
7275
         *
7276
         * @param array<int|string,mixed> $list List of values to filter
7277
         * @param array<int|string,mixed> $values Values to compare against
7278
         * @param bool $keepMatches TRUE to keep matching values, FALSE to keep non-matching values
7279
         * @return array<int|string,mixed> Filtered values
7280
         */
7281
        protected function filterByValues( array $list, array $values, bool $keepMatches ) : array
7282
        {
7283
                $lookup = $unsupported = [];
4 ✔
7284

7285
                foreach( $values as $value )
4 ✔
7286
                {
7287
                        if( ( $key = $this->comparisonKey( $value ) ) !== null ) {
4 ✔
7288
                                $lookup[$key] = true;
4 ✔
7289
                        } else {
7290
                                $unsupported[] = $value;
×
7291
                        }
7292
                }
7293

7294
                $compare = !empty( $unsupported ) ? $this->comparator() : null;
4 ✔
7295
                $result = [];
4 ✔
7296

7297
                foreach( $list as $key => $value )
4 ✔
7298
                {
7299
                        $match = false;
4 ✔
7300

7301
                        if( ( $lookupKey = $this->comparisonKey( $value ) ) !== null )
4 ✔
7302
                        {
7303
                                $match = isset( $lookup[$lookupKey] )
4 ✔
7304
                                        || ( $compare && $this->containsValue( $unsupported, $value, $compare ) );
4 ✔
7305
                        }
7306
                        else
7307
                        {
7308
                                $match = $this->containsValue( $values, $value, $compare ?? $this->comparator() );
2 ✔
7309
                        }
7310

7311
                        if( $match === $keepMatches ) {
4 ✔
7312
                                $result[$key] = $value;
4 ✔
7313
                        }
7314
                }
7315

7316
                return $result;
4 ✔
7317
        }
7318

7319

7320
        /**
7321
         * Returns positional keys for first occurrences of mapped values.
7322
         *
7323
         * @param array<int|string,mixed> $list List of values to map and deduplicate
7324
         * @param \Closure|string|null $col Key, path or callback used for mapping
7325
         * @return array<int,bool> Positional keys of first occurrences
7326
         */
7327
        protected function dedupMappedKeys( array $list, \Closure|string|null $col ) : array
7328
        {
7329
                $keys = $seen = $rest = [];
6 ✔
7330
                $pos = 0;
6 ✔
7331

7332
                if( $col instanceof \Closure )
6 ✔
7333
                {
7334
                        foreach( $list as $key => $value )
2 ✔
7335
                        {
7336
                                $this->dedupMappedValue( $col( $value, $key ), $keys, $seen, $rest, $pos );
2 ✔
7337
                                $pos++;
2 ✔
7338
                        }
7339

7340
                        return $keys;
2 ✔
7341
                }
7342

7343
                $parts = $col ? explode( $this->sep, (string) $col ) : [];
4 ✔
7344
                $part = count( $parts ) === 1 ? current( $parts ) : null;
4 ✔
7345

7346
                foreach( $list as $value )
4 ✔
7347
                {
7348
                        if( $part !== null && is_array( $value ) ) {
4 ✔
7349
                                $value = $value[$part] ?? null;
2 ✔
7350
                        } elseif( is_array( $value ) ) {
2 ✔
7351
                                $value = $this->arrayVal( $value, $parts );
2 ✔
7352
                        } else {
7353
                                $value = $this->val( $value, $parts );
×
7354
                        }
7355

7356
                        $this->dedupMappedValue( $value, $keys, $seen, $rest, $pos );
4 ✔
7357
                        $pos++;
4 ✔
7358
                }
7359

7360
                return $keys;
4 ✔
7361
        }
7362

7363

7364
        /**
7365
         * Stores the positional key if the mapped value hasn't been seen before.
7366
         *
7367
         * @param mixed $value Mapped value
7368
         * @param array<int,bool> &$keys Positional keys of first occurrences
7369
         * @param array<string,bool> &$seen Seen scalar/string values
7370
         * @param array<int,mixed> &$rest Seen non-scalar values
7371
         * @param int $pos Current position
7372
         */
7373
        protected function dedupMappedValue( mixed $value, array &$keys, array &$seen, array &$rest, int $pos ) : void
7374
        {
7375
                if( is_scalar( $value ) || $value === null || $value instanceof \Stringable )
6 ✔
7376
                {
7377
                        $str = (string) $value;
6 ✔
7378

7379
                        if( !isset( $seen[$str] ) )
6 ✔
7380
                        {
7381
                                $seen[$str] = true;
6 ✔
7382
                                $keys[$pos] = true;
6 ✔
7383
                        }
7384
                }
7385
                elseif( !in_array( $value, $rest, true ) )
×
7386
                {
7387
                        $rest[] = $value;
×
7388
                        $keys[$pos] = true;
×
7389
                }
7390
        }
7391

7392

7393
        /**
7394
         * Tests if the item matches the value or callback used by restrict(), isSole() and sole().
7395
         *
7396
         * @param mixed $item List item to test
7397
         * @param int|string $mapkey Key of the list item
7398
         * @param mixed $value Value or callback to compare with
7399
         * @param string|int|null $key Key to compare the value for if $value is not a callback
7400
         * @return bool TRUE if the item matches, FALSE if not
7401
         */
7402
        protected function matches( mixed $item, int|string $mapkey, mixed $value, string|int|null $key ) : bool
7403
        {
7404
                if( $value instanceof \Closure ) {
12 ✔
7405
                        return (bool) $value( $item, $mapkey );
2 ✔
7406
                }
7407

7408
                if( $key === null ) {
10 ✔
7409
                        return $item === $value;
7 ✔
7410
                }
7411

7412
                return $this->value( $item, [$key], $found ) && $found === $value;
3 ✔
7413
        }
7414

7415

7416
        /**
7417
         * Returns lookup keys for values that can be compared by strict scalar identity.
7418
         *
7419
         * @param array<int|string,mixed> $list List of values to normalize
7420
         * @return array<string>|null Lookup keys or NULL if a value can't be represented safely
7421
         */
7422
        protected function lookupKeys( array $list ) : ?array
7423
        {
7424
                $keys = [];
×
7425

7426
                foreach( $list as $value )
×
7427
                {
7428
                        if( ( $key = $this->lookupKey( $value ) ) === null ) {
×
7429
                                return null;
×
7430
                        }
7431

7432
                        $keys[] = $key;
×
7433
                }
7434

7435
                return $keys;
×
7436
        }
7437

7438

7439
        /**
7440
         * Returns a lookup set for values that can be compared by strict scalar identity.
7441
         *
7442
         * @param array<int|string,mixed> $list List of values to index
7443
         * @return array<string,bool> Lookup set
7444
         */
7445
        protected function lookupSet( array $list ) : array
7446
        {
7447
                $lookup = [];
×
7448

7449
                foreach( $list as $value )
×
7450
                {
7451
                        if( ( $key = $this->lookupKey( $value ) ) !== null ) {
×
7452
                                $lookup[$key] = true;
×
7453
                        }
7454
                }
7455

7456
                return $lookup;
×
7457
        }
7458

7459

7460
        /**
7461
         * Returns a type-prefixed key for strict scalar comparisons.
7462
         *
7463
         * @param mixed $value Value to normalize
7464
         * @return string|null Lookup key or NULL if the value can't be represented safely
7465
         */
7466
        protected function lookupKey( mixed $value ) : ?string
7467
        {
7468
                if( is_int( $value ) ) {
×
7469
                        return 'i:' . $value;
×
7470
                }
7471

7472
                if( is_string( $value ) ) {
×
7473
                        return 's:' . $value;
×
7474
                }
7475

7476
                if( is_bool( $value ) ) {
×
7477
                        return 'b:' . (int) $value;
×
7478
                }
7479

7480
                if( is_float( $value ) )
×
7481
                {
7482
                        if( \is_nan( $value ) ) {
×
7483
                                return null;
×
7484
                        }
7485

7486
                        return 'f:' . \serialize( $value == 0.0 ? 0.0 : $value );
×
7487
                }
7488

7489
                return $value === null ? 'n:' : null;
×
7490
        }
7491

7492

7493
        /**
7494
         * Removes duplicate values from the list without throwing errors.
7495
         *
7496
         * Scalar values, NULL and stringable objects are compared by their string
7497
         * values like array_unique() does, all other values are compared strictly.
7498
         * The first occurrence of each value is kept including its key.
7499
         *
7500
         * @param array<int|string,mixed> $list List of elements
7501
         * @return array<int|string,mixed> List of elements without duplicate values
7502
         */
7503
        protected function dedup( array $list ) : array
7504
        {
7505
                if( is_array( $result = $this->native( static fn() => array_unique( $list ) ) ) ) {
5 ✔
7506
                        return $result;
3 ✔
7507
                }
7508

7509
                $unique = $seen = $rest = [];
2 ✔
7510

7511
                foreach( $list as $key => $value )
2 ✔
7512
                {
7513
                        if( is_scalar( $value ) || $value === null || $value instanceof \Stringable )
2 ✔
7514
                        {
7515
                                $str = (string) $value;
2 ✔
7516

7517
                                if( !isset( $seen[$str] ) )
2 ✔
7518
                                {
7519
                                        $seen[$str] = true;
2 ✔
7520
                                        $unique[$key] = $value;
2 ✔
7521
                                }
7522
                        }
7523
                        elseif( !in_array( $value, $rest, true ) )
2 ✔
7524
                        {
7525
                                $rest[] = $value;
2 ✔
7526
                                $unique[$key] = $value;
2 ✔
7527
                        }
7528
                }
7529

7530
                return $unique;
2 ✔
7531
        }
7532

7533

7534
        /**
7535
         * Flattens a multi-dimensional array or map into a single level array.
7536
         *
7537
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
7538
         * @param array<int|string,mixed> $result Will contain all elements from the multi-dimensional arrays afterwards
7539
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
7540
         * @param int $level Current recursion depth
7541
         */
7542
        protected function kflatten( iterable $entries, array &$result, int $depth, int $level = 0 ) : void
7543
        {
7544
                foreach( $entries as $key => $entry )
5 ✔
7545
                {
7546
                        if( is_iterable( $entry ) && $depth > 0 && $level < self::RECURSION_LIMIT ) {
5 ✔
7547
                                $this->kflatten( $entry, $result, $depth - 1, $level + 1 );
5 ✔
7548
                        } elseif( is_iterable( $entry ) && $depth > 0 ) {
5 ✔
7549
                                $this->flattenWalk( $entry, $depth - 1, true, function( $key, $entry ) use ( &$result ) {
×
7550
                                        $result[$key] = $entry;
×
7551
                                } );
×
7552
                        } else {
7553
                                $result[$key] = $entry;
5 ✔
7554
                        }
7555
                }
7556
        }
7557

7558

7559
        /**
7560
         * Returns a reference to the array of elements
7561
         *
7562
         * @phpstan-return array<TKey,TValue>
7563
         * @return array<int|string,mixed> Reference to the array of elements
7564
         */
7565
        protected function &list() : array
7566
        {
7567
                if( !is_array( $this->list ) ) {
448 ✔
7568
                        $this->list = $this->array( $this->list );
×
7569
                }
7570

7571
                return $this->list;
448 ✔
7572
        }
7573

7574

7575
        /**
7576
         * Returns a closure that retrieves the value for the passed key
7577
         *
7578
         * @param \Closure|string|null $key Closure or key (e.g. "key1/key2/key3") to retrieve the value for
7579
         * @return \Closure Closure that retrieves the value for the passed key
7580
         */
7581
        protected function mapper( \Closure|string|null $key = null ) : \Closure
7582
        {
7583
                if( $key instanceof \Closure ) {
×
7584
                        return $key;
×
7585
                }
7586

7587
                $parts = $key ? explode( $this->sep, (string) $key ) : [];
×
7588

7589
                return function( $item ) use ( $parts ) {
×
7590
                        return $this->val( $item, $parts );
×
7591
                };
×
7592
        }
7593

7594

7595
        /**
7596
         * Executes the function using native PHP functions and falls back to the given function on errors.
7597
         *
7598
         * PHP warnings are turned into exceptions temporarily so native functions
7599
         * fail fast for values they can't compare instead of continuing with
7600
         * useless string representations like "Array".
7601
         *
7602
         * @param \Closure $fcn Function using native PHP functions
7603
         * @param \Closure|null $fallback Fallback function executed in case of an error or NULL to return NULL instead
7604
         * @return mixed Result of the executed or fallback function, NULL in case of an error and no fallback
7605
         */
7606
        protected function native( \Closure $fcn, ?\Closure $fallback = null ) : mixed
7607
        {
7608
                set_error_handler( static function( int $code, string $msg ) {
27 ✔
7609
                        throw new \ErrorException( $msg, $code );
2 ✔
7610
                } );
27 ✔
7611

7612
                try {
7613
                        return $fcn();
27 ✔
7614
                } catch( \Throwable $t ) {
7 ✔
7615
                        ; // use the fallback function outside so its warnings aren't turned into exceptions
7616
                } finally {
7617
                        restore_error_handler();
27 ✔
7618
                }
7619

7620
                return $fallback ? $fallback() : null;
7 ✔
7621
        }
7622

7623

7624
        /**
7625
         * Flattens a multi-dimensional array or map into a single level array.
7626
         *
7627
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
7628
         * @param array<mixed> &$result Will contain all elements from the multi-dimensional arrays afterwards
7629
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
7630
         * @param int $level Current recursion depth
7631
         */
7632
        protected function nflatten( iterable $entries, array &$result, int $depth, int $level = 0 ) : void
7633
        {
7634
                foreach( $entries as $entry )
5 ✔
7635
                {
7636
                        if( is_iterable( $entry ) && $depth > 0 && $level < self::RECURSION_LIMIT ) {
5 ✔
7637
                                $this->nflatten( $entry, $result, $depth - 1, $level + 1 );
4 ✔
7638
                        } elseif( is_iterable( $entry ) && $depth > 0 ) {
5 ✔
7639
                                $this->flattenWalk( $entry, $depth - 1, false, function( $key, $entry ) use ( &$result ) {
×
7640
                                        $result[] = $entry;
×
7641
                                } );
×
7642
                        } else {
7643
                                $result[] = $entry;
5 ✔
7644
                        }
7645
                }
7646
        }
7647

7648

7649
        /**
7650
         * Returns a cryptographically secure random integer between 0 and the passed maximum.
7651
         *
7652
         * The buffer is filled with random integers in batches to avoid the syscall
7653
         * overhead of random_int() for each generated integer. Values above the
7654
         * maximum are rejected and redrawn so the result is unbiased.
7655
         *
7656
         * @param int $max Highest value to return (inclusive), must be below 2^32
7657
         * @param array<mixed> &$buf Buffer filled with random integers
7658
         * @param int &$pos Current position in the buffer
7659
         * @return int Random integer between 0 and the passed maximum (inclusive)
7660
         */
7661
        protected function rand( int $max, array &$buf, int &$pos ) : int
7662
        {
7663
                if( $max < 1 ) {
6 ✔
7664
                        return 0;
×
7665
                }
7666

7667
                $mask = $max;
6 ✔
7668
                $mask |= $mask >> 1;
6 ✔
7669
                $mask |= $mask >> 2;
6 ✔
7670
                $mask |= $mask >> 4;
6 ✔
7671
                $mask |= $mask >> 8;
6 ✔
7672
                $mask |= $mask >> 16;
6 ✔
7673

7674
                do
7675
                {
7676
                        if( !isset( $buf[++$pos] ) )
6 ✔
7677
                        {
7678
                                $buf = (array) unpack( 'N*', random_bytes( 4096 ) );
6 ✔
7679
                                $pos = 1;
6 ✔
7680
                        }
7681

7682
                        $val = (int) $buf[$pos] & $mask;
6 ✔
7683
                }
7684
                while( $val > $max );
6 ✔
7685

7686
                return $val;
6 ✔
7687
        }
7688

7689

7690
        /**
7691
         * Flattens a multi-dimensional array or map into an array with joined keys.
7692
         *
7693
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
7694
         * @param array<int|string,mixed> $result Will contain joined key/value pairs from the multi-dimensional arrays afterwards
7695
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
7696
         * @param string $path Path prefix of the current key
7697
         * @param int $level Current recursion depth
7698
         */
7699
        protected function rflatten( iterable $entries, array &$result, int $depth, string $path = '', int $level = 0 ) : void
7700
        {
7701
                foreach( $entries as $key => $entry )
1 ✔
7702
                {
7703
                        if( is_iterable( $entry ) && $depth > 0 && $level < self::RECURSION_LIMIT ) {
1 ✔
7704
                                $this->rflatten( $entry, $result, $depth - 1, $path . $key . $this->sep, $level + 1 );
1 ✔
7705
                        } elseif( is_iterable( $entry ) && $depth > 0 ) {
1 ✔
7706
                                $pathfcn = function( string $path, int|string $key ) : string {
7707
                                        return $path . $key . $this->sep;
×
7708
                                };
7709

7710
                                $this->flattenWalk( $entry, $depth - 1, true, function( $key, $entry, $path ) use ( &$result ) {
×
7711
                                        $result[$path . $key] = $entry;
×
7712
                                }, $pathfcn, $path . $key . $this->sep );
×
7713
                        } else {
7714
                                $result[$path . $key] = $entry;
1 ✔
7715
                        }
7716
                }
7717
        }
7718

7719

7720
        /**
7721
         * Adds a prefix to all leaf values in nested arrays recursively.
7722
         *
7723
         * @param array<int|string,mixed> $list List of elements to update
7724
         * @param \Closure|string $prefix Prefix string or callback
7725
         * @param int $depth Maximum depth to dive into nested arrays
7726
         * @param int $level Current recursion depth
7727
         */
7728
        protected function prefixRecursive( array &$list, \Closure|string $prefix, int $depth, int $level = 0 ) : void
7729
        {
7730
                if( $level >= self::RECURSION_LIMIT )
1 ✔
7731
                {
7732
                        $this->prefixStack( $list, $prefix, $depth );
×
7733
                        return;
×
7734
                }
7735

7736
                foreach( $list as $key => &$item )
1 ✔
7737
                {
7738
                        if( is_array( $item ) )
1 ✔
7739
                        {
7740
                                if( $depth > 1 ) {
1 ✔
7741
                                        $this->prefixRecursive( $item, $prefix, $depth - 1, $level + 1 );
1 ✔
7742
                                }
7743
                        }
7744
                        else
7745
                        {
7746
                                $item = ( $prefix instanceof \Closure ? $prefix( $item, $key ) : $prefix ) . $item;
1 ✔
7747
                        }
7748
                }
7749

7750
                unset( $item );
1 ✔
7751
        }
7752

7753

7754
        /**
7755
         * Adds a prefix to all leaf values in nested arrays iteratively.
7756
         *
7757
         * @param array<int|string,mixed> $list List of elements to update
7758
         * @param \Closure|string $prefix Prefix string or callback
7759
         * @param int $depth Maximum depth to dive into nested arrays
7760
         */
7761
        protected function prefixStack( array &$list, \Closure|string $prefix, int $depth ) : void
7762
        {
7763
                $stack = [['list' => &$list, 'depth' => $depth]];
×
7764

7765
                while( !empty( $stack ) )
×
7766
                {
7767
                        $frame = array_pop( $stack );
×
7768

7769
                        foreach( $frame['list'] as $key => &$item )
×
7770
                        {
7771
                                if( is_array( $item ) )
×
7772
                                {
7773
                                        if( $frame['depth'] > 1 ) {
×
7774
                                                $stack[] = ['list' => &$item, 'depth' => $frame['depth'] - 1];
×
7775
                                        }
7776
                                }
7777
                                else
7778
                                {
7779
                                        $item = ( $prefix instanceof \Closure ? $prefix( $item, $key ) : $prefix ) . $item;
×
7780
                                }
7781
                        }
7782

7783
                        unset( $item );
×
7784
                }
7785
        }
7786

7787

7788
        /**
7789
         * Adds a suffix to all leaf values in nested arrays recursively.
7790
         *
7791
         * @param array<int|string,mixed> $list List of elements to update
7792
         * @param \Closure|string $suffix Suffix string or callback
7793
         * @param int $depth Maximum depth to dive into nested arrays
7794
         * @param int $level Current recursion depth
7795
         */
7796
        protected function suffixRecursive( array &$list, \Closure|string $suffix, int $depth, int $level = 0 ) : void
7797
        {
7798
                if( $level >= self::RECURSION_LIMIT )
1 ✔
7799
                {
7800
                        $this->suffixStack( $list, $suffix, $depth );
×
7801
                        return;
×
7802
                }
7803

7804
                foreach( $list as $key => &$item )
1 ✔
7805
                {
7806
                        if( is_array( $item ) )
1 ✔
7807
                        {
7808
                                if( $depth > 1 ) {
1 ✔
7809
                                        $this->suffixRecursive( $item, $suffix, $depth - 1, $level + 1 );
1 ✔
7810
                                }
7811
                        }
7812
                        else
7813
                        {
7814
                                $item = $item . ( $suffix instanceof \Closure ? $suffix( $item, $key ) : $suffix );
1 ✔
7815
                        }
7816
                }
7817

7818
                unset( $item );
1 ✔
7819
        }
7820

7821

7822
        /**
7823
         * Adds a suffix to all leaf values in nested arrays iteratively.
7824
         *
7825
         * @param array<int|string,mixed> $list List of elements to update
7826
         * @param \Closure|string $suffix Suffix string or callback
7827
         * @param int $depth Maximum depth to dive into nested arrays
7828
         */
7829
        protected function suffixStack( array &$list, \Closure|string $suffix, int $depth ) : void
7830
        {
7831
                $stack = [['list' => &$list, 'depth' => $depth]];
×
7832

7833
                while( !empty( $stack ) )
×
7834
                {
7835
                        $frame = array_pop( $stack );
×
7836

7837
                        foreach( $frame['list'] as $key => &$item )
×
7838
                        {
7839
                                if( is_array( $item ) )
×
7840
                                {
7841
                                        if( $frame['depth'] > 1 ) {
×
7842
                                                $stack[] = ['list' => &$item, 'depth' => $frame['depth'] - 1];
×
7843
                                        }
7844
                                }
7845
                                else
7846
                                {
7847
                                        $item = $item . ( $suffix instanceof \Closure ? $suffix( $item, $key ) : $suffix );
×
7848
                                }
7849
                        }
7850

7851
                        unset( $item );
×
7852
                }
7853
        }
7854

7855

7856
        /**
7857
         * Iterates over nested entries and calls the leaf callback for every flattened entry.
7858
         *
7859
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
7860
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
7861
         * @param bool $preserveKeys TRUE to preserve keys, FALSE to create numeric keys
7862
         * @param \Closure $leaf Callback with ($key, $entry, $path) arguments for flattened entries
7863
         * @param \Closure|null $pathfcn Callback with ($path, $key) arguments returning the child path
7864
         * @param string $path Path prefix of the current key
7865
         */
7866
        protected function flattenWalk(
7867
                iterable $entries,
7868
                int $depth,
7869
                bool $preserveKeys,
7870
                \Closure $leaf,
7871
                ?\Closure $pathfcn = null,
7872
                string $path = ''
7873
        ) : void
7874
        {
7875
                $stack = [];
×
7876
                $entries = $preserveKeys ? $this->array( $entries ) : ( is_array( $entries ) ? $entries : iterator_to_array( $entries, false ) );
×
7877

7878
                foreach( array_reverse( $entries, $preserveKeys ) as $key => $entry ) {
×
7879
                        $stack[] = [$key, $entry, $depth, $path];
×
7880
                }
7881

7882
                while( !empty( $stack ) )
×
7883
                {
7884
                        [$key, $entry, $depth, $path] = array_pop( $stack );
×
7885

7886
                        if( is_iterable( $entry ) && $depth > 0 )
×
7887
                        {
7888
                                $entries = $preserveKeys ? $this->array( $entry ) : ( is_array( $entry ) ? $entry : iterator_to_array( $entry, false ) );
×
7889
                                $childPath = $pathfcn ? $pathfcn( $path, $key ) : $path;
×
7890

7891
                                foreach( array_reverse( $entries, $preserveKeys ) as $ckey => $child ) {
×
7892
                                        $stack[] = [$ckey, $child, $depth - 1, $childPath];
×
7893
                                }
7894
                        }
7895
                        else
7896
                        {
7897
                                $leaf( $key, $entry, $path );
×
7898
                        }
7899
                }
7900
        }
7901

7902

7903
        /**
7904
         * Returns the position of the first element that doesn't match the condition
7905
         *
7906
         * @param iterable<int|string,mixed> $list List of elements to check
7907
         * @param \Closure $callback Closure with ($item, $key) arguments to check the condition
7908
         * @return int Position of the first element that doesn't match the condition
7909
         */
7910
        protected function until( iterable $list, \Closure $callback ) : int
7911
        {
7912
                $idx = 0;
2 ✔
7913

7914
                foreach( $list as $key => $item )
2 ✔
7915
                {
7916
                        if( !$callback( $item, $key ) ) {
2 ✔
7917
                                break;
2 ✔
7918
                        }
7919

7920
                        ++$idx;
2 ✔
7921
                }
7922

7923
                return $idx;
2 ✔
7924
        }
7925

7926

7927
        /**
7928
         * Returns a predicate for where() comparisons.
7929
         *
7930
         * @param string $key Key or path of the value in the array or object used for comparison
7931
         * @param string $op Operator used for comparison
7932
         * @param mixed $value Value used for comparison
7933
         * @return \Closure Predicate with ($item) parameter returning TRUE if the item matches
7934
         * @throws \InvalidArgumentException If the operator isn't supported
7935
         */
7936
        protected function whereFilter( string $key, string $op, mixed $value ) : \Closure
7937
        {
7938
                $parts = explode( $this->sep, $key );
9 ✔
7939
                $list = in_array( $op, ['-', 'in'], true ) ? $this->array( $value ) : [];
9 ✔
7940
                $start = $end = null;
9 ✔
7941

7942
                if( $op === '-' && $list !== [] ) {
9 ✔
7943
                        $start = reset( $list );
1 ✔
7944
                        $end = end( $list );
1 ✔
7945
                }
7946

7947
                return match( $op ) {
9 ✔
7948
                        '-' => function( $item ) use ( $parts, $list, $start, $end ) {
1 ✔
7949
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
1 ✔
7950
                                        && $list !== [] && $val >= $start && $val <= $end;
1 ✔
7951
                        },
1 ✔
7952
                        'in' => function( $item ) use ( $parts, $list ) {
1 ✔
7953
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
1 ✔
7954
                                        && in_array( $val, $list );
1 ✔
7955
                        },
1 ✔
7956
                        '<' => function( $item ) use ( $parts, $value ) {
1 ✔
7957
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
1 ✔
7958
                                        && $val < $value;
1 ✔
7959
                        },
1 ✔
7960
                        '>' => function( $item ) use ( $parts, $value ) {
2 ✔
7961
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
2 ✔
7962
                                        && $val > $value;
2 ✔
7963
                        },
2 ✔
7964
                        '<=' => function( $item ) use ( $parts, $value ) {
1 ✔
7965
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
1 ✔
7966
                                        && $val <= $value;
1 ✔
7967
                        },
1 ✔
7968
                        '>=' => function( $item ) use ( $parts, $value ) {
1 ✔
7969
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
1 ✔
7970
                                        && $val >= $value;
1 ✔
7971
                        },
1 ✔
7972
                        '===' => function( $item ) use ( $parts, $value ) {
2 ✔
7973
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
2 ✔
7974
                                        && $val === $value;
2 ✔
7975
                        },
2 ✔
7976
                        '!==' => function( $item ) use ( $parts, $value ) {
2 ✔
7977
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
2 ✔
7978
                                        && $val !== $value;
2 ✔
7979
                        },
2 ✔
7980
                        '!=' => function( $item ) use ( $parts, $value ) {
4 ✔
7981
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
4 ✔
7982
                                        && $val != $value;
4 ✔
7983
                        },
4 ✔
7984
                        '==' => function( $item ) use ( $parts, $value ) {
5 ✔
7985
                                return ( is_array( $item ) ? $this->arrayPath( $item, $parts, $val ) : $this->value( $item, $parts, $val ) )
5 ✔
7986
                                        && $val == $value;
5 ✔
7987
                        },
5 ✔
7988
                        default => throw new \InvalidArgumentException( 'Unsupported operator "' . $op . '"' ),
9 ✔
7989
                };
9 ✔
7990
        }
7991

7992

7993
        /**
7994
         * Resolves default values used by accessors.
7995
         *
7996
         * @param mixed $default Default value, closure or throwable
7997
         * @param bool $pass TRUE to pass the optional value to closure defaults
7998
         * @param mixed $value Optional value passed to closure defaults
7999
         * @return mixed Resolved default value
8000
         */
8001
        protected function fallback( mixed $default, bool $pass = false, mixed $value = null ) : mixed
8002
        {
8003
                if( $default instanceof \Closure ) {
46 ✔
8004
                        return $pass ? $default( $value ) : $default();
12 ✔
8005
                }
8006

8007
                if( $default instanceof \Throwable ) {
34 ✔
8008
                        throw $default;
12 ✔
8009
                }
8010

8011
                return $default;
22 ✔
8012
        }
8013

8014

8015
        /**
8016
         * Normalizes tree IDs to PHP array keys.
8017
         *
8018
         * @param mixed $id ID or parent ID from a tree node
8019
         * @return int|string Normalized key
8020
         */
8021
        protected function treeId( mixed $id ) : int|string
8022
        {
8023
                return is_int( $id ) || is_string( $id ) ? $id : ( $id === null ? '' : (int) $id );
6 ✔
8024
        }
8025

8026

8027
        /**
8028
         * Removes an item by top-level key or path.
8029
         *
8030
         * @param int|string $key Key or path to remove
8031
         * @return bool TRUE if the item existed and was removed, FALSE if not
8032
         */
8033
        protected function forget( int|string $key ) : bool
8034
        {
8035
                $list = &$this->list();
4 ✔
8036

8037
                if( array_key_exists( $key, $list ) ) {
4 ✔
8038
                        unset( $list[$key] );
2 ✔
8039
                        return true;
2 ✔
8040
                }
8041

8042
                return $this->unsetValue( $list, explode( $this->sep, (string) $key ) );
2 ✔
8043
        }
8044

8045

8046
        /**
8047
         * Returns an item by top-level key or path and tells if it exists.
8048
         *
8049
         * @param int|string $key Key or path to the requested item
8050
         * @param mixed $value Found value
8051
         * @return bool TRUE if the item exists, FALSE if not
8052
         */
8053
        protected function item( int|string $key, mixed &$value ) : bool
8054
        {
8055
                $list = $this->list();
32 ✔
8056

8057
                if( array_key_exists( $key, $list ) ) {
32 ✔
8058
                        $value = $list[$key];
11 ✔
8059
                        return true;
11 ✔
8060
                }
8061

8062
                if( !str_contains( (string) $key, $this->sep ) ) {
29 ✔
8063
                        return false;
22 ✔
8064
                }
8065

8066
                return $this->value( $list, explode( $this->sep, (string) $key ), $value );
15 ✔
8067
        }
8068

8069

8070
        /**
8071
         * Returns a configuration value from an array.
8072
         *
8073
         * @param array<mixed>|object $entry The array or object to look at
8074
         * @param array<int|string> $parts Path parts to look for inside the array or object
8075
         * @return mixed Found value or null if no value is available
8076
         */
8077
        protected function val( mixed $entry, array $parts ) : mixed
8078
        {
8079
                return $this->value( $entry, $parts, $value ) ? $value : null;
1 ✔
8080
        }
8081

8082

8083
        /**
8084
         * Returns a configuration value from an array and tells if the path exists.
8085
         *
8086
         * @param mixed $entry The array or object to look at
8087
         * @param array<int|string> $parts Path parts to look for inside the array or object
8088
         * @param mixed $value Found value
8089
         * @return bool TRUE if the path exists, FALSE if not
8090
         */
8091
        protected function value( mixed $entry, array $parts, mixed &$value ) : bool
8092
        {
8093
                foreach( $parts as $part )
21 ✔
8094
                {
8095
                        if( is_array( $entry ) )
21 ✔
8096
                        {
8097
                                if( !array_key_exists( $part, $entry ) ) {
20 ✔
8098
                                        return false;
3 ✔
8099
                                }
8100

8101
                                $entry = $entry[$part];
20 ✔
8102
                        }
8103
                        elseif( $entry instanceof \ArrayAccess )
5 ✔
8104
                        {
8105
                                if( !isset( $entry[$part] ) && !$entry->offsetExists( $part ) ) {
×
8106
                                        return false;
×
8107
                                }
8108

8109
                                $entry = $entry[$part];
×
8110
                        }
8111
                        elseif( is_object( $entry ) )
5 ✔
8112
                        {
8113
                                if( array_key_exists( (string) $part, get_object_vars( $entry ) ) || isset( $entry->{$part} ) ) {
4 ✔
8114
                                        $entry = $entry->{$part};
3 ✔
8115
                                } else {
8116
                                        return false;
1 ✔
8117
                                }
8118
                        }
8119
                        else
8120
                        {
8121
                                return false;
1 ✔
8122
                        }
8123
                }
8124

8125
                $value = $entry;
21 ✔
8126
                return true;
21 ✔
8127
        }
8128

8129

8130
        /**
8131
         * Removes a configuration value from an array or object.
8132
         *
8133
         * @param mixed $entry The array or object to remove the value from
8134
         * @param array<int|string> $parts Path parts to look for inside the array or object
8135
         * @return bool TRUE if the path exists and was removed, FALSE if not
8136
         */
8137
        protected function unsetValue( mixed &$entry, array $parts ) : bool
8138
        {
8139
                $part = array_shift( $parts );
2 ✔
8140

8141
                if( $part === null ) {
2 ✔
8142
                        return false;
×
8143
                }
8144

8145
                if( is_array( $entry ) )
2 ✔
8146
                {
8147
                        if( !array_key_exists( $part, $entry ) ) {
2 ✔
8148
                                return false;
×
8149
                        }
8150

8151
                        if( empty( $parts ) ) {
2 ✔
8152
                                unset( $entry[$part] );
2 ✔
8153
                                return true;
2 ✔
8154
                        }
8155

8156
                        return $this->unsetValue( $entry[$part], $parts );
2 ✔
8157
                }
8158

8159
                if( $entry instanceof \ArrayAccess )
×
8160
                {
8161
                        if( !isset( $entry[$part] ) && !$entry->offsetExists( $part ) ) {
×
8162
                                return false;
×
8163
                        }
8164

8165
                        if( empty( $parts ) )
×
8166
                        {
8167
                                $entry->offsetUnset( $part );
×
8168
                                return true;
×
8169
                        }
8170

8171
                        $value = $entry[$part];
×
8172

8173
                        if( !$this->unsetValue( $value, $parts ) ) {
×
8174
                                return false;
×
8175
                        }
8176

8177
                        $entry[$part] = $value;
×
8178
                        return true;
×
8179
                }
8180

8181
                if( is_object( $entry ) )
×
8182
                {
8183
                        if( !array_key_exists( (string) $part, get_object_vars( $entry ) ) && !isset( $entry->{$part} ) ) {
×
8184
                                return false;
×
8185
                        }
8186

8187
                        if( empty( $parts ) )
×
8188
                        {
8189
                                unset( $entry->{$part} );
×
8190
                                return true;
×
8191
                        }
8192

8193
                        $value = $entry->{$part};
×
8194

8195
                        if( !$this->unsetValue( $value, $parts ) ) {
×
8196
                                return false;
×
8197
                        }
8198

8199
                        $entry->{$part} = $value;
×
8200
                        return true;
×
8201
                }
8202

8203
                return false;
×
8204
        }
8205

8206

8207
        /**
8208
         * Visits each entry, calls the callback and returns the items in the result argument
8209
         *
8210
         * @param iterable<int|string,mixed> $entries List of entries with children (optional)
8211
         * @param array<mixed> $result Numerically indexed list of all visited entries
8212
         * @param int $level Current depth of the nodes in the tree
8213
         * @param callable|null $callback Callback with ($entry, $key, $level) arguments, returns the entry added to result
8214
         * @param string $nestKey Key to the children of each entry
8215
         * @param array<mixed>|object|null $parent Parent entry
8216
         */
8217
        protected function visit( iterable $entries, array &$result, int $level, ?callable $callback, string $nestKey, array|object|null $parent = null ) : void
8218
        {
8219
                if( $level >= self::RECURSION_LIMIT )
5 ✔
8220
                {
8221
                        $this->visitStack( $entries, $result, $level, $callback, $nestKey, $parent );
×
8222
                        return;
×
8223
                }
8224

8225
                foreach( $entries as $key => $entry )
5 ✔
8226
                {
8227
                        $result[] = $callback ? $callback( $entry, $key, $level, $parent ) : $entry;
5 ✔
8228

8229
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$nestKey] ) ) {
5 ✔
8230
                                $children = $entry[$nestKey];
4 ✔
8231
                        } elseif( is_object( $entry ) && isset( $entry->{$nestKey} ) ) {
1 ✔
8232
                                $children = $entry->{$nestKey};
1 ✔
8233
                        } else {
8234
                                continue;
×
8235
                        }
8236

8237
                        if( is_iterable( $children ) ) {
5 ✔
8238
                                $this->visit( $children, $result, $level + 1, $callback, $nestKey, $entry );
5 ✔
8239
                        }
8240
                }
8241
        }
8242

8243

8244
        /**
8245
         * Visits each entry iteratively to avoid deep recursion.
8246
         *
8247
         * @param iterable<int|string,mixed> $entries List of entries with children (optional)
8248
         * @param array<mixed> $result Numerically indexed list of all visited entries
8249
         * @param int $level Current depth of the nodes in the tree
8250
         * @param callable|null $callback Callback with ($entry, $key, $level) arguments, returns the entry added to result
8251
         * @param string $nestKey Key to the children of each entry
8252
         * @param array<mixed>|object|null $parent Parent entry
8253
         */
8254
        protected function visitStack( iterable $entries, array &$result, int $level, ?callable $callback, string $nestKey, array|object|null $parent = null ) : void
8255
        {
8256
                $stack = [];
×
8257

8258
                foreach( array_reverse( $this->array( $entries ), true ) as $key => $entry ) {
×
8259
                        $stack[] = [$key, $entry, $level, $parent];
×
8260
                }
8261

8262
                while( !empty( $stack ) )
×
8263
                {
8264
                        [$key, $entry, $level, $parent] = array_pop( $stack );
×
8265

8266
                        $result[] = $callback ? $callback( $entry, $key, $level, $parent ) : $entry;
×
8267

8268
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$nestKey] ) ) {
×
8269
                                $children = $entry[$nestKey];
×
8270
                        } elseif( is_object( $entry ) && isset( $entry->{$nestKey} ) ) {
×
8271
                                $children = $entry->{$nestKey};
×
8272
                        } else {
8273
                                continue;
×
8274
                        }
8275

8276
                        if( is_iterable( $children ) )
×
8277
                        {
8278
                                foreach( array_reverse( $this->array( $children ), true ) as $ckey => $child ) {
×
8279
                                        $stack[] = [$ckey, $child, $level + 1, $entry];
×
8280
                                }
8281
                        }
8282
                }
8283
        }
8284

8285

8286
        /**
8287
         * Walks nested arrays recursively and applies the callback to leaf values.
8288
         *
8289
         * @param array<int|string,mixed> $list List of elements to walk
8290
         * @param callable $callback Function with (item, key, data) parameters
8291
         * @param mixed $data Arbitrary data that will be passed to the callback as third parameter
8292
         * @param int $level Current recursion depth
8293
         */
8294
        protected function walkRecursive( array &$list, callable $callback, mixed $data, int $level = 0 ) : void
8295
        {
8296
                if( $level >= self::RECURSION_LIMIT )
3 ✔
8297
                {
8298
                        $this->walkStack( $list, $callback, $data );
1 ✔
8299
                        return;
1 ✔
8300
                }
8301

8302
                foreach( $list as $key => &$item )
3 ✔
8303
                {
8304
                        if( is_array( $item ) ) {
3 ✔
8305
                                $this->walkRecursive( $item, $callback, $data, $level + 1 );
2 ✔
8306
                        } else {
8307
                                $callback( $item, $key, $data );
2 ✔
8308
                        }
8309
                }
8310

8311
                unset( $item );
3 ✔
8312
        }
8313

8314

8315
        /**
8316
         * Walks nested arrays iteratively to avoid deep recursion.
8317
         *
8318
         * @param array<int|string,mixed> $list List of elements to walk
8319
         * @param callable $callback Function with (item, key, data) parameters
8320
         * @param mixed $data Arbitrary data that will be passed to the callback as third parameter
8321
         */
8322
        protected function walkStack( array &$list, callable $callback, mixed $data ) : void
8323
        {
8324
                $stack = [['list' => &$list, 'keys' => array_keys( $list ), 'pos' => 0]];
1 ✔
8325
                $last = 0;
1 ✔
8326

8327
                while( $last >= 0 )
1 ✔
8328
                {
8329
                        $frame = &$stack[$last];
1 ✔
8330
                        $parent = &$frame['list'];
1 ✔
8331
                        $keys = $frame['keys'];
1 ✔
8332
                        $pos = $frame['pos'];
1 ✔
8333
                        $cnt = count( $keys );
1 ✔
8334
                        $descend = false;
1 ✔
8335

8336
                        while( $pos < $cnt )
1 ✔
8337
                        {
8338
                                $key = $keys[$pos++];
1 ✔
8339
                                $item = &$parent[$key];
1 ✔
8340

8341
                                if( is_array( $item ) )
1 ✔
8342
                                {
8343
                                        $frame['pos'] = $pos;
1 ✔
8344
                                        $stack[] = ['list' => &$item, 'keys' => array_keys( $item ), 'pos' => 0];
1 ✔
8345
                                        $last++;
1 ✔
8346
                                        $descend = true;
1 ✔
8347
                                        unset( $item );
1 ✔
8348
                                        break;
1 ✔
8349
                                }
8350

8351
                                $callback( $item, $key, $data );
1 ✔
8352
                                unset( $item );
1 ✔
8353
                        }
8354

8355
                        unset( $parent, $frame );
1 ✔
8356

8357
                        if( !$descend )
1 ✔
8358
                        {
8359
                                array_pop( $stack );
1 ✔
8360
                                $last--;
1 ✔
8361
                        }
8362
                }
8363
        }
8364
}
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