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

aimeos / map / 21869174301

10 Feb 2026 02:36PM UTC coverage: 97.808% (+0.5%) from 97.32%
21869174301

push

github

aimeos
Fixed tests for PHP 7.x

803 of 821 relevant lines covered (97.81%)

18.64 hits per line

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

97.8
/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-implements \ArrayAccess<int|string,mixed>
17
 * @template-implements \IteratorAggregate<int|string,mixed>
18
 */
19
class Map implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable
20
{
21
        /**
22
         * @var array<string,\Closure>
23
         */
24
        protected static $methods = [];
25

26
        /**
27
         * @var string
28
         */
29
        protected static $delim = '/';
30

31
        /**
32
         * @var array<int|string,mixed>|\Closure|iterable|mixed
33
         */
34
        protected $list;
35

36
        /**
37
         * @var string
38
         */
39
        protected $sep = '/';
40

41

42
        /**
43
         * Creates a new map.
44
         *
45
         * Returns a new map instance containing the list of elements. In case of
46
         * an empty array or null, the map object will contain an empty list.
47
         *
48
         * @param mixed $elements List of elements or single value
49
         */
50
        public function __construct( $elements = [] )
51
        {
52
                $this->sep = self::$delim;
1,260✔
53
                $this->list = $elements;
1,260✔
54
        }
55

56

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

78
                return call_user_func_array( \Closure::bind( static::$methods[$name], null, static::class ), $params );
3✔
79
        }
80

81

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

117
                $result = [];
6✔
118

119
                foreach( $this->list() as $key => $item )
6✔
120
                {
121
                        if( is_object( $item ) ) {
3✔
122
                                $result[$key] = $item->{$name}( ...$params );
3✔
123
                        }
124
                }
125

126
                return new static( $result );
6✔
127
        }
128

129

130
        /**
131
         * Returns the elements as a plain array.
132
         *
133
         * @return array<int|string,mixed> Plain array
134
         */
135
        public function __toArray() : array
136
        {
137
                return $this->list = $this->array( $this->list );
3✔
138
        }
139

140

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

163
                if( $char ) {
3✔
164
                        self::$delim = $char;
3✔
165
                }
166

167
                return $old;
3✔
168
        }
169

170

171
        /**
172
         * Creates a new map with the string splitted by the delimiter.
173
         *
174
         * This method creates a lazy Map and the string is split after calling
175
         * another method that operates on the Map contents.
176
         *
177
         * Examples:
178
         *  Map::explode( ',', 'a,b,c' );
179
         *  Map::explode( '<-->', 'a a<-->b b<-->c c' );
180
         *  Map::explode( '', 'string' );
181
         *  Map::explode( '|', 'a|b|c', 2 );
182
         *  Map::explode( '', 'string', 2 );
183
         *  Map::explode( '|', 'a|b|c|d', -2 );
184
         *  Map::explode( '', 'string', -3 );
185
         *
186
         * Results:
187
         *  ['a', 'b', 'c']
188
         *  ['a a', 'b b', 'c c']
189
         *  ['s', 't', 'r', 'i', 'n', 'g']
190
         *  ['a', 'b|c']
191
         *  ['s', 't', 'ring']
192
         *  ['a', 'b']
193
         *  ['s', 't', 'r']
194
         *
195
         * A limit of "0" is treated the same as "1". If limit is negative, the rest of
196
         * the string is dropped and not part of the returned map.
197
         *
198
         * @param string $delimiter Delimiter character, string or empty string
199
         * @param string $string String to split
200
         * @param int $limit Maximum number of element with the last element containing the rest of the string
201
         * @return self<int|string,mixed> New map with splitted parts
202
         */
203
        public static function explode( string $delimiter, string $string, int $limit = PHP_INT_MAX ) : self
204
        {
205
                if( $delimiter !== '' ) {
24✔
206
                        return new static( explode( $delimiter, $string, $limit ) );
12✔
207
                }
208

209
                $limit = $limit ?: 1;
12✔
210
                $parts = mb_str_split( $string );
12✔
211

212
                if( $limit < 1 ) {
12✔
213
                        return new static( array_slice( $parts, 0, $limit ) );
3✔
214
                }
215

216
                if( $limit < count( $parts ) )
9✔
217
                {
218
                        $result = array_slice( $parts, 0, $limit );
3✔
219
                        $result[] = join( '', array_slice( $parts, $limit ) );
3✔
220

221
                        return new static( $result );
3✔
222
                }
223

224
                return new static( $parts );
6✔
225
        }
226

227

228
        /**
229
         * Creates a new map filled with given value.
230
         *
231
         * Exapmles:
232
         *  Map::fill( 3, 'a' );
233
         *  Map::fill( 3, 'a', 2 );
234
         *  Map::fill( 3, 'a', -2 );
235
         *
236
         * Results:
237
         * The first example will return [0 => 'a', 1 => 'a', 2 => 'a']. The second
238
         * example will return [2 => 'a', 3 => 'a', 4 => 'a'] and the last one
239
         * [-2 => 'a', -1 => 'a', 0 => 'a'] (PHP 8) or [-2 => 'a', 0 => 'a', 1 => 'a'] (PHP 7).
240
         *
241
         * @param int $num Number of elements to create
242
         * @param mixed $value Value to fill the map with
243
         * @param int $start Start index for the elements
244
         * @return self<int|string,mixed> New map with filled elements
245
         */
246
        public static function fill( int $num, $value, int $start = 0 ) : self
247
        {
248
                return new static( array_fill( $start, $num, $value ) );
6✔
249
        }
250

251

252
        /**
253
         * Creates a new map instance if the value isn't one already.
254
         *
255
         * Examples:
256
         *  Map::from( [] );
257
         *  Map::from( null );
258
         *  Map::from( 'a' );
259
         *  Map::from( new Map() );
260
         *  Map::from( new ArrayObject() );
261
         *
262
         * Results:
263
         * A new map instance containing the list of elements. In case of an empty
264
         * array or null, the map object will contain an empty list. If a map object
265
         * is passed, it will be returned instead of creating a new instance.
266
         *
267
         * @param mixed $elements List of elements or single element
268
         * @return self<int|string,mixed> New map object
269
         */
270
        public static function from( $elements = [] ) : self
271
        {
272
                if( $elements instanceof self ) {
606✔
273
                        return $elements;
9✔
274
                }
275

276
                return new static( $elements );
606✔
277
        }
278

279

280
        /**
281
         * Creates a new map instance from a JSON string.
282
         *
283
         * This method creates a lazy Map and the string is decoded after calling
284
         * another method that operates on the Map contents. Thus, the exception in
285
         * case of an error isn't thrown immediately but after calling the next method.
286
         *
287
         * Examples:
288
         *  Map::fromJson( '["a", "b"]' );
289
         *  Map::fromJson( '{"a": "b"}' );
290
         *  Map::fromJson( '""' );
291
         *
292
         * Results:
293
         *  ['a', 'b']
294
         *  ['a' => 'b']
295
         *  ['']
296
         *
297
         * There are several options available for decoding the JSON string:
298
         * {@link https://www.php.net/manual/en/function.json-decode.php}
299
         * The parameter can be a single JSON_* constant or a bitmask of several
300
         * constants combine by bitwise OR (|), e.g.:
301
         *
302
         *  JSON_BIGINT_AS_STRING|JSON_INVALID_UTF8_IGNORE
303
         *
304
         * @param int $options Combination of JSON_* constants
305
         * @return self<int|string,mixed> New map from decoded JSON string
306
         * @throws \RuntimeException If the passed JSON string is invalid
307
         */
308
        public static function fromJson( string $json, int $options = JSON_BIGINT_AS_STRING ) : self
309
        {
310
                if( ( $result = json_decode( $json, true, 512, $options ) ) !== null ) {
12✔
311
                        return new static( $result );
9✔
312
                }
313

314
                throw new \RuntimeException( 'Not a valid JSON string: ' . $json );
3✔
315
        }
316

317

318
        /**
319
         * Registers a custom method or returns the existing one.
320
         *
321
         * The registed method has access to the class properties if called non-static.
322
         *
323
         * Examples:
324
         *  Map::method( 'foo', function( $arg1, $arg2 ) {
325
         *      return $this->list();
326
         *  } );
327
         *
328
         * Dynamic calls have access to the class properties:
329
         *  Map::from( ['bar'] )->foo( $arg1, $arg2 );
330
         *
331
         * Static calls yield an error because $this->elements isn't available:
332
         *  Map::foo( $arg1, $arg2 );
333
         *
334
         * @param string $method Method name
335
         * @param \Closure|null $fcn Anonymous function or NULL to return the closure if available
336
         * @return \Closure|null Registered anonymous function or NULL if none has been registered
337
         */
338
        public static function method( string $method, ?\Closure $fcn = null ) : ?\Closure
339
        {
340
                if( $fcn ) {
9✔
341
                        self::$methods[$method] = $fcn;
9✔
342
                }
343

344
                return self::$methods[$method] ?? null;
9✔
345
        }
346

347

348
        /**
349
         * Creates a new map by invoking the closure the given number of times.
350
         *
351
         * This method creates a lazy Map and the entries are generated after calling
352
         * another method that operates on the Map contents. Thus, the passed callback
353
         * is not called immediately!
354
         *
355
         * Examples:
356
         *  Map::times( 3, function( $num ) {
357
         *    return $num * 10;
358
         *  } );
359
         *  Map::times( 3, function( $num, &$key ) {
360
         *    $key = $num * 2;
361
         *    return $num * 5;
362
         *  } );
363
         *  Map::times( 2, function( $num ) {
364
         *    return new \stdClass();
365
         *  } );
366
         *
367
         * Results:
368
         *  [0 => 0, 1 => 10, 2 => 20]
369
         *  [0 => 0, 2 => 5, 4 => 10]
370
         *  [0 => new \stdClass(), 1 => new \stdClass()]
371
         *
372
         * @param int $num Number of times the function is called
373
         * @param \Closure $callback Function with (value, key) parameters and returns new value
374
         * @return self<int|string,mixed> New map with the generated elements
375
         */
376
        public static function times( int $num, \Closure $callback ) : self
377
        {
378
                $list = [];
9✔
379

380
                for( $i = 0; $i < $num; $i++ ) {
9✔
381
                        $key = $i;
9✔
382
                        $list[$key] = $callback( $i, $key );
9✔
383
                }
384

385
                return new static( $list );
9✔
386
        }
387

388

389
        /**
390
         * Returns the elements after the given one.
391
         *
392
         * Examples:
393
         *  Map::from( ['a' => 1, 'b' => 0] )->after( 1 );
394
         *  Map::from( [0 => 'b', 1 => 'a'] )->after( 'b' );
395
         *  Map::from( [0 => 'b', 1 => 'a'] )->after( 'c' );
396
         *  Map::from( ['a', 'c', 'b'] )->after( function( $item, $key ) {
397
         *      return $item >= 'c';
398
         *  } );
399
         *
400
         * Results:
401
         *  ['b' => 0]
402
         *  [1 => 'a']
403
         *  []
404
         *  [2 => 'b']
405
         *
406
         * The keys are preserved using this method.
407
         *
408
         * @param \Closure|int|string $value Value or function with (item, key) parameters
409
         * @return self<int|string,mixed> New map with the elements after the given one
410
         */
411
        public function after( $value ) : self
412
        {
413
                if( ( $pos = $this->pos( $value ) ) === null ) {
12✔
414
                        return new static();
3✔
415
                }
416

417
                return new static( array_slice( $this->list(), $pos + 1, null, true ) );
9✔
418
        }
419

420

421
        /**
422
         * Returns the elements as a plain array.
423
         *
424
         * @return array<int|string,mixed> Plain array
425
         */
426
        public function all() : array
427
        {
428
                return $this->list = $this->array( $this->list );
×
429
        }
430

431

432
        /**
433
         * Tests if at least one element satisfies the callback function.
434
         *
435
         * Examples:
436
         *  Map::from( ['a', 'b'] )->any( function( $item, $key ) {
437
         *    return $item === 'a';
438
         *  } );
439
         *  Map::from( ['a', 'b'] )->any( function( $item, $key ) {
440
         *    return !is_string( $item );
441
         *  } );
442
         *
443
         * Results:
444
         * The first example will return TRUE while the last one will return FALSE
445
         *
446
         * @param \Closure $callback Anonymous function with (item, key) parameter
447
         * @return bool TRUE if at least one element satisfies the callback function, FALSE if not
448
         */
449
        public function any( \Closure $callback ) : bool
450
        {
451
                if( function_exists( 'array_any' ) ) {
3✔
452
                        return array_any( $this->list(), $callback );
1✔
453
                }
454

455
                foreach( $this->list() as $key => $item )
2✔
456
                {
457
                        if( $callback( $item, $key ) ) {
2✔
458
                                return true;
2✔
459
                        }
460
                }
461

462
                return false;
2✔
463
        }
464

465

466
        /**
467
         * Sorts all elements in reverse order and maintains the key association.
468
         *
469
         * Examples:
470
         *  Map::from( ['b' => 0, 'a' => 1] )->arsort();
471
         *  Map::from( ['a', 'b'] )->arsort();
472
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsort();
473
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsort( SORT_STRING|SORT_FLAG_CASE );
474
         *
475
         * Results:
476
         *  ['a' => 1, 'b' => 0]
477
         *  ['b', 'a']
478
         *  [1 => 'b', 0 => 'C']
479
         *  [0 => 'C', 1 => 'b'] // because 'C' -> 'c' and 'c' > 'b'
480
         *
481
         * The parameter modifies how the values are compared. Possible parameter values are:
482
         * - SORT_REGULAR : compare elements normally (don't change types)
483
         * - SORT_NUMERIC : compare elements numerically
484
         * - SORT_STRING : compare elements as strings
485
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
486
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
487
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
488
         *
489
         * The keys are preserved using this method and no new map is created.
490
         *
491
         * @param int $options Sort options for arsort()
492
         * @return self<int|string,mixed> Updated map for fluid interface
493
         */
494
        public function arsort( int $options = SORT_REGULAR ) : self
495
        {
496
                arsort( $this->list(), $options );
12✔
497
                return $this;
12✔
498
        }
499

500

501
        /**
502
         * Sorts a copy of all elements in reverse order and maintains the key association.
503
         *
504
         * Examples:
505
         *  Map::from( ['b' => 0, 'a' => 1] )->arsorted();
506
         *  Map::from( ['a', 'b'] )->arsorted();
507
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsorted();
508
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsorted( SORT_STRING|SORT_FLAG_CASE );
509
         *
510
         * Results:
511
         *  ['a' => 1, 'b' => 0]
512
         *  ['b', 'a']
513
         *  [1 => 'b', 0 => 'C']
514
         *  [0 => 'C', 1 => 'b'] // because 'C' -> 'c' and 'c' > 'b'
515
         *
516
         * The parameter modifies how the values are compared. Possible parameter values are:
517
         * - SORT_REGULAR : compare elements normally (don't change types)
518
         * - SORT_NUMERIC : compare elements numerically
519
         * - SORT_STRING : compare elements as strings
520
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
521
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
522
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
523
         *
524
         * The keys are preserved using this method and a new map is created.
525
         *
526
         * @param int $options Sort options for arsort()
527
         * @return self<int|string,mixed> Updated map for fluid interface
528
         */
529
        public function arsorted( int $options = SORT_REGULAR ) : self
530
        {
531
                return ( clone $this )->arsort( $options );
3✔
532
        }
533

534

535
        /**
536
         * Sorts all elements and maintains the key association.
537
         *
538
         * Examples:
539
         *  Map::from( ['a' => 1, 'b' => 0] )->asort();
540
         *  Map::from( [0 => 'b', 1 => 'a'] )->asort();
541
         *  Map::from( [0 => 'C', 1 => 'b'] )->asort();
542
         *  Map::from( [0 => 'C', 1 => 'b'] )->arsort( SORT_STRING|SORT_FLAG_CASE );
543
         *
544
         * Results:
545
         *  ['b' => 0, 'a' => 1]
546
         *  [1 => 'a', 0 => 'b']
547
         *  [0 => 'C', 1 => 'b'] // because 'C' < 'b'
548
         *  [1 => 'b', 0 => 'C'] // because 'C' -> 'c' and 'c' > 'b'
549
         *
550
         * The parameter modifies how the values are compared. Possible parameter values are:
551
         * - SORT_REGULAR : compare elements normally (don't change types)
552
         * - SORT_NUMERIC : compare elements numerically
553
         * - SORT_STRING : compare elements as strings
554
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
555
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
556
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
557
         *
558
         * The keys are preserved using this method and no new map is created.
559
         *
560
         * @param int $options Sort options for asort()
561
         * @return self<int|string,mixed> Updated map for fluid interface
562
         */
563
        public function asort( int $options = SORT_REGULAR ) : self
564
        {
565
                asort( $this->list(), $options );
12✔
566
                return $this;
12✔
567
        }
568

569

570
        /**
571
         * Sorts a copy of all elements and maintains the key association.
572
         *
573
         * Examples:
574
         *  Map::from( ['a' => 1, 'b' => 0] )->asorted();
575
         *  Map::from( [0 => 'b', 1 => 'a'] )->asorted();
576
         *  Map::from( [0 => 'C', 1 => 'b'] )->asorted();
577
         *  Map::from( [0 => 'C', 1 => 'b'] )->asorted( SORT_STRING|SORT_FLAG_CASE );
578
         *
579
         * Results:
580
         *  ['b' => 0, 'a' => 1]
581
         *  [1 => 'a', 0 => 'b']
582
         *  [0 => 'C', 1 => 'b'] // because 'C' < 'b'
583
         *  [1 => 'b', 0 => 'C'] // because 'C' -> 'c' and 'c' > 'b'
584
         *
585
         * The parameter modifies how the values are compared. Possible parameter values are:
586
         * - SORT_REGULAR : compare elements normally (don't change types)
587
         * - SORT_NUMERIC : compare elements numerically
588
         * - SORT_STRING : compare elements as strings
589
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
590
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
591
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
592
         *
593
         * The keys are preserved using this method and a new map is created.
594
         *
595
         * @param int $options Sort options for asort()
596
         * @return self<int|string,mixed> Updated map for fluid interface
597
         */
598
        public function asorted( int $options = SORT_REGULAR ) : self
599
        {
600
                return ( clone $this )->asort( $options );
3✔
601
        }
602

603

604
        /**
605
         * Returns the value at the given position.
606
         *
607
         * Examples:
608
         *  Map::from( [1, 3, 5] )->at( 0 );
609
         *  Map::from( [1, 3, 5] )->at( 1 );
610
         *  Map::from( [1, 3, 5] )->at( -1 );
611
         *  Map::from( [1, 3, 5] )->at( 3 );
612
         *
613
         * Results:
614
         * The first line will return "1", the second one "3", the third one "5" and
615
         * the last one NULL.
616
         *
617
         * The position starts from zero and a position of "0" returns the first element
618
         * of the map, "1" the second and so on. If the position is negative, the
619
         * sequence will start from the end of the map.
620
         *
621
         * @param int $pos Position of the value in the map
622
         * @return mixed|null Value at the given position or NULL if no value is available
623
         */
624
        public function at( int $pos )
625
        {
626
                $pair = array_slice( $this->list(), $pos, 1 );
3✔
627
                return !empty( $pair ) ? current( $pair ) : null;
3✔
628
        }
629

630

631
        /**
632
         * Returns the average of all integer and float values in the map.
633
         *
634
         * Examples:
635
         *  Map::from( [1, 3, 5] )->avg();
636
         *  Map::from( [1, null, 5] )->avg();
637
         *  Map::from( [1, 'sum', 5] )->avg();
638
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( 'p' );
639
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->avg( 'i/p' );
640
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->avg( fn( $val, $key ) => $val['i']['p'] ?? null );
641
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( fn( $val, $key ) => $key < 1 ? $val : null );
642
         *
643
         * Results:
644
         * The first and second line will return "3", the third one "2", the forth
645
         * one "30", the fifth and sixth one "40" and the last one "30".
646
         *
647
         * Non-numeric values will be removed before calculation.
648
         *
649
         * NULL values are treated as 0, non-numeric values will generate an error.
650
         *
651
         * This does also work for multi-dimensional arrays by passing the keys
652
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
653
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
654
         * public properties of objects or objects implementing __isset() and __get() methods.
655
         *
656
         * @param Closure|string|null $col Closure, key or path to the values in the nested array or object to compute the average for
657
         * @return float Average of all elements or 0 if there are no elements in the map
658
         */
659
        public function avg( $col = null ) : float
660
        {
661
                $list = $this->list();
9✔
662
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list, 'is_numeric' );
9✔
663

664
                return !empty( $vals ) ? array_sum( $vals ) / count( $vals ) : 0;
9✔
665
        }
666

667

668
        /**
669
         * Returns the elements before the given one.
670
         *
671
         * Examples:
672
         *  Map::from( ['a' => 1, 'b' => 0] )->before( 0 );
673
         *  Map::from( [0 => 'b', 1 => 'a'] )->before( 'a' );
674
         *  Map::from( [0 => 'b', 1 => 'a'] )->before( 'b' );
675
         *  Map::from( ['a', 'c', 'b'] )->before( function( $item, $key ) {
676
         *      return $key >= 1;
677
         *  } );
678
         *
679
         * Results:
680
         *  ['a' => 1]
681
         *  [0 => 'b']
682
         *  []
683
         *  [0 => 'a']
684
         *
685
         * The keys are preserved using this method.
686
         *
687
         * @param \Closure|int|string $value Value or function with (item, key) parameters
688
         * @return self<int|string,mixed> New map with the elements before the given one
689
         */
690
        public function before( $value ) : self
691
        {
692
                return new static( array_slice( $this->list(), 0, $this->pos( $value ), true ) );
12✔
693
        }
694

695

696
        /**
697
         * Returns an element by key and casts it to boolean if possible.
698
         *
699
         * Examples:
700
         *  Map::from( ['a' => true] )->bool( 'a' );
701
         *  Map::from( ['a' => '1'] )->bool( 'a' );
702
         *  Map::from( ['a' => 1.1] )->bool( 'a' );
703
         *  Map::from( ['a' => '10'] )->bool( 'a' );
704
         *  Map::from( ['a' => 'abc'] )->bool( 'a' );
705
         *  Map::from( ['a' => ['b' => ['c' => true]]] )->bool( 'a/b/c' );
706
         *  Map::from( [] )->bool( 'c', function() { return rand( 1, 2 ); } );
707
         *  Map::from( [] )->bool( 'a', true );
708
         *
709
         *  Map::from( [] )->bool( 'b' );
710
         *  Map::from( ['b' => ''] )->bool( 'b' );
711
         *  Map::from( ['b' => null] )->bool( 'b' );
712
         *  Map::from( ['b' => [true]] )->bool( 'b' );
713
         *  Map::from( ['b' => resource] )->bool( 'b' );
714
         *  Map::from( ['b' => new \stdClass] )->bool( 'b' );
715
         *
716
         *  Map::from( [] )->bool( 'c', new \Exception( 'error' ) );
717
         *
718
         * Results:
719
         * The first eight examples will return TRUE while the 9th to 14th example
720
         * returns FALSE. The last example will throw an exception.
721
         *
722
         * This does also work for multi-dimensional arrays by passing the keys
723
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
724
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
725
         * public properties of objects or objects implementing __isset() and __get() methods.
726
         *
727
         * @param int|string $key Key or path to the requested item
728
         * @param mixed $default Default value if key isn't found (will be casted to bool)
729
         * @return bool Value from map or default value
730
         */
731
        public function bool( $key, $default = false ) : bool
732
        {
733
                return (bool) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
9✔
734
        }
735

736

737
        /**
738
         * Calls the given method on all items and returns the result.
739
         *
740
         * This method can call methods on the map entries that are also implemented
741
         * by the map object itself and are therefore not reachable when using the
742
         * magic __call() method.
743
         *
744
         * Examples:
745
         *  $item = new MyClass(); // implements methods get() and toArray()
746
         *  Map::from( [$item, $item] )->call( 'get', ['myprop'] );
747
         *  Map::from( [$item, $item] )->call( 'toArray' );
748
         *
749
         * Results:
750
         * The first example will return ['...', '...'] while the second one returns [[...], [...]].
751
         *
752
         * If some entries are not objects, they will be skipped. The map keys from the
753
         * original map are preserved in the returned map.
754
         *
755
         * @param string $name Method name
756
         * @param array<mixed> $params List of parameters
757
         * @return self<int|string,mixed> New map with results from all elements
758
         */
759
        public function call( string $name, array $params = [] ) : self
760
        {
761
                $result = [];
3✔
762

763
                foreach( $this->list() as $key => $item )
3✔
764
                {
765
                        if( is_object( $item ) ) {
3✔
766
                                $result[$key] = $item->{$name}( ...$params );
3✔
767
                        }
768
                }
769

770
                return new static( $result );
3✔
771
        }
772

773

774
        /**
775
         * Casts all entries to the passed type.
776
         *
777
         * Examples:
778
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast();
779
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast( 'bool' );
780
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast( 'int' );
781
         *  Map::from( [true, 1, 1.0, 'yes'] )->cast( 'float' );
782
         *  Map::from( [new stdClass, new stdClass] )->cast( 'array' );
783
         *  Map::from( [[], []] )->cast( 'object' );
784
         *
785
         * Results:
786
         * The examples will return (in this order):
787
         * ['1', '1', '1.0', 'yes']
788
         * [true, true, true, true]
789
         * [1, 1, 1, 0]
790
         * [1.0, 1.0, 1.0, 0.0]
791
         * [[], []]
792
         * [new stdClass, new stdClass]
793
         *
794
         * Casting arrays and objects to scalar values won't return anything useful!
795
         *
796
         * @param string $type Type to cast the values to ("string", "bool", "int", "float", "array", "object")
797
         * @return self<int|string,mixed> Updated map with casted elements
798
         */
799
        public function cast( string $type = 'string' ) : self
800
        {
801
                foreach( $this->list() as &$item )
3✔
802
                {
803
                        switch( $type )
804
                        {
805
                                case 'bool': $item = (bool) $item; break;
3✔
806
                                case 'int': $item = (int) $item; break;
3✔
807
                                case 'float': $item = (float) $item; break;
3✔
808
                                case 'string': $item = (string) $item; break;
3✔
809
                                case 'array': $item = (array) $item; break;
3✔
810
                                case 'object': $item = (object) $item; break;
3✔
811
                        }
812
                }
813

814
                return $this;
3✔
815
        }
816

817

818
        /**
819
         * Chunks the map into arrays with the given number of elements.
820
         *
821
         * Examples:
822
         *  Map::from( [0, 1, 2, 3, 4] )->chunk( 3 );
823
         *  Map::from( ['a' => 0, 'b' => 1, 'c' => 2] )->chunk( 2 );
824
         *
825
         * Results:
826
         *  [[0, 1, 2], [3, 4]]
827
         *  [['a' => 0, 'b' => 1], ['c' => 2]]
828
         *
829
         * The last chunk may contain less elements than the given number.
830
         *
831
         * The sub-arrays of the returned map are plain PHP arrays. If you need Map
832
         * objects, then wrap them with Map::from() when you iterate over the map.
833
         *
834
         * @param int $size Maximum size of the sub-arrays
835
         * @param bool $preserve Preserve keys in new map
836
         * @return self<int|string,mixed> New map with elements chunked in sub-arrays
837
         * @throws \InvalidArgumentException If size is smaller than 1
838
         */
839
        public function chunk( int $size, bool $preserve = false ) : self
840
        {
841
                if( $size < 1 ) {
9✔
842
                        throw new \InvalidArgumentException( 'Chunk size must be greater or equal than 1' );
3✔
843
                }
844

845
                return new static( array_chunk( $this->list(), $size, $preserve ) );
6✔
846
        }
847

848

849
        /**
850
         * Removes all elements from the current map.
851
         *
852
         * @return self<int|string,mixed> Updated map for fluid interface
853
         */
854
        public function clear() : self
855
        {
856
                $this->list = [];
12✔
857
                return $this;
12✔
858
        }
859

860

861
        /**
862
         * Clones the map and all objects within.
863
         *
864
         * Examples:
865
         *  Map::from( [new \stdClass, new \stdClass] )->clone();
866
         *
867
         * Results:
868
         *   [new \stdClass, new \stdClass]
869
         *
870
         * The objects within the Map are NOT the same as before but new cloned objects.
871
         * This is different to copy(), which doesn't clone the objects within.
872
         *
873
         * The keys are preserved using this method.
874
         *
875
         * @return self<int|string,mixed> New map with cloned objects
876
         */
877
        public function clone() : self
878
        {
879
                $list = [];
3✔
880

881
                foreach( $this->list() as $key => $item ) {
3✔
882
                        $list[$key] = is_object( $item ) ? clone $item : $item;
3✔
883
                }
884

885
                return new static( $list );
3✔
886
        }
887

888

889
        /**
890
         * Returns the values of a single column/property from an array of arrays or objects in a new map.
891
         *
892
         * Examples:
893
         *  Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( 'val' );
894
         *  Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( 'val', 'id' );
895
         *  Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( null, 'id' );
896
         *  Map::from( [['id' => 'ix', 'val' => 'v1'], ['id' => 'ix', 'val' => 'v2']] )->col( null, 'id' );
897
         *  Map::from( [['foo' => ['bar' => 'one', 'baz' => 'two']]] )->col( 'foo/baz', 'foo/bar' );
898
         *  Map::from( [['foo' => ['bar' => 'one']]] )->col( 'foo/baz', 'foo/bar' );
899
         *  Map::from( [['foo' => ['baz' => 'two']]] )->col( 'foo/baz', 'foo/bar' );
900
         *
901
         * Results:
902
         *  ['v1', 'v2']
903
         *  ['i1' => 'v1', 'i2' => 'v2']
904
         *  ['i1' => ['id' => 'i1', 'val' => 'v1'], 'i2' => ['id' => 'i2', 'val' => 'v2']]
905
         *  ['ix' => ['id' => 'ix', 'val' => 'v2']]
906
         *  ['one' => 'two']
907
         *  ['one' => null]
908
         *  ['two']
909
         *
910
         * If $indexcol is omitted, it's value is NULL or not set, the result will be indexed from 0-n.
911
         * Items with the same value for $indexcol will overwrite previous items and only the last
912
         * one will be part of the resulting map.
913
         *
914
         * This does also work to map values from multi-dimensional arrays by passing the keys
915
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
916
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
917
         * public properties of objects or objects implementing __isset() and __get() methods.
918
         *
919
         * @param string|null $valuecol Name or path of the value property
920
         * @param string|null $indexcol Name or path of the index property
921
         * @return self<int|string,mixed> New map with mapped entries
922
         */
923
        public function col( ?string $valuecol = null, ?string $indexcol = null ) : self
924
        {
925
                $vparts = explode( $this->sep, (string) $valuecol );
27✔
926
                $iparts = explode( $this->sep, (string) $indexcol );
27✔
927

928
                if( ( $valuecol === null || count( $vparts ) === 1 )
27✔
929
                        && ( $indexcol === null || count( $iparts ) === 1 )
27✔
930
                ) {
931
                        return new static( array_column( $this->list(), $valuecol, $indexcol ) );
18✔
932
                }
933

934
                $list = [];
9✔
935

936
                foreach( $this->list() as $key => $item )
9✔
937
                {
938
                        $v = $valuecol ? $this->val( $item, $vparts ) : $item;
9✔
939

940
                        if( $indexcol && ( $k = (string) $this->val( $item, $iparts ) ) ) {
9✔
941
                                $list[$k] = $v;
6✔
942
                        } else {
943
                                $list[$key] = $v;
3✔
944
                        }
945
                }
946

947
                return new static( $list );
9✔
948
        }
949

950

951
        /**
952
         * Collapses all sub-array elements recursively to a new map overwriting existing keys.
953
         *
954
         * Examples:
955
         *  Map::from( [0 => ['a' => 0, 'b' => 1], 1 => ['c' => 2, 'd' => 3]] )->collapse();
956
         *  Map::from( [0 => ['a' => 0, 'b' => 1], 1 => ['a' => 2]] )->collapse();
957
         *  Map::from( [0 => [0 => 0, 1 => 1], 1 => [0 => ['a' => 2, 0 => 3], 1 => 4]] )->collapse();
958
         *  Map::from( [0 => [0 => 0, 'a' => 1], 1 => [0 => ['b' => 2, 0 => 3], 1 => 4]] )->collapse( 1 );
959
         *  Map::from( [0 => [0 => 0, 'a' => 1], 1 => Map::from( [0 => ['b' => 2, 0 => 3], 1 => 4] )] )->collapse();
960
         *
961
         * Results:
962
         *  ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3]
963
         *  ['a' => 2, 'b' => 1]
964
         *  [0 => 3, 1 => 4, 'a' => 2]
965
         *  [0 => ['b' => 2, 0 => 3], 1 => 4, 'a' => 1]
966
         *  [0 => 3, 'a' => 1, 'b' => 2, 1 => 4]
967
         *
968
         * The keys are preserved and already existing elements will be overwritten.
969
         * This is also true for numeric keys! A value smaller than 1 for depth will
970
         * return the same map elements. Collapsing does also work if elements
971
         * implement the "Traversable" interface (which the Map object does).
972
         *
973
         * This method is similar than flat() but replaces already existing elements.
974
         *
975
         * @param int|null $depth Number of levels to collapse for multi-dimensional arrays or NULL for all
976
         * @return self<int|string,mixed> New map with all sub-array elements added into it recursively, up to the specified depth
977
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
978
         */
979
        public function collapse( ?int $depth = null ) : self
980
        {
981
                if( $depth < 0 ) {
18✔
982
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
3✔
983
                }
984

985
                $result = [];
15✔
986
                $this->kflatten( $this->list(), $result, $depth ?? 0x7fffffff );
15✔
987
                return new static( $result );
15✔
988
        }
989

990

991
        /**
992
         * Combines the values of the map as keys with the passed elements as values.
993
         *
994
         * Examples:
995
         *  Map::from( ['name', 'age'] )->combine( ['Tom', 29] );
996
         *
997
         * Results:
998
         *  ['name' => 'Tom', 'age' => 29]
999
         *
1000
         * @param iterable<int|string,mixed> $values Values of the new map
1001
         * @return self<int|string,mixed> New map
1002
         */
1003
        public function combine( iterable $values ) : self
1004
        {
1005
                return new static( array_combine( $this->list(), $this->array( $values ) ) );
3✔
1006
        }
1007

1008

1009
        /**
1010
         * Compares the value against all map elements.
1011
         *
1012
         * This method is an alias for strCompare().
1013
         *
1014
         * @param string $value Value to compare map elements to
1015
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
1016
         * @return bool TRUE If at least one element matches, FALSE if value is not in map
1017
         * @deprecated Use strCompare() method instead
1018
         */
1019
        public function compare( string $value, bool $case = true ) : bool
1020
        {
1021
                return $this->strCompare( $value, $case );
3✔
1022
        }
1023

1024

1025
        /**
1026
         * Pushs all of the given elements onto the map with new keys without creating a new map.
1027
         *
1028
         * Examples:
1029
         *  Map::from( ['foo'] )->concat( new Map( ['bar'] ));
1030
         *
1031
         * Results:
1032
         *  ['foo', 'bar']
1033
         *
1034
         * The keys of the passed elements are NOT preserved!
1035
         *
1036
         * @param iterable<int|string,mixed> $elements List of elements
1037
         * @return self<int|string,mixed> Updated map for fluid interface
1038
         */
1039
        public function concat( iterable $elements ) : self
1040
        {
1041
                $this->list();
6✔
1042

1043
                foreach( $elements as $item ) {
6✔
1044
                        $this->list[] = $item;
6✔
1045
                }
1046

1047
                return $this;
6✔
1048
        }
1049

1050

1051
        /**
1052
         * Determines if an item exists in the map.
1053
         *
1054
         * This method combines the power of the where() method with some() to check
1055
         * if the map contains at least one of the passed values or conditions.
1056
         *
1057
         * Examples:
1058
         *  Map::from( ['a', 'b'] )->contains( 'a' );
1059
         *  Map::from( ['a', 'b'] )->contains( ['a', 'c'] );
1060
         *  Map::from( ['a', 'b'] )->contains( function( $item, $key ) {
1061
         *    return $item === 'a'
1062
         *  } );
1063
         *  Map::from( [['type' => 'name']] )->contains( 'type', 'name' );
1064
         *  Map::from( [['type' => 'name']] )->contains( 'type', '==', 'name' );
1065
         *
1066
         * Results:
1067
         * All method calls will return TRUE because at least "a" is included in the
1068
         * map or there's a "type" key with a value "name" like in the last two
1069
         * examples.
1070
         *
1071
         * Check the where() method for available operators.
1072
         *
1073
         * @param \Closure|iterable|mixed $values Anonymous function with (item, key) parameter, element or list of elements to test against
1074
         * @param string|null $op Operator used for comparison
1075
         * @param mixed $value Value used for comparison
1076
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
1077
         */
1078
        public function contains( $key, ?string $operator = null, $value = null ) : bool
1079
        {
1080
                if( $operator === null ) {
6✔
1081
                        return $this->some( $key );
3✔
1082
                }
1083

1084
                if( $value === null ) {
3✔
1085
                        return !$this->where( $key, '==', $operator )->isEmpty();
3✔
1086
                }
1087

1088
                return !$this->where( $key, $operator, $value )->isEmpty();
3✔
1089
        }
1090

1091

1092
        /**
1093
         * Creates a new map with the same elements.
1094
         *
1095
         * Both maps share the same array until one of the map objects modifies the
1096
         * array. Then, the array is copied and the copy is modfied (copy on write).
1097
         *
1098
         * @return self<int|string,mixed> New map
1099
         */
1100
        public function copy() : self
1101
        {
1102
                return clone $this;
9✔
1103
        }
1104

1105

1106
        /**
1107
         * Counts the total number of elements in the map.
1108
         *
1109
         * @return int Number of elements
1110
         */
1111
        public function count() : int
1112
        {
1113
                return count( $this->list() );
51✔
1114
        }
1115

1116

1117
        /**
1118
         * Counts how often the same values are in the map.
1119
         *
1120
         * Examples:
1121
         *  Map::from( [1, 'foo', 2, 'foo', 1] )->countBy();
1122
         *  Map::from( [1.11, 3.33, 3.33, 9.99] )->countBy();
1123
         *  Map::from( [['i' => ['p' => 1.11]], ['i' => ['p' => 3.33]], ['i' => ['p' => 3.33]]] )->countBy( 'i/p' );
1124
         *  Map::from( ['a@gmail.com', 'b@yahoo.com', 'c@gmail.com'] )->countBy( function( $email ) {
1125
         *    return substr( strrchr( $email, '@' ), 1 );
1126
         *  } );
1127
         *
1128
         * Results:
1129
         *  [1 => 2, 'foo' => 2, 2 => 1]
1130
         *  ['1.11' => 1, '3.33' => 2, '9.99' => 1]
1131
         *  ['1.11' => 1, '3.33' => 2]
1132
         *  ['gmail.com' => 2, 'yahoo.com' => 1]
1133
         *
1134
         * Counting values does only work for integers and strings because these are
1135
         * the only types allowed as array keys. All elements are casted to strings
1136
         * if no callback is passed. Custom callbacks need to make sure that only
1137
         * string or integer values are returned!
1138
         *
1139
         * This does also work for multi-dimensional arrays by passing the keys
1140
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1141
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1142
         * public properties of objects or objects implementing __isset() and __get() methods.
1143
         *
1144
         * @param \Closure|string|null $col Key as "key1/key2/key3" or function with (value, key) parameters returning the values for counting
1145
         * @return self<int|string,mixed> New map with values as keys and their count as value
1146
         */
1147
        public function countBy( $col = null ) : self
1148
        {
1149
                if( !( $col instanceof \Closure ) )
12✔
1150
                {
1151
                        $parts = $col ? explode( $this->sep, (string) $col ) : [];
9✔
1152

1153
                        $col = function( $item ) use ( $parts ) {
9✔
1154
                                return (string) $this->val( $item, $parts );
9✔
1155
                        };
9✔
1156
                }
1157

1158
                return new static( array_count_values( array_map( $col, $this->list() ) ) );
12✔
1159
        }
1160

1161

1162
        /**
1163
         * Dumps the map content and terminates the script.
1164
         *
1165
         * The dd() method is very helpful to see what are the map elements passed
1166
         * between two map methods in a method call chain. It stops execution of the
1167
         * script afterwards to avoid further output.
1168
         *
1169
         * Examples:
1170
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->sort()->dd();
1171
         *
1172
         * Results:
1173
         *  Array
1174
         *  (
1175
         *      [0] => bar
1176
         *      [1] => foo
1177
         *  )
1178
         *
1179
         * @param callable|null $callback Function receiving the map elements as parameter (optional)
1180
         */
1181
        public function dd( ?callable $callback = null ) : void
1182
        {
1183
                $this->dump( $callback );
×
1184
                exit( 1 );
×
1185
        }
1186

1187

1188
        /**
1189
         * Returns the keys/values in the map whose values are not present in the passed elements in a new map.
1190
         *
1191
         * Examples:
1192
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->diff( ['bar'] );
1193
         *
1194
         * Results:
1195
         *  ['a' => 'foo']
1196
         *
1197
         * If a callback is passed, the given function will be used to compare the values.
1198
         * The function must accept two parameters (value A and B) and must return
1199
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
1200
         * greater than value B. Both, a method name and an anonymous function can be passed:
1201
         *
1202
         *  Map::from( [0 => 'a'] )->diff( [0 => 'A'], 'strcasecmp' );
1203
         *  Map::from( ['b' => 'a'] )->diff( ['B' => 'A'], 'strcasecmp' );
1204
         *  Map::from( ['b' => 'a'] )->diff( ['c' => 'A'], function( $valA, $valB ) {
1205
         *      return strtolower( $valA ) <=> strtolower( $valB );
1206
         *  } );
1207
         *
1208
         * All examples will return an empty map because both contain the same values
1209
         * when compared case insensitive.
1210
         *
1211
         * The keys are preserved using this method.
1212
         *
1213
         * @param iterable<int|string,mixed> $elements List of elements
1214
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
1215
         * @return self<int|string,mixed> New map
1216
         */
1217
        public function diff( iterable $elements, ?callable $callback = null ) : self
1218
        {
1219
                if( $callback ) {
9✔
1220
                        return new static( array_udiff( $this->list(), $this->array( $elements ), $callback ) );
3✔
1221
                }
1222

1223
                return new static( array_diff( $this->list(), $this->array( $elements ) ) );
9✔
1224
        }
1225

1226

1227
        /**
1228
         * Returns the keys/values in the map whose keys AND values are not present in the passed elements in a new map.
1229
         *
1230
         * Examples:
1231
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->diffAssoc( new Map( ['foo', 'b' => 'bar'] ) );
1232
         *
1233
         * Results:
1234
         *  ['a' => 'foo']
1235
         *
1236
         * If a callback is passed, the given function will be used to compare the values.
1237
         * The function must accept two parameters (value A and B) and must return
1238
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
1239
         * greater than value B. Both, a method name and an anonymous function can be passed:
1240
         *
1241
         *  Map::from( [0 => 'a'] )->diffAssoc( [0 => 'A'], 'strcasecmp' );
1242
         *  Map::from( ['b' => 'a'] )->diffAssoc( ['B' => 'A'], 'strcasecmp' );
1243
         *  Map::from( ['b' => 'a'] )->diffAssoc( ['c' => 'A'], function( $valA, $valB ) {
1244
         *      return strtolower( $valA ) <=> strtolower( $valB );
1245
         *  } );
1246
         *
1247
         * The first example will return an empty map because both contain the same
1248
         * values when compared case insensitive. The second and third example will return
1249
         * an empty map because 'A' is part of the passed array but the keys doesn't match
1250
         * ("b" vs. "B" and "b" vs. "c").
1251
         *
1252
         * The keys are preserved using this method.
1253
         *
1254
         * @param iterable<int|string,mixed> $elements List of elements
1255
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
1256
         * @return self<int|string,mixed> New map
1257
         */
1258
        public function diffAssoc( iterable $elements, ?callable $callback = null ) : self
1259
        {
1260
                if( $callback ) {
6✔
1261
                        return new static( array_diff_uassoc( $this->list(), $this->array( $elements ), $callback ) );
3✔
1262
                }
1263

1264
                return new static( array_diff_assoc( $this->list(), $this->array( $elements ) ) );
6✔
1265
        }
1266

1267

1268
        /**
1269
         * Returns the key/value pairs from the map whose keys are not present in the passed elements in a new map.
1270
         *
1271
         * Examples:
1272
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->diffKeys( new Map( ['foo', 'b' => 'baz'] ) );
1273
         *
1274
         * Results:
1275
         *  ['a' => 'foo']
1276
         *
1277
         * If a callback is passed, the given function will be used to compare the keys.
1278
         * The function must accept two parameters (key A and B) and must return
1279
         * -1 if key A is smaller than key B, 0 if both are equal and 1 if key A is
1280
         * greater than key B. Both, a method name and an anonymous function can be passed:
1281
         *
1282
         *  Map::from( [0 => 'a'] )->diffKeys( [0 => 'A'], 'strcasecmp' );
1283
         *  Map::from( ['b' => 'a'] )->diffKeys( ['B' => 'X'], 'strcasecmp' );
1284
         *  Map::from( ['b' => 'a'] )->diffKeys( ['c' => 'a'], function( $keyA, $keyB ) {
1285
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
1286
         *  } );
1287
         *
1288
         * The first and second example will return an empty map because both contain
1289
         * the same keys when compared case insensitive. The third example will return
1290
         * ['b' => 'a'] because the keys doesn't match ("b" vs. "c").
1291
         *
1292
         * The keys are preserved using this method.
1293
         *
1294
         * @param iterable<int|string,mixed> $elements List of elements
1295
         * @param  callable|null $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
1296
         * @return self<int|string,mixed> New map
1297
         */
1298
        public function diffKeys( iterable $elements, ?callable $callback = null ) : self
1299
        {
1300
                if( $callback ) {
6✔
1301
                        return new static( array_diff_ukey( $this->list(), $this->array( $elements ), $callback ) );
3✔
1302
                }
1303

1304
                return new static( array_diff_key( $this->list(), $this->array( $elements ) ) );
6✔
1305
        }
1306

1307

1308
        /**
1309
         * Dumps the map content using the given function (print_r by default).
1310
         *
1311
         * The dump() method is very helpful to see what are the map elements passed
1312
         * between two map methods in a method call chain.
1313
         *
1314
         * Examples:
1315
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->dump()->asort()->dump( 'var_dump' );
1316
         *
1317
         * Results:
1318
         *  Array
1319
         *  (
1320
         *      [a] => foo
1321
         *      [b] => bar
1322
         *  )
1323
         *  array(1) {
1324
         *    ["b"]=>
1325
         *    string(3) "bar"
1326
         *    ["a"]=>
1327
         *    string(3) "foo"
1328
         *  }
1329
         *
1330
         * @param callable|null $callback Function receiving the map elements as parameter (optional)
1331
         * @return self<int|string,mixed> Same map for fluid interface
1332
         */
1333
        public function dump( ?callable $callback = null ) : self
1334
        {
1335
                $callback ? $callback( $this->list() ) : print_r( $this->list() );
3✔
1336
                return $this;
3✔
1337
        }
1338

1339

1340
        /**
1341
         * Returns the duplicate values from the map.
1342
         *
1343
         * For nested arrays, you have to pass the name of the column of the nested
1344
         * array which should be used to check for duplicates.
1345
         *
1346
         * Examples:
1347
         *  Map::from( [1, 2, '1', 3] )->duplicates()
1348
         *  Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->duplicates( 'p' )
1349
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->duplicates( 'i/p' )
1350
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->duplicates( fn( $item, $key ) => $item['i']['p'] )
1351
         *
1352
         * Results:
1353
         *  [2 => '1']
1354
         *  [1 => ['p' => 1]]
1355
         *  [1 => ['i' => ['p' => 1]]]
1356
         *  [1 => ['i' => ['p' => 1]]]
1357
         *
1358
         * This does also work for multi-dimensional arrays by passing the keys
1359
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1360
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1361
         * public properties of objects or objects implementing __isset() and __get() methods.
1362
         *
1363
         * The keys are preserved using this method.
1364
         *
1365
         * @param \Closure|string|null $col Key, path of the nested array or anonymous function with ($item, $key) parameters returning the value for comparison
1366
         * @return self<int|string,mixed> New map
1367
         */
1368
        public function duplicates( $col = null ) : self
1369
        {
1370
                $list = $map = $this->list();
12✔
1371

1372
                if( $col !== null ) {
12✔
1373
                        $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
9✔
1374
                }
1375

1376
                return new static( array_diff_key( $list, array_unique( $map ) ) );
12✔
1377
        }
1378

1379

1380
        /**
1381
         * Executes a callback over each entry until FALSE is returned.
1382
         *
1383
         * Examples:
1384
         *  $result = [];
1385
         *  Map::from( [0 => 'a', 1 => 'b'] )->each( function( $value, $key ) use ( &$result ) {
1386
         *      $result[$key] = strtoupper( $value );
1387
         *      return false;
1388
         *  } );
1389
         *
1390
         * The $result array will contain [0 => 'A'] because FALSE is returned
1391
         * after the first entry and all other entries are then skipped.
1392
         *
1393
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1394
         * @return self<int|string,mixed> Same map for fluid interface
1395
         */
1396
        public function each( \Closure $callback ) : self
1397
        {
1398
                foreach( $this->list() as $key => $item )
6✔
1399
                {
1400
                        if( $callback( $item, $key ) === false ) {
6✔
1401
                                break;
3✔
1402
                        }
1403
                }
1404

1405
                return $this;
6✔
1406
        }
1407

1408

1409
        /**
1410
         * Determines if the map is empty or not.
1411
         *
1412
         * Examples:
1413
         *  Map::from( [] )->empty();
1414
         *  Map::from( ['a'] )->empty();
1415
         *
1416
         * Results:
1417
         *  The first example returns TRUE while the second returns FALSE
1418
         *
1419
         * The method is equivalent to isEmpty().
1420
         *
1421
         * @return bool TRUE if map is empty, FALSE if not
1422
         */
1423
        public function empty() : bool
1424
        {
1425
                return empty( $this->list() );
6✔
1426
        }
1427

1428

1429
        /**
1430
         * Tests if the passed elements are equal to the elements in the map.
1431
         *
1432
         * Examples:
1433
         *  Map::from( ['a'] )->equals( ['a', 'b'] );
1434
         *  Map::from( ['a', 'b'] )->equals( ['b'] );
1435
         *  Map::from( ['a', 'b'] )->equals( ['b', 'a'] );
1436
         *
1437
         * Results:
1438
         * The first and second example will return FALSE, the third example will return TRUE
1439
         *
1440
         * The method differs to is() in the fact that it doesn't care about the keys
1441
         * by default. The elements are only loosely compared and the keys are ignored.
1442
         *
1443
         * Values are compared by their string values:
1444
         * (string) $item1 === (string) $item2
1445
         *
1446
         * @param iterable<int|string,mixed> $elements List of elements to test against
1447
         * @return bool TRUE if both are equal, FALSE if not
1448
         */
1449
        public function equals( iterable $elements ) : bool
1450
        {
1451
                $list = $this->list();
18✔
1452
                $elements = $this->array( $elements );
18✔
1453

1454
                return array_diff( $list, $elements ) === [] && array_diff( $elements, $list ) === [];
18✔
1455
        }
1456

1457

1458
        /**
1459
         * Verifies that all elements pass the test of the given callback.
1460
         *
1461
         * Examples:
1462
         *  Map::from( [0 => 'a', 1 => 'b'] )->every( function( $value, $key ) {
1463
         *      return is_string( $value );
1464
         *  } );
1465
         *
1466
         *  Map::from( [0 => 'a', 1 => 100] )->every( function( $value, $key ) {
1467
         *      return is_string( $value );
1468
         *  } );
1469
         *
1470
         * The first example will return TRUE because all values are a string while
1471
         * the second example will return FALSE.
1472
         *
1473
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1474
         * @return bool True if all elements pass the test, false if if fails for at least one element
1475
         */
1476
        public function every( \Closure $callback ) : bool
1477
        {
1478
                foreach( $this->list() as $key => $item )
3✔
1479
                {
1480
                        if( $callback( $item, $key ) === false ) {
3✔
1481
                                return false;
3✔
1482
                        }
1483
                }
1484

1485
                return true;
3✔
1486
        }
1487

1488

1489
        /**
1490
         * Returns a new map without the passed element keys.
1491
         *
1492
         * Examples:
1493
         *  Map::from( ['a' => 1, 'b' => 2, 'c' => 3] )->except( 'b' );
1494
         *  Map::from( [1 => 'a', 2 => 'b', 3 => 'c'] )->except( [1, 3] );
1495
         *
1496
         * Results:
1497
         *  ['a' => 1, 'c' => 3]
1498
         *  [2 => 'b']
1499
         *
1500
         * The keys in the result map are preserved.
1501
         *
1502
         * @param iterable<string|int>|array<string|int>|string|int $keys List of keys to remove
1503
         * @return self<int|string,mixed> New map
1504
         */
1505
        public function except( $keys ) : self
1506
        {
1507
                return ( clone $this )->remove( $keys );
3✔
1508
        }
1509

1510

1511
        /**
1512
         * Applies a filter to all elements of the map and returns a new map.
1513
         *
1514
         * Examples:
1515
         *  Map::from( [null, 0, 1, '', '0', 'a'] )->filter();
1516
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->filter( function( $value, $key ) {
1517
         *      return $key < 10 && $value < 'n';
1518
         *  } );
1519
         *
1520
         * Results:
1521
         *  [1, 'a']
1522
         *  ['a', 'b']
1523
         *
1524
         * If no callback is passed, all values which are empty, null or false will be
1525
         * removed if their value converted to boolean is FALSE:
1526
         *  (bool) $value === false
1527
         *
1528
         * The keys in the result map are preserved.
1529
         *
1530
         * @param  callable|null $callback Function with (item, key) parameters and returns TRUE/FALSE
1531
         * @return self<int|string,mixed> New map
1532
         */
1533
        public function filter( ?callable $callback = null ) : self
1534
        {
1535
                // PHP 7.x compatibility
1536
                if( $callback ) {
60✔
1537
                        return new static( array_filter( $this->list(), $callback, ARRAY_FILTER_USE_BOTH ) );
57✔
1538
                }
1539

1540
                return new static( array_filter( $this->list() ) );
3✔
1541
        }
1542

1543

1544
        /**
1545
         * Returns the first/last matching element where the callback returns TRUE.
1546
         *
1547
         * Examples:
1548
         *  Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
1549
         *      return $value >= 'b';
1550
         *  } );
1551
         *  Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
1552
         *      return $value >= 'b';
1553
         *  }, null, true );
1554
         *  Map::from( [] )->find( function( $value, $key ) {
1555
         *      return $value >= 'b';
1556
         *  }, fn() => 'none' );
1557
         *  Map::from( [] )->find( function( $value, $key ) {
1558
         *      return $value >= 'b';
1559
         *  }, new \Exception( 'error' ) );
1560
         *
1561
         * Results:
1562
         * The first example will return 'c' while the second will return 'e' (last element).
1563
         * The third and forth one will return "none" and the last one will throw the exception.
1564
         *
1565
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1566
         * @param mixed $default Default value, closure or exception if the callback only returns FALSE
1567
         * @param bool $reverse TRUE to test elements from back to front, FALSE for front to back (default)
1568
         * @return mixed First matching value, passed default value or an exception
1569
         */
1570
        public function find( \Closure $callback, $default = null, bool $reverse = false )
1571
        {
1572
                $list = $this->list();
15✔
1573

1574
                if( !empty( $list ) )
15✔
1575
                {
1576
                        if( $reverse )
15✔
1577
                        {
1578
                                $value = end( $list );
6✔
1579
                                $key = key( $list );
6✔
1580

1581
                                do
1582
                                {
1583
                                        if( $callback( $value, $key ) ) {
6✔
1584
                                                return $value;
3✔
1585
                                        }
1586
                                }
1587
                                while( ( $value = prev( $list ) ) !== false && ( $key = key( $list ) ) !== null );
6✔
1588

1589
                                reset( $list );
3✔
1590
                        }
1591
                        else
1592
                        {
1593
                                foreach( $list as $key => $value )
9✔
1594
                                {
1595
                                        if( $callback( $value, $key ) ) {
9✔
1596
                                                return $value;
3✔
1597
                                        }
1598
                                }
1599
                        }
1600
                }
1601

1602
                if( $default instanceof \Closure ) {
9✔
1603
                        return $default();
3✔
1604
                }
1605

1606
                if( $default instanceof \Throwable ) {
6✔
1607
                        throw $default;
3✔
1608
                }
1609

1610
                return $default;
3✔
1611
        }
1612

1613

1614
        /**
1615
         * Returns the first/last key where the callback returns TRUE.
1616
         *
1617
         * Examples:
1618
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1619
         *      return $value >= 'b';
1620
         *  } );
1621
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1622
         *      return $value >= 'b';
1623
         *  }, null, true );
1624
         *  Map::from( [] )->findKey( function( $value, $key ) {
1625
         *      return $value >= 'b';
1626
         *  }, 'none' );
1627
         *  Map::from( [] )->findKey( function( $value, $key ) {
1628
         *      return $value >= 'b';
1629
         *  }, fn() => 'none' );
1630
         *  Map::from( [] )->findKey( function( $value, $key ) {
1631
         *      return $value >= 'b';
1632
         *  }, new \Exception( 'error' ) );
1633
         *
1634
         * Results:
1635
         * The first example will return '1' while the second will return '2' (last element).
1636
         * The third and forth one will return "none" and the last one will throw the exception.
1637
         *
1638
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1639
         * @param mixed $default Default value, closure or exception if the callback only returns FALSE
1640
         * @param bool $reverse TRUE to test elements from back to front, FALSE for front to back (default)
1641
         * @return mixed Key of first matching element, passed default value or an exception
1642
         */
1643
        public function findKey( \Closure $callback, $default = null, bool $reverse = false )
1644
        {
1645
                $list = $this->list();
15✔
1646

1647
                if( !empty( $list ) )
15✔
1648
                {
1649
                        if( $reverse )
6✔
1650
                        {
1651
                                $value = end( $list );
3✔
1652
                                $key = key( $list );
3✔
1653

1654
                                do
1655
                                {
1656
                                        if( $callback( $value, $key ) ) {
3✔
1657
                                                return $key;
3✔
1658
                                        }
1659
                                }
1660
                                while( ( $value = prev( $list ) ) !== false && ( $key = key( $list ) ) !== null );
×
1661

1662
                                reset( $list );
×
1663
                        }
1664
                        else
1665
                        {
1666
                                foreach( $list as $key => $value )
3✔
1667
                                {
1668
                                        if( $callback( $value, $key ) ) {
3✔
1669
                                                return $key;
3✔
1670
                                        }
1671
                                }
1672
                        }
1673
                }
1674

1675
                if( $default instanceof \Closure ) {
9✔
1676
                        return $default();
3✔
1677
                }
1678

1679
                if( $default instanceof \Throwable ) {
6✔
1680
                        throw $default;
3✔
1681
                }
1682

1683
                return $default;
3✔
1684
        }
1685

1686

1687
        /**
1688
         * Returns the first element from the map.
1689
         *
1690
         * Examples:
1691
         *  Map::from( ['a', 'b'] )->first();
1692
         *  Map::from( [] )->first( 'x' );
1693
         *  Map::from( [] )->first( new \Exception( 'error' ) );
1694
         *  Map::from( [] )->first( function() { return rand(); } );
1695
         *
1696
         * Results:
1697
         * The first example will return 'b' and the second one 'x'. The third example
1698
         * will throw the exception passed if the map contains no elements. In the
1699
         * fourth example, a random value generated by the closure function will be
1700
         * returned.
1701
         *
1702
         * Using this method doesn't affect the internal array pointer.
1703
         *
1704
         * @param mixed $default Default value, closure or exception if the map contains no elements
1705
         * @return mixed First value of map, (generated) default value or an exception
1706
         */
1707
        public function first( $default = null )
1708
        {
1709
                if( !empty( $this->list() ) ) {
33✔
1710
                        return current( array_slice( $this->list(), 0, 1 ) );
18✔
1711
                }
1712

1713
                if( $default instanceof \Closure ) {
18✔
1714
                        return $default();
3✔
1715
                }
1716

1717
                if( $default instanceof \Throwable ) {
15✔
1718
                        throw $default;
6✔
1719
                }
1720

1721
                return $default;
9✔
1722
        }
1723

1724

1725
        /**
1726
         * Returns the first key from the map.
1727
         *
1728
         * Examples:
1729
         *  Map::from( ['a' => 1, 'b' => 2] )->firstKey();
1730
         *  Map::from( [] )->firstKey( 'x' );
1731
         *  Map::from( [] )->firstKey( new \Exception( 'error' ) );
1732
         *  Map::from( [] )->firstKey( function() { return rand(); } );
1733
         *
1734
         * Results:
1735
         * The first example will return 'a' and the second one 'x', the third one will throw
1736
         * an exception and the last one will return a random value.
1737
         *
1738
         * Using this method doesn't affect the internal array pointer.
1739
         *
1740
         * @param mixed $default Default value, closure or exception if the map contains no elements
1741
         * @return mixed First key of map, (generated) default value or an exception
1742
         */
1743
        public function firstKey( $default = null )
1744
        {
1745
                $list = $this->list();
15✔
1746

1747
                // PHP 7.x compatibility
1748
                if( function_exists( 'array_key_first' ) ) {
15✔
1749
                        $key = array_key_first( $list );
15✔
1750
                } else {
1751
                        $key = key( array_slice( $list, 0, 1, true ) );
×
1752
                }
1753

1754
                if( $key !== null ) {
15✔
1755
                        return $key;
3✔
1756
                }
1757

1758
                if( $default instanceof \Closure ) {
12✔
1759
                        return $default();
3✔
1760
                }
1761

1762
                if( $default instanceof \Throwable ) {
9✔
1763
                        throw $default;
3✔
1764
                }
1765

1766
                return $default;
6✔
1767
        }
1768

1769

1770
        /**
1771
         * Creates a new map with all sub-array elements added recursively without overwriting existing keys.
1772
         *
1773
         * Examples:
1774
         *  Map::from( [[0, 1], [2, 3]] )->flat();
1775
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat();
1776
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat( 1 );
1777
         *  Map::from( [[0, 1], Map::from( [[2, 3], 4] )] )->flat();
1778
         *
1779
         * Results:
1780
         *  [0, 1, 2, 3]
1781
         *  [0, 1, 2, 3, 4]
1782
         *  [0, 1, [2, 3], 4]
1783
         *  [0, 1, 2, 3, 4]
1784
         *
1785
         * The keys are not preserved and the new map elements will be numbered from
1786
         * 0-n. A value smaller than 1 for depth will return the same map elements
1787
         * indexed from 0-n. Flattening does also work if elements implement the
1788
         * "Traversable" interface (which the Map object does).
1789
         *
1790
         * This method is similar than collapse() but doesn't replace existing elements.
1791
         * Keys are NOT preserved using this method!
1792
         *
1793
         * @param int|null $depth Number of levels to flatten multi-dimensional arrays or NULL for all
1794
         * @return self<int|string,mixed> New map with all sub-array elements added into it recursively, up to the specified depth
1795
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
1796
         */
1797
        public function flat( ?int $depth = null ) : self
1798
        {
1799
                if( $depth < 0 ) {
18✔
1800
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
3✔
1801
                }
1802

1803
                $result = [];
15✔
1804
                $this->nflatten( $this->list(), $result, $depth ?? 0x7fffffff );
15✔
1805
                return new static( $result );
15✔
1806
        }
1807

1808

1809
        /**
1810
         * Creates a new map with keys joined recursively.
1811
         *
1812
         * Examples:
1813
         *  Map::from( ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]] )->flatten();
1814
         *  Map::from( ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]] )->flatten( 1 );
1815
         *  Map::from( ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]] )->sep( '.' )->flatten();
1816
         *
1817
         * Results:
1818
         *  ['a/b/c' => 1, 'a/b/d' => 2, 'b/e' => 3]
1819
         *  ['a/b' => ['c' => 1, 'd' => 2], 'b/e' => 3]
1820
         *  ['a.b.c' => 1, 'a.b.d' => 2, 'b.e' => 3]
1821
         *
1822
         * To create the original multi-dimensional array again, use the unflatten() method.
1823
         *
1824
         * @param int|null $depth Number of levels to flatten multi-dimensional arrays or NULL for all
1825
         * @return self<string,mixed> New map with keys joined recursively, up to the specified depth
1826
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
1827
         */
1828
        public function flatten( ?int $depth = null ) : self
1829
        {
1830
                if( $depth < 0 ) {
6✔
1831
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
3✔
1832
                }
1833

1834
                $result = [];
3✔
1835
                $this->rflatten( $this->list(), $result, $depth ?? 0x7fffffff );
3✔
1836
                return new static( $result );
3✔
1837
        }
1838

1839

1840
        /**
1841
         * Exchanges the keys with their values and vice versa.
1842
         *
1843
         * Examples:
1844
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->flip();
1845
         *
1846
         * Results:
1847
         *  ['X' => 'a', 'Y' => 'b']
1848
         *
1849
         * @return self<int|string,mixed> New map with keys as values and values as keys
1850
         */
1851
        public function flip() : self
1852
        {
1853
                return new static( array_flip( $this->list() ) );
3✔
1854
        }
1855

1856

1857
        /**
1858
         * Returns an element by key and casts it to float if possible.
1859
         *
1860
         * Examples:
1861
         *  Map::from( ['a' => true] )->float( 'a' );
1862
         *  Map::from( ['a' => 1] )->float( 'a' );
1863
         *  Map::from( ['a' => '1.1'] )->float( 'a' );
1864
         *  Map::from( ['a' => '10'] )->float( 'a' );
1865
         *  Map::from( ['a' => ['b' => ['c' => 1.1]]] )->float( 'a/b/c' );
1866
         *  Map::from( [] )->float( 'c', function() { return 1.1; } );
1867
         *  Map::from( [] )->float( 'a', 1.1 );
1868
         *
1869
         *  Map::from( [] )->float( 'b' );
1870
         *  Map::from( ['b' => ''] )->float( 'b' );
1871
         *  Map::from( ['b' => null] )->float( 'b' );
1872
         *  Map::from( ['b' => 'abc'] )->float( 'b' );
1873
         *  Map::from( ['b' => [1]] )->float( 'b' );
1874
         *  Map::from( ['b' => #resource] )->float( 'b' );
1875
         *  Map::from( ['b' => new \stdClass] )->float( 'b' );
1876
         *
1877
         *  Map::from( [] )->float( 'c', new \Exception( 'error' ) );
1878
         *
1879
         * Results:
1880
         * The first eight examples will return the float values for the passed keys
1881
         * while the 9th to 14th example returns 0. The last example will throw an exception.
1882
         *
1883
         * This does also work for multi-dimensional arrays by passing the keys
1884
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1885
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1886
         * public properties of objects or objects implementing __isset() and __get() methods.
1887
         *
1888
         * @param int|string $key Key or path to the requested item
1889
         * @param mixed $default Default value if key isn't found (will be casted to float)
1890
         * @return float Value from map or default value
1891
         */
1892
        public function float( $key, $default = 0.0 ) : float
1893
        {
1894
                return (float) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
9✔
1895
        }
1896

1897

1898
        /**
1899
         * Returns an element from the map by key.
1900
         *
1901
         * Examples:
1902
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'a' );
1903
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'c', 'Z' );
1904
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->get( 'a/b/c' );
1905
         *  Map::from( [] )->get( 'Y', new \Exception( 'error' ) );
1906
         *  Map::from( [] )->get( 'Y', function() { return rand(); } );
1907
         *
1908
         * Results:
1909
         * The first example will return 'X', the second 'Z' and the third 'Y'. The forth
1910
         * example will throw the exception passed if the map contains no elements. In
1911
         * the fifth example, a random value generated by the closure function will be
1912
         * returned.
1913
         *
1914
         * This does also work for multi-dimensional arrays by passing the keys
1915
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1916
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1917
         * public properties of objects or objects implementing __isset() and __get() methods.
1918
         *
1919
         * @param int|string $key Key or path to the requested item
1920
         * @param mixed $default Default value if no element matches
1921
         * @return mixed Value from map or default value
1922
         */
1923
        public function get( $key, $default = null )
1924
        {
1925
                $list = $this->list();
69✔
1926

1927
                if( array_key_exists( $key, $list ) ) {
69✔
1928
                        return $list[$key];
18✔
1929
                }
1930

1931
                if( ( $v = $this->val( $list, explode( $this->sep, (string) $key ) ) ) !== null ) {
63✔
1932
                        return $v;
21✔
1933
                }
1934

1935
                if( $default instanceof \Closure ) {
54✔
1936
                        return $default();
18✔
1937
                }
1938

1939
                if( $default instanceof \Throwable ) {
36✔
1940
                        throw $default;
18✔
1941
                }
1942

1943
                return $default;
18✔
1944
        }
1945

1946

1947
        /**
1948
         * Returns an iterator for the elements.
1949
         *
1950
         * This method will be used by e.g. foreach() to loop over all entries:
1951
         *  foreach( Map::from( ['a', 'b'] ) as $value )
1952
         *
1953
         * @return \ArrayIterator<int|string,mixed> Iterator for map elements
1954
         */
1955
        public function getIterator() : \ArrayIterator
1956
        {
1957
                return new \ArrayIterator( $this->list() );
15✔
1958
        }
1959

1960

1961
        /**
1962
         * Returns only items which matches the regular expression.
1963
         *
1964
         * All items are converted to string first before they are compared to the
1965
         * regular expression. Thus, fractions of ".0" will be removed in float numbers
1966
         * which may result in unexpected results.
1967
         *
1968
         * Examples:
1969
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/b/' );
1970
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/a/', PREG_GREP_INVERT );
1971
         *  Map::from( [1.5, 0, 1.0, 'a'] )->grep( '/^(\d+)?\.\d+$/' );
1972
         *
1973
         * Results:
1974
         *  ['ab', 'bc']
1975
         *  ['bc', 'cd']
1976
         *  [1.5] // float 1.0 is converted to string "1"
1977
         *
1978
         * The keys are preserved using this method.
1979
         *
1980
         * @param string $pattern Regular expression pattern, e.g. "/ab/"
1981
         * @param int $flags PREG_GREP_INVERT to return elements not matching the pattern
1982
         * @return self<int|string,mixed> New map containing only the matched elements
1983
         */
1984
        public function grep( string $pattern, int $flags = 0 ) : self
1985
        {
1986
                if( ( $result = preg_grep( $pattern, $this->list(), $flags ) ) === false )
12✔
1987
                {
1988
                        switch( preg_last_error() )
3✔
1989
                        {
1990
                                case PREG_INTERNAL_ERROR: $msg = 'Internal error'; break;
3✔
1991
                                case PREG_BACKTRACK_LIMIT_ERROR: $msg = 'Backtrack limit error'; break;
×
1992
                                case PREG_RECURSION_LIMIT_ERROR: $msg = 'Recursion limit error'; break;
×
1993
                                case PREG_BAD_UTF8_ERROR: $msg = 'Bad UTF8 error'; break;
×
1994
                                case PREG_BAD_UTF8_OFFSET_ERROR: $msg = 'Bad UTF8 offset error'; break;
×
1995
                                case PREG_JIT_STACKLIMIT_ERROR: $msg = 'JIT stack limit error'; break;
×
1996
                                default: $msg = 'Unknown error';
×
1997
                        }
1998

1999
                        throw new \RuntimeException( 'Regular expression error: ' . $msg );
3✔
2000
                }
2001

2002
                return new static( $result );
9✔
2003
        }
2004

2005

2006
        /**
2007
         * Groups associative array elements or objects by the passed key or closure.
2008
         *
2009
         * Instead of overwriting items with the same keys like to the col() method
2010
         * does, groupBy() keeps all entries in sub-arrays. It's preserves the keys
2011
         * of the orignal map entries too.
2012
         *
2013
         * Examples:
2014
         *  $list = [
2015
         *    10 => ['aid' => 123, 'code' => 'x-abc'],
2016
         *    20 => ['aid' => 123, 'code' => 'x-def'],
2017
         *    30 => ['aid' => 456, 'code' => 'x-def']
2018
         *  ];
2019
         *  Map::from( $list )->groupBy( 'aid' );
2020
         *  Map::from( $list )->groupBy( function( $item, $key ) {
2021
         *    return substr( $item['code'], -3 );
2022
         *  } );
2023
         *  Map::from( $list )->groupBy( 'xid' );
2024
         *
2025
         * Results:
2026
         *  [
2027
         *    123 => [10 => ['aid' => 123, 'code' => 'x-abc'], 20 => ['aid' => 123, 'code' => 'x-def']],
2028
         *    456 => [30 => ['aid' => 456, 'code' => 'x-def']]
2029
         *  ]
2030
         *  [
2031
         *    'abc' => [10 => ['aid' => 123, 'code' => 'x-abc']],
2032
         *    'def' => [20 => ['aid' => 123, 'code' => 'x-def'], 30 => ['aid' => 456, 'code' => 'x-def']]
2033
         *  ]
2034
         *  [
2035
         *    '' => [
2036
         *      10 => ['aid' => 123, 'code' => 'x-abc'],
2037
         *      20 => ['aid' => 123, 'code' => 'x-def'],
2038
         *      30 => ['aid' => 456, 'code' => 'x-def']
2039
         *    ]
2040
         *  ]
2041
         *
2042
         * In case the passed key doesn't exist in one or more items, these items
2043
         * are stored in a sub-array using an empty string as key.
2044
         *
2045
         * This does also work for multi-dimensional arrays by passing the keys
2046
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2047
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2048
         * public properties of objects or objects implementing __isset() and __get() methods.
2049
         *
2050
         * @param  \Closure|string|int $key Closure function with (item, idx) parameters returning the key or the key itself to group by
2051
         * @return self<int|string,mixed> New map with elements grouped by the given key
2052
         */
2053
        public function groupBy( $key ) : self
2054
        {
2055
                $result = [];
12✔
2056

2057
                if( is_callable( $key ) )
12✔
2058
                {
2059
                        foreach( $this->list() as $idx => $item )
3✔
2060
                        {
2061
                                $keyval = (string) $key( $item, $idx );
3✔
2062
                                $result[$keyval][$idx] = $item;
3✔
2063
                        }
2064
                }
2065
                else
2066
                {
2067
                        $parts = explode( $this->sep, (string) $key );
9✔
2068

2069
                        foreach( $this->list() as $idx => $item )
9✔
2070
                        {
2071
                                $keyval = (string) $this->val( $item, $parts );
9✔
2072
                                $result[$keyval][$idx] = $item;
9✔
2073
                        }
2074
                }
2075

2076
                return new static( $result );
12✔
2077
        }
2078

2079

2080
        /**
2081
         * Determines if a key or several keys exists in the map.
2082
         *
2083
         * If several keys are passed as array, all keys must exist in the map for
2084
         * TRUE to be returned.
2085
         *
2086
         * Examples:
2087
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'a' );
2088
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'b'] );
2089
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->has( 'a/b/c' );
2090
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'c' );
2091
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'c'] );
2092
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'X' );
2093
         *
2094
         * Results:
2095
         * The first three examples will return TRUE while the other ones will return FALSE
2096
         *
2097
         * This does also work for multi-dimensional arrays by passing the keys
2098
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2099
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2100
         * public properties of objects or objects implementing __isset() and __get() methods.
2101
         *
2102
         * @param array<int|string>|int|string $key Key of the requested item or list of keys
2103
         * @return bool TRUE if key or keys are available in map, FALSE if not
2104
         */
2105
        public function has( $key ) : bool
2106
        {
2107
                $list = $this->list();
9✔
2108

2109
                foreach( (array) $key as $entry )
9✔
2110
                {
2111
                        if( array_key_exists( $entry, $list ) === false
9✔
2112
                                && $this->val( $list, explode( $this->sep, (string) $entry ) ) === null
9✔
2113
                        ) {
2114
                                return false;
9✔
2115
                        }
2116
                }
2117

2118
                return true;
9✔
2119
        }
2120

2121

2122
        /**
2123
         * Executes callbacks depending on the condition.
2124
         *
2125
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2126
         * executed and their returned value is passed back within a Map object. In
2127
         * case no "then" or "else" closure is given, the method will return the same
2128
         * map object.
2129
         *
2130
         * Examples:
2131
         *  Map::from( [] )->if( strpos( 'abc', 'b' ) !== false, function( $map ) {
2132
         *    echo 'found';
2133
         *  } );
2134
         *
2135
         *  Map::from( [] )->if( function( $map ) {
2136
         *    return $map->empty();
2137
         *  }, function( $map ) {
2138
         *    echo 'then';
2139
         *  } );
2140
         *
2141
         *  Map::from( ['a'] )->if( function( $map ) {
2142
         *    return $map->empty();
2143
         *  }, function( $map ) {
2144
         *    echo 'then';
2145
         *  }, function( $map ) {
2146
         *    echo 'else';
2147
         *  } );
2148
         *
2149
         *  Map::from( ['a', 'b'] )->if( true, function( $map ) {
2150
         *    return $map->push( 'c' );
2151
         *  } );
2152
         *
2153
         *  Map::from( ['a', 'b'] )->if( false, null, function( $map ) {
2154
         *    return $map->pop();
2155
         *  } );
2156
         *
2157
         * Results:
2158
         * The first example returns "found" while the second one returns "then" and
2159
         * the third one "else". The forth one will return ['a', 'b', 'c'] while the
2160
         * fifth one will return 'b', which is turned into a map of ['b'] again.
2161
         *
2162
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2163
         * (a short form for anonymous closures) as parameters. The automatically have access
2164
         * to previously defined variables but can not modify them. Also, they can not have
2165
         * a void return type and must/will always return something. Details about
2166
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2167
         *
2168
         * @param \Closure|bool $condition Boolean or function with (map) parameter returning a boolean
2169
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2170
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2171
         * @return self<int|string,mixed> New map
2172
         */
2173
        public function if( $condition, ?\Closure $then = null, ?\Closure $else = null ) : self
2174
        {
2175
                if( $condition instanceof \Closure ) {
24✔
2176
                        $condition = $condition( $this );
6✔
2177
                }
2178

2179
                if( $condition ) {
24✔
2180
                        return $then ? static::from( $then( $this, $condition ) ) : $this;
15✔
2181
                } elseif( $else ) {
9✔
2182
                        return static::from( $else( $this, $condition ) );
9✔
2183
                }
2184

2185
                return $this;
×
2186
        }
2187

2188

2189
        /**
2190
         * Executes callbacks depending if the map contains elements or not.
2191
         *
2192
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2193
         * executed and their returned value is passed back within a Map object. In
2194
         * case no "then" or "else" closure is given, the method will return the same
2195
         * map object.
2196
         *
2197
         * Examples:
2198
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2199
         *    $map->push( 'b' );
2200
         *  } );
2201
         *
2202
         *  Map::from( [] )->ifAny( null, function( $map ) {
2203
         *    return $map->push( 'b' );
2204
         *  } );
2205
         *
2206
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2207
         *    return 'c';
2208
         *  } );
2209
         *
2210
         * Results:
2211
         * The first example returns a Map containing ['a', 'b'] because the the initial
2212
         * Map is not empty. The second one returns  a Map with ['b'] because the initial
2213
         * Map is empty and the "else" closure is used. The last example returns ['c']
2214
         * as new map content.
2215
         *
2216
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2217
         * (a short form for anonymous closures) as parameters. The automatically have access
2218
         * to previously defined variables but can not modify them. Also, they can not have
2219
         * a void return type and must/will always return something. Details about
2220
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2221
         *
2222
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2223
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2224
         * @return self<int|string,mixed> New map
2225
         */
2226
        public function ifAny( ?\Closure $then = null, ?\Closure $else = null ) : self
2227
        {
2228
                return $this->if( !empty( $this->list() ), $then, $else );
9✔
2229
        }
2230

2231

2232
        /**
2233
         * Executes callbacks depending if the map is empty or not.
2234
         *
2235
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2236
         * executed and their returned value is passed back within a Map object. In
2237
         * case no "then" or "else" closure is given, the method will return the same
2238
         * map object.
2239
         *
2240
         * Examples:
2241
         *  Map::from( [] )->ifEmpty( function( $map ) {
2242
         *    $map->push( 'a' );
2243
         *  } );
2244
         *
2245
         *  Map::from( ['a'] )->ifEmpty( null, function( $map ) {
2246
         *    return $map->push( 'b' );
2247
         *  } );
2248
         *
2249
         * Results:
2250
         * The first example returns a Map containing ['a'] because the the initial Map
2251
         * is empty. The second one returns  a Map with ['a', 'b'] because the initial
2252
         * Map is not empty and the "else" closure is used.
2253
         *
2254
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2255
         * (a short form for anonymous closures) as parameters. The automatically have access
2256
         * to previously defined variables but can not modify them. Also, they can not have
2257
         * a void return type and must/will always return something. Details about
2258
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2259
         *
2260
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2261
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2262
         * @return self<int|string,mixed> New map
2263
         */
2264
        public function ifEmpty( ?\Closure $then = null, ?\Closure $else = null ) : self
2265
        {
2266
                return $this->if( empty( $this->list() ), $then, $else );
×
2267
        }
2268

2269

2270
        /**
2271
         * Tests if all entries in the map are objects implementing the given interface.
2272
         *
2273
         * Examples:
2274
         *  Map::from( [new Map(), new Map()] )->implements( '\Countable' );
2275
         *  Map::from( [new Map(), new stdClass()] )->implements( '\Countable' );
2276
         *  Map::from( [new Map(), 123] )->implements( '\Countable' );
2277
         *  Map::from( [new Map(), 123] )->implements( '\Countable', true );
2278
         *  Map::from( [new Map(), 123] )->implements( '\Countable', '\RuntimeException' );
2279
         *
2280
         * Results:
2281
         *  The first example returns TRUE while the second and third one return FALSE.
2282
         *  The forth example will throw an UnexpectedValueException while the last one
2283
         *  throws a RuntimeException.
2284
         *
2285
         * @param string $interface Name of the interface that must be implemented
2286
         * @param \Throwable|bool $throw Passing TRUE or an exception name will throw the exception instead of returning FALSE
2287
         * @return bool TRUE if all entries implement the interface or FALSE if at least one doesn't
2288
         * @throws \UnexpectedValueException|\Throwable If one entry doesn't implement the interface
2289
         */
2290
        public function implements( string $interface, $throw = false ) : bool
2291
        {
2292
                foreach( $this->list() as $entry )
9✔
2293
                {
2294
                        if( !( $entry instanceof $interface ) )
9✔
2295
                        {
2296
                                if( $throw )
9✔
2297
                                {
2298
                                        $name = is_string( $throw ) ? $throw : '\UnexpectedValueException';
6✔
2299
                                        throw new $name( "Does not implement $interface: " . print_r( $entry, true ) );
6✔
2300
                                }
2301

2302
                                return false;
3✔
2303
                        }
2304
                }
2305

2306
                return true;
3✔
2307
        }
2308

2309

2310
        /**
2311
         * Tests if the passed element or elements are part of the map.
2312
         *
2313
         * Examples:
2314
         *  Map::from( ['a', 'b'] )->in( 'a' );
2315
         *  Map::from( ['a', 'b'] )->in( ['a', 'b'] );
2316
         *  Map::from( ['a', 'b'] )->in( 'x' );
2317
         *  Map::from( ['a', 'b'] )->in( ['a', 'x'] );
2318
         *  Map::from( ['1', '2'] )->in( 2, true );
2319
         *
2320
         * Results:
2321
         * The first and second example will return TRUE while the other ones will return FALSE
2322
         *
2323
         * @param mixed|array $element Element or elements to search for in the map
2324
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2325
         * @return bool TRUE if all elements are available in map, FALSE if not
2326
         */
2327
        public function in( $element, bool $strict = false ) : bool
2328
        {
2329
                if( !is_array( $element ) ) {
12✔
2330
                        return in_array( $element, $this->list(), $strict );
12✔
2331
                };
2332

2333
                foreach( $element as $entry )
3✔
2334
                {
2335
                        if( in_array( $entry, $this->list(), $strict ) === false ) {
3✔
2336
                                return false;
3✔
2337
                        }
2338
                }
2339

2340
                return true;
3✔
2341
        }
2342

2343

2344
        /**
2345
         * Tests if the passed element or elements are part of the map.
2346
         *
2347
         * This method is an alias for in(). For performance reasons, in() should be
2348
         * preferred because it uses one method call less than includes().
2349
         *
2350
         * @param mixed|array $element Element or elements to search for in the map
2351
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2352
         * @return bool TRUE if all elements are available in map, FALSE if not
2353
         * @see in() - Underlying method with same parameters and return value but better performance
2354
         */
2355
        public function includes( $element, bool $strict = false ) : bool
2356
        {
2357
                return $this->in( $element, $strict );
3✔
2358
        }
2359

2360

2361
        /**
2362
         * Returns the numerical index of the given key.
2363
         *
2364
         * Examples:
2365
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( '8' );
2366
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( function( $key ) {
2367
         *      return $key == '8';
2368
         *  } );
2369
         *
2370
         * Results:
2371
         * Both examples will return "1" because the value "b" is at the second position
2372
         * and the returned index is zero based so the first item has the index "0".
2373
         *
2374
         * @param \Closure|string|int $value Key to search for or function with (key) parameters return TRUE if key is found
2375
         * @return int|null Position of the found value (zero based) or NULL if not found
2376
         */
2377
        public function index( $value ) : ?int
2378
        {
2379
                if( $value instanceof \Closure )
12✔
2380
                {
2381
                        $pos = 0;
6✔
2382

2383
                        foreach( $this->list() as $key => $item )
6✔
2384
                        {
2385
                                if( $value( $key ) ) {
3✔
2386
                                        return $pos;
3✔
2387
                                }
2388

2389
                                ++$pos;
3✔
2390
                        }
2391

2392
                        return null;
3✔
2393
                }
2394

2395
                $pos = array_search( $value, array_keys( $this->list() ) );
6✔
2396
                return $pos !== false ? $pos : null;
6✔
2397
        }
2398

2399

2400
        /**
2401
         * Inserts the value or values after the given element.
2402
         *
2403
         * Examples:
2404
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAfter( 'foo', 'baz' );
2405
         *  Map::from( ['foo', 'bar'] )->insertAfter( 'foo', ['baz', 'boo'] );
2406
         *  Map::from( ['foo', 'bar'] )->insertAfter( null, 'baz' );
2407
         *
2408
         * Results:
2409
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2410
         *  ['foo', 'baz', 'boo', 'bar']
2411
         *  ['foo', 'bar', 'baz']
2412
         *
2413
         * Numerical array indexes are not preserved.
2414
         *
2415
         * @param mixed $element Element after the value is inserted
2416
         * @param mixed $value Element or list of elements to insert
2417
         * @return self<int|string,mixed> Updated map for fluid interface
2418
         */
2419
        public function insertAfter( $element, $value ) : self
2420
        {
2421
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
9✔
2422
                array_splice( $this->list(), $position + 1, 0, $this->array( $value ) );
9✔
2423

2424
                return $this;
9✔
2425
        }
2426

2427

2428
        /**
2429
         * Inserts the item at the given position in the map.
2430
         *
2431
         * Examples:
2432
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 0, 'baz' );
2433
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 1, 'baz', 'c' );
2434
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 4, 'baz' );
2435
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( -1, 'baz', 'c' );
2436
         *
2437
         * Results:
2438
         *  [0 => 'baz', 'a' => 'foo', 'b' => 'bar']
2439
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2440
         *  ['a' => 'foo', 'b' => 'bar', 'c' => 'baz']
2441
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2442
         *
2443
         * @param int $pos Position the value should be inserted at
2444
         * @param mixed $value Value to be inserted
2445
         * @param mixed|null $key Value key or NULL to assign an integer key automatically
2446
         * @return self<int|string,mixed> Updated map for fluid interface
2447
         */
2448
        public function insertAt( int $pos, $value, $key = null ) : self
2449
        {
2450
                if( $key !== null )
15✔
2451
                {
2452
                        $list = $this->list();
6✔
2453

2454
                        $this->list = array_merge(
6✔
2455
                                array_slice( $list, 0, $pos, true ),
6✔
2456
                                [$key => $value],
6✔
2457
                                array_slice( $list, $pos, null, true )
6✔
2458
                        );
6✔
2459
                }
2460
                else
2461
                {
2462
                        array_splice( $this->list(), $pos, 0, [$value] );
9✔
2463
                }
2464

2465
                return $this;
15✔
2466
        }
2467

2468

2469
        /**
2470
         * Inserts the value or values before the given element.
2471
         *
2472
         * Examples:
2473
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertBefore( 'bar', 'baz' );
2474
         *  Map::from( ['foo', 'bar'] )->insertBefore( 'bar', ['baz', 'boo'] );
2475
         *  Map::from( ['foo', 'bar'] )->insertBefore( null, 'baz' );
2476
         *
2477
         * Results:
2478
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2479
         *  ['foo', 'baz', 'boo', 'bar']
2480
         *  ['foo', 'bar', 'baz']
2481
         *
2482
         * Numerical array indexes are not preserved.
2483
         *
2484
         * @param mixed $element Element before the value is inserted
2485
         * @param mixed $value Element or list of elements to insert
2486
         * @return self<int|string,mixed> Updated map for fluid interface
2487
         */
2488
        public function insertBefore( $element, $value ) : self
2489
        {
2490
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
9✔
2491
                array_splice( $this->list(), $position, 0, $this->array( $value ) );
9✔
2492

2493
                return $this;
9✔
2494
        }
2495

2496

2497
        /**
2498
         * Tests if the passed value or values are part of the strings in the map.
2499
         *
2500
         * Examples:
2501
         *  Map::from( ['abc'] )->inString( 'c' );
2502
         *  Map::from( ['abc'] )->inString( 'bc' );
2503
         *  Map::from( [12345] )->inString( '23' );
2504
         *  Map::from( [123.4] )->inString( 23.4 );
2505
         *  Map::from( [12345] )->inString( false );
2506
         *  Map::from( [12345] )->inString( true );
2507
         *  Map::from( [false] )->inString( false );
2508
         *  Map::from( ['abc'] )->inString( '' );
2509
         *  Map::from( [''] )->inString( false );
2510
         *  Map::from( ['abc'] )->inString( 'BC', false );
2511
         *  Map::from( ['abc', 'def'] )->inString( ['de', 'xy'] );
2512
         *  Map::from( ['abc', 'def'] )->inString( ['E', 'x'] );
2513
         *  Map::from( ['abc', 'def'] )->inString( 'E' );
2514
         *  Map::from( [23456] )->inString( true );
2515
         *  Map::from( [false] )->inString( 0 );
2516
         *
2517
         * Results:
2518
         * The first eleven examples will return TRUE while the last four will return FALSE
2519
         *
2520
         * All scalar values (bool, float, int and string) are casted to string values before
2521
         * comparing to the given value. Non-scalar values in the map are ignored.
2522
         *
2523
         * @param array|string $value Value or values to compare the map elements, will be casted to string type
2524
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
2525
         * @return bool TRUE If at least one element matches, FALSE if value is not in any string of the map
2526
         * @deprecated Use multi-byte aware strContains() instead
2527
         */
2528
        public function inString( $value, bool $case = true ) : bool
2529
        {
2530
                $fcn = $case ? 'strpos' : 'stripos';
3✔
2531

2532
                foreach( (array) $value as $val )
3✔
2533
                {
2534
                        if( (string) $val === '' ) {
3✔
2535
                                return true;
3✔
2536
                        }
2537

2538
                        foreach( $this->list() as $item )
3✔
2539
                        {
2540
                                if( is_scalar( $item ) && $fcn( (string) $item, (string) $val ) !== false ) {
3✔
2541
                                        return true;
3✔
2542
                                }
2543
                        }
2544
                }
2545

2546
                return false;
3✔
2547
        }
2548

2549

2550
        /**
2551
         * Returns an element by key and casts it to integer if possible.
2552
         *
2553
         * Examples:
2554
         *  Map::from( ['a' => true] )->int( 'a' );
2555
         *  Map::from( ['a' => '1'] )->int( 'a' );
2556
         *  Map::from( ['a' => 1.1] )->int( 'a' );
2557
         *  Map::from( ['a' => '10'] )->int( 'a' );
2558
         *  Map::from( ['a' => ['b' => ['c' => 1]]] )->int( 'a/b/c' );
2559
         *  Map::from( [] )->int( 'c', function() { return rand( 1, 1 ); } );
2560
         *  Map::from( [] )->int( 'a', 1 );
2561
         *
2562
         *  Map::from( [] )->int( 'b' );
2563
         *  Map::from( ['b' => ''] )->int( 'b' );
2564
         *  Map::from( ['b' => 'abc'] )->int( 'b' );
2565
         *  Map::from( ['b' => null] )->int( 'b' );
2566
         *  Map::from( ['b' => [1]] )->int( 'b' );
2567
         *  Map::from( ['b' => #resource] )->int( 'b' );
2568
         *  Map::from( ['b' => new \stdClass] )->int( 'b' );
2569
         *
2570
         *  Map::from( [] )->int( 'c', new \Exception( 'error' ) );
2571
         *
2572
         * Results:
2573
         * The first seven examples will return 1 while the 8th to 14th example
2574
         * returns 0. The last example will throw an exception.
2575
         *
2576
         * This does also work for multi-dimensional arrays by passing the keys
2577
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2578
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2579
         * public properties of objects or objects implementing __isset() and __get() methods.
2580
         *
2581
         * @param int|string $key Key or path to the requested item
2582
         * @param mixed $default Default value if key isn't found (will be casted to integer)
2583
         * @return int Value from map or default value
2584
         */
2585
        public function int( $key, $default = 0 ) : int
2586
        {
2587
                return (int) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
9✔
2588
        }
2589

2590

2591
        /**
2592
         * Returns all values in a new map that are available in both, the map and the given elements.
2593
         *
2594
         * Examples:
2595
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersect( ['bar'] );
2596
         *
2597
         * Results:
2598
         *  ['b' => 'bar']
2599
         *
2600
         * If a callback is passed, the given function will be used to compare the values.
2601
         * The function must accept two parameters (value A and B) and must return
2602
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2603
         * greater than value B. Both, a method name and an anonymous function can be passed:
2604
         *
2605
         *  Map::from( [0 => 'a'] )->intersect( [0 => 'A'], 'strcasecmp' );
2606
         *  Map::from( ['b' => 'a'] )->intersect( ['B' => 'A'], 'strcasecmp' );
2607
         *  Map::from( ['b' => 'a'] )->intersect( ['c' => 'A'], function( $valA, $valB ) {
2608
         *      return strtolower( $valA ) <=> strtolower( $valB );
2609
         *  } );
2610
         *
2611
         * All examples will return a map containing ['a'] because both contain the same
2612
         * values when compared case insensitive.
2613
         *
2614
         * The keys are preserved using this method.
2615
         *
2616
         * @param iterable<int|string,mixed> $elements List of elements
2617
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2618
         * @return self<int|string,mixed> New map
2619
         */
2620
        public function intersect( iterable $elements, ?callable $callback = null ) : self
2621
        {
2622
                $list = $this->list();
6✔
2623
                $elements = $this->array( $elements );
6✔
2624

2625
                if( $callback ) {
6✔
2626
                        return new static( array_uintersect( $list, $elements, $callback ) );
3✔
2627
                }
2628

2629
                return new static( array_intersect( $list, $elements ) );
3✔
2630
        }
2631

2632

2633
        /**
2634
         * Returns all values in a new map that are available in both, the map and the given elements while comparing the keys too.
2635
         *
2636
         * Examples:
2637
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectAssoc( new Map( ['foo', 'b' => 'bar'] ) );
2638
         *
2639
         * Results:
2640
         *  ['a' => 'foo']
2641
         *
2642
         * If a callback is passed, the given function will be used to compare the values.
2643
         * The function must accept two parameters (value A and B) and must return
2644
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2645
         * greater than value B. Both, a method name and an anonymous function can be passed:
2646
         *
2647
         *  Map::from( [0 => 'a'] )->intersectAssoc( [0 => 'A'], 'strcasecmp' );
2648
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['B' => 'A'], 'strcasecmp' );
2649
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['c' => 'A'], function( $valA, $valB ) {
2650
         *      return strtolower( $valA ) <=> strtolower( $valB );
2651
         *  } );
2652
         *
2653
         * The first example will return [0 => 'a'] because both contain the same
2654
         * values when compared case insensitive. The second and third example will return
2655
         * an empty map because the keys doesn't match ("b" vs. "B" and "b" vs. "c").
2656
         *
2657
         * The keys are preserved using this method.
2658
         *
2659
         * @param iterable<int|string,mixed> $elements List of elements
2660
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2661
         * @return self<int|string,mixed> New map
2662
         */
2663
        public function intersectAssoc( iterable $elements, ?callable $callback = null ) : self
2664
        {
2665
                $elements = $this->array( $elements );
15✔
2666

2667
                if( $callback ) {
15✔
2668
                        return new static( array_uintersect_assoc( $this->list(), $elements, $callback ) );
3✔
2669
                }
2670

2671
                return new static( array_intersect_assoc( $this->list(), $elements ) );
12✔
2672
        }
2673

2674

2675
        /**
2676
         * Returns all values in a new map that are available in both, the map and the given elements by comparing the keys only.
2677
         *
2678
         * Examples:
2679
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectKeys( new Map( ['foo', 'b' => 'baz'] ) );
2680
         *
2681
         * Results:
2682
         *  ['b' => 'bar']
2683
         *
2684
         * If a callback is passed, the given function will be used to compare the keys.
2685
         * The function must accept two parameters (key A and B) and must return
2686
         * -1 if key A is smaller than key B, 0 if both are equal and 1 if key A is
2687
         * greater than key B. Both, a method name and an anonymous function can be passed:
2688
         *
2689
         *  Map::from( [0 => 'a'] )->intersectKeys( [0 => 'A'], 'strcasecmp' );
2690
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['B' => 'X'], 'strcasecmp' );
2691
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['c' => 'a'], function( $keyA, $keyB ) {
2692
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
2693
         *  } );
2694
         *
2695
         * The first example will return a map with [0 => 'a'] and the second one will
2696
         * return a map with ['b' => 'a'] because both contain the same keys when compared
2697
         * case insensitive. The third example will return an empty map because the keys
2698
         * doesn't match ("b" vs. "c").
2699
         *
2700
         * The keys are preserved using this method.
2701
         *
2702
         * @param iterable<int|string,mixed> $elements List of elements
2703
         * @param  callable|null $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
2704
         * @return self<int|string,mixed> New map
2705
         */
2706
        public function intersectKeys( iterable $elements, ?callable $callback = null ) : self
2707
        {
2708
                $elements = $this->array( $elements );
9✔
2709

2710
                if( $callback ) {
9✔
2711
                        return new static( array_intersect_ukey( $this->list(), $elements, $callback ) );
3✔
2712
                }
2713

2714
                return new static( array_intersect_key( $this->list(), $elements ) );
6✔
2715
        }
2716

2717

2718
        /**
2719
         * Tests if the map consists of the same keys and values
2720
         *
2721
         * Examples:
2722
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'] );
2723
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'], true );
2724
         *  Map::from( [1, 2] )->is( ['1', '2'] );
2725
         *
2726
         * Results:
2727
         *  The first example returns TRUE while the second and third one returns FALSE
2728
         *
2729
         * @param iterable<int|string,mixed> $list List of key/value pairs to compare with
2730
         * @param bool $strict TRUE for comparing order of elements too, FALSE for key/values only
2731
         * @return bool TRUE if given list is equal, FALSE if not
2732
         */
2733
        public function is( iterable $list, bool $strict = false ) : bool
2734
        {
2735
                $list = $this->array( $list );
9✔
2736

2737
                if( $strict ) {
9✔
2738
                        return $this->list() === $list;
6✔
2739
                }
2740

2741
                return $this->list() == $list;
3✔
2742
        }
2743

2744

2745
        /**
2746
         * Determines if the map is empty or not.
2747
         *
2748
         * Examples:
2749
         *  Map::from( [] )->isEmpty();
2750
         *  Map::from( ['a'] )->isEmpty();
2751
         *
2752
         * Results:
2753
         *  The first example returns TRUE while the second returns FALSE
2754
         *
2755
         * The method is equivalent to empty().
2756
         *
2757
         * @return bool TRUE if map is empty, FALSE if not
2758
         */
2759
        public function isEmpty() : bool
2760
        {
2761
                return empty( $this->list() );
12✔
2762
        }
2763

2764

2765
        /**
2766
         * Checks if the map contains a list of subsequentially numbered keys.
2767
         *
2768
         * Examples:
2769
         * Map::from( [] )->isList();
2770
         * Map::from( [1, 3, 2] )->isList();
2771
         * Map::from( [0 => 1, 1 => 2, 2 => 3] )->isList();
2772
         * Map::from( [1 => 1, 2 => 2, 3 => 3] )->isList();
2773
         * Map::from( [0 => 1, 2 => 2, 3 => 3] )->isList();
2774
         * Map::from( ['a' => 1, 1 => 2, 'c' => 3] )->isList();
2775
         *
2776
         * Results:
2777
         * The first three examples return TRUE while the last three return FALSE
2778
         *
2779
         * @return bool TRUE if the map is a list, FALSE if not
2780
         */
2781
        public function isList() : bool
2782
        {
2783
                $i = -1;
3✔
2784

2785
                foreach( $this->list() as $k => $v )
3✔
2786
                {
2787
                        if( $k !== ++$i ) {
3✔
2788
                                return false;
3✔
2789
                        }
2790
                }
2791

2792
                return true;
3✔
2793
        }
2794

2795

2796
        /**
2797
         * Determines if all entries are numeric values.
2798
         *
2799
         * Examples:
2800
         *  Map::from( [] )->isNumeric();
2801
         *  Map::from( [1] )->isNumeric();
2802
         *  Map::from( [1.1] )->isNumeric();
2803
         *  Map::from( [010] )->isNumeric();
2804
         *  Map::from( [0x10] )->isNumeric();
2805
         *  Map::from( [0b10] )->isNumeric();
2806
         *  Map::from( ['010'] )->isNumeric();
2807
         *  Map::from( ['10'] )->isNumeric();
2808
         *  Map::from( ['10.1'] )->isNumeric();
2809
         *  Map::from( [' 10 '] )->isNumeric();
2810
         *  Map::from( ['10e2'] )->isNumeric();
2811
         *  Map::from( ['0b10'] )->isNumeric();
2812
         *  Map::from( ['0x10'] )->isNumeric();
2813
         *  Map::from( ['null'] )->isNumeric();
2814
         *  Map::from( [null] )->isNumeric();
2815
         *  Map::from( [true] )->isNumeric();
2816
         *  Map::from( [[]] )->isNumeric();
2817
         *  Map::from( [''] )->isNumeric();
2818
         *
2819
         * Results:
2820
         *  The first eleven examples return TRUE while the last seven return FALSE
2821
         *
2822
         * @return bool TRUE if all map entries are numeric values, FALSE if not
2823
         */
2824
        public function isNumeric() : bool
2825
        {
2826
                foreach( $this->list() as $val )
3✔
2827
                {
2828
                        if( !is_numeric( $val ) ) {
3✔
2829
                                return false;
3✔
2830
                        }
2831
                }
2832

2833
                return true;
3✔
2834
        }
2835

2836

2837
        /**
2838
         * Determines if all entries are objects.
2839
         *
2840
         * Examples:
2841
         *  Map::from( [] )->isObject();
2842
         *  Map::from( [new stdClass] )->isObject();
2843
         *  Map::from( [1] )->isObject();
2844
         *
2845
         * Results:
2846
         *  The first two examples return TRUE while the last one return FALSE
2847
         *
2848
         * @return bool TRUE if all map entries are objects, FALSE if not
2849
         */
2850
        public function isObject() : bool
2851
        {
2852
                foreach( $this->list() as $val )
3✔
2853
                {
2854
                        if( !is_object( $val ) ) {
3✔
2855
                                return false;
3✔
2856
                        }
2857
                }
2858

2859
                return true;
3✔
2860
        }
2861

2862

2863
        /**
2864
         * Determines if all entries are scalar values.
2865
         *
2866
         * Examples:
2867
         *  Map::from( [] )->isScalar();
2868
         *  Map::from( [1] )->isScalar();
2869
         *  Map::from( [1.1] )->isScalar();
2870
         *  Map::from( ['abc'] )->isScalar();
2871
         *  Map::from( [true, false] )->isScalar();
2872
         *  Map::from( [new stdClass] )->isScalar();
2873
         *  Map::from( [#resource] )->isScalar();
2874
         *  Map::from( [null] )->isScalar();
2875
         *  Map::from( [[1]] )->isScalar();
2876
         *
2877
         * Results:
2878
         *  The first five examples return TRUE while the others return FALSE
2879
         *
2880
         * @return bool TRUE if all map entries are scalar values, FALSE if not
2881
         */
2882
        public function isScalar() : bool
2883
        {
2884
                foreach( $this->list() as $val )
3✔
2885
                {
2886
                        if( !is_scalar( $val ) ) {
3✔
2887
                                return false;
3✔
2888
                        }
2889
                }
2890

2891
                return true;
3✔
2892
        }
2893

2894

2895
        /**
2896
         * Tests for the matching item, but is true only if exactly one item is matching.
2897
         *
2898
         * Examples:
2899
         *  Map::from( ['a', 'b'] )->isSole( 'a' );
2900
         *  Map::from( ['a', 'b', 'a'] )->isSole( fn( $v, $k ) => $v === 'a' && $k < 2 );
2901
         *  Map::from( [['name' => 'test'], ['name' => 'user']] )->isSole( fn( $v, $k ) => $v['name'] === 'user' );
2902
         *  Map::from( ['b', 'c'] )->isSole( 'a' );
2903
         *  Map::from( ['a', 'b', 'a'] )->isSole( 'a' );
2904
         *  Map::from( [['name' => 'test'], ['name' => 'user'], ['name' => 'test']] )->isSole( 'test', 'name' );
2905
         *
2906
         * Results:
2907
         * The first three examples will return TRUE while all others will return FALSE.
2908
         *
2909
         * @param \Closure|mixed $values Closure with (item, key) parameter or element to test against
2910
         * @param string|int|null $key Key to compare the value for if $values is not a closure
2911
         * @return bool TRUE if exactly one item matches, FALSE if no or more than one item matches
2912
         */
2913
        public function isSole( $value = null, $key = null ) : bool
2914
        {
2915
                return $this->restrict( $value, $key )->count() === 1;
9✔
2916
        }
2917

2918

2919
        /**
2920
         * Determines if all entries are string values.
2921
         *
2922
         * Examples:
2923
         *  Map::from( ['abc'] )->isString();
2924
         *  Map::from( [] )->isString();
2925
         *  Map::from( [1] )->isString();
2926
         *  Map::from( [1.1] )->isString();
2927
         *  Map::from( [true, false] )->isString();
2928
         *  Map::from( [new stdClass] )->isString();
2929
         *  Map::from( [#resource] )->isString();
2930
         *  Map::from( [null] )->isString();
2931
         *  Map::from( [[1]] )->isString();
2932
         *
2933
         * Results:
2934
         *  The first two examples return TRUE while the others return FALSE
2935
         *
2936
         * @return bool TRUE if all map entries are string values, FALSE if not
2937
         */
2938
        public function isString() : bool
2939
        {
2940
                foreach( $this->list() as $val )
3✔
2941
                {
2942
                        if( !is_string( $val ) ) {
3✔
2943
                                return false;
3✔
2944
                        }
2945
                }
2946

2947
                return true;
3✔
2948
        }
2949

2950

2951
        /**
2952
         * Concatenates the string representation of all elements.
2953
         *
2954
         * Objects that implement __toString() does also work, otherwise (and in case
2955
         * of arrays) a PHP notice is generated. NULL and FALSE values are treated as
2956
         * empty strings.
2957
         *
2958
         * Examples:
2959
         *  Map::from( ['a', 'b', false] )->join();
2960
         *  Map::from( ['a', 'b', null, false] )->join( '-' );
2961
         *
2962
         * Results:
2963
         * The first example will return "ab" while the second one will return "a-b--"
2964
         *
2965
         * @param string $glue Character or string added between elements
2966
         * @return string String of concatenated map elements
2967
         */
2968
        public function join( string $glue = '' ) : string
2969
        {
2970
                return implode( $glue, $this->list() );
3✔
2971
        }
2972

2973

2974
        /**
2975
         * Specifies the data which should be serialized to JSON by json_encode().
2976
         *
2977
         * Examples:
2978
         *   json_encode( Map::from( ['a', 'b'] ) );
2979
         *   json_encode( Map::from( ['a' => 0, 'b' => 1] ) );
2980
         *
2981
         * Results:
2982
         *   ["a", "b"]
2983
         *   {"a":0,"b":1}
2984
         *
2985
         * @return array<int|string,mixed> Data to serialize to JSON
2986
         */
2987
        #[\ReturnTypeWillChange]
2988
        public function jsonSerialize()
2989
        {
2990
                return $this->list = $this->array( $this->list );
3✔
2991
        }
2992

2993

2994
        /**
2995
         * Returns the keys of the all elements in a new map object.
2996
         *
2997
         * Examples:
2998
         *  Map::from( ['a', 'b'] );
2999
         *  Map::from( ['a' => 0, 'b' => 1] );
3000
         *
3001
         * Results:
3002
         * The first example returns a map containing [0, 1] while the second one will
3003
         * return a map with ['a', 'b'].
3004
         *
3005
         * @return self<int|string,mixed> New map
3006
         */
3007
        public function keys() : self
3008
        {
3009
                return new static( array_keys( $this->list() ) );
3✔
3010
        }
3011

3012

3013
        /**
3014
         * Sorts the elements by their keys in reverse order.
3015
         *
3016
         * Examples:
3017
         *  Map::from( ['b' => 0, 'a' => 1] )->krsort();
3018
         *  Map::from( [1 => 'a', 0 => 'b'] )->krsort();
3019
         *
3020
         * Results:
3021
         *  ['a' => 1, 'b' => 0]
3022
         *  [0 => 'b', 1 => 'a']
3023
         *
3024
         * The parameter modifies how the keys are compared. Possible values are:
3025
         * - SORT_REGULAR : compare elements normally (don't change types)
3026
         * - SORT_NUMERIC : compare elements numerically
3027
         * - SORT_STRING : compare elements as strings
3028
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3029
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3030
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3031
         *
3032
         * The keys are preserved using this method and no new map is created.
3033
         *
3034
         * @param int $options Sort options for krsort()
3035
         * @return self<int|string,mixed> Updated map for fluid interface
3036
         */
3037
        public function krsort( int $options = SORT_REGULAR ) : self
3038
        {
3039
                krsort( $this->list(), $options );
9✔
3040
                return $this;
9✔
3041
        }
3042

3043

3044
        /**
3045
         * Sorts a copy of the elements by their keys in reverse order.
3046
         *
3047
         * Examples:
3048
         *  Map::from( ['b' => 0, 'a' => 1] )->krsorted();
3049
         *  Map::from( [1 => 'a', 0 => 'b'] )->krsorted();
3050
         *
3051
         * Results:
3052
         *  ['a' => 1, 'b' => 0]
3053
         *  [0 => 'b', 1 => 'a']
3054
         *
3055
         * The parameter modifies how the keys are compared. Possible values are:
3056
         * - SORT_REGULAR : compare elements normally (don't change types)
3057
         * - SORT_NUMERIC : compare elements numerically
3058
         * - SORT_STRING : compare elements as strings
3059
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3060
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3061
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3062
         *
3063
         * The keys are preserved using this method and a new map is created.
3064
         *
3065
         * @param int $options Sort options for krsort()
3066
         * @return self<int|string,mixed> Updated map for fluid interface
3067
         */
3068
        public function krsorted( int $options = SORT_REGULAR ) : self
3069
        {
3070
                return ( clone $this )->krsort();
3✔
3071
        }
3072

3073

3074
        /**
3075
         * Sorts the elements by their keys.
3076
         *
3077
         * Examples:
3078
         *  Map::from( ['b' => 0, 'a' => 1] )->ksort();
3079
         *  Map::from( [1 => 'a', 0 => 'b'] )->ksort();
3080
         *
3081
         * Results:
3082
         *  ['a' => 1, 'b' => 0]
3083
         *  [0 => 'b', 1 => 'a']
3084
         *
3085
         * The parameter modifies how the keys are compared. Possible values are:
3086
         * - SORT_REGULAR : compare elements normally (don't change types)
3087
         * - SORT_NUMERIC : compare elements numerically
3088
         * - SORT_STRING : compare elements as strings
3089
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3090
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3091
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3092
         *
3093
         * The keys are preserved using this method and no new map is created.
3094
         *
3095
         * @param int $options Sort options for ksort()
3096
         * @return self<int|string,mixed> Updated map for fluid interface
3097
         */
3098
        public function ksort( int $options = SORT_REGULAR ) : self
3099
        {
3100
                ksort( $this->list(), $options );
9✔
3101
                return $this;
9✔
3102
        }
3103

3104

3105
        /**
3106
         * Sorts a copy of the elements by their keys.
3107
         *
3108
         * Examples:
3109
         *  Map::from( ['b' => 0, 'a' => 1] )->ksorted();
3110
         *  Map::from( [1 => 'a', 0 => 'b'] )->ksorted();
3111
         *
3112
         * Results:
3113
         *  ['a' => 1, 'b' => 0]
3114
         *  [0 => 'b', 1 => 'a']
3115
         *
3116
         * The parameter modifies how the keys are compared. Possible values are:
3117
         * - SORT_REGULAR : compare elements normally (don't change types)
3118
         * - SORT_NUMERIC : compare elements numerically
3119
         * - SORT_STRING : compare elements as strings
3120
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
3121
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
3122
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
3123
         *
3124
         * The keys are preserved using this method and no new map is created.
3125
         *
3126
         * @param int $options Sort options for ksort()
3127
         * @return self<int|string,mixed> Updated map for fluid interface
3128
         */
3129
        public function ksorted( int $options = SORT_REGULAR ) : self
3130
        {
3131
                return ( clone $this )->ksort();
3✔
3132
        }
3133

3134

3135
        /**
3136
         * Returns the last element from the map.
3137
         *
3138
         * Examples:
3139
         *  Map::from( ['a', 'b'] )->last();
3140
         *  Map::from( [] )->last( 'x' );
3141
         *  Map::from( [] )->last( new \Exception( 'error' ) );
3142
         *  Map::from( [] )->last( function() { return rand(); } );
3143
         *
3144
         * Results:
3145
         * The first example will return 'b' and the second one 'x'. The third example
3146
         * will throw the exception passed if the map contains no elements. In the
3147
         * fourth example, a random value generated by the closure function will be
3148
         * returned.
3149
         *
3150
         * Using this method doesn't affect the internal array pointer.
3151
         *
3152
         * @param mixed $default Default value or exception if the map contains no elements
3153
         * @return mixed Last value of map, (generated) default value or an exception
3154
         */
3155
        public function last( $default = null )
3156
        {
3157
                if( !empty( $this->list() ) ) {
18✔
3158
                        return current( array_slice( $this->list(), -1, 1 ) );
6✔
3159
                }
3160

3161
                if( $default instanceof \Closure ) {
12✔
3162
                        return $default();
3✔
3163
                }
3164

3165
                if( $default instanceof \Throwable ) {
9✔
3166
                        throw $default;
3✔
3167
                }
3168

3169
                return $default;
6✔
3170
        }
3171

3172

3173
        /**
3174
         * Returns the last key from the map.
3175
         *
3176
         * Examples:
3177
         *  Map::from( ['a' => 1, 'b' => 2] )->lastKey();
3178
         *  Map::from( [] )->lastKey( 'x' );
3179
         *  Map::from( [] )->lastKey( new \Exception( 'error' ) );
3180
         *  Map::from( [] )->lastKey( function() { return rand(); } );
3181
         *
3182
         * Results:
3183
         * The first example will return 'a' and the second one 'x', the third one will throw
3184
         * an exception and the last one will return a random value.
3185
         *
3186
         * Using this method doesn't affect the internal array pointer.
3187
         *
3188
         * @param mixed $default Default value, closure or exception if the map contains no elements
3189
         * @return mixed Last key of map, (generated) default value or an exception
3190
         */
3191
        public function lastKey( $default = null )
3192
        {
3193
                $list = $this->list();
15✔
3194

3195
                // PHP 7.x compatibility
3196
                if( function_exists( 'array_key_last' ) ) {
15✔
3197
                        $key = array_key_last( $list );
15✔
3198
                } else {
3199
                        $key = key( array_slice( $list, -1, 1, true ) );
×
3200
                }
3201

3202
                if( $key !== null ) {
15✔
3203
                        return $key;
3✔
3204
                }
3205

3206
                if( $default instanceof \Closure ) {
12✔
3207
                        return $default();
3✔
3208
                }
3209

3210
                if( $default instanceof \Throwable ) {
9✔
3211
                        throw $default;
3✔
3212
                }
3213

3214
                return $default;
6✔
3215
        }
3216

3217

3218
        /**
3219
         * Removes the passed characters from the left of all strings.
3220
         *
3221
         * Examples:
3222
         *  Map::from( [" abc\n", "\tcde\r\n"] )->ltrim();
3223
         *  Map::from( ["a b c", "cbxa"] )->ltrim( 'abc' );
3224
         *
3225
         * Results:
3226
         * The first example will return ["abc\n", "cde\r\n"] while the second one will return [" b c", "xa"].
3227
         *
3228
         * @param string $chars List of characters to trim
3229
         * @return self<int|string,mixed> Updated map for fluid interface
3230
         */
3231
        public function ltrim( string $chars = " \n\r\t\v\x00" ) : self
3232
        {
3233
                foreach( $this->list() as &$entry )
3✔
3234
                {
3235
                        if( is_string( $entry ) ) {
3✔
3236
                                $entry = ltrim( $entry, $chars );
3✔
3237
                        }
3238
                }
3239

3240
                return $this;
3✔
3241
        }
3242

3243

3244
        /**
3245
         * Maps new values to the existing keys using the passed function and returns a new map for the result.
3246
         *
3247
         * Examples:
3248
         *  Map::from( ['a' => 2, 'b' => 4] )->map( function( $value, $key ) {
3249
         *      return $value * 2;
3250
         *  } );
3251
         *
3252
         * Results:
3253
         *  ['a' => 4, 'b' => 8]
3254
         *
3255
         * The keys are preserved using this method.
3256
         *
3257
         * @param callable $callback Function with (value, key) parameters and returns computed result
3258
         * @return self<int|string,mixed> New map with the original keys and the computed values
3259
         * @see rekey() - Changes the keys according to the passed function
3260
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
3261
         */
3262
        public function map( callable $callback ) : self
3263
        {
3264
                $list = $this->list();
3✔
3265
                $keys = array_keys( $list );
3✔
3266
                $map = array_map( $callback, array_values( $list ), $keys );
3✔
3267

3268
                return new static( array_combine( $keys, $map ) );
3✔
3269
        }
3270

3271

3272
        /**
3273
         * Returns the maximum value of all elements.
3274
         *
3275
         * Examples:
3276
         *  Map::from( [1, 3, 2, 5, 4] )->max()
3277
         *  Map::from( ['bar', 'foo', 'baz'] )->max()
3278
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->max( 'p' )
3279
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( 'i/p' )
3280
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( fn( $val, $key ) => $val['i']['p'] ?? null )
3281
         *  Map::from( [50, 10, 30] )->max( fn( $val, $key ) => $key > 0 ? $val : null )
3282
         *
3283
         * Results:
3284
         * The first line will return "5", the second one "foo" and the third to fitfh
3285
         * one return 50 while the last one will return 30.
3286
         *
3287
         * NULL values are removed before the comparison. If there are no values or all
3288
         * values are NULL, NULL is returned.
3289
         *
3290
         * This does also work for multi-dimensional arrays by passing the keys
3291
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3292
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3293
         * public properties of objects or objects implementing __isset() and __get() methods.
3294
         *
3295
         * Be careful comparing elements of different types because this can have
3296
         * unpredictable results due to the PHP comparison rules:
3297
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3298
         *
3299
         * @param Closure|string|null $col Closure, key or path to the value of the nested array or object
3300
         * @return mixed Maximum value or NULL if there are no elements in the map
3301
         */
3302
        public function max( $col = null )
3303
        {
3304
                $list = $this->list();
12✔
3305
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list );
12✔
3306

3307
                return !empty( $vals ) ? max( $vals ) : null;
12✔
3308
        }
3309

3310

3311
        /**
3312
         * Merges the map with the given elements without returning a new map.
3313
         *
3314
         * Elements with the same non-numeric keys will be overwritten, elements
3315
         * with the same numeric keys will be added.
3316
         *
3317
         * Examples:
3318
         *  Map::from( ['a', 'b'] )->merge( ['b', 'c'] );
3319
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6] );
3320
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6], true );
3321
         *
3322
         * Results:
3323
         *  ['a', 'b', 'b', 'c']
3324
         *  ['a' => 1, 'b' => 4, 'c' => 6]
3325
         *  ['a' => 1, 'b' => [2, 4], 'c' => 6]
3326
         *
3327
         * The method is similar to replace() but doesn't replace elements with
3328
         * the same numeric keys. If you want to be sure that all passed elements
3329
         * are added without replacing existing ones, use concat() instead.
3330
         *
3331
         * The keys are preserved using this method.
3332
         *
3333
         * @param iterable<int|string,mixed> $elements List of elements
3334
         * @param bool $recursive TRUE to merge nested arrays too, FALSE for first level elements only
3335
         * @return self<int|string,mixed> Updated map for fluid interface
3336
         */
3337
        public function merge( iterable $elements, bool $recursive = false ) : self
3338
        {
3339
                if( $recursive ) {
9✔
3340
                        $this->list = array_merge_recursive( $this->list(), $this->array( $elements ) );
3✔
3341
                } else {
3342
                        $this->list = array_merge( $this->list(), $this->array( $elements ) );
6✔
3343
                }
3344

3345
                return $this;
9✔
3346
        }
3347

3348

3349
        /**
3350
         * Returns the minimum value of all elements.
3351
         *
3352
         * Examples:
3353
         *  Map::from( [2, 3, 1, 5, 4] )->min()
3354
         *  Map::from( ['baz', 'foo', 'bar'] )->min()
3355
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->min( 'p' )
3356
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->min( 'i/p' )
3357
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->min( fn( $val, $key ) => $val['i']['p'] ?? null )
3358
         *  Map::from( [10, 50, 30] )->min( fn( $val, $key ) => $key > 0 ? $val : null )
3359
         *
3360
         * Results:
3361
         * The first line will return "1", the second one "bar", the third one
3362
         * 10, and the forth to the last one 30.
3363
         *
3364
         * NULL values are removed before the comparison. If there are no values or all
3365
         * values are NULL, NULL is returned.
3366
         *
3367
         * This does also work for multi-dimensional arrays by passing the keys
3368
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3369
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3370
         * public properties of objects or objects implementing __isset() and __get() methods.
3371
         *
3372
         * Be careful comparing elements of different types because this can have
3373
         * unpredictable results due to the PHP comparison rules:
3374
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3375
         *
3376
         * @param Closure|string|null $key Closure, key or path to the value of the nested array or object
3377
         * @return mixed Minimum value or NULL if there are no elements in the map
3378
         */
3379
        public function min( $col = null )
3380
        {
3381
                $list = $this->list();
12✔
3382
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list );
12✔
3383

3384
                return !empty( $vals ) ? min( $vals ) : null;
12✔
3385
        }
3386

3387

3388
        /**
3389
         * Tests if none of the elements are part of the map.
3390
         *
3391
         * Examples:
3392
         *  Map::from( ['a', 'b'] )->none( 'x' );
3393
         *  Map::from( ['a', 'b'] )->none( ['x', 'y'] );
3394
         *  Map::from( ['1', '2'] )->none( 2, true );
3395
         *  Map::from( ['a', 'b'] )->none( 'a' );
3396
         *  Map::from( ['a', 'b'] )->none( ['a', 'b'] );
3397
         *  Map::from( ['a', 'b'] )->none( ['a', 'x'] );
3398
         *
3399
         * Results:
3400
         * The first three examples will return TRUE while the other ones will return FALSE
3401
         *
3402
         * @param mixed|array $element Element or elements to search for in the map
3403
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
3404
         * @return bool TRUE if none of the elements is part of the map, FALSE if at least one is
3405
         */
3406
        public function none( $element, bool $strict = false ) : bool
3407
        {
3408
                $list = $this->list();
3✔
3409

3410
                if( !is_array( $element ) ) {
3✔
3411
                        return !in_array( $element, $list, $strict );
3✔
3412
                };
3413

3414
                foreach( $element as $entry )
3✔
3415
                {
3416
                        if( in_array( $entry, $list, $strict ) === true ) {
3✔
3417
                                return false;
3✔
3418
                        }
3419
                }
3420

3421
                return true;
3✔
3422
        }
3423

3424

3425
        /**
3426
         * Returns every nth element from the map.
3427
         *
3428
         * Examples:
3429
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2 );
3430
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2, 1 );
3431
         *
3432
         * Results:
3433
         *  ['a', 'c', 'e']
3434
         *  ['b', 'd', 'f']
3435
         *
3436
         * @param int $step Step width
3437
         * @param int $offset Number of element to start from (0-based)
3438
         * @return self<int|string,mixed> New map
3439
         */
3440
        public function nth( int $step, int $offset = 0 ) : self
3441
        {
3442
                if( $step < 1 ) {
9✔
3443
                        throw new \InvalidArgumentException( 'Step width must be greater than zero' );
3✔
3444
                }
3445

3446
                if( $step === 1 ) {
6✔
3447
                        return clone $this;
3✔
3448
                }
3449

3450
                $result = [];
3✔
3451
                $list = $this->list();
3✔
3452

3453
                while( !empty( $pair = array_slice( $list, $offset, 1, true ) ) )
3✔
3454
                {
3455
                        $result += $pair;
3✔
3456
                        $offset += $step;
3✔
3457
                }
3458

3459
                return new static( $result );
3✔
3460
        }
3461

3462

3463
        /**
3464
         * Determines if an element exists at an offset.
3465
         *
3466
         * Examples:
3467
         *  $map = Map::from( ['a' => 1, 'b' => 3, 'c' => null] );
3468
         *  isset( $map['b'] );
3469
         *  isset( $map['c'] );
3470
         *  isset( $map['d'] );
3471
         *
3472
         * Results:
3473
         *  The first isset() will return TRUE while the second and third one will return FALSE
3474
         *
3475
         * @param int|string $key Key to check for
3476
         * @return bool TRUE if key exists, FALSE if not
3477
         */
3478
        public function offsetExists( $key ) : bool
3479
        {
3480
                return isset( $this->list()[$key] );
21✔
3481
        }
3482

3483

3484
        /**
3485
         * Returns an element at a given offset.
3486
         *
3487
         * Examples:
3488
         *  $map = Map::from( ['a' => 1, 'b' => 3] );
3489
         *  $map['b'];
3490
         *
3491
         * Results:
3492
         *  $map['b'] will return 3
3493
         *
3494
         * @param int|string $key Key to return the element for
3495
         * @return mixed Value associated to the given key
3496
         */
3497
        #[\ReturnTypeWillChange]
3498
        public function offsetGet( $key )
3499
        {
3500
                return $this->list()[$key] ?? null;
15✔
3501
        }
3502

3503

3504
        /**
3505
         * Sets the element at a given offset.
3506
         *
3507
         * Examples:
3508
         *  $map = Map::from( ['a' => 1] );
3509
         *  $map['b'] = 2;
3510
         *  $map[0] = 4;
3511
         *
3512
         * Results:
3513
         *  ['a' => 1, 'b' => 2, 0 => 4]
3514
         *
3515
         * @param int|string|null $key Key to set the element for or NULL to append value
3516
         * @param mixed $value New value set for the key
3517
         */
3518
        public function offsetSet( $key, $value ) : void
3519
        {
3520
                if( $key !== null ) {
9✔
3521
                        $this->list()[$key] = $value;
6✔
3522
                } else {
3523
                        $this->list()[] = $value;
6✔
3524
                }
3525
        }
3526

3527

3528
        /**
3529
         * Unsets the element at a given offset.
3530
         *
3531
         * Examples:
3532
         *  $map = Map::from( ['a' => 1] );
3533
         *  unset( $map['a'] );
3534
         *
3535
         * Results:
3536
         *  The map will be empty
3537
         *
3538
         * @param int|string $key Key for unsetting the item
3539
         */
3540
        public function offsetUnset( $key ) : void
3541
        {
3542
                unset( $this->list()[$key] );
6✔
3543
        }
3544

3545

3546
        /**
3547
         * Returns a new map with only those elements specified by the given keys.
3548
         *
3549
         * Examples:
3550
         *  Map::from( ['a' => 1, 0 => 'b'] )->only( 'a' );
3551
         *  Map::from( ['a' => 1, 0 => 'b', 1 => 'c'] )->only( [0, 1] );
3552
         *
3553
         * Results:
3554
         *  ['a' => 1]
3555
         *  [0 => 'b', 1 => 'c']
3556
         *
3557
         * The keys are preserved using this method.
3558
         *
3559
         * @param iterable<mixed>|array<mixed>|string|int $keys Keys of the elements that should be returned
3560
         * @return self<int|string,mixed> New map with only the elements specified by the keys
3561
         */
3562
        public function only( $keys ) : self
3563
        {
3564
                return $this->intersectKeys( array_flip( $this->array( $keys ) ) );
3✔
3565
        }
3566

3567

3568
        /**
3569
         * Returns a new map with elements ordered by the passed keys.
3570
         *
3571
         * If there are less keys passed than available in the map, the remaining
3572
         * elements are removed. Otherwise, if keys are passed that are not in the
3573
         * map, they will be also available in the returned map but their value is
3574
         * NULL.
3575
         *
3576
         * Examples:
3577
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 'a'] );
3578
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 2] );
3579
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1] );
3580
         *
3581
         * Results:
3582
         *  [0 => 'b', 1 => 'c', 'a' => 1]
3583
         *  [0 => 'b', 1 => 'c', 2 => null]
3584
         *  [0 => 'b', 1 => 'c']
3585
         *
3586
         * The keys are preserved using this method.
3587
         *
3588
         * @param iterable<mixed> $keys Keys of the elements in the required order
3589
         * @return self<int|string,mixed> New map with elements ordered by the passed keys
3590
         */
3591
        public function order( iterable $keys ) : self
3592
        {
3593
                $result = [];
3✔
3594
                $list = $this->list();
3✔
3595

3596
                foreach( $keys as $key ) {
3✔
3597
                        $result[$key] = $list[$key] ?? null;
3✔
3598
                }
3599

3600
                return new static( $result );
3✔
3601
        }
3602

3603

3604
        /**
3605
         * Fill up to the specified length with the given value
3606
         *
3607
         * In case the given number is smaller than the number of element that are
3608
         * already in the list, the map is unchanged. If the size is positive, the
3609
         * new elements are padded on the right, if it's negative then the elements
3610
         * are padded on the left.
3611
         *
3612
         * Examples:
3613
         *  Map::from( [1, 2, 3] )->pad( 5 );
3614
         *  Map::from( [1, 2, 3] )->pad( -5 );
3615
         *  Map::from( [1, 2, 3] )->pad( 5, '0' );
3616
         *  Map::from( [1, 2, 3] )->pad( 2 );
3617
         *  Map::from( [10 => 1, 20 => 2] )->pad( 3 );
3618
         *  Map::from( ['a' => 1, 'b' => 2] )->pad( 3, 3 );
3619
         *
3620
         * Results:
3621
         *  [1, 2, 3, null, null]
3622
         *  [null, null, 1, 2, 3]
3623
         *  [1, 2, 3, '0', '0']
3624
         *  [1, 2, 3]
3625
         *  [0 => 1, 1 => 2, 2 => null]
3626
         *  ['a' => 1, 'b' => 2, 0 => 3]
3627
         *
3628
         * Associative keys are preserved, numerical keys are replaced and numerical
3629
         * keys are used for the new elements.
3630
         *
3631
         * @param int $size Total number of elements that should be in the list
3632
         * @param mixed $value Value to fill up with if the map length is smaller than the given size
3633
         * @return self<int|string,mixed> New map
3634
         */
3635
        public function pad( int $size, $value = null ) : self
3636
        {
3637
                return new static( array_pad( $this->list(), $size, $value ) );
3✔
3638
        }
3639

3640

3641
        /**
3642
         * Breaks the list of elements into the given number of groups.
3643
         *
3644
         * Examples:
3645
         *  Map::from( [1, 2, 3, 4, 5] )->partition( 3 );
3646
         *  Map::from( [1, 2, 3, 4, 5] )->partition( function( $val, $idx ) {
3647
         *                return $idx % 3;
3648
         *        } );
3649
         *
3650
         * Results:
3651
         *  [[0 => 1, 1 => 2], [2 => 3, 3 => 4], [4 => 5]]
3652
         *  [0 => [0 => 1, 3 => 4], 1 => [1 => 2, 4 => 5], 2 => [2 => 3]]
3653
         *
3654
         * The keys of the original map are preserved in the returned map.
3655
         *
3656
         * @param \Closure|int $number Function with (value, index) as arguments returning the bucket key or number of groups
3657
         * @return self<int|string,mixed> New map
3658
         */
3659
        public function partition( $number ) : self
3660
        {
3661
                $list = $this->list();
12✔
3662

3663
                if( empty( $list ) ) {
12✔
3664
                        return new static();
3✔
3665
                }
3666

3667
                $result = [];
9✔
3668

3669
                if( $number instanceof \Closure )
9✔
3670
                {
3671
                        foreach( $list as $idx => $item ) {
3✔
3672
                                $result[$number( $item, $idx )][$idx] = $item;
3✔
3673
                        }
3674

3675
                        return new static( $result );
3✔
3676
                }
3677

3678
                if( is_int( $number ) )
6✔
3679
                {
3680
                        $start = 0;
3✔
3681
                        $size = (int) ceil( count( $list ) / $number );
3✔
3682

3683
                        for( $i = 0; $i < $number; $i++ )
3✔
3684
                        {
3685
                                $result[] = array_slice( $list, $start, $size, true );
3✔
3686
                                $start += $size;
3✔
3687
                        }
3688

3689
                        return new static( $result );
3✔
3690
                }
3691

3692
                throw new \InvalidArgumentException( 'Parameter is no closure or integer' );
3✔
3693
        }
3694

3695

3696
        /**
3697
         * Returns the percentage of all elements passing the test in the map.
3698
         *
3699
         * Examples:
3700
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50 );
3701
         *  Map::from( [] )->percentage( fn( $val, $key ) => true );
3702
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 100 );
3703
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 3 );
3704
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 0 );
3705
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50, -1 );
3706
         *
3707
         * Results:
3708
         * The first line will return "66.67", the second and third one "0.0", the forth
3709
         * one "33.333", the fifth one "33.0" and the last one "70.0" (66 rounded up).
3710
         *
3711
         * @param Closure $fcn Closure to filter the values in the nested array or object to compute the percentage
3712
         * @param int $precision Number of decimal digits use by the result value
3713
         * @return float Percentage of all elements passing the test in the map
3714
         */
3715
        public function percentage( \Closure $fcn, int $precision = 2 ) : float
3716
        {
3717
                $vals = array_filter( $this->list(), $fcn, ARRAY_FILTER_USE_BOTH );
3✔
3718

3719
                $cnt = count( $this->list() );
3✔
3720
                return $cnt > 0 ? round( count( $vals ) * 100 / $cnt, $precision ) : 0;
3✔
3721
        }
3722

3723

3724
        /**
3725
         * Passes the map to the given callback and return the result.
3726
         *
3727
         * Examples:
3728
         *  Map::from( ['a', 'b'] )->pipe( function( $map ) {
3729
         *      return join( '-', $map->toArray() );
3730
         *  } );
3731
         *
3732
         * Results:
3733
         *  "a-b" will be returned
3734
         *
3735
         * @param \Closure $callback Function with map as parameter which returns arbitrary result
3736
         * @return mixed Result returned by the callback
3737
         */
3738
        public function pipe( \Closure $callback )
3739
        {
3740
                return $callback( $this );
3✔
3741
        }
3742

3743

3744
        /**
3745
         * Returns the values of a single column/property from an array of arrays or objects in a new map.
3746
         *
3747
         * This method is an alias for col(). For performance reasons, col() should
3748
         * be preferred because it uses one method call less than pluck().
3749
         *
3750
         * @param string|null $valuecol Name or path of the value property
3751
         * @param string|null $indexcol Name or path of the index property
3752
         * @return self<int|string,mixed> New map with mapped entries
3753
         * @see col() - Underlying method with same parameters and return value but better performance
3754
         */
3755
        public function pluck( ?string $valuecol = null, ?string $indexcol = null ) : self
3756
        {
3757
                return $this->col( $valuecol, $indexcol );
3✔
3758
        }
3759

3760

3761
        /**
3762
         * Returns and removes the last element from the map.
3763
         *
3764
         * Examples:
3765
         *  Map::from( ['a', 'b'] )->pop();
3766
         *
3767
         * Results:
3768
         *  "b" will be returned and the map only contains ['a'] afterwards
3769
         *
3770
         * @return mixed Last element of the map or null if empty
3771
         */
3772
        public function pop()
3773
        {
3774
                return array_pop( $this->list() );
6✔
3775
        }
3776

3777

3778
        /**
3779
         * Returns the numerical index of the value.
3780
         *
3781
         * Examples:
3782
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( 'b' );
3783
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( function( $item, $key ) {
3784
         *      return $item === 'b';
3785
         *  } );
3786
         *
3787
         * Results:
3788
         * Both examples will return "1" because the value "b" is at the second position
3789
         * and the returned index is zero based so the first item has the index "0".
3790
         *
3791
         * @param \Closure|mixed $value Value to search for or function with (item, key) parameters return TRUE if value is found
3792
         * @return int|null Position of the found value (zero based) or NULL if not found
3793
         */
3794
        public function pos( $value ) : ?int
3795
        {
3796
                $pos = 0;
45✔
3797
                $list = $this->list();
45✔
3798

3799
                if( $value instanceof \Closure )
45✔
3800
                {
3801
                        foreach( $list as $key => $item )
9✔
3802
                        {
3803
                                if( $value( $item, $key ) ) {
9✔
3804
                                        return $pos;
9✔
3805
                                }
3806

3807
                                ++$pos;
9✔
3808
                        }
3809

3810
                        return null;
×
3811
                }
3812

3813
                if( ( $key = array_search( $value, $list, true ) ) !== false
36✔
3814
                        && ( $pos = array_search( $key, array_keys( $list ), true ) ) !== false
36✔
3815
                ) {
3816
                        return $pos;
30✔
3817
                }
3818

3819
                return null;
6✔
3820
        }
3821

3822

3823
        /**
3824
         * Adds a prefix in front of each map entry.
3825
         *
3826
         * By defaul, nested arrays are walked recusively so all entries at all levels are prefixed.
3827
         *
3828
         * Examples:
3829
         *  Map::from( ['a', 'b'] )->prefix( '1-' );
3830
         *  Map::from( ['a', ['b']] )->prefix( '1-' );
3831
         *  Map::from( ['a', ['b']] )->prefix( '1-', 1 );
3832
         *  Map::from( ['a', 'b'] )->prefix( function( $item, $key ) {
3833
         *      return ( ord( $item ) + ord( $key ) ) . '-';
3834
         *  } );
3835
         *
3836
         * Results:
3837
         *  The first example returns ['1-a', '1-b'] while the second one will return
3838
         *  ['1-a', ['1-b']]. In the third example, the depth is limited to the first
3839
         *  level only so it will return ['1-a', ['b']]. The forth example passing
3840
         *  the closure will return ['145-a', '147-b'].
3841
         *
3842
         * The keys of the original map are preserved in the returned map.
3843
         *
3844
         * @param \Closure|string $prefix Prefix string or anonymous function with ($item, $key) as parameters
3845
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
3846
         * @return self<int|string,mixed> Updated map for fluid interface
3847
         */
3848
        public function prefix( $prefix, ?int $depth = null ) : self
3849
        {
3850
                $fcn = function( array $list, $prefix, int $depth ) use ( &$fcn ) {
3✔
3851

3852
                        foreach( $list as $key => $item )
3✔
3853
                        {
3854
                                if( is_array( $item ) ) {
3✔
3855
                                        $list[$key] = $depth > 1 ? $fcn( $item, $prefix, $depth - 1 ) : $item;
3✔
3856
                                } else {
3857
                                        $list[$key] = ( is_callable( $prefix ) ? $prefix( $item, $key ) : $prefix ) . $item;
3✔
3858
                                }
3859
                        }
3860

3861
                        return $list;
3✔
3862
                };
3✔
3863

3864
                $this->list = $fcn( $this->list(), $prefix, $depth ?? 0x7fffffff );
3✔
3865
                return $this;
3✔
3866
        }
3867

3868

3869
        /**
3870
         * Pushes an element onto the beginning of the map without returning a new map.
3871
         *
3872
         * This method is an alias for unshift().
3873
         *
3874
         * @param mixed $value Item to add at the beginning
3875
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
3876
         * @return self<int|string,mixed> Updated map for fluid interface
3877
         * @see unshift() - Underlying method with same parameters and return value but better performance
3878
         */
3879
        public function prepend( $value, $key = null ) : self
3880
        {
3881
                return $this->unshift( $value, $key );
3✔
3882
        }
3883

3884

3885
        /**
3886
         * Returns and removes an element from the map by its key.
3887
         *
3888
         * Examples:
3889
         *  Map::from( ['a', 'b', 'c'] )->pull( 1 );
3890
         *  Map::from( ['a', 'b', 'c'] )->pull( 'x', 'none' );
3891
         *  Map::from( [] )->pull( 'Y', new \Exception( 'error' ) );
3892
         *  Map::from( [] )->pull( 'Z', function() { return rand(); } );
3893
         *
3894
         * Results:
3895
         * The first example will return "b" and the map contains ['a', 'c'] afterwards.
3896
         * The second one will return "none" and the map content stays untouched. If you
3897
         * pass an exception as default value, it will throw that exception if the map
3898
         * contains no elements. In the fourth example, a random value generated by the
3899
         * closure function will be returned.
3900
         *
3901
         * @param int|string $key Key to retrieve the value for
3902
         * @param mixed $default Default value if key isn't available
3903
         * @return mixed Value from map or default value
3904
         */
3905
        public function pull( $key, $default = null )
3906
        {
3907
                $value = $this->get( $key, $default );
12✔
3908
                unset( $this->list()[$key] );
9✔
3909

3910
                return $value;
9✔
3911
        }
3912

3913

3914
        /**
3915
         * Pushes an element onto the end of the map without returning a new map.
3916
         *
3917
         * Examples:
3918
         *  Map::from( ['a', 'b'] )->push( 'aa' );
3919
         *
3920
         * Results:
3921
         *  ['a', 'b', 'aa']
3922
         *
3923
         * @param mixed $value Value to add to the end
3924
         * @return self<int|string,mixed> Updated map for fluid interface
3925
         */
3926
        public function push( $value ) : self
3927
        {
3928
                $this->list()[] = $value;
9✔
3929
                return $this;
9✔
3930
        }
3931

3932

3933
        /**
3934
         * Sets the given key and value in the map without returning a new map.
3935
         *
3936
         * This method is an alias for set(). For performance reasons, set() should be
3937
         * preferred because it uses one method call less than put().
3938
         *
3939
         * @param int|string $key Key to set the new value for
3940
         * @param mixed $value New element that should be set
3941
         * @return self<int|string,mixed> Updated map for fluid interface
3942
         * @see set() - Underlying method with same parameters and return value but better performance
3943
         */
3944
        public function put( $key, $value ) : self
3945
        {
3946
                return $this->set( $key, $value );
3✔
3947
        }
3948

3949

3950
        /**
3951
         * Returns one or more random element from the map incl. their keys.
3952
         *
3953
         * Examples:
3954
         *  Map::from( [2, 4, 8, 16] )->random();
3955
         *  Map::from( [2, 4, 8, 16] )->random( 2 );
3956
         *  Map::from( [2, 4, 8, 16] )->random( 5 );
3957
         *
3958
         * Results:
3959
         * The first example will return a map including [0 => 8] or any other value,
3960
         * the second one will return a map with [0 => 16, 1 => 2] or any other values
3961
         * and the third example will return a map of the whole list in random order. The
3962
         * less elements are in the map, the less random the order will be, especially if
3963
         * the maximum number of values is high or close to the number of elements.
3964
         *
3965
         * The keys of the original map are preserved in the returned map.
3966
         *
3967
         * @param int $max Maximum number of elements that should be returned
3968
         * @return self<int|string,mixed> New map with key/element pairs from original map in random order
3969
         * @throws \InvalidArgumentException If requested number of elements is less than 1
3970
         */
3971
        public function random( int $max = 1 ) : self
3972
        {
3973
                if( $max < 1 ) {
15✔
3974
                        throw new \InvalidArgumentException( 'Requested number of elements must be greater or equal than 1' );
3✔
3975
                }
3976

3977
                $list = $this->list();
12✔
3978

3979
                if( empty( $list ) ) {
12✔
3980
                        return new static();
3✔
3981
                }
3982

3983
                if( ( $num = count( $list ) ) < $max ) {
9✔
3984
                        $max = $num;
3✔
3985
                }
3986

3987
                $keys = array_rand( $list, $max );
9✔
3988

3989
                return new static( array_intersect_key( $list, array_flip( (array) $keys ) ) );
9✔
3990
        }
3991

3992

3993
        /**
3994
         * Iteratively reduces the array to a single value using a callback function.
3995
         * Afterwards, the map will be empty.
3996
         *
3997
         * Examples:
3998
         *  Map::from( [2, 8] )->reduce( function( $result, $value ) {
3999
         *      return $result += $value;
4000
         *  }, 10 );
4001
         *
4002
         * Results:
4003
         *  "20" will be returned because the sum is computed by 10 (initial value) + 2 + 8
4004
         *
4005
         * @param callable $callback Function with (result, value) parameters and returns result
4006
         * @param mixed $initial Initial value when computing the result
4007
         * @return mixed Value computed by the callback function
4008
         */
4009
        public function reduce( callable $callback, $initial = null )
4010
        {
4011
                return array_reduce( $this->list(), $callback, $initial );
3✔
4012
        }
4013

4014

4015
        /**
4016
         * Removes all matched elements and returns a new map.
4017
         *
4018
         * Examples:
4019
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->reject( function( $value, $key ) {
4020
         *      return $value < 'm';
4021
         *  } );
4022
         *  Map::from( [2 => 'a', 13 => 'm', 30 => 'z'] )->reject( 'm' );
4023
         *  Map::from( [2 => 'a', 6 => null, 13 => 'm'] )->reject();
4024
         *
4025
         * Results:
4026
         *  [13 => 'm', 30 => 'z']
4027
         *  [2 => 'a', 30 => 'z']
4028
         *  [6 => null]
4029
         *
4030
         * This method is the inverse of the filter() and should return TRUE if the
4031
         * item should be removed from the returned map.
4032
         *
4033
         * If no callback is passed, all values which are NOT empty, null or false will be
4034
         * removed. The keys of the original map are preserved in the returned map.
4035
         *
4036
         * @param Closure|mixed $callback Function with (item, key) parameter which returns TRUE/FALSE
4037
         * @return self<int|string,mixed> New map
4038
         */
4039
        public function reject( $callback = true ) : self
4040
        {
4041
                $result = [];
9✔
4042

4043
                if( $callback instanceof \Closure )
9✔
4044
                {
4045
                        foreach( $this->list() as $key => $value )
3✔
4046
                        {
4047
                                if( !$callback( $value, $key ) ) {
3✔
4048
                                        $result[$key] = $value;
3✔
4049
                                }
4050
                        }
4051
                }
4052
                else
4053
                {
4054
                        foreach( $this->list() as $key => $value )
6✔
4055
                        {
4056
                                if( $value != $callback ) {
6✔
4057
                                        $result[$key] = $value;
6✔
4058
                                }
4059
                        }
4060
                }
4061

4062
                return new static( $result );
9✔
4063
        }
4064

4065

4066
        /**
4067
         * Changes the keys according to the passed function.
4068
         *
4069
         * Examples:
4070
         *  Map::from( ['a' => 2, 'b' => 4] )->rekey( function( $value, $key ) {
4071
         *      return 'key-' . $key;
4072
         *  } );
4073
         *
4074
         * Results:
4075
         *  ['key-a' => 2, 'key-b' => 4]
4076
         *
4077
         * @param callable $callback Function with (value, key) parameters and returns new key
4078
         * @return self<int|string,mixed> New map with new keys and original values
4079
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
4080
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
4081
         */
4082
        public function rekey( callable $callback ) : self
4083
        {
4084
                $list = $this->list();
3✔
4085
                $newKeys = array_map( $callback, $list, array_keys( $list ) );
3✔
4086

4087
                return new static( array_combine( $newKeys, array_values( $list ) ) );
3✔
4088
        }
4089

4090

4091
        /**
4092
         * Removes one or more elements from the map by its keys without returning a new map.
4093
         *
4094
         * Examples:
4095
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( 'a' );
4096
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( [2, 'a'] );
4097
         *
4098
         * Results:
4099
         * The first example will result in [2 => 'b'] while the second one resulting
4100
         * in an empty list
4101
         *
4102
         * @param iterable<string|int>|array<string|int>|string|int $keys List of keys to remove
4103
         * @return self<int|string,mixed> Updated map for fluid interface
4104
         */
4105
        public function remove( $keys ) : self
4106
        {
4107
                foreach( $this->array( $keys ) as $key ) {
15✔
4108
                        unset( $this->list()[$key] );
15✔
4109
                }
4110

4111
                return $this;
15✔
4112
        }
4113

4114

4115
        /**
4116
         * Replaces elements in the map with the given elements without returning a new map.
4117
         *
4118
         * Examples:
4119
         *  Map::from( ['a' => 1, 2 => 'b'] )->replace( ['a' => 2] );
4120
         *  Map::from( ['a' => 1, 'b' => ['c' => 3, 'd' => 4]] )->replace( ['b' => ['c' => 9]] );
4121
         *
4122
         * Results:
4123
         *  ['a' => 2, 2 => 'b']
4124
         *  ['a' => 1, 'b' => ['c' => 9, 'd' => 4]]
4125
         *
4126
         * The method is similar to merge() but it also replaces elements with numeric
4127
         * keys. These would be added by merge() with a new numeric key.
4128
         *
4129
         * The keys are preserved using this method.
4130
         *
4131
         * @param iterable<int|string,mixed> $elements List of elements
4132
         * @param bool $recursive TRUE to replace recursively (default), FALSE to replace elements only
4133
         * @return self<int|string,mixed> Updated map for fluid interface
4134
         */
4135
        public function replace( iterable $elements, bool $recursive = true ) : self
4136
        {
4137
                if( $recursive ) {
15✔
4138
                        $this->list = array_replace_recursive( $this->list(), $this->array( $elements ) );
12✔
4139
                } else {
4140
                        $this->list = array_replace( $this->list(), $this->array( $elements ) );
3✔
4141
                }
4142

4143
                return $this;
15✔
4144
        }
4145

4146

4147
        /**
4148
         * Returns only the items matching the value (and key) from the map.
4149
         *
4150
         * Examples:
4151
         *  Map::from( ['a', 'b', 'a'] )->restrict( 'a' );
4152
         *  Map::from( [['name' => 'test'], ['name' => 'user'], ['name' => 'test']] )->restrict( 'test', 'name' );
4153
         *  Map::from( [['name' => 'test'], ['name' => 'user']] )->restrict( fn( $v, $k ) => $v['name'] === 'user' );
4154
         *  Map::from( ['a', 'b', 'a'] )->restrict( fn( $v, $k ) => $v === 'a' && $k < 2 );
4155
         *
4156
         * Results:
4157
         *  [0 => 'a', 2 => 'a']
4158
         *  [0 => ['name' => 'test'], 2 => ['name' => 'test']]
4159
         *  [1 => ['name' => 'user']]
4160
         *  [0 => 'a']
4161
         *
4162
         * The keys are preserved in the returned map.
4163
         *
4164
         * @param \Closure|mixed $value Closure with (item, key) parameter or element to test against
4165
         * @param string|int|null $key Key to compare the value to if $value is not a closure
4166
         * @return self<int|string,mixed> New map with matching items only
4167
         */
4168
        public function restrict( $value = null, $key = null ) : self
4169
        {
4170
                if( !( $value instanceof \Closure ) ) {
30✔
4171
                        $filter = $key === null ? fn( $v ) => $v === $value : fn( $v, $k ) => ( $v[$key] ?? null ) === $value;
24✔
4172
                } else {
4173
                        $filter = $value;
6✔
4174
                }
4175

4176
                return $this->filter( $filter );
30✔
4177
        }
4178

4179

4180
        /**
4181
         * Reverses the element order with keys without returning a new map.
4182
         *
4183
         * Examples:
4184
         *  Map::from( ['a', 'b'] )->reverse();
4185
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reverse();
4186
         *
4187
         * Results:
4188
         *  ['b', 'a']
4189
         *  ['last' => 'user', 'name' => 'test']
4190
         *
4191
         * The keys are preserved using this method.
4192
         *
4193
         * @return self<int|string,mixed> Updated map for fluid interface
4194
         * @see reversed() - Reverses the element order in a copy of the map
4195
         */
4196
        public function reverse() : self
4197
        {
4198
                $this->list = array_reverse( $this->list(), true );
12✔
4199
                return $this;
12✔
4200
        }
4201

4202

4203
        /**
4204
         * Reverses the element order in a copy of the map.
4205
         *
4206
         * Examples:
4207
         *  Map::from( ['a', 'b'] )->reversed();
4208
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reversed();
4209
         *
4210
         * Results:
4211
         *  ['b', 'a']
4212
         *  ['last' => 'user', 'name' => 'test']
4213
         *
4214
         * The keys are preserved using this method and a new map is created before reversing the elements.
4215
         * Thus, reverse() should be preferred for performance reasons if possible.
4216
         *
4217
         * @return self<int|string,mixed> New map with a reversed copy of the elements
4218
         * @see reverse() - Reverses the element order with keys without returning a new map
4219
         */
4220
        public function reversed() : self
4221
        {
4222
                return ( clone $this )->reverse();
6✔
4223
        }
4224

4225

4226
        /**
4227
         * Sorts all elements in reverse order using new keys.
4228
         *
4229
         * Examples:
4230
         *  Map::from( ['a' => 1, 'b' => 0] )->rsort();
4231
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsort();
4232
         *
4233
         * Results:
4234
         *  [0 => 1, 1 => 0]
4235
         *  [0 => 'b', 1 => 'a']
4236
         *
4237
         * The parameter modifies how the values are compared. Possible parameter values are:
4238
         * - SORT_REGULAR : compare elements normally (don't change types)
4239
         * - SORT_NUMERIC : compare elements numerically
4240
         * - SORT_STRING : compare elements as strings
4241
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4242
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4243
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4244
         *
4245
         * The keys aren't preserved and elements get a new index. No new map is created
4246
         *
4247
         * @param int $options Sort options for rsort()
4248
         * @return self<int|string,mixed> Updated map for fluid interface
4249
         */
4250
        public function rsort( int $options = SORT_REGULAR ) : self
4251
        {
4252
                rsort( $this->list(), $options );
9✔
4253
                return $this;
9✔
4254
        }
4255

4256

4257
        /**
4258
         * Sorts a copy of all elements in reverse order using new keys.
4259
         *
4260
         * Examples:
4261
         *  Map::from( ['a' => 1, 'b' => 0] )->rsorted();
4262
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsorted();
4263
         *
4264
         * Results:
4265
         *  [0 => 1, 1 => 0]
4266
         *  [0 => 'b', 1 => 'a']
4267
         *
4268
         * The parameter modifies how the values are compared. Possible parameter values are:
4269
         * - SORT_REGULAR : compare elements normally (don't change types)
4270
         * - SORT_NUMERIC : compare elements numerically
4271
         * - SORT_STRING : compare elements as strings
4272
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4273
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4274
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4275
         *
4276
         * The keys aren't preserved, elements get a new index and a new map is created.
4277
         *
4278
         * @param int $options Sort options for rsort()
4279
         * @return self<int|string,mixed> Updated map for fluid interface
4280
         */
4281
        public function rsorted( int $options = SORT_REGULAR ) : self
4282
        {
4283
                return ( clone $this )->rsort( $options );
3✔
4284
        }
4285

4286

4287
        /**
4288
         * Removes the passed characters from the right of all strings.
4289
         *
4290
         * Examples:
4291
         *  Map::from( [" abc\n", "\tcde\r\n"] )->rtrim();
4292
         *  Map::from( ["a b c", "cbxa"] )->rtrim( 'abc' );
4293
         *
4294
         * Results:
4295
         * The first example will return [" abc", "\tcde"] while the second one will return ["a b ", "cbx"].
4296
         *
4297
         * @param string $chars List of characters to trim
4298
         * @return self<int|string,mixed> Updated map for fluid interface
4299
         */
4300
        public function rtrim( string $chars = " \n\r\t\v\x00" ) : self
4301
        {
4302
                foreach( $this->list() as &$entry )
3✔
4303
                {
4304
                        if( is_string( $entry ) ) {
3✔
4305
                                $entry = rtrim( $entry, $chars );
3✔
4306
                        }
4307
                }
4308

4309
                return $this;
3✔
4310
        }
4311

4312

4313
        /**
4314
         * Searches the map for a given value and return the corresponding key if successful.
4315
         *
4316
         * Examples:
4317
         *  Map::from( ['a', 'b', 'c'] )->search( 'b' );
4318
         *  Map::from( [1, 2, 3] )->search( '2', true );
4319
         *
4320
         * Results:
4321
         * The first example will return 1 (array index) while the second one will
4322
         * return NULL because the types doesn't match (int vs. string)
4323
         *
4324
         * @param mixed $value Item to search for
4325
         * @param bool $strict TRUE if type of the element should be checked too
4326
         * @return int|string|null Key associated to the value or null if not found
4327
         */
4328
        public function search( $value, $strict = true )
4329
        {
4330
                if( ( $result = array_search( $value, $this->list(), $strict ) ) !== false ) {
3✔
4331
                        return $result;
3✔
4332
                }
4333

4334
                return null;
3✔
4335
        }
4336

4337

4338
        /**
4339
         * Sets the seperator for paths to values in multi-dimensional arrays or objects.
4340
         *
4341
         * This method only changes the separator for the current map instance. To
4342
         * change the separator for all maps created afterwards, use the static
4343
         * delimiter() method instead.
4344
         *
4345
         * Examples:
4346
         *  Map::from( ['foo' => ['bar' => 'baz']] )->sep( '.' )->get( 'foo.bar' );
4347
         *
4348
         * Results:
4349
         *  'baz'
4350
         *
4351
         * @param string $char Separator character, e.g. "." for "key.to.value" instead of "key/to/value"
4352
         * @return self<int|string,mixed> Same map for fluid interface
4353
         */
4354
        public function sep( string $char ) : self
4355
        {
4356
                $this->sep = $char;
9✔
4357
                return $this;
9✔
4358
        }
4359

4360

4361
        /**
4362
         * Sets an element in the map by key without returning a new map.
4363
         *
4364
         * Examples:
4365
         *  Map::from( ['a'] )->set( 1, 'b' );
4366
         *  Map::from( ['a'] )->set( 0, 'b' );
4367
         *
4368
         * Results:
4369
         *  ['a', 'b']
4370
         *  ['b']
4371
         *
4372
         * @param int|string $key Key to set the new value for
4373
         * @param mixed $value New element that should be set
4374
         * @return self<int|string,mixed> Updated map for fluid interface
4375
         */
4376
        public function set( $key, $value ) : self
4377
        {
4378
                $this->list()[(string) $key] = $value;
15✔
4379
                return $this;
15✔
4380
        }
4381

4382

4383
        /**
4384
         * Returns and removes the first element from the map.
4385
         *
4386
         * Examples:
4387
         *  Map::from( ['a', 'b'] )->shift();
4388
         *  Map::from( [] )->shift();
4389
         *
4390
         * Results:
4391
         * The first example returns "a" and shortens the map to ['b'] only while the
4392
         * second example will return NULL
4393
         *
4394
         * Performance note:
4395
         * The bigger the list, the higher the performance impact because shift()
4396
         * reindexes all existing elements. Usually, it's better to reverse() the list
4397
         * and pop() entries from the list afterwards if a significant number of elements
4398
         * should be removed from the list:
4399
         *
4400
         *  $map->reverse()->pop();
4401
         * instead of
4402
         *  $map->shift( 'a' );
4403
         *
4404
         * @return mixed|null Value from map or null if not found
4405
         */
4406
        public function shift()
4407
        {
4408
                return array_shift( $this->list() );
3✔
4409
        }
4410

4411

4412
        /**
4413
         * Shuffles the elements in the map without returning a new map.
4414
         *
4415
         * Examples:
4416
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle();
4417
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle( true );
4418
         *
4419
         * Results:
4420
         * The map in the first example will contain "a" and "b" in random order and
4421
         * with new keys assigned. The second call will also return all values in
4422
         * random order but preserves the keys of the original list.
4423
         *
4424
         * @param bool $assoc True to preserve keys, false to assign new keys
4425
         * @return self<int|string,mixed> Updated map for fluid interface
4426
         * @see shuffled() - Shuffles the elements in a copy of the map
4427
         */
4428
        public function shuffle( bool $assoc = false ) : self
4429
        {
4430
                if( $assoc )
9✔
4431
                {
4432
                        $list = $this->list();
3✔
4433
                        $keys = array_keys( $list );
3✔
4434
                        shuffle( $keys );
3✔
4435
                        $items = [];
3✔
4436

4437
                        foreach( $keys as $key ) {
3✔
4438
                                $items[$key] = $list[$key];
3✔
4439
                        }
4440

4441
                        $this->list = $items;
3✔
4442
                }
4443
                else
4444
                {
4445
                        shuffle( $this->list() );
6✔
4446
                }
4447

4448
                return $this;
9✔
4449
        }
4450

4451

4452
        /**
4453
         * Shuffles the elements in a copy of the map.
4454
         *
4455
         * Examples:
4456
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled();
4457
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled( true );
4458
         *
4459
         * Results:
4460
         * The map in the first example will contain "a" and "b" in random order and
4461
         * with new keys assigned. The second call will also return all values in
4462
         * random order but preserves the keys of the original list.
4463
         *
4464
         * @param bool $assoc True to preserve keys, false to assign new keys
4465
         * @return self<int|string,mixed> New map with a shuffled copy of the elements
4466
         * @see shuffle() - Shuffles the elements in the map without returning a new map
4467
         */
4468
        public function shuffled( bool $assoc = false ) : self
4469
        {
4470
                return ( clone $this )->shuffle( $assoc );
3✔
4471
        }
4472

4473

4474
        /**
4475
         * Returns a new map with the given number of items skipped.
4476
         *
4477
         * Examples:
4478
         *  Map::from( [1, 2, 3, 4] )->skip( 2 );
4479
         *  Map::from( [1, 2, 3, 4] )->skip( function( $item, $key ) {
4480
         *      return $item < 4;
4481
         *  } );
4482
         *
4483
         * Results:
4484
         *  [2 => 3, 3 => 4]
4485
         *  [3 => 4]
4486
         *
4487
         * The keys of the items returned in the new map are the same as in the original one.
4488
         *
4489
         * @param \Closure|int $offset Number of items to skip or function($item, $key) returning true for skipped items
4490
         * @return self<int|string,mixed> New map
4491
         */
4492
        public function skip( $offset ) : self
4493
        {
4494
                if( is_numeric( $offset ) ) {
9✔
4495
                        return new static( array_slice( $this->list(), (int) $offset, null, true ) );
3✔
4496
                }
4497

4498
                if( $offset instanceof \Closure ) {
6✔
4499
                        return new static( array_slice( $this->list(), $this->until( $this->list(), $offset ), null, true ) );
3✔
4500
                }
4501

4502
                throw new \InvalidArgumentException( 'Only an integer or a closure is allowed as first argument for skip()' );
3✔
4503
        }
4504

4505

4506
        /**
4507
         * Returns a map with the slice from the original map.
4508
         *
4509
         * Examples:
4510
         *  Map::from( ['a', 'b', 'c'] )->slice( 1 );
4511
         *  Map::from( ['a', 'b', 'c'] )->slice( 1, 1 );
4512
         *  Map::from( ['a', 'b', 'c', 'd'] )->slice( -2, -1 );
4513
         *
4514
         * Results:
4515
         * The first example will return ['b', 'c'] and the second one ['b'] only.
4516
         * The third example returns ['c'] because the slice starts at the second
4517
         * last value and ends before the last value.
4518
         *
4519
         * The rules for offsets are:
4520
         * - If offset is non-negative, the sequence will start at that offset
4521
         * - If offset is negative, the sequence will start that far from the end
4522
         *
4523
         * Similar for the length:
4524
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4525
         * - If the array is shorter than the length, then only the available array elements will be present
4526
         * - If length is given and is negative then the sequence will stop that many elements from the end
4527
         * - If it is omitted, then the sequence will have everything from offset up until the end
4528
         *
4529
         * The keys of the items returned in the new map are the same as in the original one.
4530
         *
4531
         * @param int $offset Number of elements to start from
4532
         * @param int|null $length Number of elements to return or NULL for no limit
4533
         * @return self<int|string,mixed> New map
4534
         */
4535
        public function slice( int $offset, ?int $length = null ) : self
4536
        {
4537
                return new static( array_slice( $this->list(), $offset, $length, true ) );
18✔
4538
        }
4539

4540

4541
        /**
4542
         * Returns a new map containing sliding windows of the original map.
4543
         *
4544
         * Examples:
4545
         *  Map::from( [1, 2, 3, 4] )->sliding( 2 );
4546
         *  Map::from( [1, 2, 3, 4] )->sliding( 3, 2 );
4547
         *
4548
         * Results:
4549
         * The first example will return [[0 => 1, 1 => 2], [1 => 2, 2 => 3], [2 => 3, 3 => 4]]
4550
         * while the second one will return [[0 => 1, 1 => 2, 2 => 3], [2 => 3, 3 => 4, 4 => 5]]
4551
         *
4552
         * @param int $size Size of each window
4553
         * @param int $step Step size to move the window
4554
         * @return self<int,array<int|string,mixed>> New map containing arrays for each window
4555
         */
4556
        public function sliding( int $size = 2, int $step = 1 ) : self
4557
        {
4558
                $result = [];
6✔
4559
                $chunks = floor( ( $this->count() - $size ) / $step ) + 1;
6✔
4560

4561
                for( $i = 0; $i < $chunks; $i++ ) {
6✔
4562
                        $result[] = array_slice( $this->list(), $i * $step, $size, true );
6✔
4563
                }
4564

4565
                return new static( $result );
6✔
4566
        }
4567

4568

4569
        /**
4570
         * Returns the matching item, but only if one matching item exists.
4571
         *
4572
         * Examples:
4573
         *  Map::from( ['a', 'b'] )->sole( 'a' );
4574
         *  Map::from( ['a', 'b', 'a'] )->restrict( fn( $v, $k ) => $v === 'a' && $k < 2 );
4575
         *  Map::from( [['name' => 'test'], ['name' => 'user']] )->restrict( fn( $v, $k ) => $v['name'] === 'user' );
4576
         *  Map::from( ['b', 'c'] )->sole( 'a' );
4577
         *  Map::from( ['a', 'b', 'a'] )->sole( 'a' );
4578
         *  Map::from( [['name' => 'test'], ['name' => 'user'], ['name' => 'test']] )->restrict( 'test', 'name' );
4579
         *
4580
         * Results:
4581
         * The first two examples will return "a" while the third one will return [1 => ['name' => 'user']].
4582
         * All other examples throw a LengthException because more than one item matches the test.
4583
         *
4584
         * @param \Closure|mixed $values Closure with (item, key) parameter or element to test against
4585
         * @param string|int|null $key Key to compare the value for if $values is not a closure
4586
         * @return mixed Value from map if exactly one matching item exists
4587
         * @throws \LengthException If no items or more than one item is found
4588
         */
4589
        public function sole( $value = null, $key = null )
4590
        {
4591
                $items = $this->restrict( $value, $key );
9✔
4592

4593
                if( $items->count() > 1 ) {
9✔
4594
                        throw new \LengthException( 'Multiple items found' );
3✔
4595
                }
4596

4597
                return $items->first( new \LengthException( 'No items found' ) );
6✔
4598
        }
4599

4600

4601
        /**
4602
         * Tests if at least one element passes the test or is part of the map.
4603
         *
4604
         * Examples:
4605
         *  Map::from( ['a', 'b'] )->some( 'a' );
4606
         *  Map::from( ['a', 'b'] )->some( ['a', 'c'] );
4607
         *  Map::from( ['a', 'b'] )->some( function( $item, $key ) {
4608
         *    return $item === 'a';
4609
         *  } );
4610
         *  Map::from( ['a', 'b'] )->some( ['c', 'd'] );
4611
         *  Map::from( ['1', '2'] )->some( [2], true );
4612
         *
4613
         * Results:
4614
         * The first three examples will return TRUE while the fourth and fifth will return FALSE
4615
         *
4616
         * @param \Closure|iterable|mixed $values Closure with (item, key) parameter, element or list of elements to test against
4617
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
4618
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
4619
         */
4620
        public function some( $values, bool $strict = false ) : bool
4621
        {
4622
                $list = $this->list();
18✔
4623

4624
                if( is_iterable( $values ) )
18✔
4625
                {
4626
                        foreach( $values as $entry )
9✔
4627
                        {
4628
                                if( in_array( $entry, $list, $strict ) === true ) {
9✔
4629
                                        return true;
9✔
4630
                                }
4631
                        }
4632

4633
                        return false;
6✔
4634
                }
4635

4636
                if( $values instanceof \Closure )
12✔
4637
                {
4638
                        foreach( $list as $key => $item )
6✔
4639
                        {
4640
                                if( $values( $item, $key ) ) {
6✔
4641
                                        return true;
6✔
4642
                                }
4643
                        }
4644
                }
4645

4646
                return in_array( $values, $list, $strict );
12✔
4647
        }
4648

4649

4650
        /**
4651
         * Sorts all elements in-place using new keys.
4652
         *
4653
         * Examples:
4654
         *  Map::from( ['a' => 1, 'b' => 0] )->sort();
4655
         *  Map::from( [0 => 'b', 1 => 'a'] )->sort();
4656
         *
4657
         * Results:
4658
         *  [0 => 0, 1 => 1]
4659
         *  [0 => 'a', 1 => 'b']
4660
         *
4661
         * The parameter modifies how the values are compared. Possible parameter values are:
4662
         * - SORT_REGULAR : compare elements normally (don't change types)
4663
         * - SORT_NUMERIC : compare elements numerically
4664
         * - SORT_STRING : compare elements as strings
4665
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4666
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4667
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4668
         *
4669
         * The keys aren't preserved and elements get a new index. No new map is created.
4670
         *
4671
         * @param int $options Sort options for PHP sort()
4672
         * @return self<int|string,mixed> Updated map for fluid interface
4673
         * @see sorted() - Sorts elements in a copy of the map
4674
         */
4675
        public function sort( int $options = SORT_REGULAR ) : self
4676
        {
4677
                sort( $this->list(), $options );
15✔
4678
                return $this;
15✔
4679
        }
4680

4681

4682
        /**
4683
         * Sorts the elements in a copy of the map using new keys.
4684
         *
4685
         * Examples:
4686
         *  Map::from( ['a' => 1, 'b' => 0] )->sorted();
4687
         *  Map::from( [0 => 'b', 1 => 'a'] )->sorted();
4688
         *
4689
         * Results:
4690
         *  [0 => 0, 1 => 1]
4691
         *  [0 => 'a', 1 => 'b']
4692
         *
4693
         * The parameter modifies how the values are compared. Possible parameter values are:
4694
         * - SORT_REGULAR : compare elements normally (don't change types)
4695
         * - SORT_NUMERIC : compare elements numerically
4696
         * - SORT_STRING : compare elements as strings
4697
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4698
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4699
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4700
         *
4701
         * The keys aren't preserved and elements get a new index and a new map is created before sorting the elements.
4702
         * Thus, sort() should be preferred for performance reasons if possible. A new map is created by calling this method.
4703
         *
4704
         * @param int $options Sort options for PHP sort()
4705
         * @return self<int|string,mixed> New map with a sorted copy of the elements
4706
         * @see sort() - Sorts elements in-place in the original map
4707
         */
4708
        public function sorted( int $options = SORT_REGULAR ) : self
4709
        {
4710
                return ( clone $this )->sort( $options );
6✔
4711
        }
4712

4713

4714
        /**
4715
         * Removes a portion of the map and replace it with the given replacement, then return the updated map.
4716
         *
4717
         * Examples:
4718
         *  Map::from( ['a', 'b', 'c'] )->splice( 1 );
4719
         *  Map::from( ['a', 'b', 'c'] )->splice( 1, 1, ['x', 'y'] );
4720
         *
4721
         * Results:
4722
         * The first example removes all entries after "a", so only ['a'] will be left
4723
         * in the map and ['b', 'c'] is returned. The second example replaces/returns "b"
4724
         * (start at 1, length 1) with ['x', 'y'] so the new map will contain
4725
         * ['a', 'x', 'y', 'c'] afterwards.
4726
         *
4727
         * The rules for offsets are:
4728
         * - If offset is non-negative, the sequence will start at that offset
4729
         * - If offset is negative, the sequence will start that far from the end
4730
         *
4731
         * Similar for the length:
4732
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4733
         * - If the array is shorter than the length, then only the available array elements will be present
4734
         * - If length is given and is negative then the sequence will stop that many elements from the end
4735
         * - If it is omitted, then the sequence will have everything from offset up until the end
4736
         *
4737
         * Numerical array indexes are NOT preserved.
4738
         *
4739
         * @param int $offset Number of elements to start from
4740
         * @param int|null $length Number of elements to remove, NULL for all
4741
         * @param mixed $replacement List of elements to insert
4742
         * @return self<int|string,mixed> New map
4743
         */
4744
        public function splice( int $offset, ?int $length = null, $replacement = [] ) : self
4745
        {
4746
                // PHP 7.x doesn't allow to pass NULL as replacement
4747
                if( $length === null ) {
15✔
4748
                        $length = count( $this->list() );
6✔
4749
                }
4750

4751
                return new static( array_splice( $this->list(), $offset, $length, (array) $replacement ) );
15✔
4752
        }
4753

4754

4755
        /**
4756
         * Returns the strings after the passed value.
4757
         *
4758
         * Examples:
4759
         *  Map::from( ['äöüß'] )->strAfter( 'ö' );
4760
         *  Map::from( ['abc'] )->strAfter( '' );
4761
         *  Map::from( ['abc'] )->strAfter( 'b' );
4762
         *  Map::from( ['abc'] )->strAfter( 'c' );
4763
         *  Map::from( ['abc'] )->strAfter( 'x' );
4764
         *  Map::from( [''] )->strAfter( '' );
4765
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4766
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4767
         *
4768
         * Results:
4769
         *  ['üß']
4770
         *  ['abc']
4771
         *  ['c']
4772
         *  ['']
4773
         *  []
4774
         *  []
4775
         *  ['1', '1', '1']
4776
         *  ['0', '0']
4777
         *
4778
         * All scalar values (bool, int, float, string) will be converted to strings.
4779
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4780
         *
4781
         * @param string $value Character or string to search for
4782
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4783
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4784
         * @return self<int|string,mixed> New map
4785
         */
4786
        public function strAfter( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4787
        {
4788
                $list = [];
3✔
4789
                $len = mb_strlen( $value );
3✔
4790
                $fcn = $case ? 'mb_stripos' : 'mb_strpos';
3✔
4791

4792
                foreach( $this->list() as $key => $entry )
3✔
4793
                {
4794
                        if( is_scalar( $entry ) )
3✔
4795
                        {
4796
                                $pos = null;
3✔
4797
                                $str = (string) $entry;
3✔
4798

4799
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
3✔
4800
                                        $list[$key] = mb_substr( $str, $pos + $len, null, $encoding );
3✔
4801
                                } elseif( $str !== '' && $pos !== false ) {
3✔
4802
                                        $list[$key] = $str;
3✔
4803
                                }
4804
                        }
4805
                }
4806

4807
                return new static( $list );
3✔
4808
        }
4809

4810

4811
        /**
4812
         * Returns the strings before the passed value.
4813
         *
4814
         * Examples:
4815
         *  Map::from( ['äöüß'] )->strBefore( 'ü' );
4816
         *  Map::from( ['abc'] )->strBefore( '' );
4817
         *  Map::from( ['abc'] )->strBefore( 'b' );
4818
         *  Map::from( ['abc'] )->strBefore( 'a' );
4819
         *  Map::from( ['abc'] )->strBefore( 'x' );
4820
         *  Map::from( [''] )->strBefore( '' );
4821
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4822
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4823
         *
4824
         * Results:
4825
         *  ['äö']
4826
         *  ['abc']
4827
         *  ['a']
4828
         *  ['']
4829
         *  []
4830
         *  []
4831
         *  ['1', '1', '1']
4832
         *  ['0', '0']
4833
         *
4834
         * All scalar values (bool, int, float, string) will be converted to strings.
4835
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4836
         *
4837
         * @param string $value Character or string to search for
4838
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4839
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4840
         * @return self<int|string,mixed> New map
4841
         */
4842
        public function strBefore( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4843
        {
4844
                $list = [];
3✔
4845
                $fcn = $case ? 'mb_strripos' : 'mb_strrpos';
3✔
4846

4847
                foreach( $this->list() as $key => $entry )
3✔
4848
                {
4849
                        if( is_scalar( $entry ) )
3✔
4850
                        {
4851
                                $pos = null;
3✔
4852
                                $str = (string) $entry;
3✔
4853

4854
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
3✔
4855
                                        $list[$key] = mb_substr( $str, 0, $pos, $encoding );
3✔
4856
                                } elseif( $str !== '' && $pos !== false ) {
3✔
4857
                                        $list[$key] = $str;
3✔
4858
                                }
4859
                        }
4860
                }
4861

4862
                return new static( $list );
3✔
4863
        }
4864

4865

4866
        /**
4867
         * Compares the value against all map elements.
4868
         *
4869
         * Examples:
4870
         *  Map::from( ['foo', 'bar'] )->compare( 'foo' );
4871
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo', false );
4872
         *  Map::from( [123, 12.3] )->compare( '12.3' );
4873
         *  Map::from( [false, true] )->compare( '1' );
4874
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo' );
4875
         *  Map::from( ['foo', 'bar'] )->compare( 'baz' );
4876
         *  Map::from( [new \stdClass(), 'bar'] )->compare( 'foo' );
4877
         *
4878
         * Results:
4879
         * The first four examples return TRUE, the last three examples will return FALSE.
4880
         *
4881
         * All scalar values (bool, float, int and string) are casted to string values before
4882
         * comparing to the given value. Non-scalar values in the map are ignored.
4883
         *
4884
         * @param string $value Value to compare map elements to
4885
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
4886
         * @return bool TRUE If at least one element matches, FALSE if value is not in map
4887
         */
4888
        public function strCompare( string $value, bool $case = true ) : bool
4889
        {
4890
                $fcn = $case ? 'strcmp' : 'strcasecmp';
6✔
4891

4892
                foreach( $this->list() as $item )
6✔
4893
                {
4894
                        if( is_scalar( $item ) && !$fcn( (string) $item, $value ) ) {
6✔
4895
                                return true;
6✔
4896
                        }
4897
                }
4898

4899
                return false;
6✔
4900
        }
4901

4902

4903
        /**
4904
         * Tests if at least one of the passed strings is part of at least one entry.
4905
         *
4906
         * Examples:
4907
         *  Map::from( ['abc'] )->strContains( '' );
4908
         *  Map::from( ['abc'] )->strContains( 'a' );
4909
         *  Map::from( ['abc'] )->strContains( 'bc' );
4910
         *  Map::from( [12345] )->strContains( '23' );
4911
         *  Map::from( [123.4] )->strContains( 23.4 );
4912
         *  Map::from( [12345] )->strContains( false );
4913
         *  Map::from( [12345] )->strContains( true );
4914
         *  Map::from( [false] )->strContains( false );
4915
         *  Map::from( [''] )->strContains( false );
4916
         *  Map::from( ['abc'] )->strContains( ['b', 'd'] );
4917
         *  Map::from( ['abc'] )->strContains( 'c', 'ASCII' );
4918
         *
4919
         *  Map::from( ['abc'] )->strContains( 'd' );
4920
         *  Map::from( ['abc'] )->strContains( 'cb' );
4921
         *  Map::from( [23456] )->strContains( true );
4922
         *  Map::from( [false] )->strContains( 0 );
4923
         *  Map::from( ['abc'] )->strContains( ['d', 'e'] );
4924
         *  Map::from( ['abc'] )->strContains( 'cb', 'ASCII' );
4925
         *
4926
         * Results:
4927
         * The first eleven examples will return TRUE while the last six will return FALSE.
4928
         *
4929
         * @param array|string $value The string or list of strings to search for in each entry
4930
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4931
         * @return bool TRUE if one of the entries contains one of the strings, FALSE if not
4932
         * @todo 4.0 Add $case parameter at second position
4933
         */
4934
        public function strContains( $value, string $encoding = 'UTF-8' ) : bool
4935
        {
4936
                foreach( $this->list() as $entry )
3✔
4937
                {
4938
                        $entry = (string) $entry;
3✔
4939

4940
                        foreach( (array) $value as $str )
3✔
4941
                        {
4942
                                $str = (string) $str;
3✔
4943

4944
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
3✔
4945
                                        return true;
3✔
4946
                                }
4947
                        }
4948
                }
4949

4950
                return false;
3✔
4951
        }
4952

4953

4954
        /**
4955
         * Tests if all of the entries contains one of the passed strings.
4956
         *
4957
         * Examples:
4958
         *  Map::from( ['abc', 'def'] )->strContainsAll( '' );
4959
         *  Map::from( ['abc', 'cba'] )->strContainsAll( 'a' );
4960
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'bc' );
4961
         *  Map::from( [12345, '230'] )->strContainsAll( '23' );
4962
         *  Map::from( [123.4, 23.42] )->strContainsAll( 23.4 );
4963
         *  Map::from( [12345, '234'] )->strContainsAll( [true, false] );
4964
         *  Map::from( ['', false] )->strContainsAll( false );
4965
         *  Map::from( ['abc', 'def'] )->strContainsAll( ['b', 'd'] );
4966
         *  Map::from( ['abc', 'ecf'] )->strContainsAll( 'c', 'ASCII' );
4967
         *
4968
         *  Map::from( ['abc', 'def'] )->strContainsAll( 'd' );
4969
         *  Map::from( ['abc', 'cab'] )->strContainsAll( 'cb' );
4970
         *  Map::from( [23456, '123'] )->strContainsAll( true );
4971
         *  Map::from( [false, '000'] )->strContainsAll( 0 );
4972
         *  Map::from( ['abc', 'acf'] )->strContainsAll( ['d', 'e'] );
4973
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'cb', 'ASCII' );
4974
         *
4975
         * Results:
4976
         * The first nine examples will return TRUE while the last six will return FALSE.
4977
         *
4978
         * @param array|string $value The string or list of strings to search for in each entry
4979
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4980
         * @return bool TRUE if all of the entries contains at least one of the strings, FALSE if not
4981
         * @todo 4.0 Add $case parameter at second position
4982
         */
4983
        public function strContainsAll( $value, string $encoding = 'UTF-8' ) : bool
4984
        {
4985
                $list = [];
3✔
4986

4987
                foreach( $this->list() as $entry )
3✔
4988
                {
4989
                        $entry = (string) $entry;
3✔
4990
                        $list[$entry] = 0;
3✔
4991

4992
                        foreach( (array) $value as $str )
3✔
4993
                        {
4994
                                $str = (string) $str;
3✔
4995

4996
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
3✔
4997
                                        $list[$entry] = 1; break;
3✔
4998
                                }
4999
                        }
5000
                }
5001

5002
                return array_sum( $list ) === count( $list );
3✔
5003
        }
5004

5005

5006
        /**
5007
         * Tests if at least one of the entries ends with one of the passed strings.
5008
         *
5009
         * Examples:
5010
         *  Map::from( ['abc'] )->strEnds( '' );
5011
         *  Map::from( ['abc'] )->strEnds( 'c' );
5012
         *  Map::from( ['abc'] )->strEnds( 'bc' );
5013
         *  Map::from( ['abc'] )->strEnds( ['b', 'c'] );
5014
         *  Map::from( ['abc'] )->strEnds( 'c', 'ASCII' );
5015
         *  Map::from( ['abc'] )->strEnds( 'a' );
5016
         *  Map::from( ['abc'] )->strEnds( 'cb' );
5017
         *  Map::from( ['abc'] )->strEnds( ['d', 'b'] );
5018
         *  Map::from( ['abc'] )->strEnds( 'cb', 'ASCII' );
5019
         *
5020
         * Results:
5021
         * The first five examples will return TRUE while the last four will return FALSE.
5022
         *
5023
         * @param array|string $value The string or strings to search for in each entry
5024
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5025
         * @return bool TRUE if one of the entries ends with one of the strings, FALSE if not
5026
         * @todo 4.0 Add $case parameter at second position
5027
         */
5028
        public function strEnds( $value, string $encoding = 'UTF-8' ) : bool
5029
        {
5030
                foreach( $this->list() as $entry )
3✔
5031
                {
5032
                        $entry = (string) $entry;
3✔
5033

5034
                        foreach( (array) $value as $str )
3✔
5035
                        {
5036
                                $len = mb_strlen( (string) $str );
3✔
5037

5038
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
3✔
5039
                                        return true;
3✔
5040
                                }
5041
                        }
5042
                }
5043

5044
                return false;
3✔
5045
        }
5046

5047

5048
        /**
5049
         * Tests if all of the entries ends with at least one of the passed strings.
5050
         *
5051
         * Examples:
5052
         *  Map::from( ['abc', 'def'] )->strEndsAll( '' );
5053
         *  Map::from( ['abc', 'bac'] )->strEndsAll( 'c' );
5054
         *  Map::from( ['abc', 'cbc'] )->strEndsAll( 'bc' );
5055
         *  Map::from( ['abc', 'def'] )->strEndsAll( ['c', 'f'] );
5056
         *  Map::from( ['abc', 'efc'] )->strEndsAll( 'c', 'ASCII' );
5057
         *  Map::from( ['abc', 'fed'] )->strEndsAll( 'd' );
5058
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca' );
5059
         *  Map::from( ['abc', 'acf'] )->strEndsAll( ['a', 'c'] );
5060
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca', 'ASCII' );
5061
         *
5062
         * Results:
5063
         * The first five examples will return TRUE while the last four will return FALSE.
5064
         *
5065
         * @param array|string $value The string or strings to search for in each entry
5066
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5067
         * @return bool TRUE if all of the entries ends with at least one of the strings, FALSE if not
5068
         * @todo 4.0 Add $case parameter at second position
5069
         */
5070
        public function strEndsAll( $value, string $encoding = 'UTF-8' ) : bool
5071
        {
5072
                $list = [];
3✔
5073

5074
                foreach( $this->list() as $entry )
3✔
5075
                {
5076
                        $entry = (string) $entry;
3✔
5077
                        $list[$entry] = 0;
3✔
5078

5079
                        foreach( (array) $value as $str )
3✔
5080
                        {
5081
                                $len = mb_strlen( (string) $str );
3✔
5082

5083
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
3✔
5084
                                        $list[$entry] = 1; break;
3✔
5085
                                }
5086
                        }
5087
                }
5088

5089
                return array_sum( $list ) === count( $list );
3✔
5090
        }
5091

5092

5093
        /**
5094
         * Returns an element by key and casts it to string if possible.
5095
         *
5096
         * Examples:
5097
         *  Map::from( ['a' => true] )->string( 'a' );
5098
         *  Map::from( ['a' => 1] )->string( 'a' );
5099
         *  Map::from( ['a' => 1.1] )->string( 'a' );
5100
         *  Map::from( ['a' => 'abc'] )->string( 'a' );
5101
         *  Map::from( ['a' => ['b' => ['c' => 'yes']]] )->string( 'a/b/c' );
5102
         *  Map::from( [] )->string( 'a', function() { return 'no'; } );
5103
         *
5104
         *  Map::from( [] )->string( 'b' );
5105
         *  Map::from( ['b' => ''] )->string( 'b' );
5106
         *  Map::from( ['b' => null] )->string( 'b' );
5107
         *  Map::from( ['b' => [true]] )->string( 'b' );
5108
         *  Map::from( ['b' => resource] )->string( 'b' );
5109
         *  Map::from( ['b' => new \stdClass] )->string( 'b' );
5110
         *
5111
         *  Map::from( [] )->string( 'c', new \Exception( 'error' ) );
5112
         *
5113
         * Results:
5114
         * The first six examples will return the value as string while the 9th to 12th
5115
         * example returns an empty string. The last example will throw an exception.
5116
         *
5117
         * This does also work for multi-dimensional arrays by passing the keys
5118
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5119
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5120
         * public properties of objects or objects implementing __isset() and __get() methods.
5121
         *
5122
         * @param int|string $key Key or path to the requested item
5123
         * @param mixed $default Default value if key isn't found (will be casted to bool)
5124
         * @return string Value from map or default value
5125
         */
5126
        public function string( $key, $default = '' ) : string
5127
        {
5128
                return (string) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
9✔
5129
        }
5130

5131

5132
        /**
5133
         * Converts all alphabetic characters in strings to lower case.
5134
         *
5135
         * Examples:
5136
         *  Map::from( ['My String'] )->strLower();
5137
         *  Map::from( ['Τάχιστη'] )->strLower();
5138
         *  Map::from( ['Äpfel', 'Birnen'] )->strLower( 'ISO-8859-1' );
5139
         *  Map::from( [123] )->strLower();
5140
         *  Map::from( [new stdClass] )->strLower();
5141
         *
5142
         * Results:
5143
         * The first example will return ["my string"], the second one ["τάχιστη"] and
5144
         * the third one ["äpfel", "birnen"]. The last two strings will be unchanged.
5145
         *
5146
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5147
         * @return self<int|string,mixed> Updated map for fluid interface
5148
         */
5149
        public function strLower( string $encoding = 'UTF-8' ) : self
5150
        {
5151
                foreach( $this->list() as &$entry )
3✔
5152
                {
5153
                        if( is_string( $entry ) ) {
3✔
5154
                                $entry = mb_strtolower( $entry, $encoding );
3✔
5155
                        }
5156
                }
5157

5158
                return $this;
3✔
5159
        }
5160

5161

5162
        /**
5163
         * Replaces all occurrences of the search string with the replacement string.
5164
         *
5165
         * Examples:
5166
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( '.com', '.de' );
5167
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], '.de' );
5168
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.de'] );
5169
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.fr', '.de'] );
5170
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( ['.com', '.co'], ['.co', '.de', '.fr'] );
5171
         * Map::from( ['google.com', 'aimeos.com', 123] )->strReplace( '.com', '.de' );
5172
         * Map::from( ['GOOGLE.COM', 'AIMEOS.COM'] )->strReplace( '.com', '.de', true );
5173
         *
5174
         * Restults:
5175
         * ['google.de', 'aimeos.de']
5176
         * ['google.de', 'aimeos.de']
5177
         * ['google.de', 'aimeos']
5178
         * ['google.fr', 'aimeos.de']
5179
         * ['google.de', 'aimeos.de']
5180
         * ['google.de', 'aimeos.de', 123]
5181
         * ['GOOGLE.de', 'AIMEOS.de']
5182
         *
5183
         * If you use an array of strings for search or search/replacement, the order of
5184
         * the strings matters! Each search string found is replaced by the corresponding
5185
         * replacement string at the same position.
5186
         *
5187
         * In case of array parameters and if the number of replacement strings is less
5188
         * than the number of search strings, the search strings with no corresponding
5189
         * replacement string are replaced with empty strings. Replacement strings with
5190
         * no corresponding search string are ignored.
5191
         *
5192
         * An array parameter for the replacements is only allowed if the search parameter
5193
         * is an array of strings too!
5194
         *
5195
         * Because the method replaces from left to right, it might replace a previously
5196
         * inserted value when doing multiple replacements. Entries which are non-string
5197
         * values are left untouched.
5198
         *
5199
         * @param array|string $search String or list of strings to search for
5200
         * @param array|string $replace String or list of strings of replacement strings
5201
         * @param bool $case TRUE if replacements should be case insensitive, FALSE if case-sensitive
5202
         * @return self<int|string,mixed> Updated map for fluid interface
5203
         */
5204
        public function strReplace( $search, $replace, bool $case = false ) : self
5205
        {
5206
                $fcn = $case ? 'str_ireplace' : 'str_replace';
3✔
5207

5208
                foreach( $this->list() as &$entry )
3✔
5209
                {
5210
                        if( is_string( $entry ) ) {
3✔
5211
                                $entry = $fcn( $search, $replace, $entry );
3✔
5212
                        }
5213
                }
5214

5215
                return $this;
3✔
5216
        }
5217

5218

5219
        /**
5220
         * Tests if at least one of the entries starts with at least one of the passed strings.
5221
         *
5222
         * Examples:
5223
         *  Map::from( ['abc'] )->strStarts( '' );
5224
         *  Map::from( ['abc'] )->strStarts( 'a' );
5225
         *  Map::from( ['abc'] )->strStarts( 'ab' );
5226
         *  Map::from( ['abc'] )->strStarts( ['a', 'b'] );
5227
         *  Map::from( ['abc'] )->strStarts( 'ab', 'ASCII' );
5228
         *  Map::from( ['abc'] )->strStarts( 'b' );
5229
         *  Map::from( ['abc'] )->strStarts( 'bc' );
5230
         *  Map::from( ['abc'] )->strStarts( ['b', 'c'] );
5231
         *  Map::from( ['abc'] )->strStarts( 'bc', 'ASCII' );
5232
         *
5233
         * Results:
5234
         * The first five examples will return TRUE while the last four will return FALSE.
5235
         *
5236
         * @param array|string $value The string or strings to search for in each entry
5237
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5238
         * @return bool TRUE if all of the entries ends with at least one of the strings, FALSE if not
5239
         * @todo 4.0 Add $case parameter at second position
5240
         */
5241
        public function strStarts( $value, string $encoding = 'UTF-8' ) : bool
5242
        {
5243
                foreach( $this->list() as $entry )
3✔
5244
                {
5245
                        $entry = (string) $entry;
3✔
5246

5247
                        foreach( (array) $value as $str )
3✔
5248
                        {
5249
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
3✔
5250
                                        return true;
3✔
5251
                                }
5252
                        }
5253
                }
5254

5255
                return false;
3✔
5256
        }
5257

5258

5259
        /**
5260
         * Tests if all of the entries starts with one of the passed strings.
5261
         *
5262
         * Examples:
5263
         *  Map::from( ['abc', 'def'] )->strStartsAll( '' );
5264
         *  Map::from( ['abc', 'acb'] )->strStartsAll( 'a' );
5265
         *  Map::from( ['abc', 'aba'] )->strStartsAll( 'ab' );
5266
         *  Map::from( ['abc', 'def'] )->strStartsAll( ['a', 'd'] );
5267
         *  Map::from( ['abc', 'acf'] )->strStartsAll( 'a', 'ASCII' );
5268
         *  Map::from( ['abc', 'def'] )->strStartsAll( 'd' );
5269
         *  Map::from( ['abc', 'bca'] )->strStartsAll( 'ab' );
5270
         *  Map::from( ['abc', 'bac'] )->strStartsAll( ['a', 'c'] );
5271
         *  Map::from( ['abc', 'cab'] )->strStartsAll( 'ab', 'ASCII' );
5272
         *
5273
         * Results:
5274
         * The first five examples will return TRUE while the last four will return FALSE.
5275
         *
5276
         * @param array|string $value The string or strings to search for in each entry
5277
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5278
         * @return bool TRUE if one of the entries starts with one of the strings, FALSE if not
5279
         * @todo 4.0 Add $case parameter at second position
5280
         */
5281
        public function strStartsAll( $value, string $encoding = 'UTF-8' ) : bool
5282
        {
5283
                $list = [];
3✔
5284

5285
                foreach( $this->list() as $entry )
3✔
5286
                {
5287
                        $entry = (string) $entry;
3✔
5288
                        $list[$entry] = 0;
3✔
5289

5290
                        foreach( (array) $value as $str )
3✔
5291
                        {
5292
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
3✔
5293
                                        $list[$entry] = 1; break;
3✔
5294
                                }
5295
                        }
5296
                }
5297

5298
                return array_sum( $list ) === count( $list );
3✔
5299
        }
5300

5301

5302
        /**
5303
         * Converts all alphabetic characters in strings to upper case.
5304
         *
5305
         * Examples:
5306
         *  Map::from( ['My String'] )->strUpper();
5307
         *  Map::from( ['τάχιστη'] )->strUpper();
5308
         *  Map::from( ['äpfel', 'birnen'] )->strUpper( 'ISO-8859-1' );
5309
         *  Map::from( [123] )->strUpper();
5310
         *  Map::from( [new stdClass] )->strUpper();
5311
         *
5312
         * Results:
5313
         * The first example will return ["MY STRING"], the second one ["ΤΆΧΙΣΤΗ"] and
5314
         * the third one ["ÄPFEL", "BIRNEN"]. The last two strings will be unchanged.
5315
         *
5316
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5317
         * @return self<int|string,mixed> Updated map for fluid interface
5318
         */
5319
        public function strUpper( string $encoding = 'UTF-8' ) :self
5320
        {
5321
                foreach( $this->list() as &$entry )
3✔
5322
                {
5323
                        if( is_string( $entry ) ) {
3✔
5324
                                $entry = mb_strtoupper( $entry, $encoding );
3✔
5325
                        }
5326
                }
5327

5328
                return $this;
3✔
5329
        }
5330

5331

5332
        /**
5333
         * Adds a suffix at the end of each map entry.
5334
         *
5335
         * By defaul, nested arrays are walked recusively so all entries at all levels are suffixed.
5336
         *
5337
         * Examples:
5338
         *  Map::from( ['a', 'b'] )->suffix( '-1' );
5339
         *  Map::from( ['a', ['b']] )->suffix( '-1' );
5340
         *  Map::from( ['a', ['b']] )->suffix( '-1', 1 );
5341
         *  Map::from( ['a', 'b'] )->suffix( function( $item, $key ) {
5342
         *      return '-' . ( ord( $item ) + ord( $key ) );
5343
         *  } );
5344
         *
5345
         * Results:
5346
         *  The first example returns ['a-1', 'b-1'] while the second one will return
5347
         *  ['a-1', ['b-1']]. In the third example, the depth is limited to the first
5348
         *  level only so it will return ['a-1', ['b']]. The forth example passing
5349
         *  the closure will return ['a-145', 'b-147'].
5350
         *
5351
         * The keys are preserved using this method.
5352
         *
5353
         * @param \Closure|string $suffix Suffix string or anonymous function with ($item, $key) as parameters
5354
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
5355
         * @return self<int|string,mixed> Updated map for fluid interface
5356
         */
5357
        public function suffix( $suffix, ?int $depth = null ) : self
5358
        {
5359
                $fcn = function( $list, $suffix, $depth ) use ( &$fcn ) {
3✔
5360

5361
                        foreach( $list as $key => $item )
3✔
5362
                        {
5363
                                if( is_array( $item ) ) {
3✔
5364
                                        $list[$key] = $depth > 1 ? $fcn( $item, $suffix, $depth - 1 ) : $item;
3✔
5365
                                } else {
5366
                                        $list[$key] = $item . ( is_callable( $suffix ) ? $suffix( $item, $key ) : $suffix );
3✔
5367
                                }
5368
                        }
5369

5370
                        return $list;
3✔
5371
                };
3✔
5372

5373
                $this->list = $fcn( $this->list(), $suffix, $depth ?? 0x7fffffff );
3✔
5374
                return $this;
3✔
5375
        }
5376

5377

5378
        /**
5379
         * Returns the sum of all integer and float values in the map.
5380
         *
5381
         * Examples:
5382
         *  Map::from( [1, 3, 5] )->sum();
5383
         *  Map::from( [1, 'sum', 5] )->sum();
5384
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->sum( 'p' );
5385
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( 'i/p' );
5386
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( fn( $val, $key ) => $val['i']['p'] ?? null )
5387
         *  Map::from( [30, 50, 10] )->sum( fn( $val, $key ) => $val < 50 ? $val : null )
5388
         *
5389
         * Results:
5390
         * The first line will return "9", the second one "6", the third one "90"
5391
         * the forth/fifth "80" and the last one "40".
5392
         *
5393
         * Non-numeric values will be removed before calculation.
5394
         *
5395
         * NULL values are treated as 0, non-numeric values will generate an error.
5396
         *
5397
         * This does also work for multi-dimensional arrays by passing the keys
5398
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5399
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5400
         * public properties of objects or objects implementing __isset() and __get() methods.
5401
         *
5402
         * @param Closure|string|null $col Closure, key or path to the values in the nested array or object to sum up
5403
         * @return float Sum of all elements or 0 if there are no elements in the map
5404
         */
5405
        public function sum( $col = null ) : float
5406
        {
5407
                $list = $this->list();
9✔
5408
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list, 'is_numeric' );
9✔
5409

5410
                return array_sum( $vals );
9✔
5411
        }
5412

5413

5414
        /**
5415
         * Returns a new map with the given number of items.
5416
         *
5417
         * The keys of the items returned in the new map are the same as in the original one.
5418
         *
5419
         * Examples:
5420
         *  Map::from( [1, 2, 3, 4] )->take( 2 );
5421
         *  Map::from( [1, 2, 3, 4] )->take( 2, 1 );
5422
         *  Map::from( [1, 2, 3, 4] )->take( 2, -2 );
5423
         *  Map::from( [1, 2, 3, 4] )->take( 2, function( $item, $key ) {
5424
         *      return $item < 2;
5425
         *  } );
5426
         *
5427
         * Results:
5428
         *  [0 => 1, 1 => 2]
5429
         *  [1 => 2, 2 => 3]
5430
         *  [2 => 3, 3 => 4]
5431
         *  [1 => 2, 2 => 3]
5432
         *
5433
         * The keys of the items returned in the new map are the same as in the original one.
5434
         *
5435
         * @param int $size Number of items to return
5436
         * @param \Closure|int $offset Number of items to skip or function($item, $key) returning true for skipped items
5437
         * @return self<int|string,mixed> New map
5438
         */
5439
        public function take( int $size, $offset = 0 ) : self
5440
        {
5441
                $list = $this->list();
15✔
5442

5443
                if( is_numeric( $offset ) ) {
15✔
5444
                        return new static( array_slice( $list, (int) $offset, $size, true ) );
9✔
5445
                }
5446

5447
                if( $offset instanceof \Closure ) {
6✔
5448
                        return new static( array_slice( $list, $this->until( $list, $offset ), $size, true ) );
3✔
5449
                }
5450

5451
                throw new \InvalidArgumentException( 'Only an integer or a closure is allowed as second argument for take()' );
3✔
5452
        }
5453

5454

5455
        /**
5456
         * Passes a clone of the map to the given callback.
5457
         *
5458
         * Use it to "tap" into a chain of methods to check the state between two
5459
         * method calls. The original map is not altered by anything done in the
5460
         * callback.
5461
         *
5462
         * Examples:
5463
         *  Map::from( [3, 2, 1] )->rsort()->tap( function( $map ) {
5464
         *    print_r( $map->remove( 0 )->toArray() );
5465
         *  } )->first();
5466
         *
5467
         * Results:
5468
         * It will sort the list in reverse order (`[1, 2, 3]`) while keeping the keys,
5469
         * then prints the items without the first (`[2, 3]`) in the function passed
5470
         * to `tap()` and returns the first item ("1") at the end.
5471
         *
5472
         * @param callable $callback Function receiving ($map) parameter
5473
         * @return self<int|string,mixed> Same map for fluid interface
5474
         */
5475
        public function tap( callable $callback ) : self
5476
        {
5477
                $callback( clone $this );
3✔
5478
                return $this;
3✔
5479
        }
5480

5481

5482
        /**
5483
         * Returns the elements as a plain array.
5484
         *
5485
         * @return array<int|string,mixed> Plain array
5486
         */
5487
        public function to() : array
5488
        {
5489
                return $this->list = $this->array( $this->list );
3✔
5490
        }
5491

5492

5493
        /**
5494
         * Returns the elements as a plain array.
5495
         *
5496
         * @return array<int|string,mixed> Plain array
5497
         */
5498
        public function toArray() : array
5499
        {
5500
                return $this->list = $this->array( $this->list );
744✔
5501
        }
5502

5503

5504
        /**
5505
         * Returns the elements encoded as JSON string.
5506
         *
5507
         * There are several options available to modify the JSON output:
5508
         * {@link https://www.php.net/manual/en/function.json-encode.php}
5509
         * The parameter can be a single JSON_* constant or a bitmask of several
5510
         * constants combine by bitwise OR (|), e.g.:
5511
         *
5512
         *  JSON_FORCE_OBJECT|JSON_HEX_QUOT
5513
         *
5514
         * @param int $options Combination of JSON_* constants
5515
         * @return string|null Array encoded as JSON string or NULL on failure
5516
         */
5517
        public function toJson( int $options = 0 ) : ?string
5518
        {
5519
                $result = json_encode( $this->list(), $options );
6✔
5520
                return $result !== false ? $result : null;
6✔
5521
        }
5522

5523

5524
        /**
5525
         * Reverses the element order in a copy of the map (alias).
5526
         *
5527
         * This method is an alias for reversed(). For performance reasons, reversed() should be
5528
         * preferred because it uses one method call less than toReversed().
5529
         *
5530
         * @return self<int|string,mixed> New map with a reversed copy of the elements
5531
         * @see reversed() - Underlying method with same parameters and return value but better performance
5532
         */
5533
        public function toReversed() : self
5534
        {
5535
                return $this->reversed();
3✔
5536
        }
5537

5538

5539
        /**
5540
         * Sorts the elements in a copy of the map using new keys (alias).
5541
         *
5542
         * This method is an alias for sorted(). For performance reasons, sorted() should be
5543
         * preferred because it uses one method call less than toSorted().
5544
         *
5545
         * @param int $options Sort options for PHP sort()
5546
         * @return self<int|string,mixed> New map with a sorted copy of the elements
5547
         * @see sorted() - Underlying method with same parameters and return value but better performance
5548
         */
5549
        public function toSorted( int $options = SORT_REGULAR ) : self
5550
        {
5551
                return $this->sorted( $options );
3✔
5552
        }
5553

5554

5555
        /**
5556
         * Creates a HTTP query string from the map elements.
5557
         *
5558
         * Examples:
5559
         *  Map::from( ['a' => 1, 'b' => 2] )->toUrl();
5560
         *  Map::from( ['a' => ['b' => 'abc', 'c' => 'def'], 'd' => 123] )->toUrl();
5561
         *
5562
         * Results:
5563
         *  a=1&b=2
5564
         *  a%5Bb%5D=abc&a%5Bc%5D=def&d=123
5565
         *
5566
         * @return string Parameter string for GET requests
5567
         */
5568
        public function toUrl() : string
5569
        {
5570
                return http_build_query( $this->list(), '', '&', PHP_QUERY_RFC3986 );
6✔
5571
        }
5572

5573

5574
        /**
5575
         * Creates new key/value pairs using the passed function and returns a new map for the result.
5576
         *
5577
         * Examples:
5578
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5579
         *      return [$key . '-2' => $value * 2];
5580
         *  } );
5581
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5582
         *      return [$key => $value * 2, $key . $key => $value * 4];
5583
         *  } );
5584
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5585
         *      return $key < 'b' ? [$key => $value * 2] : null;
5586
         *  } );
5587
         *  Map::from( ['la' => 2, 'le' => 4, 'li' => 6] )->transform( function( $value, $key ) {
5588
         *      return [$key[0] => $value * 2];
5589
         *  } );
5590
         *
5591
         * Results:
5592
         *  ['a-2' => 4, 'b-2' => 8]
5593
         *  ['a' => 4, 'aa' => 8, 'b' => 8, 'bb' => 16]
5594
         *  ['a' => 4]
5595
         *  ['l' => 12]
5596
         *
5597
         * If a key is returned twice, the last value will overwrite previous values.
5598
         *
5599
         * @param \Closure $callback Function with (value, key) parameters and returns an array of new key/value pair(s)
5600
         * @return self<int|string,mixed> New map with the new key/value pairs
5601
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
5602
         * @see rekey() - Changes the keys according to the passed function
5603
         */
5604
        public function transform( \Closure $callback ) : self
5605
        {
5606
                $result = [];
12✔
5607

5608
                foreach( $this->list() as $key => $value )
12✔
5609
                {
5610
                        foreach( (array) $callback( $value, $key ) as $newkey => $newval ) {
12✔
5611
                                $result[$newkey] = $newval;
12✔
5612
                        }
5613
                }
5614

5615
                return new static( $result );
12✔
5616
        }
5617

5618

5619
        /**
5620
         * Exchanges rows and columns for a two dimensional map.
5621
         *
5622
         * Examples:
5623
         *  Map::from( [
5624
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
5625
         *    ['name' => 'B', 2020 => 300, 2021 => 200, 2022 => 100],
5626
         *    ['name' => 'C', 2020 => 400, 2021 => 300, 2022 => 200],
5627
         *  ] )->transpose();
5628
         *
5629
         *  Map::from( [
5630
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
5631
         *    ['name' => 'B', 2020 => 300, 2021 => 200],
5632
         *    ['name' => 'C', 2020 => 400]
5633
         *  ] );
5634
         *
5635
         * Results:
5636
         *  [
5637
         *    'name' => ['A', 'B', 'C'],
5638
         *    2020 => [200, 300, 400],
5639
         *    2021 => [100, 200, 300],
5640
         *    2022 => [50, 100, 200]
5641
         *  ]
5642
         *
5643
         *  [
5644
         *    'name' => ['A', 'B', 'C'],
5645
         *    2020 => [200, 300, 400],
5646
         *    2021 => [100, 200],
5647
         *    2022 => [50]
5648
         *  ]
5649
         *
5650
         * @return self<int|string,mixed> New map
5651
         */
5652
        public function transpose() : self
5653
        {
5654
                $result = [];
6✔
5655

5656
                foreach( (array) $this->first( [] ) as $key => $col ) {
6✔
5657
                        $result[$key] = array_column( $this->list(), $key );
6✔
5658
                }
5659

5660
                return new static( $result );
6✔
5661
        }
5662

5663

5664
        /**
5665
         * Traverses trees of nested items passing each item to the callback.
5666
         *
5667
         * This does work for nested arrays and objects with public properties or
5668
         * objects implementing __isset() and __get() methods. To build trees
5669
         * of nested items, use the tree() method.
5670
         *
5671
         * Examples:
5672
         *   Map::from( [[
5673
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5674
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5675
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5676
         *     ]
5677
         *   ]] )->traverse();
5678
         *
5679
         *   Map::from( [[
5680
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5681
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5682
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5683
         *     ]
5684
         *   ]] )->traverse( function( $entry, $key, $level, $parent ) {
5685
         *     return str_repeat( '-', $level ) . '- ' . $entry['name'];
5686
         *   } );
5687
         *
5688
         *   Map::from( [[
5689
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5690
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5691
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5692
         *     ]
5693
         *   ]] )->traverse( function( &$entry, $key, $level, $parent ) {
5694
         *     $entry['path'] = isset( $parent['path'] ) ? $parent['path'] . '/' . $entry['name'] : $entry['name'];
5695
         *     return $entry;
5696
         *   } );
5697
         *
5698
         *   Map::from( [[
5699
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [
5700
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []]
5701
         *     ]
5702
         *   ]] )->traverse( null, 'nodes' );
5703
         *
5704
         * Results:
5705
         *   [
5706
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...]],
5707
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5708
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []],
5709
         *   ]
5710
         *
5711
         *   ['- n1', '-- n2', '-- n3']
5712
         *
5713
         *   [
5714
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...], 'path' => 'n1'],
5715
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => [], 'path' => 'n1/n2'],
5716
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => [], 'path' => 'n1/n3'],
5717
         *   ]
5718
         *
5719
         *   [
5720
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [...]],
5721
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []],
5722
         *   ]
5723
         *
5724
         * @param \Closure|null $callback Callback with (entry, key, level, $parent) arguments, returns the entry added to result
5725
         * @param string $nestKey Key to the children of each item
5726
         * @return self<int|string,mixed> New map with all items as flat list
5727
         */
5728
        public function traverse( ?\Closure $callback = null, string $nestKey = 'children' ) : self
5729
        {
5730
                $result = [];
15✔
5731
                $this->visit( $this->list(), $result, 0, $callback, $nestKey );
15✔
5732

5733
                return map( $result );
15✔
5734
        }
5735

5736

5737
        /**
5738
         * Creates a tree structure from the list items.
5739
         *
5740
         * Use this method to rebuild trees e.g. from database records. To traverse
5741
         * trees, use the traverse() method.
5742
         *
5743
         * Examples:
5744
         *  Map::from( [
5745
         *    ['id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1'],
5746
         *    ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2'],
5747
         *    ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3'],
5748
         *    ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4'],
5749
         *    ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5'],
5750
         *    ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6'],
5751
         *  ] )->tree( 'id', 'pid' );
5752
         *
5753
         * Results:
5754
         *   [1 => [
5755
         *     'id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1', 'children' => [
5756
         *       2 => ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2', 'children' => [
5757
         *         3 => ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3', 'children' => []]
5758
         *       ]],
5759
         *       4 => ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4', 'children' => [
5760
         *         5 => ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5', 'children' => []]
5761
         *       ]],
5762
         *       6 => ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6', 'children' => []]
5763
         *     ]
5764
         *   ]]
5765
         *
5766
         * To build the tree correctly, the items must be in order or at least the
5767
         * nodes of the lower levels must come first. For a tree like this:
5768
         * n1
5769
         * |- n2
5770
         * |  |- n3
5771
         * |- n4
5772
         * |  |- n5
5773
         * |- n6
5774
         *
5775
         * Accepted item order:
5776
         * - in order: n1, n2, n3, n4, n5, n6
5777
         * - lower levels first: n1, n2, n4, n6, n3, n5
5778
         *
5779
         * If your items are unordered, apply usort() first to the map entries, e.g.
5780
         *   Map::from( [['id' => 3, 'lvl' => 2], ...] )->usort( function( $item1, $item2 ) {
5781
         *     return $item1['lvl'] <=> $item2['lvl'];
5782
         *   } );
5783
         *
5784
         * @param string $idKey Name of the key with the unique ID of the node
5785
         * @param string $parentKey Name of the key with the ID of the parent node
5786
         * @param string $nestKey Name of the key with will contain the children of the node
5787
         * @return self<int|string,mixed> New map with one or more root tree nodes
5788
         */
5789
        public function tree( string $idKey, string $parentKey, string $nestKey = 'children' ) : self
5790
        {
5791
                $this->list();
3✔
5792
                $trees = $refs = [];
3✔
5793

5794
                foreach( $this->list as &$node )
3✔
5795
                {
5796
                        $node[$nestKey] = [];
3✔
5797
                        $refs[$node[$idKey]] = &$node;
3✔
5798

5799
                        if( $node[$parentKey] ) {
3✔
5800
                                $refs[$node[$parentKey]][$nestKey][$node[$idKey]] = &$node;
3✔
5801
                        } else {
5802
                                $trees[$node[$idKey]] = &$node;
3✔
5803
                        }
5804
                }
5805

5806
                return map( $trees );
3✔
5807
        }
5808

5809

5810
        /**
5811
         * Removes the passed characters from the left/right of all strings.
5812
         *
5813
         * Examples:
5814
         *  Map::from( [" abc\n", "\tcde\r\n"] )->trim();
5815
         *  Map::from( ["a b c", "cbax"] )->trim( 'abc' );
5816
         *
5817
         * Results:
5818
         * The first example will return ["abc", "cde"] while the second one will return [" b ", "x"].
5819
         *
5820
         * @param string $chars List of characters to trim
5821
         * @return self<int|string,mixed> Updated map for fluid interface
5822
         */
5823
        public function trim( string $chars = " \n\r\t\v\x00" ) : self
5824
        {
5825
                foreach( $this->list() as &$entry )
3✔
5826
                {
5827
                        if( is_string( $entry ) ) {
3✔
5828
                                $entry = trim( $entry, $chars );
3✔
5829
                        }
5830
                }
5831

5832
                return $this;
3✔
5833
        }
5834

5835

5836
        /**
5837
         * Sorts all elements using a callback and maintains the key association.
5838
         *
5839
         * The given callback will be used to compare the values. The callback must accept
5840
         * two parameters (item A and B) and must return -1 if item A is smaller than
5841
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5842
         * method name and an anonymous function can be passed.
5843
         *
5844
         * Examples:
5845
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( 'strcasecmp' );
5846
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( function( $itemA, $itemB ) {
5847
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5848
         *  } );
5849
         *
5850
         * Results:
5851
         *  ['b' => 'a', 'a' => 'B']
5852
         *  ['b' => 'a', 'a' => 'B']
5853
         *
5854
         * The keys are preserved using this method and no new map is created.
5855
         *
5856
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5857
         * @return self<int|string,mixed> Updated map for fluid interface
5858
         */
5859
        public function uasort( callable $callback ) : self
5860
        {
5861
                uasort( $this->list(), $callback );
6✔
5862
                return $this;
6✔
5863
        }
5864

5865

5866
        /**
5867
         * Sorts all elements using a callback and maintains the key association.
5868
         *
5869
         * The given callback will be used to compare the values. The callback must accept
5870
         * two parameters (item A and B) and must return -1 if item A is smaller than
5871
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5872
         * method name and an anonymous function can be passed.
5873
         *
5874
         * Examples:
5875
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( 'strcasecmp' );
5876
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( function( $itemA, $itemB ) {
5877
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5878
         *  } );
5879
         *
5880
         * Results:
5881
         *  ['b' => 'a', 'a' => 'B']
5882
         *  ['b' => 'a', 'a' => 'B']
5883
         *
5884
         * The keys are preserved using this method and a new map is created.
5885
         *
5886
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5887
         * @return self<int|string,mixed> Updated map for fluid interface
5888
         */
5889
        public function uasorted( callable $callback ) : self
5890
        {
5891
                return ( clone $this )->uasort( $callback );
3✔
5892
        }
5893

5894

5895
        /**
5896
         * Sorts the map elements by their keys using a callback.
5897
         *
5898
         * The given callback will be used to compare the keys. The callback must accept
5899
         * two parameters (key A and B) and must return -1 if key A is smaller than
5900
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
5901
         * method name and an anonymous function can be passed.
5902
         *
5903
         * Examples:
5904
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( 'strcasecmp' );
5905
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( function( $keyA, $keyB ) {
5906
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
5907
         *  } );
5908
         *
5909
         * Results:
5910
         *  ['a' => 'b', 'B' => 'a']
5911
         *  ['a' => 'b', 'B' => 'a']
5912
         *
5913
         * The keys are preserved using this method and no new map is created.
5914
         *
5915
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
5916
         * @return self<int|string,mixed> Updated map for fluid interface
5917
         */
5918
        public function uksort( callable $callback ) : self
5919
        {
5920
                uksort( $this->list(), $callback );
6✔
5921
                return $this;
6✔
5922
        }
5923

5924

5925
        /**
5926
         * Sorts a copy of the map elements by their keys using a callback.
5927
         *
5928
         * The given callback will be used to compare the keys. The callback must accept
5929
         * two parameters (key A and B) and must return -1 if key A is smaller than
5930
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
5931
         * method name and an anonymous function can be passed.
5932
         *
5933
         * Examples:
5934
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( 'strcasecmp' );
5935
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( function( $keyA, $keyB ) {
5936
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
5937
         *  } );
5938
         *
5939
         * Results:
5940
         *  ['a' => 'b', 'B' => 'a']
5941
         *  ['a' => 'b', 'B' => 'a']
5942
         *
5943
         * The keys are preserved using this method and a new map is created.
5944
         *
5945
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
5946
         * @return self<int|string,mixed> Updated map for fluid interface
5947
         */
5948
        public function uksorted( callable $callback ) : self
5949
        {
5950
                return ( clone $this )->uksort( $callback );
3✔
5951
        }
5952

5953

5954
        /**
5955
         * Unflattens the key path/value pairs into a multi-dimensional array.
5956
         *
5957
         * Examples:
5958
         *  Map::from( ['a/b/c' => 1, 'a/b/d' => 2, 'b/e' => 3] )->unflatten();
5959
         *  Map::from( ['a.b.c' => 1, 'a.b.d' => 2, 'b.e' => 3] )->sep( '.' )->unflatten();
5960
         *
5961
         * Results:
5962
         * ['a' => ['b' => ['c' => 1, 'd' => 2]], 'b' => ['e' => 3]]
5963
         *
5964
         * This is the inverse method for flatten().
5965
         *
5966
         * @return self<int|string,mixed> New map with multi-dimensional arrays
5967
         */
5968
        public function unflatten() : self
5969
        {
5970
                $result = [];
3✔
5971

5972
                foreach( $this->list() as $key => $value )
3✔
5973
                {
5974
                        $nested = &$result;
3✔
5975
                        $parts = explode( $this->sep, $key );
3✔
5976

5977
                        while( count( $parts ) > 1 ) {
3✔
5978
                                $nested = &$nested[array_shift( $parts )] ?? [];
3✔
5979
                        }
5980

5981
                        $nested[array_shift( $parts )] = $value;
3✔
5982
                }
5983

5984
                return new static( $result );
3✔
5985
        }
5986

5987

5988
        /**
5989
         * Builds a union of the elements and the given elements without overwriting existing ones.
5990
         * Existing keys in the map will not be overwritten
5991
         *
5992
         * Examples:
5993
         *  Map::from( [0 => 'a', 1 => 'b'] )->union( [0 => 'c'] );
5994
         *  Map::from( ['a' => 1, 'b' => 2] )->union( ['c' => 1] );
5995
         *
5996
         * Results:
5997
         * The first example will result in [0 => 'a', 1 => 'b'] because the key 0
5998
         * isn't overwritten. In the second example, the result will be a combined
5999
         * list: ['a' => 1, 'b' => 2, 'c' => 1].
6000
         *
6001
         * If list entries should be overwritten,  please use merge() instead!
6002
         * The keys are preserved using this method and no new map is created.
6003
         *
6004
         * @param iterable<int|string,mixed> $elements List of elements
6005
         * @return self<int|string,mixed> Updated map for fluid interface
6006
         */
6007
        public function union( iterable $elements ) : self
6008
        {
6009
                $this->list = $this->list() + $this->array( $elements );
6✔
6010
                return $this;
6✔
6011
        }
6012

6013

6014
        /**
6015
         * Returns only unique elements from the map incl. their keys.
6016
         *
6017
         * Examples:
6018
         *  Map::from( [0 => 'a', 1 => 'b', 2 => 'b', 3 => 'c'] )->unique();
6019
         *  Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->unique( 'p' )
6020
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( 'i/p' )
6021
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( fn( $item, $key ) => $item['i']['p'] )
6022
         *
6023
         * Results:
6024
         * [0 => 'a', 1 => 'b', 3 => 'c']
6025
         * [['p' => 1], ['p' => 2]]
6026
         * [['i' => ['p' => '1']]]
6027
         * [['i' => ['p' => '1']]]
6028
         *
6029
         * Two elements are considered equal if comparing their string representions returns TRUE:
6030
         * (string) $elem1 === (string) $elem2
6031
         *
6032
         * The keys of the elements are only preserved in the new map if no key is passed.
6033
         *
6034
         * @param \Closure|string|null $col Key, path of the nested array or anonymous function with ($item, $key) parameters returning the value for comparison
6035
         * @return self<int|string,mixed> New map
6036
         */
6037
        public function unique( $col = null ) : self
6038
        {
6039
                if( $col === null ) {
15✔
6040
                        return new static( array_unique( $this->list() ) );
6✔
6041
                }
6042

6043
                $list = $this->list();
9✔
6044
                $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
9✔
6045

6046
                return new static( array_intersect_key( $list, array_unique( $map ) ) );
9✔
6047
        }
6048

6049

6050
        /**
6051
         * Pushes an element onto the beginning of the map without returning a new map.
6052
         *
6053
         * Examples:
6054
         *  Map::from( ['a', 'b'] )->unshift( 'd' );
6055
         *  Map::from( ['a', 'b'] )->unshift( 'd', 'first' );
6056
         *
6057
         * Results:
6058
         *  ['d', 'a', 'b']
6059
         *  ['first' => 'd', 0 => 'a', 1 => 'b']
6060
         *
6061
         * The keys of the elements are only preserved in the new map if no key is passed.
6062
         *
6063
         * Performance note:
6064
         * The bigger the list, the higher the performance impact because unshift()
6065
         * needs to create a new list and copies all existing elements to the new
6066
         * array. Usually, it's better to push() new entries at the end and reverse()
6067
         * the list afterwards:
6068
         *
6069
         *  $map->push( 'a' )->push( 'b' )->reverse();
6070
         * instead of
6071
         *  $map->unshift( 'a' )->unshift( 'b' );
6072
         *
6073
         * @param mixed $value Item to add at the beginning
6074
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
6075
         * @return self<int|string,mixed> Updated map for fluid interface
6076
         */
6077
        public function unshift( $value, $key = null ) : self
6078
        {
6079
                if( $key === null ) {
9✔
6080
                        array_unshift( $this->list(), $value );
6✔
6081
                } else {
6082
                        $this->list = [$key => $value] + $this->list();
3✔
6083
                }
6084

6085
                return $this;
9✔
6086
        }
6087

6088

6089
        /**
6090
         * Sorts all elements using a callback using new keys.
6091
         *
6092
         * The given callback will be used to compare the values. The callback must accept
6093
         * two parameters (item A and B) and must return -1 if item A is smaller than
6094
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
6095
         * method name and an anonymous function can be passed.
6096
         *
6097
         * Examples:
6098
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usort( 'strcasecmp' );
6099
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usort( function( $itemA, $itemB ) {
6100
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
6101
         *  } );
6102
         *
6103
         * Results:
6104
         *  [0 => 'a', 1 => 'B']
6105
         *  [0 => 'a', 1 => 'B']
6106
         *
6107
         * The keys aren't preserved and elements get a new index. No new map is created.
6108
         *
6109
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
6110
         * @return self<int|string,mixed> Updated map for fluid interface
6111
         */
6112
        public function usort( callable $callback ) : self
6113
        {
6114
                usort( $this->list(), $callback );
6✔
6115
                return $this;
6✔
6116
        }
6117

6118

6119
        /**
6120
         * Sorts a copy of all elements using a callback using new keys.
6121
         *
6122
         * The given callback will be used to compare the values. The callback must accept
6123
         * two parameters (item A and B) and must return -1 if item A is smaller than
6124
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
6125
         * method name and an anonymous function can be passed.
6126
         *
6127
         * Examples:
6128
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usorted( 'strcasecmp' );
6129
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usorted( function( $itemA, $itemB ) {
6130
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
6131
         *  } );
6132
         *
6133
         * Results:
6134
         *  [0 => 'a', 1 => 'B']
6135
         *  [0 => 'a', 1 => 'B']
6136
         *
6137
         * The keys aren't preserved, elements get a new index and a new map is created.
6138
         *
6139
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
6140
         * @return self<int|string,mixed> Updated map for fluid interface
6141
         */
6142
        public function usorted( callable $callback ) : self
6143
        {
6144
                return ( clone $this )->usort( $callback );
3✔
6145
        }
6146

6147

6148
        /**
6149
         * Resets the keys and return the values in a new map.
6150
         *
6151
         * Examples:
6152
         *  Map::from( ['x' => 'b', 2 => 'a', 'c'] )->values();
6153
         *
6154
         * Results:
6155
         * A new map with [0 => 'b', 1 => 'a', 2 => 'c'] as content
6156
         *
6157
         * @return self<int|string,mixed> New map of the values
6158
         */
6159
        public function values() : self
6160
        {
6161
                return new static( array_values( $this->list() ) );
30✔
6162
        }
6163

6164

6165
        /**
6166
         * Applies the given callback to all elements.
6167
         *
6168
         * To change the values of the Map, specify the value parameter as reference
6169
         * (&$value). You can only change the values but not the keys nor the array
6170
         * structure.
6171
         *
6172
         * Examples:
6173
         *  Map::from( ['a', 'B', ['c', 'd'], 'e'] )->walk( function( &$value ) {
6174
         *    $value = strtoupper( $value );
6175
         *  } );
6176
         *  Map::from( [66 => 'B', 97 => 'a'] )->walk( function( $value, $key ) {
6177
         *    echo 'ASCII ' . $key . ' is ' . $value . "\n";
6178
         *  } );
6179
         *  Map::from( [1, 2, 3] )->walk( function( &$value, $key, $data ) {
6180
         *    $value = $data[$value] ?? $value;
6181
         *  }, [1 => 'one', 2 => 'two'] );
6182
         *
6183
         * Results:
6184
         * The first example will change the Map elements to:
6185
         *   ['A', 'B', ['C', 'D'], 'E']
6186
         * The output of the second one will be:
6187
         *  ASCII 66 is B
6188
         *  ASCII 97 is a
6189
         * The last example changes the Map elements to:
6190
         *  ['one', 'two', 3]
6191
         *
6192
         * By default, Map elements which are arrays will be traversed recursively.
6193
         * To iterate over the Map elements only, pass FALSE as third parameter.
6194
         *
6195
         * @param callable $callback Function with (item, key, data) parameters
6196
         * @param mixed $data Arbitrary data that will be passed to the callback as third parameter
6197
         * @param bool $recursive TRUE to traverse sub-arrays recursively (default), FALSE to iterate Map elements only
6198
         * @return self<int|string,mixed> Updated map for fluid interface
6199
         */
6200
        public function walk( callable $callback, $data = null, bool $recursive = true ) : self
6201
        {
6202
                if( $recursive ) {
9✔
6203
                        array_walk_recursive( $this->list(), $callback, $data );
6✔
6204
                } else {
6205
                        array_walk( $this->list(), $callback, $data );
3✔
6206
                }
6207

6208
                return $this;
9✔
6209
        }
6210

6211

6212
        /**
6213
         * Filters the list of elements by a given condition.
6214
         *
6215
         * Examples:
6216
         *  Map::from( [
6217
         *    ['id' => 1, 'type' => 'name'],
6218
         *    ['id' => 2, 'type' => 'short'],
6219
         *  ] )->where( 'type', '==', 'name' );
6220
         *
6221
         *  Map::from( [
6222
         *    ['id' => 3, 'price' => 10],
6223
         *    ['id' => 4, 'price' => 50],
6224
         *  ] )->where( 'price', '>', 20 );
6225
         *
6226
         *  Map::from( [
6227
         *    ['id' => 3, 'price' => 10],
6228
         *    ['id' => 4, 'price' => 50],
6229
         *  ] )->where( 'price', 'in', [10, 25] );
6230
         *
6231
         *  Map::from( [
6232
         *    ['id' => 3, 'price' => 10],
6233
         *    ['id' => 4, 'price' => 50],
6234
         *  ] )->where( 'price', '-', [10, 100] );
6235
         *
6236
         *  Map::from( [
6237
         *    ['item' => ['id' => 3, 'price' => 10]],
6238
         *    ['item' => ['id' => 4, 'price' => 50]],
6239
         *  ] )->where( 'item/price', '>', 30 );
6240
         *
6241
         * Results:
6242
         *  [0 => ['id' => 1, 'type' => 'name']]
6243
         *  [1 => ['id' => 4, 'price' => 50]]
6244
         *  [0 => ['id' => 3, 'price' => 10]]
6245
         *  [0 => ['id' => 3, 'price' => 10], ['id' => 4, 'price' => 50]]
6246
         *  [1 => ['item' => ['id' => 4, 'price' => 50]]]
6247
         *
6248
         * Available operators are:
6249
         * * '==' : Equal
6250
         * * '===' : Equal and same type
6251
         * * '!=' : Not equal
6252
         * * '!==' : Not equal and same type
6253
         * * '<=' : Smaller than an equal
6254
         * * '>=' : Greater than an equal
6255
         * * '<' : Smaller
6256
         * * '>' : Greater
6257
         * 'in' : Array of value which are in the list of values
6258
         * '-' : Values between array of start and end value, e.g. [10, 100] (inclusive)
6259
         *
6260
         * This does also work for multi-dimensional arrays by passing the keys
6261
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
6262
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
6263
         * public properties of objects or objects implementing __isset() and __get() methods.
6264
         *
6265
         * The keys of the original map are preserved in the returned map.
6266
         *
6267
         * @param string $key Key or path of the value in the array or object used for comparison
6268
         * @param string $op Operator used for comparison
6269
         * @param mixed $value Value used for comparison
6270
         * @return self<int|string,mixed> New map for fluid interface
6271
         */
6272
        public function where( string $key, string $op, $value ) : self
6273
        {
6274
                return $this->filter( function( $item ) use ( $key, $op, $value ) {
18✔
6275

6276
                        if( ( $val = $this->val( $item, explode( $this->sep, $key ) ) ) !== null )
18✔
6277
                        {
6278
                                switch( $op )
6279
                                {
6280
                                        case '-':
15✔
6281
                                                $list = (array) $value;
3✔
6282
                                                return $val >= current( $list ) && $val <= end( $list );
3✔
6283
                                        case 'in': return in_array( $val, (array) $value );
12✔
6284
                                        case '<': return $val < $value;
9✔
6285
                                        case '>': return $val > $value;
9✔
6286
                                        case '<=': return $val <= $value;
6✔
6287
                                        case '>=': return $val >= $value;
6✔
6288
                                        case '===': return $val === $value;
6✔
6289
                                        case '!==': return $val !== $value;
6✔
6290
                                        case '!=': return $val != $value;
6✔
6291
                                        default: return $val == $value;
6✔
6292
                                }
6293
                        }
6294

6295
                        return false;
3✔
6296
                } );
18✔
6297
        }
6298

6299

6300
        /**
6301
         * Returns a copy of the map with the element at the given index replaced with the given value.
6302
         *
6303
         * Examples:
6304
         *  $m = Map::from( ['a' => 1] );
6305
         *  $m->with( 2, 'b' );
6306
         *  $m->with( 'a', 2 );
6307
         *
6308
         * Results:
6309
         *  ['a' => 1, 2 => 'b']
6310
         *  ['a' => 2]
6311
         *
6312
         * The original map ($m) stays untouched!
6313
         * This method is a shortcut for calling the copy() and set() methods.
6314
         *
6315
         * @param int|string $key Array key to set or replace
6316
         * @param mixed $value New value for the given key
6317
         * @return self<int|string,mixed> New map
6318
         */
6319
        public function with( $key, $value ) : self
6320
        {
6321
                return ( clone $this )->set( $key, $value );
3✔
6322
        }
6323

6324

6325
        /**
6326
         * Merges the values of all arrays at the corresponding index.
6327
         *
6328
         * Examples:
6329
         *  $en = ['one', 'two', 'three'];
6330
         *  $es = ['uno', 'dos', 'tres'];
6331
         *  $m = Map::from( [1, 2, 3] )->zip( $en, $es );
6332
         *
6333
         * Results:
6334
         *  [
6335
         *    [1, 'one', 'uno'],
6336
         *    [2, 'two', 'dos'],
6337
         *    [3, 'three', 'tres'],
6338
         *  ]
6339
         *
6340
         * @param array<int|string,mixed>|\Traversable<int|string,mixed>|\Iterator<int|string,mixed> $arrays List of arrays to merge with at the same position
6341
         * @return self<int|string,mixed> New map of arrays
6342
         */
6343
        public function zip( ...$arrays ) : self
6344
        {
6345
                $args = array_map( function( $items ) {
3✔
6346
                        return $this->array( $items );
3✔
6347
                }, $arrays );
3✔
6348

6349
                return new static( array_map( null, $this->list(), ...$args ) );
3✔
6350
        }
6351

6352

6353
        /**
6354
         * Returns a plain array of the given elements.
6355
         *
6356
         * @param mixed $elements List of elements or single value
6357
         * @return array<int|string,mixed> Plain array
6358
         */
6359
        protected function array( $elements ) : array
6360
        {
6361
                if( is_array( $elements ) ) {
789✔
6362
                        return $elements;
759✔
6363
                }
6364

6365
                if( $elements instanceof \Closure ) {
117✔
6366
                        return (array) $elements();
×
6367
                }
6368

6369
                if( $elements instanceof \Aimeos\Map ) {
117✔
6370
                        return $elements->toArray();
69✔
6371
                }
6372

6373
                if( is_iterable( $elements ) ) {
51✔
6374
                        return iterator_to_array( $elements, true );
9✔
6375
                }
6376

6377
                return $elements !== null ? [$elements] : [];
42✔
6378
        }
6379

6380

6381
        /**
6382
         * Flattens a multi-dimensional array or map into a single level array.
6383
         *
6384
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
6385
         * @param array<int|string,mixed> $result Will contain all elements from the multi-dimensional arrays afterwards
6386
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
6387
         */
6388
        protected function kflatten( iterable $entries, array &$result, int $depth ) : void
6389
        {
6390
                foreach( $entries as $key => $entry )
15✔
6391
                {
6392
                        if( is_iterable( $entry ) && $depth > 0 ) {
15✔
6393
                                $this->kflatten( $entry, $result, $depth - 1 );
15✔
6394
                        } else {
6395
                                $result[$key] = $entry;
15✔
6396
                        }
6397
                }
6398
        }
6399

6400

6401
        /**
6402
         * Returns a reference to the array of elements
6403
         *
6404
         * @return array Reference to the array of elements
6405
         */
6406
        protected function &list() : array
6407
        {
6408
                if( !is_array( $this->list ) ) {
1,128✔
6409
                        $this->list = $this->array( $this->list );
×
6410
                }
6411

6412
                return $this->list;
1,128✔
6413
        }
6414

6415

6416
        /**
6417
         * Returns a closure that retrieves the value for the passed key
6418
         *
6419
         * @param \Closure|string|null $key Closure or key (e.g. "key1/key2/key3") to retrieve the value for
6420
         * @return \Closure Closure that retrieves the value for the passed key
6421
         */
6422
        protected function mapper( $key = null ) : \Closure
6423
        {
6424
                if( $key instanceof \Closure ) {
42✔
6425
                        return $key;
18✔
6426
                }
6427

6428
                $parts = $key ? explode( $this->sep, (string) $key ) : [];
24✔
6429

6430
                return function( $item ) use ( $parts ) {
24✔
6431
                        return $this->val( $item, $parts );
24✔
6432
                };
24✔
6433
        }
6434

6435

6436
        /**
6437
         * Flattens a multi-dimensional array or map into a single level array.
6438
         *
6439
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
6440
         * @param array<mixed> &$result Will contain all elements from the multi-dimensional arrays afterwards
6441
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
6442
         */
6443
        protected function nflatten( iterable $entries, array &$result, int $depth ) : void
6444
        {
6445
                foreach( $entries as $entry )
15✔
6446
                {
6447
                        if( is_iterable( $entry ) && $depth > 0 ) {
15✔
6448
                                $this->nflatten( $entry, $result, $depth - 1 );
12✔
6449
                        } else {
6450
                                $result[] = $entry;
15✔
6451
                        }
6452
                }
6453
        }
6454

6455

6456
        /**
6457
         * Flattens a multi-dimensional array or map into an array with joined keys.
6458
         *
6459
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
6460
         * @param array<int|string,mixed> $result Will contain joined key/value pairs from the multi-dimensional arrays afterwards
6461
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
6462
         * @param string $path Path prefix of the current key
6463
         */
6464
        protected function rflatten( iterable $entries, array &$result, int $depth, string $path = '' ) : void
6465
        {
6466
                foreach( $entries as $key => $entry )
3✔
6467
                {
6468
                        if( is_iterable( $entry ) && $depth > 0 ) {
3✔
6469
                                $this->rflatten( $entry, $result, $depth - 1, $path . $key . $this->sep );
3✔
6470
                        } else {
6471
                                $result[$path . $key] = $entry;
3✔
6472
                        }
6473
                }
6474
        }
6475

6476

6477
        /**
6478
         * Returns the position of the first element that doesn't match the condition
6479
         *
6480
         * @param iterable<int|string,mixed> $list List of elements to check
6481
         * @param \Closure $callback Closure with ($item, $key) arguments to check the condition
6482
         * @return int Position of the first element that doesn't match the condition
6483
         */
6484
        protected function until( iterable $list, \Closure $callback ) : int
6485
        {
6486
                $idx = 0;
6✔
6487

6488
                foreach( $list as $key => $item )
6✔
6489
                {
6490
                        if( !$callback( $item, $key ) ) {
6✔
6491
                                break;
6✔
6492
                        }
6493

6494
                        ++$idx;
6✔
6495
                }
6496

6497
                return $idx;
6✔
6498
        }
6499

6500

6501
        /**
6502
         * Returns a configuration value from an array.
6503
         *
6504
         * @param array<mixed>|object $entry The array or object to look at
6505
         * @param array<string> $parts Path parts to look for inside the array or object
6506
         * @return mixed Found value or null if no value is available
6507
         */
6508
        protected function val( $entry, array $parts )
6509
        {
6510
                foreach( $parts as $part )
141✔
6511
                {
6512
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$part] ) ) {
135✔
6513
                                $entry = $entry[$part];
78✔
6514
                        } elseif( is_object( $entry ) && isset( $entry->{$part} ) ) {
81✔
6515
                                $entry = $entry->{$part};
6✔
6516
                        } else {
6517
                                return null;
75✔
6518
                        }
6519
                }
6520

6521
                return $entry;
87✔
6522
        }
6523

6524

6525
        /**
6526
         * Visits each entry, calls the callback and returns the items in the result argument
6527
         *
6528
         * @param iterable<int|string,mixed> $entries List of entries with children (optional)
6529
         * @param array<mixed> $result Numerically indexed list of all visited entries
6530
         * @param int $level Current depth of the nodes in the tree
6531
         * @param \Closure|null $callback Callback with ($entry, $key, $level) arguments, returns the entry added to result
6532
         * @param string $nestKey Key to the children of each entry
6533
         * @param array<mixed>|object|null $parent Parent entry
6534
         */
6535
        protected function visit( iterable $entries, array &$result, int $level, ?\Closure $callback, string $nestKey, $parent = null ) : void
6536
        {
6537
                foreach( $entries as $key => $entry )
15✔
6538
                {
6539
                        $result[] = $callback ? $callback( $entry, $key, $level, $parent ) : $entry;
15✔
6540

6541
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$nestKey] ) ) {
15✔
6542
                                $this->visit( $entry[$nestKey], $result, $level + 1, $callback, $nestKey, $entry );
12✔
6543
                        } elseif( is_object( $entry ) && isset( $entry->{$nestKey} ) ) {
3✔
6544
                                $this->visit( $entry->{$nestKey}, $result, $level + 1, $callback, $nestKey, $entry );
3✔
6545
                        }
6546
                }
6547
        }
6548
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc