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

aimeos / map / 13418744114

19 Feb 2025 05:32PM UTC coverage: 97.201% (-0.04%) from 97.24%
13418744114

push

github

aimeos
Improved duplicate() and unique() implementation

14 of 14 new or added lines in 1 file covered. (100.0%)

22 existing lines in 1 file now uncovered.

764 of 786 relevant lines covered (97.2%)

49.1 hits per line

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

97.19
/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;
3,144✔
53
                $this->list = $elements;
3,144✔
54
        }
786✔
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
         *
71
         * @throws \BadMethodCallException
72
         */
73
        public static function __callStatic( string $name, array $params )
74
        {
75
                if( !isset( static::$methods[$name] ) ) {
16✔
76
                        throw new \BadMethodCallException( sprintf( 'Method %s::%s does not exist.', static::class, $name ) );
8✔
77
                }
78

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

82

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

118
                $result = [];
16✔
119

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

127
                return new static( $result );
16✔
128
        }
129

130

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

141

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

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

168
                return $old;
8✔
169
        }
170

171

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

210
                $limit = $limit ?: 1;
32✔
211
                $parts = mb_str_split( $string );
32✔
212

213
                if( $limit < 1 ) {
32✔
214
                        return new static( array_slice( $parts, 0, $limit ) );
8✔
215
                }
216

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

222
                        return new static( $result );
8✔
223
                }
224

225
                return new static( $parts );
16✔
226
        }
227

228

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

252

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

277
                return new static( $elements );
1,456✔
278
        }
279

280

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

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

318

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

345
                return self::$methods[$method] ?? null;
24✔
346
        }
347

348

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

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

386
                return new static( $list );
24✔
387
        }
388

389

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

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

421

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

432

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

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

463
                return false;
8✔
464
        }
465

466

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

501

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

535

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

570

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

604

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

631

632
        /**
633
         * Returns the average of all integer and float values in the map.
634
         *
635
         * Examples:
636
         *  Map::from( [1, 3, 5] )->avg();
637
         *  Map::from( [1, null, 5] )->avg();
638
         *  Map::from( [1, 'sum', 5] )->avg();
639
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( 'p' );
640
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->avg( 'i/p' );
641
         *  Map::from( [30, 50, 10] )->avg( fn( $val, $key ) => $val < 50 );
642
         *
643
         * Results:
644
         * The first and second line will return "3", the third one "2", the forth
645
         * one "30", the fifth one "40" and the last one "20".
646
         *
647
         * NULL values are treated as 0, non-numeric values will generate an error.
648
         *
649
         * This does also work for multi-dimensional arrays by passing the keys
650
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
651
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
652
         * public properties of objects or objects implementing __isset() and __get() methods.
653
         *
654
         * @param Closure|string|null $col Closure, key or path to the values in the nested array or object to compute the average for
655
         * @return float Average of all elements or 0 if there are no elements in the map
656
         */
657
        public function avg( $col = null ) : float
658
        {
659
                if( $col instanceof \Closure ) {
24✔
660
                        $vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
8✔
661
                } elseif( is_string( $col ) ) {
16✔
662
                        $vals = $this->col( $col )->toArray();
8✔
663
                } elseif( is_null( $col ) ) {
8✔
664
                        $vals = $this->list();
8✔
665
                } else {
UNCOV
666
                        throw new \InvalidArgumentException( 'Parameter is no closure or string' );
×
667
                }
668

669
                $cnt = count( $vals );
24✔
670
                return $cnt > 0 ? array_sum( $vals ) / $cnt : 0;
24✔
671
        }
672

673

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

701

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

742

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

769
                foreach( $this->list() as $key => $item )
8✔
770
                {
771
                        if( is_object( $item ) ) {
8✔
772
                                $result[$key] = $item->{$name}( ...$params );
8✔
773
                        }
774
                }
775

776
                return new static( $result );
8✔
777
        }
778

779

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

820
                return $this;
8✔
821
        }
822

823

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

851
                return new static( array_chunk( $this->list(), $size, $preserve ) );
16✔
852
        }
853

854

855
        /**
856
         * Removes all elements from the current map.
857
         *
858
         * @return self<int|string,mixed> Updated map for fluid interface
859
         */
860
        public function clear() : self
861
        {
862
                $this->list = [];
32✔
863
                return $this;
32✔
864
        }
865

866

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

887
                foreach( $this->list() as $key => $item ) {
8✔
888
                        $list[$key] = is_object( $item ) ? clone $item : $item;
8✔
889
                }
890

891
                return new static( $list );
8✔
892
        }
893

894

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

934
                if( count( $vparts ) === 1 && count( $iparts ) === 1 ) {
104✔
935
                        return new static( array_column( $this->list(), $valuecol, $indexcol ) );
80✔
936
                }
937

938
                $list = [];
56✔
939

940
                foreach( $this->list() as $item )
56✔
941
                {
942
                        $v = $valuecol !== null ? $this->val( $item, $vparts ) : $item;
56✔
943

944
                        if( $indexcol !== null && ( $key = $this->val( $item, $iparts ) ) !== null ) {
56✔
945
                                $list[(string) $key] = $v;
16✔
946
                        } else {
947
                                $list[] = $v;
42✔
948
                        }
949
                }
950

951
                return new static( $list );
56✔
952
        }
953

954

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

989
                $result = [];
40✔
990
                $this->kflatten( $this->list(), $result, $depth ?? 0x7fffffff );
40✔
991
                return new static( $result );
40✔
992
        }
993

994

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

1012

1013
        /**
1014
         * Compares the value against all map elements.
1015
         *
1016
         * Examples:
1017
         *  Map::from( ['foo', 'bar'] )->compare( 'foo' );
1018
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo', false );
1019
         *  Map::from( [123, 12.3] )->compare( '12.3' );
1020
         *  Map::from( [false, true] )->compare( '1' );
1021
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo' );
1022
         *  Map::from( ['foo', 'bar'] )->compare( 'baz' );
1023
         *  Map::from( [new \stdClass(), 'bar'] )->compare( 'foo' );
1024
         *
1025
         * Results:
1026
         * The first four examples return TRUE, the last three examples will return FALSE.
1027
         *
1028
         * All scalar values (bool, float, int and string) are casted to string values before
1029
         * comparing to the given value. Non-scalar values in the map are ignored.
1030
         *
1031
         * @param string $value Value to compare map elements to
1032
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
1033
         * @return bool TRUE If at least one element matches, FALSE if value is not in map
1034
         */
1035
        public function compare( string $value, bool $case = true ) : bool
1036
        {
1037
                $fcn = $case ? 'strcmp' : 'strcasecmp';
8✔
1038

1039
                foreach( $this->list() as $item )
8✔
1040
                {
1041
                        if( is_scalar( $item ) && !$fcn( (string) $item, $value ) ) {
8✔
1042
                                return true;
8✔
1043
                        }
1044
                }
1045

1046
                return false;
8✔
1047
        }
1048

1049

1050
        /**
1051
         * Pushs all of the given elements onto the map with new keys without creating a new map.
1052
         *
1053
         * Examples:
1054
         *  Map::from( ['foo'] )->concat( new Map( ['bar'] ));
1055
         *
1056
         * Results:
1057
         *  ['foo', 'bar']
1058
         *
1059
         * The keys of the passed elements are NOT preserved!
1060
         *
1061
         * @param iterable<int|string,mixed> $elements List of elements
1062
         * @return self<int|string,mixed> Updated map for fluid interface
1063
         */
1064
        public function concat( iterable $elements ) : self
1065
        {
1066
                $this->list();
16✔
1067

1068
                foreach( $elements as $item ) {
16✔
1069
                        $this->list[] = $item;
16✔
1070
                }
1071

1072
                return $this;
16✔
1073
        }
1074

1075

1076
        /**
1077
         * Determines if an item exists in the map.
1078
         *
1079
         * This method combines the power of the where() method with some() to check
1080
         * if the map contains at least one of the passed values or conditions.
1081
         *
1082
         * Examples:
1083
         *  Map::from( ['a', 'b'] )->contains( 'a' );
1084
         *  Map::from( ['a', 'b'] )->contains( ['a', 'c'] );
1085
         *  Map::from( ['a', 'b'] )->contains( function( $item, $key ) {
1086
         *    return $item === 'a'
1087
         *  } );
1088
         *  Map::from( [['type' => 'name']] )->contains( 'type', 'name' );
1089
         *  Map::from( [['type' => 'name']] )->contains( 'type', '==', 'name' );
1090
         *
1091
         * Results:
1092
         * All method calls will return TRUE because at least "a" is included in the
1093
         * map or there's a "type" key with a value "name" like in the last two
1094
         * examples.
1095
         *
1096
         * Check the where() method for available operators.
1097
         *
1098
         * @param \Closure|iterable|mixed $values Anonymous function with (item, key) parameter, element or list of elements to test against
1099
         * @param string|null $op Operator used for comparison
1100
         * @param mixed $value Value used for comparison
1101
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
1102
         */
1103
        public function contains( $key, ?string $operator = null, $value = null ) : bool
1104
        {
1105
                if( $operator === null ) {
16✔
1106
                        return $this->some( $key );
8✔
1107
                }
1108

1109
                if( $value === null ) {
8✔
1110
                        return !$this->where( $key, '==', $operator )->isEmpty();
8✔
1111
                }
1112

1113
                return !$this->where( $key, $operator, $value )->isEmpty();
8✔
1114
        }
1115

1116

1117
        /**
1118
         * Creates a new map with the same elements.
1119
         *
1120
         * Both maps share the same array until one of the map objects modifies the
1121
         * array. Then, the array is copied and the copy is modfied (copy on write).
1122
         *
1123
         * @return self<int|string,mixed> New map
1124
         */
1125
        public function copy() : self
1126
        {
1127
                return clone $this;
24✔
1128
        }
1129

1130

1131
        /**
1132
         * Counts the total number of elements in the map.
1133
         *
1134
         * @return int Number of elements
1135
         */
1136
        public function count() : int
1137
        {
1138
                return count( $this->list() );
72✔
1139
        }
1140

1141

1142
        /**
1143
         * Counts how often the same values are in the map.
1144
         *
1145
         * Examples:
1146
         *  Map::from( [1, 'foo', 2, 'foo', 1] )->countBy();
1147
         *  Map::from( [1.11, 3.33, 3.33, 9.99] )->countBy();
1148
         *  Map::from( ['a@gmail.com', 'b@yahoo.com', 'c@gmail.com'] )->countBy( function( $email ) {
1149
         *    return substr( strrchr( $email, '@' ), 1 );
1150
         *  } );
1151
         *
1152
         * Results:
1153
         *  [1 => 2, 'foo' => 2, 2 => 1]
1154
         *  ['1.11' => 1, '3.33' => 2, '9.99' => 1]
1155
         *  ['gmail.com' => 2, 'yahoo.com' => 1]
1156
         *
1157
         * Counting values does only work for integers and strings because these are
1158
         * the only types allowed as array keys. All elements are casted to strings
1159
         * if no callback is passed. Custom callbacks need to make sure that only
1160
         * string or integer values are returned!
1161
         *
1162
         * @param  callable|null $callback Function with (value, key) parameters which returns the value to use for counting
1163
         * @return self<int|string,mixed> New map with values as keys and their count as value
1164
         */
1165
        public function countBy( ?callable $callback = null ) : self
1166
        {
1167
                $callback = $callback ?: function( $value ) {
18✔
1168
                        return (string) $value;
16✔
1169
                };
24✔
1170

1171
                return new static( array_count_values( array_map( $callback, $this->list() ) ) );
24✔
1172
        }
1173

1174

1175
        /**
1176
         * Dumps the map content and terminates the script.
1177
         *
1178
         * The dd() method is very helpful to see what are the map elements passed
1179
         * between two map methods in a method call chain. It stops execution of the
1180
         * script afterwards to avoid further output.
1181
         *
1182
         * Examples:
1183
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->sort()->dd();
1184
         *
1185
         * Results:
1186
         *  Array
1187
         *  (
1188
         *      [0] => bar
1189
         *      [1] => foo
1190
         *  )
1191
         *
1192
         * @param callable|null $callback Function receiving the map elements as parameter (optional)
1193
         */
1194
        public function dd( ?callable $callback = null ) : void
1195
        {
UNCOV
1196
                $this->dump( $callback );
×
UNCOV
1197
                exit( 1 );
×
1198
        }
1199

1200

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

1236
                return new static( array_diff( $this->list(), $this->array( $elements ) ) );
24✔
1237
        }
1238

1239

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

1277
                return new static( array_diff_assoc( $this->list(), $this->array( $elements ) ) );
16✔
1278
        }
1279

1280

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

1317
                return new static( array_diff_key( $this->list(), $this->array( $elements ) ) );
16✔
1318
        }
1319

1320

1321
        /**
1322
         * Dumps the map content using the given function (print_r by default).
1323
         *
1324
         * The dump() method is very helpful to see what are the map elements passed
1325
         * between two map methods in a method call chain.
1326
         *
1327
         * Examples:
1328
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->dump()->asort()->dump( 'var_dump' );
1329
         *
1330
         * Results:
1331
         *  Array
1332
         *  (
1333
         *      [a] => foo
1334
         *      [b] => bar
1335
         *  )
1336
         *  array(1) {
1337
         *    ["b"]=>
1338
         *    string(3) "bar"
1339
         *    ["a"]=>
1340
         *    string(3) "foo"
1341
         *  }
1342
         *
1343
         * @param callable|null $callback Function receiving the map elements as parameter (optional)
1344
         * @return self<int|string,mixed> Same map for fluid interface
1345
         */
1346
        public function dump( ?callable $callback = null ) : self
1347
        {
1348
                $callback ? $callback( $this->list() ) : print_r( $this->list() );
8✔
1349
                return $this;
8✔
1350
        }
1351

1352

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

1385
                if( $col !== null ) {
32✔
1386
                        $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
24✔
1387
                }
1388

1389
                return new static( array_diff_key( $list, array_unique( $map ) ) );
32✔
1390
        }
1391

1392

1393
        /**
1394
         * Executes a callback over each entry until FALSE is returned.
1395
         *
1396
         * Examples:
1397
         *  $result = [];
1398
         *  Map::from( [0 => 'a', 1 => 'b'] )->each( function( $value, $key ) use ( &$result ) {
1399
         *      $result[$key] = strtoupper( $value );
1400
         *      return false;
1401
         *  } );
1402
         *
1403
         * The $result array will contain [0 => 'A'] because FALSE is returned
1404
         * after the first entry and all other entries are then skipped.
1405
         *
1406
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1407
         * @return self<int|string,mixed> Same map for fluid interface
1408
         */
1409
        public function each( \Closure $callback ) : self
1410
        {
1411
                foreach( $this->list() as $key => $item )
16✔
1412
                {
1413
                        if( $callback( $item, $key ) === false ) {
16✔
1414
                                break;
9✔
1415
                        }
1416
                }
1417

1418
                return $this;
16✔
1419
        }
1420

1421

1422
        /**
1423
         * Determines if the map is empty or not.
1424
         *
1425
         * Examples:
1426
         *  Map::from( [] )->empty();
1427
         *  Map::from( ['a'] )->empty();
1428
         *
1429
         * Results:
1430
         *  The first example returns TRUE while the second returns FALSE
1431
         *
1432
         * The method is equivalent to isEmpty().
1433
         *
1434
         * @return bool TRUE if map is empty, FALSE if not
1435
         */
1436
        public function empty() : bool
1437
        {
1438
                return empty( $this->list() );
16✔
1439
        }
1440

1441

1442
        /**
1443
         * Tests if the passed elements are equal to the elements in the map.
1444
         *
1445
         * Examples:
1446
         *  Map::from( ['a'] )->equals( ['a', 'b'] );
1447
         *  Map::from( ['a', 'b'] )->equals( ['b'] );
1448
         *  Map::from( ['a', 'b'] )->equals( ['b', 'a'] );
1449
         *
1450
         * Results:
1451
         * The first and second example will return FALSE, the third example will return TRUE
1452
         *
1453
         * The method differs to is() in the fact that it doesn't care about the keys
1454
         * by default. The elements are only loosely compared and the keys are ignored.
1455
         *
1456
         * Values are compared by their string values:
1457
         * (string) $item1 === (string) $item2
1458
         *
1459
         * @param iterable<int|string,mixed> $elements List of elements to test against
1460
         * @return bool TRUE if both are equal, FALSE if not
1461
         */
1462
        public function equals( iterable $elements ) : bool
1463
        {
1464
                $list = $this->list();
48✔
1465
                $elements = $this->array( $elements );
48✔
1466

1467
                return array_diff( $list, $elements ) === [] && array_diff( $elements, $list ) === [];
48✔
1468
        }
1469

1470

1471
        /**
1472
         * Verifies that all elements pass the test of the given callback.
1473
         *
1474
         * Examples:
1475
         *  Map::from( [0 => 'a', 1 => 'b'] )->every( function( $value, $key ) {
1476
         *      return is_string( $value );
1477
         *  } );
1478
         *
1479
         *  Map::from( [0 => 'a', 1 => 100] )->every( function( $value, $key ) {
1480
         *      return is_string( $value );
1481
         *  } );
1482
         *
1483
         * The first example will return TRUE because all values are a string while
1484
         * the second example will return FALSE.
1485
         *
1486
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1487
         * @return bool True if all elements pass the test, false if if fails for at least one element
1488
         */
1489
        public function every( \Closure $callback ) : bool
1490
        {
1491
                foreach( $this->list() as $key => $item )
8✔
1492
                {
1493
                        if( $callback( $item, $key ) === false ) {
8✔
1494
                                return false;
8✔
1495
                        }
1496
                }
1497

1498
                return true;
8✔
1499
        }
1500

1501

1502
        /**
1503
         * Returns a new map without the passed element keys.
1504
         *
1505
         * Examples:
1506
         *  Map::from( ['a' => 1, 'b' => 2, 'c' => 3] )->except( 'b' );
1507
         *  Map::from( [1 => 'a', 2 => 'b', 3 => 'c'] )->except( [1, 3] );
1508
         *
1509
         * Results:
1510
         *  ['a' => 1, 'c' => 3]
1511
         *  [2 => 'b']
1512
         *
1513
         * The keys in the result map are preserved.
1514
         *
1515
         * @param iterable<string|int>|array<string|int>|string|int $keys List of keys to remove
1516
         * @return self<int|string,mixed> New map
1517
         */
1518
        public function except( $keys ) : self
1519
        {
1520
                return ( clone $this )->remove( $keys );
8✔
1521
        }
1522

1523

1524
        /**
1525
         * Applies a filter to all elements of the map and returns a new map.
1526
         *
1527
         * Examples:
1528
         *  Map::from( [null, 0, 1, '', '0', 'a'] )->filter();
1529
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->filter( function( $value, $key ) {
1530
         *      return $key < 10 && $value < 'n';
1531
         *  } );
1532
         *
1533
         * Results:
1534
         *  [1, 'a']
1535
         *  ['a', 'b']
1536
         *
1537
         * If no callback is passed, all values which are empty, null or false will be
1538
         * removed if their value converted to boolean is FALSE:
1539
         *  (bool) $value === false
1540
         *
1541
         * The keys in the result map are preserved.
1542
         *
1543
         * @param  callable|null $callback Function with (item, key) parameters and returns TRUE/FALSE
1544
         * @return self<int|string,mixed> New map
1545
         */
1546
        public function filter( ?callable $callback = null ) : self
1547
        {
1548
                if( $callback ) {
80✔
1549
                        return new static( array_filter( $this->list(), $callback, ARRAY_FILTER_USE_BOTH ) );
72✔
1550
                }
1551

1552
                return new static( array_filter( $this->list() ) );
8✔
1553
        }
1554

1555

1556
        /**
1557
         * Returns the first/last matching element where the callback returns TRUE.
1558
         *
1559
         * Examples:
1560
         *  Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
1561
         *      return $value >= 'b';
1562
         *  } );
1563
         *  Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
1564
         *      return $value >= 'b';
1565
         *  }, null, true );
1566
         *  Map::from( [] )->find( function( $value, $key ) {
1567
         *      return $value >= 'b';
1568
         *  }, 'none' );
1569
         *  Map::from( [] )->find( function( $value, $key ) {
1570
         *      return $value >= 'b';
1571
         *  }, new \Exception( 'error' ) );
1572
         *
1573
         * Results:
1574
         * The first example will return 'c' while the second will return 'e' (last element).
1575
         * The third one will return "none" and the last one will throw the exception.
1576
         *
1577
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1578
         * @param mixed $default Default value or exception if the map contains no elements
1579
         * @param bool $reverse TRUE to test elements from back to front, FALSE for front to back (default)
1580
         * @return mixed First matching value, passed default value or an exception
1581
         */
1582
        public function find( \Closure $callback, $default = null, bool $reverse = false )
1583
        {
1584
                foreach( ( $reverse ? array_reverse( $this->list(), true ) : $this->list() ) as $key => $value )
32✔
1585
                {
1586
                        if( $callback( $value, $key ) ) {
32✔
1587
                                return $value;
18✔
1588
                        }
1589
                }
1590

1591
                if( $default instanceof \Throwable ) {
16✔
1592
                        throw $default;
8✔
1593
                }
1594

1595
                return $default;
8✔
1596
        }
1597

1598

1599
        /**
1600
         * Returns the first/last key where the callback returns TRUE.
1601
         *
1602
         * Examples:
1603
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1604
         *      return $value >= 'b';
1605
         *  } );
1606
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1607
         *      return $value >= 'b';
1608
         *  }, null, true );
1609
         *  Map::from( [] )->findKey( function( $value, $key ) {
1610
         *      return $value >= 'b';
1611
         *  }, 'none' );
1612
         *  Map::from( [] )->findKey( function( $value, $key ) {
1613
         *      return $value >= 'b';
1614
         *  }, new \Exception( 'error' ) );
1615
         *
1616
         * Results:
1617
         * The first example will return '1' while the second will return '2' (last element).
1618
         * The third one will return "none" and the last one will throw the exception.
1619
         *
1620
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1621
         * @param mixed $default Default value or exception if the map contains no elements
1622
         * @param bool $reverse TRUE to test elements from back to front, FALSE for front to back (default)
1623
         * @return mixed Key of first matching element, passed default value or an exception
1624
         */
1625
        public function findKey( \Closure $callback, $default = null, bool $reverse = false )
1626
        {
1627
                foreach( ( $reverse ? array_reverse( $this->list(), true ) : $this->list() ) as $key => $value )
32✔
1628
                {
1629
                        if( $callback( $value, $key ) ) {
16✔
1630
                                return $key;
16✔
1631
                        }
1632
                }
1633

1634
                if( $default instanceof \Throwable ) {
16✔
1635
                        throw $default;
8✔
1636
                }
1637

1638
                return $default;
8✔
1639
        }
1640

1641

1642
        /**
1643
         * Returns the first element from the map.
1644
         *
1645
         * Examples:
1646
         *  Map::from( ['a', 'b'] )->first();
1647
         *  Map::from( [] )->first( 'x' );
1648
         *  Map::from( [] )->first( new \Exception( 'error' ) );
1649
         *  Map::from( [] )->first( function() { return rand(); } );
1650
         *
1651
         * Results:
1652
         * The first example will return 'b' and the second one 'x'. The third example
1653
         * will throw the exception passed if the map contains no elements. In the
1654
         * fourth example, a random value generated by the closure function will be
1655
         * returned.
1656
         *
1657
         * @param mixed $default Default value or exception if the map contains no elements
1658
         * @return mixed First value of map, (generated) default value or an exception
1659
         */
1660
        public function first( $default = null )
1661
        {
1662
                if( ( $value = reset( $this->list() ) ) !== false ) {
64✔
1663
                        return $value;
40✔
1664
                }
1665

1666
                if( $default instanceof \Closure ) {
32✔
1667
                        return $default();
8✔
1668
                }
1669

1670
                if( $default instanceof \Throwable ) {
24✔
1671
                        throw $default;
8✔
1672
                }
1673

1674
                return $default;
16✔
1675
        }
1676

1677

1678
        /**
1679
         * Returns the first key from the map.
1680
         *
1681
         * Examples:
1682
         *  Map::from( ['a' => 1, 'b' => 2] )->firstKey();
1683
         *  Map::from( [] )->firstKey();
1684
         *
1685
         * Results:
1686
         * The first example will return 'a' and the second one NULL.
1687
         *
1688
         * @return mixed First key of map or NULL if empty
1689
         */
1690
        public function firstKey()
1691
        {
1692
                $list = $this->list();
16✔
1693

1694
                if( function_exists( 'array_key_first' ) ) {
16✔
1695
                        return array_key_first( $list );
16✔
1696
                }
1697

UNCOV
1698
                reset( $list );
×
UNCOV
1699
                return key( $list );
×
1700
        }
1701

1702

1703
        /**
1704
         * Creates a new map with all sub-array elements added recursively withput overwriting existing keys.
1705
         *
1706
         * Examples:
1707
         *  Map::from( [[0, 1], [2, 3]] )->flat();
1708
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat();
1709
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat( 1 );
1710
         *  Map::from( [[0, 1], Map::from( [[2, 3], 4] )] )->flat();
1711
         *
1712
         * Results:
1713
         *  [0, 1, 2, 3]
1714
         *  [0, 1, 2, 3, 4]
1715
         *  [0, 1, [2, 3], 4]
1716
         *  [0, 1, 2, 3, 4]
1717
         *
1718
         * The keys are not preserved and the new map elements will be numbered from
1719
         * 0-n. A value smaller than 1 for depth will return the same map elements
1720
         * indexed from 0-n. Flattening does also work if elements implement the
1721
         * "Traversable" interface (which the Map object does).
1722
         *
1723
         * This method is similar than collapse() but doesn't replace existing elements.
1724
         * Keys are NOT preserved using this method!
1725
         *
1726
         * @param int|null $depth Number of levels to flatten multi-dimensional arrays or NULL for all
1727
         * @return self<int|string,mixed> New map with all sub-array elements added into it recursively, up to the specified depth
1728
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
1729
         */
1730
        public function flat( ?int $depth = null ) : self
1731
        {
1732
                if( $depth < 0 ) {
48✔
1733
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
8✔
1734
                }
1735

1736
                $result = [];
40✔
1737
                $this->flatten( $this->list(), $result, $depth ?? 0x7fffffff );
40✔
1738
                return new static( $result );
40✔
1739
        }
1740

1741

1742
        /**
1743
         * Exchanges the keys with their values and vice versa.
1744
         *
1745
         * Examples:
1746
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->flip();
1747
         *
1748
         * Results:
1749
         *  ['X' => 'a', 'Y' => 'b']
1750
         *
1751
         * @return self<int|string,mixed> New map with keys as values and values as keys
1752
         */
1753
        public function flip() : self
1754
        {
1755
                return new static( array_flip( $this->list() ) );
8✔
1756
        }
1757

1758

1759
        /**
1760
         * Returns an element by key and casts it to float if possible.
1761
         *
1762
         * Examples:
1763
         *  Map::from( ['a' => true] )->float( 'a' );
1764
         *  Map::from( ['a' => 1] )->float( 'a' );
1765
         *  Map::from( ['a' => '1.1'] )->float( 'a' );
1766
         *  Map::from( ['a' => '10'] )->float( 'a' );
1767
         *  Map::from( ['a' => ['b' => ['c' => 1.1]]] )->float( 'a/b/c' );
1768
         *  Map::from( [] )->float( 'c', function() { return 1.1; } );
1769
         *  Map::from( [] )->float( 'a', 1.1 );
1770
         *
1771
         *  Map::from( [] )->float( 'b' );
1772
         *  Map::from( ['b' => ''] )->float( 'b' );
1773
         *  Map::from( ['b' => null] )->float( 'b' );
1774
         *  Map::from( ['b' => 'abc'] )->float( 'b' );
1775
         *  Map::from( ['b' => [1]] )->float( 'b' );
1776
         *  Map::from( ['b' => #resource] )->float( 'b' );
1777
         *  Map::from( ['b' => new \stdClass] )->float( 'b' );
1778
         *
1779
         *  Map::from( [] )->float( 'c', new \Exception( 'error' ) );
1780
         *
1781
         * Results:
1782
         * The first eight examples will return the float values for the passed keys
1783
         * while the 9th to 14th example returns 0. The last example will throw an exception.
1784
         *
1785
         * This does also work for multi-dimensional arrays by passing the keys
1786
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1787
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1788
         * public properties of objects or objects implementing __isset() and __get() methods.
1789
         *
1790
         * @param int|string $key Key or path to the requested item
1791
         * @param mixed $default Default value if key isn't found (will be casted to float)
1792
         * @return float Value from map or default value
1793
         */
1794
        public function float( $key, $default = 0.0 ) : float
1795
        {
1796
                return (float) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
24✔
1797
        }
1798

1799

1800
        /**
1801
         * Returns an element from the map by key.
1802
         *
1803
         * Examples:
1804
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'a' );
1805
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'c', 'Z' );
1806
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->get( 'a/b/c' );
1807
         *  Map::from( [] )->get( 'Y', new \Exception( 'error' ) );
1808
         *  Map::from( [] )->get( 'Y', function() { return rand(); } );
1809
         *
1810
         * Results:
1811
         * The first example will return 'X', the second 'Z' and the third 'Y'. The forth
1812
         * example will throw the exception passed if the map contains no elements. In
1813
         * the fifth example, a random value generated by the closure function will be
1814
         * returned.
1815
         *
1816
         * This does also work for multi-dimensional arrays by passing the keys
1817
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1818
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1819
         * public properties of objects or objects implementing __isset() and __get() methods.
1820
         *
1821
         * @param int|string $key Key or path to the requested item
1822
         * @param mixed $default Default value if no element matches
1823
         * @return mixed Value from map or default value
1824
         */
1825
        public function get( $key, $default = null )
1826
        {
1827
                $list = $this->list();
184✔
1828

1829
                if( array_key_exists( $key, $list ) ) {
184✔
1830
                        return $list[$key];
48✔
1831
                }
1832

1833
                if( ( $v = $this->val( $list, explode( $this->sep, (string) $key ) ) ) !== null ) {
168✔
1834
                        return $v;
56✔
1835
                }
1836

1837
                if( $default instanceof \Closure ) {
144✔
1838
                        return $default();
48✔
1839
                }
1840

1841
                if( $default instanceof \Throwable ) {
96✔
1842
                        throw $default;
48✔
1843
                }
1844

1845
                return $default;
48✔
1846
        }
1847

1848

1849
        /**
1850
         * Returns an iterator for the elements.
1851
         *
1852
         * This method will be used by e.g. foreach() to loop over all entries:
1853
         *  foreach( Map::from( ['a', 'b'] ) as $value )
1854
         *
1855
         * @return \ArrayIterator<int|string,mixed> Iterator for map elements
1856
         */
1857
        public function getIterator() : \ArrayIterator
1858
        {
1859
                return new \ArrayIterator( $this->list() );
40✔
1860
        }
1861

1862

1863
        /**
1864
         * Returns only items which matches the regular expression.
1865
         *
1866
         * All items are converted to string first before they are compared to the
1867
         * regular expression. Thus, fractions of ".0" will be removed in float numbers
1868
         * which may result in unexpected results.
1869
         *
1870
         * Examples:
1871
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/b/' );
1872
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/a/', PREG_GREP_INVERT );
1873
         *  Map::from( [1.5, 0, 1.0, 'a'] )->grep( '/^(\d+)?\.\d+$/' );
1874
         *
1875
         * Results:
1876
         *  ['ab', 'bc']
1877
         *  ['bc', 'cd']
1878
         *  [1.5] // float 1.0 is converted to string "1"
1879
         *
1880
         * The keys are preserved using this method.
1881
         *
1882
         * @param string $pattern Regular expression pattern, e.g. "/ab/"
1883
         * @param int $flags PREG_GREP_INVERT to return elements not matching the pattern
1884
         * @return self<int|string,mixed> New map containing only the matched elements
1885
         */
1886
        public function grep( string $pattern, int $flags = 0 ) : self
1887
        {
1888
                if( ( $result = preg_grep( $pattern, $this->list(), $flags ) ) === false )
32✔
1889
                {
1890
                        switch( preg_last_error() )
8✔
1891
                        {
1892
                                case PREG_INTERNAL_ERROR: $msg = 'Internal error'; break;
8✔
UNCOV
1893
                                case PREG_BACKTRACK_LIMIT_ERROR: $msg = 'Backtrack limit error'; break;
×
UNCOV
1894
                                case PREG_RECURSION_LIMIT_ERROR: $msg = 'Recursion limit error'; break;
×
UNCOV
1895
                                case PREG_BAD_UTF8_ERROR: $msg = 'Bad UTF8 error'; break;
×
UNCOV
1896
                                case PREG_BAD_UTF8_OFFSET_ERROR: $msg = 'Bad UTF8 offset error'; break;
×
UNCOV
1897
                                case PREG_JIT_STACKLIMIT_ERROR: $msg = 'JIT stack limit error'; break;
×
UNCOV
1898
                                default: $msg = 'Unknown error';
×
1899
                        }
1900

1901
                        throw new \RuntimeException( 'Regular expression error: ' . $msg );
8✔
1902
                }
1903

1904
                return new static( $result );
24✔
1905
        }
1906

1907

1908
        /**
1909
         * Groups associative array elements or objects by the passed key or closure.
1910
         *
1911
         * Instead of overwriting items with the same keys like to the col() method
1912
         * does, groupBy() keeps all entries in sub-arrays. It's preserves the keys
1913
         * of the orignal map entries too.
1914
         *
1915
         * Examples:
1916
         *  $list = [
1917
         *    10 => ['aid' => 123, 'code' => 'x-abc'],
1918
         *    20 => ['aid' => 123, 'code' => 'x-def'],
1919
         *    30 => ['aid' => 456, 'code' => 'x-def']
1920
         *  ];
1921
         *  Map::from( $list )->groupBy( 'aid' );
1922
         *  Map::from( $list )->groupBy( function( $item, $key ) {
1923
         *    return substr( $item['code'], -3 );
1924
         *  } );
1925
         *  Map::from( $list )->groupBy( 'xid' );
1926
         *
1927
         * Results:
1928
         *  [
1929
         *    123 => [10 => ['aid' => 123, 'code' => 'x-abc'], 20 => ['aid' => 123, 'code' => 'x-def']],
1930
         *    456 => [30 => ['aid' => 456, 'code' => 'x-def']]
1931
         *  ]
1932
         *  [
1933
         *    'abc' => [10 => ['aid' => 123, 'code' => 'x-abc']],
1934
         *    'def' => [20 => ['aid' => 123, 'code' => 'x-def'], 30 => ['aid' => 456, 'code' => 'x-def']]
1935
         *  ]
1936
         *  [
1937
         *    '' => [
1938
         *      10 => ['aid' => 123, 'code' => 'x-abc'],
1939
         *      20 => ['aid' => 123, 'code' => 'x-def'],
1940
         *      30 => ['aid' => 456, 'code' => 'x-def']
1941
         *    ]
1942
         *  ]
1943
         *
1944
         * In case the passed key doesn't exist in one or more items, these items
1945
         * are stored in a sub-array using an empty string as key.
1946
         *
1947
         * @param  \Closure|string|int $key Closure function with (item, idx) parameters returning the key or the key itself to group by
1948
         * @return self<int|string,mixed> New map with elements grouped by the given key
1949
         */
1950
        public function groupBy( $key ) : self
1951
        {
1952
                $result = [];
32✔
1953

1954
                foreach( $this->list() as $idx => $item )
32✔
1955
                {
1956
                        if( is_callable( $key ) ) {
32✔
1957
                                $keyval = $key( $item, $idx );
8✔
1958
                        } elseif( ( is_array( $item ) || $item instanceof \ArrayAccess ) && isset( $item[$key] ) ) {
24✔
1959
                                $keyval = $item[$key];
8✔
1960
                        } elseif( is_object( $item ) && isset( $item->{$key} ) ) {
16✔
1961
                                $keyval = $item->{$key};
8✔
1962
                        } else {
1963
                                $keyval = '';
8✔
1964
                        }
1965

1966
                        $result[$keyval][$idx] = $item;
32✔
1967
                }
1968

1969
                return new static( $result );
32✔
1970
        }
1971

1972

1973
        /**
1974
         * Determines if a key or several keys exists in the map.
1975
         *
1976
         * If several keys are passed as array, all keys must exist in the map for
1977
         * TRUE to be returned.
1978
         *
1979
         * Examples:
1980
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'a' );
1981
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'b'] );
1982
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->has( 'a/b/c' );
1983
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'c' );
1984
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'c'] );
1985
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'X' );
1986
         *
1987
         * Results:
1988
         * The first three examples will return TRUE while the other ones will return FALSE
1989
         *
1990
         * This does also work for multi-dimensional arrays by passing the keys
1991
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1992
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1993
         * public properties of objects or objects implementing __isset() and __get() methods.
1994
         *
1995
         * @param array<int|string>|int|string $key Key of the requested item or list of keys
1996
         * @return bool TRUE if key or keys are available in map, FALSE if not
1997
         */
1998
        public function has( $key ) : bool
1999
        {
2000
                $list = $this->list();
24✔
2001

2002
                foreach( (array) $key as $entry )
24✔
2003
                {
2004
                        if( array_key_exists( $entry, $list ) === false
24✔
2005
                                && $this->val( $list, explode( $this->sep, (string) $entry ) ) === null
24✔
2006
                        ) {
2007
                                return false;
24✔
2008
                        }
2009
                }
2010

2011
                return true;
24✔
2012
        }
2013

2014

2015
        /**
2016
         * Executes callbacks depending on the condition.
2017
         *
2018
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2019
         * executed and their returned value is passed back within a Map object. In
2020
         * case no "then" or "else" closure is given, the method will return the same
2021
         * map object.
2022
         *
2023
         * Examples:
2024
         *  Map::from( [] )->if( strpos( 'abc', 'b' ) !== false, function( $map ) {
2025
         *    echo 'found';
2026
         *  } );
2027
         *
2028
         *  Map::from( [] )->if( function( $map ) {
2029
         *    return $map->empty();
2030
         *  }, function( $map ) {
2031
         *    echo 'then';
2032
         *  } );
2033
         *
2034
         *  Map::from( ['a'] )->if( function( $map ) {
2035
         *    return $map->empty();
2036
         *  }, function( $map ) {
2037
         *    echo 'then';
2038
         *  }, function( $map ) {
2039
         *    echo 'else';
2040
         *  } );
2041
         *
2042
         *  Map::from( ['a', 'b'] )->if( true, function( $map ) {
2043
         *    return $map->push( 'c' );
2044
         *  } );
2045
         *
2046
         *  Map::from( ['a', 'b'] )->if( false, null, function( $map ) {
2047
         *    return $map->pop();
2048
         *  } );
2049
         *
2050
         * Results:
2051
         * The first example returns "found" while the second one returns "then" and
2052
         * the third one "else". The forth one will return ['a', 'b', 'c'] while the
2053
         * fifth one will return 'b', which is turned into a map of ['b'] again.
2054
         *
2055
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2056
         * (a short form for anonymous closures) as parameters. The automatically have access
2057
         * to previously defined variables but can not modify them. Also, they can not have
2058
         * a void return type and must/will always return something. Details about
2059
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2060
         *
2061
         * @param \Closure|bool $condition Boolean or function with (map) parameter returning a boolean
2062
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2063
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2064
         * @return self<int|string,mixed> New map
2065
         */
2066
        public function if( $condition, ?\Closure $then = null, ?\Closure $else = null ) : self
2067
        {
2068
                if( $condition instanceof \Closure ) {
64✔
2069
                        $condition = $condition( $this );
16✔
2070
                }
2071

2072
                if( $condition ) {
64✔
2073
                        return $then ? static::from( $then( $this, $condition ) ) : $this;
40✔
2074
                } elseif( $else ) {
24✔
2075
                        return static::from( $else( $this, $condition ) );
24✔
2076
                }
2077

UNCOV
2078
                return $this;
×
2079
        }
2080

2081

2082
        /**
2083
         * Executes callbacks depending if the map contains elements or not.
2084
         *
2085
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2086
         * executed and their returned value is passed back within a Map object. In
2087
         * case no "then" or "else" closure is given, the method will return the same
2088
         * map object.
2089
         *
2090
         * Examples:
2091
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2092
         *    $map->push( 'b' );
2093
         *  } );
2094
         *
2095
         *  Map::from( [] )->ifAny( null, function( $map ) {
2096
         *    return $map->push( 'b' );
2097
         *  } );
2098
         *
2099
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2100
         *    return 'c';
2101
         *  } );
2102
         *
2103
         * Results:
2104
         * The first example returns a Map containing ['a', 'b'] because the the initial
2105
         * Map is not empty. The second one returns  a Map with ['b'] because the initial
2106
         * Map is empty and the "else" closure is used. The last example returns ['c']
2107
         * as new map content.
2108
         *
2109
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2110
         * (a short form for anonymous closures) as parameters. The automatically have access
2111
         * to previously defined variables but can not modify them. Also, they can not have
2112
         * a void return type and must/will always return something. Details about
2113
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2114
         *
2115
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2116
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2117
         * @return self<int|string,mixed> New map
2118
         */
2119
        public function ifAny( ?\Closure $then = null, ?\Closure $else = null ) : self
2120
        {
2121
                return $this->if( !empty( $this->list() ), $then, $else );
24✔
2122
        }
2123

2124

2125
        /**
2126
         * Executes callbacks depending if the map is empty or not.
2127
         *
2128
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2129
         * executed and their returned value is passed back within a Map object. In
2130
         * case no "then" or "else" closure is given, the method will return the same
2131
         * map object.
2132
         *
2133
         * Examples:
2134
         *  Map::from( [] )->ifEmpty( function( $map ) {
2135
         *    $map->push( 'a' );
2136
         *  } );
2137
         *
2138
         *  Map::from( ['a'] )->ifEmpty( null, function( $map ) {
2139
         *    return $map->push( 'b' );
2140
         *  } );
2141
         *
2142
         * Results:
2143
         * The first example returns a Map containing ['a'] because the the initial Map
2144
         * is empty. The second one returns  a Map with ['a', 'b'] because the initial
2145
         * Map is not empty and the "else" closure is used.
2146
         *
2147
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2148
         * (a short form for anonymous closures) as parameters. The automatically have access
2149
         * to previously defined variables but can not modify them. Also, they can not have
2150
         * a void return type and must/will always return something. Details about
2151
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2152
         *
2153
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2154
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2155
         * @return self<int|string,mixed> New map
2156
         */
2157
        public function ifEmpty( ?\Closure $then = null, ?\Closure $else = null ) : self
2158
        {
UNCOV
2159
                return $this->if( empty( $this->list() ), $then, $else );
×
2160
        }
2161

2162

2163
        /**
2164
         * Tests if all entries in the map are objects implementing the given interface.
2165
         *
2166
         * Examples:
2167
         *  Map::from( [new Map(), new Map()] )->implements( '\Countable' );
2168
         *  Map::from( [new Map(), new stdClass()] )->implements( '\Countable' );
2169
         *  Map::from( [new Map(), 123] )->implements( '\Countable' );
2170
         *  Map::from( [new Map(), 123] )->implements( '\Countable', true );
2171
         *  Map::from( [new Map(), 123] )->implements( '\Countable', '\RuntimeException' );
2172
         *
2173
         * Results:
2174
         *  The first example returns TRUE while the second and third one return FALSE.
2175
         *  The forth example will throw an UnexpectedValueException while the last one
2176
         *  throws a RuntimeException.
2177
         *
2178
         * @param string $interface Name of the interface that must be implemented
2179
         * @param \Throwable|bool $throw Passing TRUE or an exception name will throw the exception instead of returning FALSE
2180
         * @return bool TRUE if all entries implement the interface or FALSE if at least one doesn't
2181
         * @throws \UnexpectedValueException|\Throwable If one entry doesn't implement the interface
2182
         */
2183
        public function implements( string $interface, $throw = false ) : bool
2184
        {
2185
                foreach( $this->list() as $entry )
24✔
2186
                {
2187
                        if( !( $entry instanceof $interface ) )
24✔
2188
                        {
2189
                                if( $throw )
24✔
2190
                                {
2191
                                        $name = is_string( $throw ) ? $throw : '\UnexpectedValueException';
16✔
2192
                                        throw new $name( "Does not implement $interface: " . print_r( $entry, true ) );
16✔
2193
                                }
2194

2195
                                return false;
10✔
2196
                        }
2197
                }
2198

2199
                return true;
8✔
2200
        }
2201

2202

2203
        /**
2204
         * Tests if the passed element or elements are part of the map.
2205
         *
2206
         * Examples:
2207
         *  Map::from( ['a', 'b'] )->in( 'a' );
2208
         *  Map::from( ['a', 'b'] )->in( ['a', 'b'] );
2209
         *  Map::from( ['a', 'b'] )->in( 'x' );
2210
         *  Map::from( ['a', 'b'] )->in( ['a', 'x'] );
2211
         *  Map::from( ['1', '2'] )->in( 2, true );
2212
         *
2213
         * Results:
2214
         * The first and second example will return TRUE while the other ones will return FALSE
2215
         *
2216
         * @param mixed|array $element Element or elements to search for in the map
2217
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2218
         * @return bool TRUE if all elements are available in map, FALSE if not
2219
         */
2220
        public function in( $element, bool $strict = false ) : bool
2221
        {
2222
                if( !is_array( $element ) ) {
32✔
2223
                        return in_array( $element, $this->list(), $strict );
32✔
2224
                };
2225

2226
                foreach( $element as $entry )
8✔
2227
                {
2228
                        if( in_array( $entry, $this->list(), $strict ) === false ) {
8✔
2229
                                return false;
8✔
2230
                        }
2231
                }
2232

2233
                return true;
8✔
2234
        }
2235

2236

2237
        /**
2238
         * Tests if the passed element or elements are part of the map.
2239
         *
2240
         * This method is an alias for in(). For performance reasons, in() should be
2241
         * preferred because it uses one method call less than includes().
2242
         *
2243
         * @param mixed|array $element Element or elements to search for in the map
2244
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2245
         * @return bool TRUE if all elements are available in map, FALSE if not
2246
         * @see in() - Underlying method with same parameters and return value but better performance
2247
         */
2248
        public function includes( $element, bool $strict = false ) : bool
2249
        {
2250
                return $this->in( $element, $strict );
8✔
2251
        }
2252

2253

2254
        /**
2255
         * Returns the numerical index of the given key.
2256
         *
2257
         * Examples:
2258
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( '8' );
2259
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( function( $key ) {
2260
         *      return $key == '8';
2261
         *  } );
2262
         *
2263
         * Results:
2264
         * Both examples will return "1" because the value "b" is at the second position
2265
         * and the returned index is zero based so the first item has the index "0".
2266
         *
2267
         * @param \Closure|string|int $value Key to search for or function with (key) parameters return TRUE if key is found
2268
         * @return int|null Position of the found value (zero based) or NULL if not found
2269
         */
2270
        public function index( $value ) : ?int
2271
        {
2272
                if( $value instanceof \Closure )
32✔
2273
                {
2274
                        $pos = 0;
16✔
2275

2276
                        foreach( $this->list() as $key => $item )
16✔
2277
                        {
2278
                                if( $value( $key ) ) {
8✔
2279
                                        return $pos;
8✔
2280
                                }
2281

2282
                                ++$pos;
8✔
2283
                        }
2284

2285
                        return null;
8✔
2286
                }
2287

2288
                $pos = array_search( $value, array_keys( $this->list() ) );
16✔
2289
                return $pos !== false ? $pos : null;
16✔
2290
        }
2291

2292

2293
        /**
2294
         * Inserts the value or values after the given element.
2295
         *
2296
         * Examples:
2297
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAfter( 'foo', 'baz' );
2298
         *  Map::from( ['foo', 'bar'] )->insertAfter( 'foo', ['baz', 'boo'] );
2299
         *  Map::from( ['foo', 'bar'] )->insertAfter( null, 'baz' );
2300
         *
2301
         * Results:
2302
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2303
         *  ['foo', 'baz', 'boo', 'bar']
2304
         *  ['foo', 'bar', 'baz']
2305
         *
2306
         * Numerical array indexes are not preserved.
2307
         *
2308
         * @param mixed $element Element after the value is inserted
2309
         * @param mixed $value Element or list of elements to insert
2310
         * @return self<int|string,mixed> Updated map for fluid interface
2311
         */
2312
        public function insertAfter( $element, $value ) : self
2313
        {
2314
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
24✔
2315
                array_splice( $this->list(), $position + 1, 0, $this->array( $value ) );
24✔
2316

2317
                return $this;
24✔
2318
        }
2319

2320

2321
        /**
2322
         * Inserts the item at the given position in the map.
2323
         *
2324
         * Examples:
2325
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 0, 'baz' );
2326
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 1, 'baz', 'c' );
2327
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 4, 'baz' );
2328
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( -1, 'baz', 'c' );
2329
         *
2330
         * Results:
2331
         *  [0 => 'baz', 'a' => 'foo', 'b' => 'bar']
2332
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2333
         *  ['a' => 'foo', 'b' => 'bar', 'c' => 'baz']
2334
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2335
         *
2336
         * @param int $pos Position the element it should be inserted at
2337
         * @param mixed $element Element to be inserted
2338
         * @param mixed|null $key Element key or NULL to assign an integer key automatically
2339
         * @return self<int|string,mixed> Updated map for fluid interface
2340
         */
2341
        public function insertAt( int $pos, $element, $key = null ) : self
2342
        {
2343
                if( $key !== null )
40✔
2344
                {
2345
                        $list = $this->list();
16✔
2346

2347
                        $this->list = array_merge(
16✔
2348
                                array_slice( $list, 0, $pos, true ),
16✔
2349
                                [$key => $element],
16✔
2350
                                array_slice( $list, $pos, null, true )
16✔
2351
                        );
12✔
2352
                }
2353
                else
2354
                {
2355
                        array_splice( $this->list(), $pos, 0, [$element] );
24✔
2356
                }
2357

2358
                return $this;
40✔
2359
        }
2360

2361

2362
        /**
2363
         * Inserts the value or values before the given element.
2364
         *
2365
         * Examples:
2366
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertBefore( 'bar', 'baz' );
2367
         *  Map::from( ['foo', 'bar'] )->insertBefore( 'bar', ['baz', 'boo'] );
2368
         *  Map::from( ['foo', 'bar'] )->insertBefore( null, 'baz' );
2369
         *
2370
         * Results:
2371
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2372
         *  ['foo', 'baz', 'boo', 'bar']
2373
         *  ['foo', 'bar', 'baz']
2374
         *
2375
         * Numerical array indexes are not preserved.
2376
         *
2377
         * @param mixed $element Element before the value is inserted
2378
         * @param mixed $value Element or list of elements to insert
2379
         * @return self<int|string,mixed> Updated map for fluid interface
2380
         */
2381
        public function insertBefore( $element, $value ) : self
2382
        {
2383
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
24✔
2384
                array_splice( $this->list(), $position, 0, $this->array( $value ) );
24✔
2385

2386
                return $this;
24✔
2387
        }
2388

2389

2390
        /**
2391
         * Tests if the passed value or values are part of the strings in the map.
2392
         *
2393
         * Examples:
2394
         *  Map::from( ['abc'] )->inString( 'c' );
2395
         *  Map::from( ['abc'] )->inString( 'bc' );
2396
         *  Map::from( [12345] )->inString( '23' );
2397
         *  Map::from( [123.4] )->inString( 23.4 );
2398
         *  Map::from( [12345] )->inString( false );
2399
         *  Map::from( [12345] )->inString( true );
2400
         *  Map::from( [false] )->inString( false );
2401
         *  Map::from( ['abc'] )->inString( '' );
2402
         *  Map::from( [''] )->inString( false );
2403
         *  Map::from( ['abc'] )->inString( 'BC', false );
2404
         *  Map::from( ['abc', 'def'] )->inString( ['de', 'xy'] );
2405
         *  Map::from( ['abc', 'def'] )->inString( ['E', 'x'] );
2406
         *  Map::from( ['abc', 'def'] )->inString( 'E' );
2407
         *  Map::from( [23456] )->inString( true );
2408
         *  Map::from( [false] )->inString( 0 );
2409
         *
2410
         * Results:
2411
         * The first eleven examples will return TRUE while the last four will return FALSE
2412
         *
2413
         * All scalar values (bool, float, int and string) are casted to string values before
2414
         * comparing to the given value. Non-scalar values in the map are ignored.
2415
         *
2416
         * @param array|string $value Value or values to compare the map elements, will be casted to string type
2417
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
2418
         * @return bool TRUE If at least one element matches, FALSE if value is not in any string of the map
2419
         * @deprecated Use multi-byte aware strContains() instead
2420
         */
2421
        public function inString( $value, bool $case = true ) : bool
2422
        {
2423
                $fcn = $case ? 'strpos' : 'stripos';
8✔
2424

2425
                foreach( (array) $value as $val )
8✔
2426
                {
2427
                        if( (string) $val === '' ) {
8✔
2428
                                return true;
8✔
2429
                        }
2430

2431
                        foreach( $this->list() as $item )
8✔
2432
                        {
2433
                                if( is_scalar( $item ) && $fcn( (string) $item, (string) $val ) !== false ) {
8✔
2434
                                        return true;
8✔
2435
                                }
2436
                        }
2437
                }
2438

2439
                return false;
8✔
2440
        }
2441

2442

2443
        /**
2444
         * Returns an element by key and casts it to integer if possible.
2445
         *
2446
         * Examples:
2447
         *  Map::from( ['a' => true] )->int( 'a' );
2448
         *  Map::from( ['a' => '1'] )->int( 'a' );
2449
         *  Map::from( ['a' => 1.1] )->int( 'a' );
2450
         *  Map::from( ['a' => '10'] )->int( 'a' );
2451
         *  Map::from( ['a' => ['b' => ['c' => 1]]] )->int( 'a/b/c' );
2452
         *  Map::from( [] )->int( 'c', function() { return rand( 1, 1 ); } );
2453
         *  Map::from( [] )->int( 'a', 1 );
2454
         *
2455
         *  Map::from( [] )->int( 'b' );
2456
         *  Map::from( ['b' => ''] )->int( 'b' );
2457
         *  Map::from( ['b' => 'abc'] )->int( 'b' );
2458
         *  Map::from( ['b' => null] )->int( 'b' );
2459
         *  Map::from( ['b' => [1]] )->int( 'b' );
2460
         *  Map::from( ['b' => #resource] )->int( 'b' );
2461
         *  Map::from( ['b' => new \stdClass] )->int( 'b' );
2462
         *
2463
         *  Map::from( [] )->int( 'c', new \Exception( 'error' ) );
2464
         *
2465
         * Results:
2466
         * The first seven examples will return 1 while the 8th to 14th example
2467
         * returns 0. The last example will throw an exception.
2468
         *
2469
         * This does also work for multi-dimensional arrays by passing the keys
2470
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2471
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2472
         * public properties of objects or objects implementing __isset() and __get() methods.
2473
         *
2474
         * @param int|string $key Key or path to the requested item
2475
         * @param mixed $default Default value if key isn't found (will be casted to integer)
2476
         * @return int Value from map or default value
2477
         */
2478
        public function int( $key, $default = 0 ) : int
2479
        {
2480
                return (int) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
24✔
2481
        }
2482

2483

2484
        /**
2485
         * Returns all values in a new map that are available in both, the map and the given elements.
2486
         *
2487
         * Examples:
2488
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersect( ['bar'] );
2489
         *
2490
         * Results:
2491
         *  ['b' => 'bar']
2492
         *
2493
         * If a callback is passed, the given function will be used to compare the values.
2494
         * The function must accept two parameters (value A and B) and must return
2495
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2496
         * greater than value B. Both, a method name and an anonymous function can be passed:
2497
         *
2498
         *  Map::from( [0 => 'a'] )->intersect( [0 => 'A'], 'strcasecmp' );
2499
         *  Map::from( ['b' => 'a'] )->intersect( ['B' => 'A'], 'strcasecmp' );
2500
         *  Map::from( ['b' => 'a'] )->intersect( ['c' => 'A'], function( $valA, $valB ) {
2501
         *      return strtolower( $valA ) <=> strtolower( $valB );
2502
         *  } );
2503
         *
2504
         * All examples will return a map containing ['a'] because both contain the same
2505
         * values when compared case insensitive.
2506
         *
2507
         * The keys are preserved using this method.
2508
         *
2509
         * @param iterable<int|string,mixed> $elements List of elements
2510
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2511
         * @return self<int|string,mixed> New map
2512
         */
2513
        public function intersect( iterable $elements, ?callable $callback = null ) : self
2514
        {
2515
                $list = $this->list();
16✔
2516
                $elements = $this->array( $elements );
16✔
2517

2518
                if( $callback ) {
16✔
2519
                        return new static( array_uintersect( $list, $elements, $callback ) );
8✔
2520
                }
2521

2522
                return new static( array_intersect( $list, $elements ) );
8✔
2523
        }
2524

2525

2526
        /**
2527
         * Returns all values in a new map that are available in both, the map and the given elements while comparing the keys too.
2528
         *
2529
         * Examples:
2530
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectAssoc( new Map( ['foo', 'b' => 'bar'] ) );
2531
         *
2532
         * Results:
2533
         *  ['a' => 'foo']
2534
         *
2535
         * If a callback is passed, the given function will be used to compare the values.
2536
         * The function must accept two parameters (value A and B) and must return
2537
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2538
         * greater than value B. Both, a method name and an anonymous function can be passed:
2539
         *
2540
         *  Map::from( [0 => 'a'] )->intersectAssoc( [0 => 'A'], 'strcasecmp' );
2541
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['B' => 'A'], 'strcasecmp' );
2542
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['c' => 'A'], function( $valA, $valB ) {
2543
         *      return strtolower( $valA ) <=> strtolower( $valB );
2544
         *  } );
2545
         *
2546
         * The first example will return [0 => 'a'] because both contain the same
2547
         * values when compared case insensitive. The second and third example will return
2548
         * an empty map because the keys doesn't match ("b" vs. "B" and "b" vs. "c").
2549
         *
2550
         * The keys are preserved using this method.
2551
         *
2552
         * @param iterable<int|string,mixed> $elements List of elements
2553
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2554
         * @return self<int|string,mixed> New map
2555
         */
2556
        public function intersectAssoc( iterable $elements, ?callable $callback = null ) : self
2557
        {
2558
                $elements = $this->array( $elements );
40✔
2559

2560
                if( $callback ) {
40✔
2561
                        return new static( array_uintersect_assoc( $this->list(), $elements, $callback ) );
8✔
2562
                }
2563

2564
                return new static( array_intersect_assoc( $this->list(), $elements ) );
32✔
2565
        }
2566

2567

2568
        /**
2569
         * Returns all values in a new map that are available in both, the map and the given elements by comparing the keys only.
2570
         *
2571
         * Examples:
2572
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectKeys( new Map( ['foo', 'b' => 'baz'] ) );
2573
         *
2574
         * Results:
2575
         *  ['b' => 'bar']
2576
         *
2577
         * If a callback is passed, the given function will be used to compare the keys.
2578
         * The function must accept two parameters (key A and B) and must return
2579
         * -1 if key A is smaller than key B, 0 if both are equal and 1 if key A is
2580
         * greater than key B. Both, a method name and an anonymous function can be passed:
2581
         *
2582
         *  Map::from( [0 => 'a'] )->intersectKeys( [0 => 'A'], 'strcasecmp' );
2583
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['B' => 'X'], 'strcasecmp' );
2584
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['c' => 'a'], function( $keyA, $keyB ) {
2585
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
2586
         *  } );
2587
         *
2588
         * The first example will return a map with [0 => 'a'] and the second one will
2589
         * return a map with ['b' => 'a'] because both contain the same keys when compared
2590
         * case insensitive. The third example will return an empty map because the keys
2591
         * doesn't match ("b" vs. "c").
2592
         *
2593
         * The keys are preserved using this method.
2594
         *
2595
         * @param iterable<int|string,mixed> $elements List of elements
2596
         * @param  callable|null $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
2597
         * @return self<int|string,mixed> New map
2598
         */
2599
        public function intersectKeys( iterable $elements, ?callable $callback = null ) : self
2600
        {
2601
                $elements = $this->array( $elements );
24✔
2602

2603
                if( $callback ) {
24✔
2604
                        return new static( array_intersect_ukey( $this->list(), $elements, $callback ) );
8✔
2605
                }
2606

2607
                return new static( array_intersect_key( $this->list(), $elements ) );
16✔
2608
        }
2609

2610

2611
        /**
2612
         * Tests if the map consists of the same keys and values
2613
         *
2614
         * Examples:
2615
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'] );
2616
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'], true );
2617
         *  Map::from( [1, 2] )->is( ['1', '2'] );
2618
         *
2619
         * Results:
2620
         *  The first example returns TRUE while the second and third one returns FALSE
2621
         *
2622
         * @param iterable<int|string,mixed> $list List of key/value pairs to compare with
2623
         * @param bool $strict TRUE for comparing order of elements too, FALSE for key/values only
2624
         * @return bool TRUE if given list is equal, FALSE if not
2625
         */
2626
        public function is( iterable $list, bool $strict = false ) : bool
2627
        {
2628
                $list = $this->array( $list );
24✔
2629

2630
                if( $strict ) {
24✔
2631
                        return $this->list() === $list;
16✔
2632
                }
2633

2634
                return $this->list() == $list;
8✔
2635
        }
2636

2637

2638
        /**
2639
         * Determines if the map is empty or not.
2640
         *
2641
         * Examples:
2642
         *  Map::from( [] )->isEmpty();
2643
         *  Map::from( ['a'] )->isEmpty();
2644
         *
2645
         * Results:
2646
         *  The first example returns TRUE while the second returns FALSE
2647
         *
2648
         * The method is equivalent to empty().
2649
         *
2650
         * @return bool TRUE if map is empty, FALSE if not
2651
         */
2652
        public function isEmpty() : bool
2653
        {
2654
                return empty( $this->list() );
32✔
2655
        }
2656

2657

2658
        /**
2659
         * Checks if the map contains a list of subsequentially numbered keys.
2660
         *
2661
         * Examples:
2662
         * Map::from( [] )->isList();
2663
         * Map::from( [1, 3, 2] )->isList();
2664
         * Map::from( [0 => 1, 1 => 2, 2 => 3] )->isList();
2665
         * Map::from( [1 => 1, 2 => 2, 3 => 3] )->isList();
2666
         * Map::from( [0 => 1, 2 => 2, 3 => 3] )->isList();
2667
         * Map::from( ['a' => 1, 1 => 2, 'c' => 3] )->isList();
2668
         *
2669
         * Results:
2670
         * The first three examples return TRUE while the last three return FALSE
2671
         *
2672
         * @return bool TRUE if the map is a list, FALSE if not
2673
         */
2674
        public function isList() : bool
2675
        {
2676
                $i = -1;
8✔
2677

2678
                foreach( $this->list() as $k => $v )
8✔
2679
                {
2680
                        if( $k !== ++$i ) {
8✔
2681
                                return false;
8✔
2682
                        }
2683
                }
2684

2685
                return true;
8✔
2686
        }
2687

2688

2689
        /**
2690
         * Determines if all entries are numeric values.
2691
         *
2692
         * Examples:
2693
         *  Map::from( [] )->isNumeric();
2694
         *  Map::from( [1] )->isNumeric();
2695
         *  Map::from( [1.1] )->isNumeric();
2696
         *  Map::from( [010] )->isNumeric();
2697
         *  Map::from( [0x10] )->isNumeric();
2698
         *  Map::from( [0b10] )->isNumeric();
2699
         *  Map::from( ['010'] )->isNumeric();
2700
         *  Map::from( ['10'] )->isNumeric();
2701
         *  Map::from( ['10.1'] )->isNumeric();
2702
         *  Map::from( [' 10 '] )->isNumeric();
2703
         *  Map::from( ['10e2'] )->isNumeric();
2704
         *  Map::from( ['0b10'] )->isNumeric();
2705
         *  Map::from( ['0x10'] )->isNumeric();
2706
         *  Map::from( ['null'] )->isNumeric();
2707
         *  Map::from( [null] )->isNumeric();
2708
         *  Map::from( [true] )->isNumeric();
2709
         *  Map::from( [[]] )->isNumeric();
2710
         *  Map::from( [''] )->isNumeric();
2711
         *
2712
         * Results:
2713
         *  The first eleven examples return TRUE while the last seven return FALSE
2714
         *
2715
         * @return bool TRUE if all map entries are numeric values, FALSE if not
2716
         */
2717
        public function isNumeric() : bool
2718
        {
2719
                foreach( $this->list() as $val )
8✔
2720
                {
2721
                        if( !is_numeric( $val ) ) {
8✔
2722
                                return false;
8✔
2723
                        }
2724
                }
2725

2726
                return true;
8✔
2727
        }
2728

2729

2730
        /**
2731
         * Determines if all entries are objects.
2732
         *
2733
         * Examples:
2734
         *  Map::from( [] )->isObject();
2735
         *  Map::from( [new stdClass] )->isObject();
2736
         *  Map::from( [1] )->isObject();
2737
         *
2738
         * Results:
2739
         *  The first two examples return TRUE while the last one return FALSE
2740
         *
2741
         * @return bool TRUE if all map entries are objects, FALSE if not
2742
         */
2743
        public function isObject() : bool
2744
        {
2745
                foreach( $this->list() as $val )
8✔
2746
                {
2747
                        if( !is_object( $val ) ) {
8✔
2748
                                return false;
8✔
2749
                        }
2750
                }
2751

2752
                return true;
8✔
2753
        }
2754

2755

2756
        /**
2757
         * Determines if all entries are scalar values.
2758
         *
2759
         * Examples:
2760
         *  Map::from( [] )->isScalar();
2761
         *  Map::from( [1] )->isScalar();
2762
         *  Map::from( [1.1] )->isScalar();
2763
         *  Map::from( ['abc'] )->isScalar();
2764
         *  Map::from( [true, false] )->isScalar();
2765
         *  Map::from( [new stdClass] )->isScalar();
2766
         *  Map::from( [#resource] )->isScalar();
2767
         *  Map::from( [null] )->isScalar();
2768
         *  Map::from( [[1]] )->isScalar();
2769
         *
2770
         * Results:
2771
         *  The first five examples return TRUE while the others return FALSE
2772
         *
2773
         * @return bool TRUE if all map entries are scalar values, FALSE if not
2774
         */
2775
        public function isScalar() : bool
2776
        {
2777
                foreach( $this->list() as $val )
8✔
2778
                {
2779
                        if( !is_scalar( $val ) ) {
8✔
2780
                                return false;
8✔
2781
                        }
2782
                }
2783

2784
                return true;
8✔
2785
        }
2786

2787

2788
        /**
2789
         * Determines if all entries are string values.
2790
         *
2791
         * Examples:
2792
         *  Map::from( ['abc'] )->isString();
2793
         *  Map::from( [] )->isString();
2794
         *  Map::from( [1] )->isString();
2795
         *  Map::from( [1.1] )->isString();
2796
         *  Map::from( [true, false] )->isString();
2797
         *  Map::from( [new stdClass] )->isString();
2798
         *  Map::from( [#resource] )->isString();
2799
         *  Map::from( [null] )->isString();
2800
         *  Map::from( [[1]] )->isString();
2801
         *
2802
         * Results:
2803
         *  The first two examples return TRUE while the others return FALSE
2804
         *
2805
         * @return bool TRUE if all map entries are string values, FALSE if not
2806
         */
2807
        public function isString() : bool
2808
        {
2809
                foreach( $this->list() as $val )
8✔
2810
                {
2811
                        if( !is_string( $val ) ) {
8✔
2812
                                return false;
8✔
2813
                        }
2814
                }
2815

2816
                return true;
8✔
2817
        }
2818

2819

2820
        /**
2821
         * Concatenates the string representation of all elements.
2822
         *
2823
         * Objects that implement __toString() does also work, otherwise (and in case
2824
         * of arrays) a PHP notice is generated. NULL and FALSE values are treated as
2825
         * empty strings.
2826
         *
2827
         * Examples:
2828
         *  Map::from( ['a', 'b', false] )->join();
2829
         *  Map::from( ['a', 'b', null, false] )->join( '-' );
2830
         *
2831
         * Results:
2832
         * The first example will return "ab" while the second one will return "a-b--"
2833
         *
2834
         * @param string $glue Character or string added between elements
2835
         * @return string String of concatenated map elements
2836
         */
2837
        public function join( string $glue = '' ) : string
2838
        {
2839
                return implode( $glue, $this->list() );
8✔
2840
        }
2841

2842

2843
        /**
2844
         * Specifies the data which should be serialized to JSON by json_encode().
2845
         *
2846
         * Examples:
2847
         *   json_encode( Map::from( ['a', 'b'] ) );
2848
         *   json_encode( Map::from( ['a' => 0, 'b' => 1] ) );
2849
         *
2850
         * Results:
2851
         *   ["a", "b"]
2852
         *   {"a":0,"b":1}
2853
         *
2854
         * @return array<int|string,mixed> Data to serialize to JSON
2855
         */
2856
        #[\ReturnTypeWillChange]
2857
        public function jsonSerialize()
2858
        {
2859
                return $this->list = $this->array( $this->list );
8✔
2860
        }
2861

2862

2863
        /**
2864
         * Returns the keys of the all elements in a new map object.
2865
         *
2866
         * Examples:
2867
         *  Map::from( ['a', 'b'] );
2868
         *  Map::from( ['a' => 0, 'b' => 1] );
2869
         *
2870
         * Results:
2871
         * The first example returns a map containing [0, 1] while the second one will
2872
         * return a map with ['a', 'b'].
2873
         *
2874
         * @return self<int|string,mixed> New map
2875
         */
2876
        public function keys() : self
2877
        {
2878
                return new static( array_keys( $this->list() ) );
8✔
2879
        }
2880

2881

2882
        /**
2883
         * Sorts the elements by their keys in reverse order.
2884
         *
2885
         * Examples:
2886
         *  Map::from( ['b' => 0, 'a' => 1] )->krsort();
2887
         *  Map::from( [1 => 'a', 0 => 'b'] )->krsort();
2888
         *
2889
         * Results:
2890
         *  ['a' => 1, 'b' => 0]
2891
         *  [0 => 'b', 1 => 'a']
2892
         *
2893
         * The parameter modifies how the keys are compared. Possible values are:
2894
         * - SORT_REGULAR : compare elements normally (don't change types)
2895
         * - SORT_NUMERIC : compare elements numerically
2896
         * - SORT_STRING : compare elements as strings
2897
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
2898
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
2899
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
2900
         *
2901
         * The keys are preserved using this method and no new map is created.
2902
         *
2903
         * @param int $options Sort options for krsort()
2904
         * @return self<int|string,mixed> Updated map for fluid interface
2905
         */
2906
        public function krsort( int $options = SORT_REGULAR ) : self
2907
        {
2908
                krsort( $this->list(), $options );
24✔
2909
                return $this;
24✔
2910
        }
2911

2912

2913
        /**
2914
         * Sorts a copy of the elements by their keys in reverse order.
2915
         *
2916
         * Examples:
2917
         *  Map::from( ['b' => 0, 'a' => 1] )->krsorted();
2918
         *  Map::from( [1 => 'a', 0 => 'b'] )->krsorted();
2919
         *
2920
         * Results:
2921
         *  ['a' => 1, 'b' => 0]
2922
         *  [0 => 'b', 1 => 'a']
2923
         *
2924
         * The parameter modifies how the keys are compared. Possible values are:
2925
         * - SORT_REGULAR : compare elements normally (don't change types)
2926
         * - SORT_NUMERIC : compare elements numerically
2927
         * - SORT_STRING : compare elements as strings
2928
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
2929
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
2930
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
2931
         *
2932
         * The keys are preserved using this method and a new map is created.
2933
         *
2934
         * @param int $options Sort options for krsort()
2935
         * @return self<int|string,mixed> Updated map for fluid interface
2936
         */
2937
        public function krsorted( int $options = SORT_REGULAR ) : self
2938
        {
2939
                return ( clone $this )->krsort();
8✔
2940
        }
2941

2942

2943
        /**
2944
         * Sorts the elements by their keys.
2945
         *
2946
         * Examples:
2947
         *  Map::from( ['b' => 0, 'a' => 1] )->ksort();
2948
         *  Map::from( [1 => 'a', 0 => 'b'] )->ksort();
2949
         *
2950
         * Results:
2951
         *  ['a' => 1, 'b' => 0]
2952
         *  [0 => 'b', 1 => 'a']
2953
         *
2954
         * The parameter modifies how the keys are compared. Possible values are:
2955
         * - SORT_REGULAR : compare elements normally (don't change types)
2956
         * - SORT_NUMERIC : compare elements numerically
2957
         * - SORT_STRING : compare elements as strings
2958
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
2959
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
2960
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
2961
         *
2962
         * The keys are preserved using this method and no new map is created.
2963
         *
2964
         * @param int $options Sort options for ksort()
2965
         * @return self<int|string,mixed> Updated map for fluid interface
2966
         */
2967
        public function ksort( int $options = SORT_REGULAR ) : self
2968
        {
2969
                ksort( $this->list(), $options );
24✔
2970
                return $this;
24✔
2971
        }
2972

2973

2974
        /**
2975
         * Sorts a copy of the elements by their keys.
2976
         *
2977
         * Examples:
2978
         *  Map::from( ['b' => 0, 'a' => 1] )->ksorted();
2979
         *  Map::from( [1 => 'a', 0 => 'b'] )->ksorted();
2980
         *
2981
         * Results:
2982
         *  ['a' => 1, 'b' => 0]
2983
         *  [0 => 'b', 1 => 'a']
2984
         *
2985
         * The parameter modifies how the keys are compared. Possible values are:
2986
         * - SORT_REGULAR : compare elements normally (don't change types)
2987
         * - SORT_NUMERIC : compare elements numerically
2988
         * - SORT_STRING : compare elements as strings
2989
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
2990
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
2991
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
2992
         *
2993
         * The keys are preserved using this method and no new map is created.
2994
         *
2995
         * @param int $options Sort options for ksort()
2996
         * @return self<int|string,mixed> Updated map for fluid interface
2997
         */
2998
        public function ksorted( int $options = SORT_REGULAR ) : self
2999
        {
3000
                return ( clone $this )->ksort();
8✔
3001
        }
3002

3003

3004
        /**
3005
         * Returns the last element from the map.
3006
         *
3007
         * Examples:
3008
         *  Map::from( ['a', 'b'] )->last();
3009
         *  Map::from( [] )->last( 'x' );
3010
         *  Map::from( [] )->last( new \Exception( 'error' ) );
3011
         *  Map::from( [] )->last( function() { return rand(); } );
3012
         *
3013
         * Results:
3014
         * The first example will return 'b' and the second one 'x'. The third example
3015
         * will throw the exception passed if the map contains no elements. In the
3016
         * fourth example, a random value generated by the closure function will be
3017
         * returned.
3018
         *
3019
         * @param mixed $default Default value or exception if the map contains no elements
3020
         * @return mixed Last value of map, (generated) default value or an exception
3021
         */
3022
        public function last( $default = null )
3023
        {
3024
                if( ( $value = end( $this->list() ) ) !== false ) {
40✔
3025
                        return $value;
16✔
3026
                }
3027

3028
                if( $default instanceof \Closure ) {
24✔
3029
                        return $default();
8✔
3030
                }
3031

3032
                if( $default instanceof \Throwable ) {
16✔
3033
                        throw $default;
8✔
3034
                }
3035

3036
                return $default;
8✔
3037
        }
3038

3039

3040
        /**
3041
         * Returns the last key from the map.
3042
         *
3043
         * Examples:
3044
         *  Map::from( ['a' => 1, 'b' => 2] )->lastKey();
3045
         *  Map::from( [] )->lastKey();
3046
         *
3047
         * Results:
3048
         * The first example will return 'b' and the second one NULL.
3049
         *
3050
         * @return mixed Last key of map or NULL if empty
3051
         */
3052
        public function lastKey()
3053
        {
3054
                $list = $this->list();
16✔
3055

3056
                if( function_exists( 'array_key_last' ) ) {
16✔
3057
                        return array_key_last( $list );
16✔
3058
                }
3059

UNCOV
3060
                end( $list );
×
UNCOV
3061
                return key( $list );
×
3062
        }
3063

3064

3065
        /**
3066
         * Removes the passed characters from the left of all strings.
3067
         *
3068
         * Examples:
3069
         *  Map::from( [" abc\n", "\tcde\r\n"] )->ltrim();
3070
         *  Map::from( ["a b c", "cbxa"] )->ltrim( 'abc' );
3071
         *
3072
         * Results:
3073
         * The first example will return ["abc\n", "cde\r\n"] while the second one will return [" b c", "xa"].
3074
         *
3075
         * @param string $chars List of characters to trim
3076
         * @return self<int|string,mixed> Updated map for fluid interface
3077
         */
3078
        public function ltrim( string $chars = " \n\r\t\v\x00" ) : self
3079
        {
3080
                foreach( $this->list() as &$entry )
8✔
3081
                {
3082
                        if( is_string( $entry ) ) {
8✔
3083
                                $entry = ltrim( $entry, $chars );
8✔
3084
                        }
3085
                }
3086

3087
                return $this;
8✔
3088
        }
3089

3090

3091
        /**
3092
         * Maps new values to the existing keys using the passed function and returns a new map for the result.
3093
         *
3094
         * Examples:
3095
         *  Map::from( ['a' => 2, 'b' => 4] )->map( function( $value, $key ) {
3096
         *      return $value * 2;
3097
         *  } );
3098
         *
3099
         * Results:
3100
         *  ['a' => 4, 'b' => 8]
3101
         *
3102
         * The keys are preserved using this method.
3103
         *
3104
         * @param callable $callback Function with (value, key) parameters and returns computed result
3105
         * @return self<int|string,mixed> New map with the original keys and the computed values
3106
         * @see rekey() - Changes the keys according to the passed function
3107
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
3108
         */
3109
        public function map( callable $callback ) : self
3110
        {
3111
                $list = $this->list();
8✔
3112
                $keys = array_keys( $list );
8✔
3113
                $elements = array_map( $callback, $list, $keys );
8✔
3114

3115
                return new static( array_combine( $keys, $elements ) ?: [] );
8✔
3116
        }
3117

3118

3119
        /**
3120
         * Returns the maximum value of all elements.
3121
         *
3122
         * Examples:
3123
         *  Map::from( [1, 3, 2, 5, 4] )->max()
3124
         *  Map::from( ['bar', 'foo', 'baz'] )->max()
3125
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->max( 'p' )
3126
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( 'i/p' )
3127
         *  Map::from( [50, 10, 30] )->max( fn( $val, $key ) => $key > 0 )
3128
         *
3129
         * Results:
3130
         * The first line will return "5", the second one "foo" and the third/fourth
3131
         * one return both 50 while the last one will return 30.
3132
         *
3133
         * This does also work for multi-dimensional arrays by passing the keys
3134
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3135
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3136
         * public properties of objects or objects implementing __isset() and __get() methods.
3137
         *
3138
         * Be careful comparing elements of different types because this can have
3139
         * unpredictable results due to the PHP comparison rules:
3140
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3141
         *
3142
         * @param Closure|string|null $col Closure, key or path to the value of the nested array or object
3143
         * @return mixed Maximum value or NULL if there are no elements in the map
3144
         */
3145
        public function max( $col = null )
3146
        {
3147
                if( $col instanceof \Closure ) {
32✔
3148
                        $vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
8✔
3149
                } elseif( is_string( $col ) ) {
24✔
3150
                        $vals = $this->col( $col )->toArray();
8✔
3151
                } elseif( is_null( $col ) ) {
16✔
3152
                        $vals = $this->list();
16✔
3153
                } else {
UNCOV
3154
                        throw new \InvalidArgumentException( 'Parameter is no closure or string' );
×
3155
                }
3156

3157
                return !empty( $vals ) ? max( $vals ) : null;
32✔
3158
        }
3159

3160

3161
        /**
3162
         * Merges the map with the given elements without returning a new map.
3163
         *
3164
         * Elements with the same non-numeric keys will be overwritten, elements
3165
         * with the same numeric keys will be added.
3166
         *
3167
         * Examples:
3168
         *  Map::from( ['a', 'b'] )->merge( ['b', 'c'] );
3169
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6] );
3170
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6], true );
3171
         *
3172
         * Results:
3173
         *  ['a', 'b', 'b', 'c']
3174
         *  ['a' => 1, 'b' => 4, 'c' => 6]
3175
         *  ['a' => 1, 'b' => [2, 4], 'c' => 6]
3176
         *
3177
         * The method is similar to replace() but doesn't replace elements with
3178
         * the same numeric keys. If you want to be sure that all passed elements
3179
         * are added without replacing existing ones, use concat() instead.
3180
         *
3181
         * The keys are preserved using this method.
3182
         *
3183
         * @param iterable<int|string,mixed> $elements List of elements
3184
         * @param bool $recursive TRUE to merge nested arrays too, FALSE for first level elements only
3185
         * @return self<int|string,mixed> Updated map for fluid interface
3186
         */
3187
        public function merge( iterable $elements, bool $recursive = false ) : self
3188
        {
3189
                if( $recursive ) {
24✔
3190
                        $this->list = array_merge_recursive( $this->list(), $this->array( $elements ) );
8✔
3191
                } else {
3192
                        $this->list = array_merge( $this->list(), $this->array( $elements ) );
16✔
3193
                }
3194

3195
                return $this;
24✔
3196
        }
3197

3198

3199
        /**
3200
         * Returns the minimum value of all elements.
3201
         *
3202
         * Examples:
3203
         *  Map::from( [2, 3, 1, 5, 4] )->min()
3204
         *  Map::from( ['baz', 'foo', 'bar'] )->min()
3205
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->min( 'p' )
3206
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->min( 'i/p' )
3207
         *  Map::from( [10, 50, 30] )->min( fn( $val, $key ) => $key > 0 )
3208
         *
3209
         * Results:
3210
         * The first line will return "1", the second one "bar", the third one
3211
         * 10, the forth and last one 30.
3212
         *
3213
         * This does also work for multi-dimensional arrays by passing the keys
3214
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3215
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3216
         * public properties of objects or objects implementing __isset() and __get() methods.
3217
         *
3218
         * Be careful comparing elements of different types because this can have
3219
         * unpredictable results due to the PHP comparison rules:
3220
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3221
         *
3222
         * @param Closure|string|null $key Closure, key or path to the value of the nested array or object
3223
         * @return mixed Minimum value or NULL if there are no elements in the map
3224
         */
3225
        public function min( $col = null )
3226
        {
3227
                if( $col instanceof \Closure ) {
32✔
3228
                        $vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
8✔
3229
                } elseif( is_string( $col ) ) {
24✔
3230
                        $vals = $this->col( $col )->toArray();
8✔
3231
                } elseif( is_null( $col ) ) {
16✔
3232
                        $vals = $this->list();
16✔
3233
                } else {
UNCOV
3234
                        throw new \InvalidArgumentException( 'Parameter is no closure or string' );
×
3235
                }
3236

3237
                return !empty( $vals ) ? min( $vals ) : null;
32✔
3238
        }
3239

3240

3241
        /**
3242
         * Tests if none of the elements are part of the map.
3243
         *
3244
         * Examples:
3245
         *  Map::from( ['a', 'b'] )->none( 'x' );
3246
         *  Map::from( ['a', 'b'] )->none( ['x', 'y'] );
3247
         *  Map::from( ['1', '2'] )->none( 2, true );
3248
         *  Map::from( ['a', 'b'] )->none( 'a' );
3249
         *  Map::from( ['a', 'b'] )->none( ['a', 'b'] );
3250
         *  Map::from( ['a', 'b'] )->none( ['a', 'x'] );
3251
         *
3252
         * Results:
3253
         * The first three examples will return TRUE while the other ones will return FALSE
3254
         *
3255
         * @param mixed|array $element Element or elements to search for in the map
3256
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
3257
         * @return bool TRUE if none of the elements is part of the map, FALSE if at least one is
3258
         */
3259
        public function none( $element, bool $strict = false ) : bool
3260
        {
3261
                $list = $this->list();
8✔
3262

3263
                if( !is_array( $element ) ) {
8✔
3264
                        return !in_array( $element, $list, $strict );
8✔
3265
                };
3266

3267
                foreach( $element as $entry )
8✔
3268
                {
3269
                        if( in_array( $entry, $list, $strict ) === true ) {
8✔
3270
                                return false;
8✔
3271
                        }
3272
                }
3273

3274
                return true;
8✔
3275
        }
3276

3277

3278
        /**
3279
         * Returns every nth element from the map.
3280
         *
3281
         * Examples:
3282
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2 );
3283
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2, 1 );
3284
         *
3285
         * Results:
3286
         *  ['a', 'c', 'e']
3287
         *  ['b', 'd', 'f']
3288
         *
3289
         * @param int $step Step width
3290
         * @param int $offset Number of element to start from (0-based)
3291
         * @return self<int|string,mixed> New map
3292
         */
3293
        public function nth( int $step, int $offset = 0 ) : self
3294
        {
3295
                if( $step < 1 ) {
24✔
3296
                        throw new \InvalidArgumentException( 'Step width must be greater than zero' );
8✔
3297
                }
3298

3299
                if( $step === 1 ) {
16✔
3300
                        return clone $this;
8✔
3301
                }
3302

3303
                $result = [];
8✔
3304
                $list = $this->list();
8✔
3305

3306
                while( !empty( $pair = array_slice( $list, $offset, 1, true ) ) )
8✔
3307
                {
3308
                        $result += $pair;
8✔
3309
                        $offset += $step;
8✔
3310
                }
3311

3312
                return new static( $result );
8✔
3313
        }
3314

3315

3316
        /**
3317
         * Determines if an element exists at an offset.
3318
         *
3319
         * Examples:
3320
         *  $map = Map::from( ['a' => 1, 'b' => 3, 'c' => null] );
3321
         *  isset( $map['b'] );
3322
         *  isset( $map['c'] );
3323
         *  isset( $map['d'] );
3324
         *
3325
         * Results:
3326
         *  The first isset() will return TRUE while the second and third one will return FALSE
3327
         *
3328
         * @param int|string $key Key to check for
3329
         * @return bool TRUE if key exists, FALSE if not
3330
         */
3331
        public function offsetExists( $key ) : bool
3332
        {
3333
                return isset( $this->list()[$key] );
56✔
3334
        }
3335

3336

3337
        /**
3338
         * Returns an element at a given offset.
3339
         *
3340
         * Examples:
3341
         *  $map = Map::from( ['a' => 1, 'b' => 3] );
3342
         *  $map['b'];
3343
         *
3344
         * Results:
3345
         *  $map['b'] will return 3
3346
         *
3347
         * @param int|string $key Key to return the element for
3348
         * @return mixed Value associated to the given key
3349
         */
3350
        #[\ReturnTypeWillChange]
3351
        public function offsetGet( $key )
3352
        {
3353
                return $this->list()[$key] ?? null;
40✔
3354
        }
3355

3356

3357
        /**
3358
         * Sets the element at a given offset.
3359
         *
3360
         * Examples:
3361
         *  $map = Map::from( ['a' => 1] );
3362
         *  $map['b'] = 2;
3363
         *  $map[0] = 4;
3364
         *
3365
         * Results:
3366
         *  ['a' => 1, 'b' => 2, 0 => 4]
3367
         *
3368
         * @param int|string|null $key Key to set the element for or NULL to append value
3369
         * @param mixed $value New value set for the key
3370
         */
3371
        public function offsetSet( $key, $value ) : void
3372
        {
3373
                if( $key !== null ) {
24✔
3374
                        $this->list()[$key] = $value;
16✔
3375
                } else {
3376
                        $this->list()[] = $value;
16✔
3377
                }
3378
        }
6✔
3379

3380

3381
        /**
3382
         * Unsets the element at a given offset.
3383
         *
3384
         * Examples:
3385
         *  $map = Map::from( ['a' => 1] );
3386
         *  unset( $map['a'] );
3387
         *
3388
         * Results:
3389
         *  The map will be empty
3390
         *
3391
         * @param int|string $key Key for unsetting the item
3392
         */
3393
        public function offsetUnset( $key ) : void
3394
        {
3395
                unset( $this->list()[$key] );
16✔
3396
        }
4✔
3397

3398

3399
        /**
3400
         * Returns a new map with only those elements specified by the given keys.
3401
         *
3402
         * Examples:
3403
         *  Map::from( ['a' => 1, 0 => 'b'] )->only( 'a' );
3404
         *  Map::from( ['a' => 1, 0 => 'b', 1 => 'c'] )->only( [0, 1] );
3405
         *
3406
         * Results:
3407
         *  ['a' => 1]
3408
         *  [0 => 'b', 1 => 'c']
3409
         *
3410
         * The keys are preserved using this method.
3411
         *
3412
         * @param iterable<mixed>|array<mixed>|string|int $keys Keys of the elements that should be returned
3413
         * @return self<int|string,mixed> New map with only the elements specified by the keys
3414
         */
3415
        public function only( $keys ) : self
3416
        {
3417
                return $this->intersectKeys( array_flip( $this->array( $keys ) ) );
8✔
3418
        }
3419

3420

3421
        /**
3422
         * Returns a new map with elements ordered by the passed keys.
3423
         *
3424
         * If there are less keys passed than available in the map, the remaining
3425
         * elements are removed. Otherwise, if keys are passed that are not in the
3426
         * map, they will be also available in the returned map but their value is
3427
         * NULL.
3428
         *
3429
         * Examples:
3430
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 'a'] );
3431
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 2] );
3432
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1] );
3433
         *
3434
         * Results:
3435
         *  [0 => 'b', 1 => 'c', 'a' => 1]
3436
         *  [0 => 'b', 1 => 'c', 2 => null]
3437
         *  [0 => 'b', 1 => 'c']
3438
         *
3439
         * The keys are preserved using this method.
3440
         *
3441
         * @param iterable<mixed> $keys Keys of the elements in the required order
3442
         * @return self<int|string,mixed> New map with elements ordered by the passed keys
3443
         */
3444
        public function order( iterable $keys ) : self
3445
        {
3446
                $result = [];
8✔
3447
                $list = $this->list();
8✔
3448

3449
                foreach( $keys as $key ) {
8✔
3450
                        $result[$key] = $list[$key] ?? null;
8✔
3451
                }
3452

3453
                return new static( $result );
8✔
3454
        }
3455

3456

3457
        /**
3458
         * Fill up to the specified length with the given value
3459
         *
3460
         * In case the given number is smaller than the number of element that are
3461
         * already in the list, the map is unchanged. If the size is positive, the
3462
         * new elements are padded on the right, if it's negative then the elements
3463
         * are padded on the left.
3464
         *
3465
         * Examples:
3466
         *  Map::from( [1, 2, 3] )->pad( 5 );
3467
         *  Map::from( [1, 2, 3] )->pad( -5 );
3468
         *  Map::from( [1, 2, 3] )->pad( 5, '0' );
3469
         *  Map::from( [1, 2, 3] )->pad( 2 );
3470
         *  Map::from( [10 => 1, 20 => 2] )->pad( 3 );
3471
         *  Map::from( ['a' => 1, 'b' => 2] )->pad( 3, 3 );
3472
         *
3473
         * Results:
3474
         *  [1, 2, 3, null, null]
3475
         *  [null, null, 1, 2, 3]
3476
         *  [1, 2, 3, '0', '0']
3477
         *  [1, 2, 3]
3478
         *  [0 => 1, 1 => 2, 2 => null]
3479
         *  ['a' => 1, 'b' => 2, 0 => 3]
3480
         *
3481
         * Associative keys are preserved, numerical keys are replaced and numerical
3482
         * keys are used for the new elements.
3483
         *
3484
         * @param int $size Total number of elements that should be in the list
3485
         * @param mixed $value Value to fill up with if the map length is smaller than the given size
3486
         * @return self<int|string,mixed> New map
3487
         */
3488
        public function pad( int $size, $value = null ) : self
3489
        {
3490
                return new static( array_pad( $this->list(), $size, $value ) );
8✔
3491
        }
3492

3493

3494
        /**
3495
         * Breaks the list of elements into the given number of groups.
3496
         *
3497
         * Examples:
3498
         *  Map::from( [1, 2, 3, 4, 5] )->partition( 3 );
3499
         *  Map::from( [1, 2, 3, 4, 5] )->partition( function( $val, $idx ) {
3500
         *                return $idx % 3;
3501
         *        } );
3502
         *
3503
         * Results:
3504
         *  [[0 => 1, 1 => 2], [2 => 3, 3 => 4], [4 => 5]]
3505
         *  [0 => [0 => 1, 3 => 4], 1 => [1 => 2, 4 => 5], 2 => [2 => 3]]
3506
         *
3507
         * The keys of the original map are preserved in the returned map.
3508
         *
3509
         * @param \Closure|int $number Function with (value, index) as arguments returning the bucket key or number of groups
3510
         * @return self<int|string,mixed> New map
3511
         */
3512
        public function partition( $number ) : self
3513
        {
3514
                $list = $this->list();
32✔
3515

3516
                if( empty( $list ) ) {
32✔
3517
                        return new static();
8✔
3518
                }
3519

3520
                $result = [];
24✔
3521

3522
                if( $number instanceof \Closure )
24✔
3523
                {
3524
                        foreach( $list as $idx => $item ) {
8✔
3525
                                $result[$number( $item, $idx )][$idx] = $item;
8✔
3526
                        }
3527

3528
                        return new static( $result );
8✔
3529
                }
3530
                elseif( is_int( $number ) )
16✔
3531
                {
3532
                        $start = 0;
8✔
3533
                        $size = (int) ceil( count( $list ) / $number );
8✔
3534

3535
                        for( $i = 0; $i < $number; $i++ )
8✔
3536
                        {
3537
                                $result[] = array_slice( $list, $start, $size, true );
8✔
3538
                                $start += $size;
8✔
3539
                        }
3540

3541
                        return new static( $result );
8✔
3542
                }
3543

3544
                throw new \InvalidArgumentException( 'Parameter is no closure or integer' );
8✔
3545
        }
3546

3547

3548
        /**
3549
         * Returns the percentage of all elements passing the test in the map.
3550
         *
3551
         * Examples:
3552
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50 );
3553
         *  Map::from( [] )->percentage( fn( $val, $key ) => true );
3554
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 100 );
3555
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 3 );
3556
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 0 );
3557
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50, -1 );
3558
         *
3559
         * Results:
3560
         * The first line will return "66.67", the second and third one "0.0", the forth
3561
         * one "33.333", the fifth one "33.0" and the last one "70.0" (66 rounded up).
3562
         *
3563
         * @param Closure $fcn Closure to filter the values in the nested array or object to compute the percentage
3564
         * @param int $precision Number of decimal digits use by the result value
3565
         * @return float Percentage of all elements passing the test in the map
3566
         */
3567
        public function percentage( \Closure $fcn, int $precision = 2 ) : float
3568
        {
3569
                $vals = array_filter( $this->list(), $fcn, ARRAY_FILTER_USE_BOTH );
8✔
3570

3571
                $cnt = count( $this->list() );
8✔
3572
                return $cnt > 0 ? round( count( $vals ) * 100 / $cnt, $precision ) : 0;
8✔
3573
        }
3574

3575

3576
        /**
3577
         * Passes the map to the given callback and return the result.
3578
         *
3579
         * Examples:
3580
         *  Map::from( ['a', 'b'] )->pipe( function( $map ) {
3581
         *      return join( '-', $map->toArray() );
3582
         *  } );
3583
         *
3584
         * Results:
3585
         *  "a-b" will be returned
3586
         *
3587
         * @param \Closure $callback Function with map as parameter which returns arbitrary result
3588
         * @return mixed Result returned by the callback
3589
         */
3590
        public function pipe( \Closure $callback )
3591
        {
3592
                return $callback( $this );
8✔
3593
        }
3594

3595

3596
        /**
3597
         * Returns the values of a single column/property from an array of arrays or objects in a new map.
3598
         *
3599
         * This method is an alias for col(). For performance reasons, col() should
3600
         * be preferred because it uses one method call less than pluck().
3601
         *
3602
         * @param string|null $valuecol Name or path of the value property
3603
         * @param string|null $indexcol Name or path of the index property
3604
         * @return self<int|string,mixed> New map with mapped entries
3605
         * @see col() - Underlying method with same parameters and return value but better performance
3606
         */
3607
        public function pluck( ?string $valuecol = null, ?string $indexcol = null ) : self
3608
        {
3609
                return $this->col( $valuecol, $indexcol );
8✔
3610
        }
3611

3612

3613
        /**
3614
         * Returns and removes the last element from the map.
3615
         *
3616
         * Examples:
3617
         *  Map::from( ['a', 'b'] )->pop();
3618
         *
3619
         * Results:
3620
         *  "b" will be returned and the map only contains ['a'] afterwards
3621
         *
3622
         * @return mixed Last element of the map or null if empty
3623
         */
3624
        public function pop()
3625
        {
3626
                return array_pop( $this->list() );
16✔
3627
        }
3628

3629

3630
        /**
3631
         * Returns the numerical index of the value.
3632
         *
3633
         * Examples:
3634
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( 'b' );
3635
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( function( $item, $key ) {
3636
         *      return $item === 'b';
3637
         *  } );
3638
         *
3639
         * Results:
3640
         * Both examples will return "1" because the value "b" is at the second position
3641
         * and the returned index is zero based so the first item has the index "0".
3642
         *
3643
         * @param \Closure|mixed $value Value to search for or function with (item, key) parameters return TRUE if value is found
3644
         * @return int|null Position of the found value (zero based) or NULL if not found
3645
         */
3646
        public function pos( $value ) : ?int
3647
        {
3648
                $pos = 0;
120✔
3649
                $list = $this->list();
120✔
3650

3651
                if( $value instanceof \Closure )
120✔
3652
                {
3653
                        foreach( $list as $key => $item )
24✔
3654
                        {
3655
                                if( $value( $item, $key ) ) {
24✔
3656
                                        return $pos;
24✔
3657
                                }
3658

3659
                                ++$pos;
24✔
3660
                        }
3661
                }
3662

3663
                if( ( $key = array_search( $value, $list, true ) ) !== false
96✔
3664
                        && ( $pos = array_search( $key, array_keys( $list ), true ) ) !== false
96✔
3665
                ) {
3666
                        return $pos;
80✔
3667
                }
3668

3669
                return null;
16✔
3670
        }
3671

3672

3673
        /**
3674
         * Adds a prefix in front of each map entry.
3675
         *
3676
         * By defaul, nested arrays are walked recusively so all entries at all levels are prefixed.
3677
         *
3678
         * Examples:
3679
         *  Map::from( ['a', 'b'] )->prefix( '1-' );
3680
         *  Map::from( ['a', ['b']] )->prefix( '1-' );
3681
         *  Map::from( ['a', ['b']] )->prefix( '1-', 1 );
3682
         *  Map::from( ['a', 'b'] )->prefix( function( $item, $key ) {
3683
         *      return ( ord( $item ) + ord( $key ) ) . '-';
3684
         *  } );
3685
         *
3686
         * Results:
3687
         *  The first example returns ['1-a', '1-b'] while the second one will return
3688
         *  ['1-a', ['1-b']]. In the third example, the depth is limited to the first
3689
         *  level only so it will return ['1-a', ['b']]. The forth example passing
3690
         *  the closure will return ['145-a', '147-b'].
3691
         *
3692
         * The keys of the original map are preserved in the returned map.
3693
         *
3694
         * @param \Closure|string $prefix Prefix string or anonymous function with ($item, $key) as parameters
3695
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
3696
         * @return self<int|string,mixed> Updated map for fluid interface
3697
         */
3698
        public function prefix( $prefix, ?int $depth = null ) : self
3699
        {
3700
                $fcn = function( array $list, $prefix, int $depth ) use ( &$fcn ) {
6✔
3701

3702
                        foreach( $list as $key => $item )
8✔
3703
                        {
3704
                                if( is_array( $item ) ) {
8✔
3705
                                        $list[$key] = $depth > 1 ? $fcn( $item, $prefix, $depth - 1 ) : $item;
8✔
3706
                                } else {
3707
                                        $list[$key] = ( is_callable( $prefix ) ? $prefix( $item, $key ) : $prefix ) . $item;
8✔
3708
                                }
3709
                        }
3710

3711
                        return $list;
8✔
3712
                };
8✔
3713

3714
                $this->list = $fcn( $this->list(), $prefix, $depth ?? 0x7fffffff );
8✔
3715
                return $this;
8✔
3716
        }
3717

3718

3719
        /**
3720
         * Pushes an element onto the beginning of the map without returning a new map.
3721
         *
3722
         * This method is an alias for unshift().
3723
         *
3724
         * @param mixed $value Item to add at the beginning
3725
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
3726
         * @return self<int|string,mixed> Updated map for fluid interface
3727
         * @see unshift() - Underlying method with same parameters and return value but better performance
3728
         */
3729
        public function prepend( $value, $key = null ) : self
3730
        {
3731
                return $this->unshift( $value, $key );
8✔
3732
        }
3733

3734

3735
        /**
3736
         * Returns and removes an element from the map by its key.
3737
         *
3738
         * Examples:
3739
         *  Map::from( ['a', 'b', 'c'] )->pull( 1 );
3740
         *  Map::from( ['a', 'b', 'c'] )->pull( 'x', 'none' );
3741
         *  Map::from( [] )->pull( 'Y', new \Exception( 'error' ) );
3742
         *  Map::from( [] )->pull( 'Z', function() { return rand(); } );
3743
         *
3744
         * Results:
3745
         * The first example will return "b" and the map contains ['a', 'c'] afterwards.
3746
         * The second one will return "none" and the map content stays untouched. If you
3747
         * pass an exception as default value, it will throw that exception if the map
3748
         * contains no elements. In the fourth example, a random value generated by the
3749
         * closure function will be returned.
3750
         *
3751
         * @param int|string $key Key to retrieve the value for
3752
         * @param mixed $default Default value if key isn't available
3753
         * @return mixed Value from map or default value
3754
         */
3755
        public function pull( $key, $default = null )
3756
        {
3757
                $value = $this->get( $key, $default );
32✔
3758
                unset( $this->list()[$key] );
24✔
3759

3760
                return $value;
24✔
3761
        }
3762

3763

3764
        /**
3765
         * Pushes an element onto the end of the map without returning a new map.
3766
         *
3767
         * Examples:
3768
         *  Map::from( ['a', 'b'] )->push( 'aa' );
3769
         *
3770
         * Results:
3771
         *  ['a', 'b', 'aa']
3772
         *
3773
         * @param mixed $value Value to add to the end
3774
         * @return self<int|string,mixed> Updated map for fluid interface
3775
         */
3776
        public function push( $value ) : self
3777
        {
3778
                $this->list()[] = $value;
24✔
3779
                return $this;
24✔
3780
        }
3781

3782

3783
        /**
3784
         * Sets the given key and value in the map without returning a new map.
3785
         *
3786
         * This method is an alias for set(). For performance reasons, set() should be
3787
         * preferred because it uses one method call less than put().
3788
         *
3789
         * @param int|string $key Key to set the new value for
3790
         * @param mixed $value New element that should be set
3791
         * @return self<int|string,mixed> Updated map for fluid interface
3792
         * @see set() - Underlying method with same parameters and return value but better performance
3793
         */
3794
        public function put( $key, $value ) : self
3795
        {
3796
                return $this->set( $key, $value );
8✔
3797
        }
3798

3799

3800
        /**
3801
         * Returns one or more random element from the map incl. their keys.
3802
         *
3803
         * Examples:
3804
         *  Map::from( [2, 4, 8, 16] )->random();
3805
         *  Map::from( [2, 4, 8, 16] )->random( 2 );
3806
         *  Map::from( [2, 4, 8, 16] )->random( 5 );
3807
         *
3808
         * Results:
3809
         * The first example will return a map including [0 => 8] or any other value,
3810
         * the second one will return a map with [0 => 16, 1 => 2] or any other values
3811
         * and the third example will return a map of the whole list in random order. The
3812
         * less elements are in the map, the less random the order will be, especially if
3813
         * the maximum number of values is high or close to the number of elements.
3814
         *
3815
         * The keys of the original map are preserved in the returned map.
3816
         *
3817
         * @param int $max Maximum number of elements that should be returned
3818
         * @return self<int|string,mixed> New map with key/element pairs from original map in random order
3819
         * @throws \InvalidArgumentException If requested number of elements is less than 1
3820
         */
3821
        public function random( int $max = 1 ) : self
3822
        {
3823
                if( $max < 1 ) {
40✔
3824
                        throw new \InvalidArgumentException( 'Requested number of elements must be greater or equal than 1' );
8✔
3825
                }
3826

3827
                $list = $this->list();
32✔
3828

3829
                if( empty( $list ) ) {
32✔
3830
                        return new static();
8✔
3831
                }
3832

3833
                if( ( $num = count( $list ) ) < $max ) {
24✔
3834
                        $max = $num;
8✔
3835
                }
3836

3837
                $keys = array_rand( $list, $max );
24✔
3838

3839
                return new static( array_intersect_key( $list, array_flip( (array) $keys ) ) );
24✔
3840
        }
3841

3842

3843
        /**
3844
         * Iteratively reduces the array to a single value using a callback function.
3845
         * Afterwards, the map will be empty.
3846
         *
3847
         * Examples:
3848
         *  Map::from( [2, 8] )->reduce( function( $result, $value ) {
3849
         *      return $result += $value;
3850
         *  }, 10 );
3851
         *
3852
         * Results:
3853
         *  "20" will be returned because the sum is computed by 10 (initial value) + 2 + 8
3854
         *
3855
         * @param callable $callback Function with (result, value) parameters and returns result
3856
         * @param mixed $initial Initial value when computing the result
3857
         * @return mixed Value computed by the callback function
3858
         */
3859
        public function reduce( callable $callback, $initial = null )
3860
        {
3861
                return array_reduce( $this->list(), $callback, $initial );
8✔
3862
        }
3863

3864

3865
        /**
3866
         * Removes all matched elements and returns a new map.
3867
         *
3868
         * Examples:
3869
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->reject( function( $value, $key ) {
3870
         *      return $value < 'm';
3871
         *  } );
3872
         *  Map::from( [2 => 'a', 13 => 'm', 30 => 'z'] )->reject( 'm' );
3873
         *  Map::from( [2 => 'a', 6 => null, 13 => 'm'] )->reject();
3874
         *
3875
         * Results:
3876
         *  [13 => 'm', 30 => 'z']
3877
         *  [2 => 'a', 30 => 'z']
3878
         *  [6 => null]
3879
         *
3880
         * This method is the inverse of the filter() and should return TRUE if the
3881
         * item should be removed from the returned map.
3882
         *
3883
         * If no callback is passed, all values which are NOT empty, null or false will be
3884
         * removed. The keys of the original map are preserved in the returned map.
3885
         *
3886
         * @param Closure|mixed $callback Function with (item) parameter which returns TRUE/FALSE or value to compare with
3887
         * @return self<int|string,mixed> New map
3888
         */
3889
        public function reject( $callback = true ) : self
3890
        {
3891
                $isCallable = $callback instanceof \Closure;
24✔
3892

3893
                return new static( array_filter( $this->list(), function( $value, $key ) use  ( $callback, $isCallable ) {
18✔
3894
                        return $isCallable ? !$callback( $value, $key ) : $value != $callback;
24✔
3895
                }, ARRAY_FILTER_USE_BOTH ) );
24✔
3896
        }
3897

3898

3899
        /**
3900
         * Changes the keys according to the passed function.
3901
         *
3902
         * Examples:
3903
         *  Map::from( ['a' => 2, 'b' => 4] )->rekey( function( $value, $key ) {
3904
         *      return 'key-' . $key;
3905
         *  } );
3906
         *
3907
         * Results:
3908
         *  ['key-a' => 2, 'key-b' => 4]
3909
         *
3910
         * @param callable $callback Function with (value, key) parameters and returns new key
3911
         * @return self<int|string,mixed> New map with new keys and original values
3912
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
3913
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
3914
         */
3915
        public function rekey( callable $callback ) : self
3916
        {
3917
                $list = $this->list();
8✔
3918
                $keys = array_keys( $list );
8✔
3919
                $newKeys = array_map( $callback, $list, $keys );
8✔
3920

3921
                return new static( array_combine( $newKeys, $list ) ?: [] );
8✔
3922
        }
3923

3924

3925
        /**
3926
         * Removes one or more elements from the map by its keys without returning a new map.
3927
         *
3928
         * Examples:
3929
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( 'a' );
3930
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( [2, 'a'] );
3931
         *
3932
         * Results:
3933
         * The first example will result in [2 => 'b'] while the second one resulting
3934
         * in an empty list
3935
         *
3936
         * @param iterable<string|int>|array<string|int>|string|int $keys List of keys to remove
3937
         * @return self<int|string,mixed> Updated map for fluid interface
3938
         */
3939
        public function remove( $keys ) : self
3940
        {
3941
                foreach( $this->array( $keys ) as $key ) {
40✔
3942
                        unset( $this->list()[$key] );
40✔
3943
                }
3944

3945
                return $this;
40✔
3946
        }
3947

3948

3949
        /**
3950
         * Replaces elements in the map with the given elements without returning a new map.
3951
         *
3952
         * Examples:
3953
         *  Map::from( ['a' => 1, 2 => 'b'] )->replace( ['a' => 2] );
3954
         *  Map::from( ['a' => 1, 'b' => ['c' => 3, 'd' => 4]] )->replace( ['b' => ['c' => 9]] );
3955
         *
3956
         * Results:
3957
         *  ['a' => 2, 2 => 'b']
3958
         *  ['a' => 1, 'b' => ['c' => 9, 'd' => 4]]
3959
         *
3960
         * The method is similar to merge() but it also replaces elements with numeric
3961
         * keys. These would be added by merge() with a new numeric key.
3962
         *
3963
         * The keys are preserved using this method.
3964
         *
3965
         * @param iterable<int|string,mixed> $elements List of elements
3966
         * @param bool $recursive TRUE to replace recursively (default), FALSE to replace elements only
3967
         * @return self<int|string,mixed> Updated map for fluid interface
3968
         */
3969
        public function replace( iterable $elements, bool $recursive = true ) : self
3970
        {
3971
                if( $recursive ) {
40✔
3972
                        $this->list = array_replace_recursive( $this->list(), $this->array( $elements ) );
32✔
3973
                } else {
3974
                        $this->list = array_replace( $this->list(), $this->array( $elements ) );
8✔
3975
                }
3976

3977
                return $this;
40✔
3978
        }
3979

3980

3981
        /**
3982
         * Reverses the element order with keys without returning a new map.
3983
         *
3984
         * Examples:
3985
         *  Map::from( ['a', 'b'] )->reverse();
3986
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reverse();
3987
         *
3988
         * Results:
3989
         *  ['b', 'a']
3990
         *  ['last' => 'user', 'name' => 'test']
3991
         *
3992
         * The keys are preserved using this method.
3993
         *
3994
         * @return self<int|string,mixed> Updated map for fluid interface
3995
         * @see reversed() - Reverses the element order in a copy of the map
3996
         */
3997
        public function reverse() : self
3998
        {
3999
                $this->list = array_reverse( $this->list(), true );
32✔
4000
                return $this;
32✔
4001
        }
4002

4003

4004
        /**
4005
         * Reverses the element order in a copy of the map.
4006
         *
4007
         * Examples:
4008
         *  Map::from( ['a', 'b'] )->reversed();
4009
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reversed();
4010
         *
4011
         * Results:
4012
         *  ['b', 'a']
4013
         *  ['last' => 'user', 'name' => 'test']
4014
         *
4015
         * The keys are preserved using this method and a new map is created before reversing the elements.
4016
         * Thus, reverse() should be preferred for performance reasons if possible.
4017
         *
4018
         * @return self<int|string,mixed> New map with a reversed copy of the elements
4019
         * @see reverse() - Reverses the element order with keys without returning a new map
4020
         */
4021
        public function reversed() : self
4022
        {
4023
                return ( clone $this )->reverse();
16✔
4024
        }
4025

4026

4027
        /**
4028
         * Sorts all elements in reverse order using new keys.
4029
         *
4030
         * Examples:
4031
         *  Map::from( ['a' => 1, 'b' => 0] )->rsort();
4032
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsort();
4033
         *
4034
         * Results:
4035
         *  [0 => 1, 1 => 0]
4036
         *  [0 => 'b', 1 => 'a']
4037
         *
4038
         * The parameter modifies how the values are compared. Possible parameter values are:
4039
         * - SORT_REGULAR : compare elements normally (don't change types)
4040
         * - SORT_NUMERIC : compare elements numerically
4041
         * - SORT_STRING : compare elements as strings
4042
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4043
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4044
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4045
         *
4046
         * The keys aren't preserved and elements get a new index. No new map is created
4047
         *
4048
         * @param int $options Sort options for rsort()
4049
         * @return self<int|string,mixed> Updated map for fluid interface
4050
         */
4051
        public function rsort( int $options = SORT_REGULAR ) : self
4052
        {
4053
                rsort( $this->list(), $options );
24✔
4054
                return $this;
24✔
4055
        }
4056

4057

4058
        /**
4059
         * Sorts a copy of all elements in reverse order using new keys.
4060
         *
4061
         * Examples:
4062
         *  Map::from( ['a' => 1, 'b' => 0] )->rsorted();
4063
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsorted();
4064
         *
4065
         * Results:
4066
         *  [0 => 1, 1 => 0]
4067
         *  [0 => 'b', 1 => 'a']
4068
         *
4069
         * The parameter modifies how the values are compared. Possible parameter values are:
4070
         * - SORT_REGULAR : compare elements normally (don't change types)
4071
         * - SORT_NUMERIC : compare elements numerically
4072
         * - SORT_STRING : compare elements as strings
4073
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4074
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4075
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4076
         *
4077
         * The keys aren't preserved, elements get a new index and a new map is created.
4078
         *
4079
         * @param int $options Sort options for rsort()
4080
         * @return self<int|string,mixed> Updated map for fluid interface
4081
         */
4082
        public function rsorted( int $options = SORT_REGULAR ) : self
4083
        {
4084
                return ( clone $this )->rsort( $options );
8✔
4085
        }
4086

4087

4088
        /**
4089
         * Removes the passed characters from the right of all strings.
4090
         *
4091
         * Examples:
4092
         *  Map::from( [" abc\n", "\tcde\r\n"] )->rtrim();
4093
         *  Map::from( ["a b c", "cbxa"] )->rtrim( 'abc' );
4094
         *
4095
         * Results:
4096
         * The first example will return [" abc", "\tcde"] while the second one will return ["a b ", "cbx"].
4097
         *
4098
         * @param string $chars List of characters to trim
4099
         * @return self<int|string,mixed> Updated map for fluid interface
4100
         */
4101
        public function rtrim( string $chars = " \n\r\t\v\x00" ) : self
4102
        {
4103
                foreach( $this->list() as &$entry )
8✔
4104
                {
4105
                        if( is_string( $entry ) ) {
8✔
4106
                                $entry = rtrim( $entry, $chars );
8✔
4107
                        }
4108
                }
4109

4110
                return $this;
8✔
4111
        }
4112

4113

4114
        /**
4115
         * Searches the map for a given value and return the corresponding key if successful.
4116
         *
4117
         * Examples:
4118
         *  Map::from( ['a', 'b', 'c'] )->search( 'b' );
4119
         *  Map::from( [1, 2, 3] )->search( '2', true );
4120
         *
4121
         * Results:
4122
         * The first example will return 1 (array index) while the second one will
4123
         * return NULL because the types doesn't match (int vs. string)
4124
         *
4125
         * @param mixed $value Item to search for
4126
         * @param bool $strict TRUE if type of the element should be checked too
4127
         * @return int|string|null Key associated to the value or null if not found
4128
         */
4129
        public function search( $value, $strict = true )
4130
        {
4131
                if( ( $result = array_search( $value, $this->list(), $strict ) ) !== false ) {
8✔
4132
                        return $result;
8✔
4133
                }
4134

4135
                return null;
8✔
4136
        }
4137

4138

4139
        /**
4140
         * Sets the seperator for paths to values in multi-dimensional arrays or objects.
4141
         *
4142
         * This method only changes the separator for the current map instance. To
4143
         * change the separator for all maps created afterwards, use the static
4144
         * delimiter() method instead.
4145
         *
4146
         * Examples:
4147
         *  Map::from( ['foo' => ['bar' => 'baz']] )->sep( '/' )->get( 'foo/bar' );
4148
         *
4149
         * Results:
4150
         *  'baz'
4151
         *
4152
         * @param string $char Separator character, e.g. "." for "key.to.value" instead of "key/to/value"
4153
         * @return self<int|string,mixed> Same map for fluid interface
4154
         */
4155
        public function sep( string $char ) : self
4156
        {
4157
                $this->sep = $char;
8✔
4158
                return $this;
8✔
4159
        }
4160

4161

4162
        /**
4163
         * Sets an element in the map by key without returning a new map.
4164
         *
4165
         * Examples:
4166
         *  Map::from( ['a'] )->set( 1, 'b' );
4167
         *  Map::from( ['a'] )->set( 0, 'b' );
4168
         *
4169
         * Results:
4170
         *  ['a', 'b']
4171
         *  ['b']
4172
         *
4173
         * @param int|string $key Key to set the new value for
4174
         * @param mixed $value New element that should be set
4175
         * @return self<int|string,mixed> Updated map for fluid interface
4176
         */
4177
        public function set( $key, $value ) : self
4178
        {
4179
                $this->list()[(string) $key] = $value;
40✔
4180
                return $this;
40✔
4181
        }
4182

4183

4184
        /**
4185
         * Returns and removes the first element from the map.
4186
         *
4187
         * Examples:
4188
         *  Map::from( ['a', 'b'] )->shift();
4189
         *  Map::from( [] )->shift();
4190
         *
4191
         * Results:
4192
         * The first example returns "a" and shortens the map to ['b'] only while the
4193
         * second example will return NULL
4194
         *
4195
         * Performance note:
4196
         * The bigger the list, the higher the performance impact because shift()
4197
         * reindexes all existing elements. Usually, it's better to reverse() the list
4198
         * and pop() entries from the list afterwards if a significant number of elements
4199
         * should be removed from the list:
4200
         *
4201
         *  $map->reverse()->pop();
4202
         * instead of
4203
         *  $map->shift( 'a' );
4204
         *
4205
         * @return mixed|null Value from map or null if not found
4206
         */
4207
        public function shift()
4208
        {
4209
                return array_shift( $this->list() );
8✔
4210
        }
4211

4212

4213
        /**
4214
         * Shuffles the elements in the map without returning a new map.
4215
         *
4216
         * Examples:
4217
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle();
4218
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle( true );
4219
         *
4220
         * Results:
4221
         * The map in the first example will contain "a" and "b" in random order and
4222
         * with new keys assigned. The second call will also return all values in
4223
         * random order but preserves the keys of the original list.
4224
         *
4225
         * @param bool $assoc True to preserve keys, false to assign new keys
4226
         * @return self<int|string,mixed> Updated map for fluid interface
4227
         * @see shuffled() - Shuffles the elements in a copy of the map
4228
         */
4229
        public function shuffle( bool $assoc = false ) : self
4230
        {
4231
                if( $assoc )
24✔
4232
                {
4233
                        $list = $this->list();
8✔
4234
                        $keys = array_keys( $list );
8✔
4235
                        shuffle( $keys );
8✔
4236
                        $items = [];
8✔
4237

4238
                        foreach( $keys as $key ) {
8✔
4239
                                $items[$key] = $list[$key];
8✔
4240
                        }
4241

4242
                        $this->list = $items;
8✔
4243
                }
4244
                else
4245
                {
4246
                        shuffle( $this->list() );
16✔
4247
                }
4248

4249
                return $this;
24✔
4250
        }
4251

4252

4253
        /**
4254
         * Shuffles the elements in a copy of the map.
4255
         *
4256
         * Examples:
4257
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled();
4258
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled( true );
4259
         *
4260
         * Results:
4261
         * The map in the first example will contain "a" and "b" in random order and
4262
         * with new keys assigned. The second call will also return all values in
4263
         * random order but preserves the keys of the original list.
4264
         *
4265
         * @param bool $assoc True to preserve keys, false to assign new keys
4266
         * @return self<int|string,mixed> New map with a shuffled copy of the elements
4267
         * @see shuffle() - Shuffles the elements in the map without returning a new map
4268
         */
4269
        public function shuffled( bool $assoc = false ) : self
4270
        {
4271
                return ( clone $this )->shuffle( $assoc );
8✔
4272
        }
4273

4274

4275
        /**
4276
         * Returns a new map with the given number of items skipped.
4277
         *
4278
         * Examples:
4279
         *  Map::from( [1, 2, 3, 4] )->skip( 2 );
4280
         *  Map::from( [1, 2, 3, 4] )->skip( function( $item, $key ) {
4281
         *      return $item < 4;
4282
         *  } );
4283
         *
4284
         * Results:
4285
         *  [2 => 3, 3 => 4]
4286
         *  [3 => 4]
4287
         *
4288
         * The keys of the items returned in the new map are the same as in the original one.
4289
         *
4290
         * @param \Closure|int $offset Number of items to skip or function($item, $key) returning true for skipped items
4291
         * @return self<int|string,mixed> New map
4292
         */
4293
        public function skip( $offset ) : self
4294
        {
4295
                if( is_scalar( $offset ) ) {
24✔
4296
                        return new static( array_slice( $this->list(), (int) $offset, null, true ) );
8✔
4297
                }
4298

4299
                if( is_callable( $offset ) )
16✔
4300
                {
4301
                        $idx = 0;
8✔
4302
                        $list = $this->list();
8✔
4303

4304
                        foreach( $list as $key => $item )
8✔
4305
                        {
4306
                                if( !$offset( $item, $key ) ) {
8✔
4307
                                        break;
8✔
4308
                                }
4309

4310
                                ++$idx;
8✔
4311
                        }
4312

4313
                        return new static( array_slice( $list, $idx, null, true ) );
8✔
4314
                }
4315

4316
                throw new \InvalidArgumentException( 'Only an integer or a closure is allowed as first argument for skip()' );
8✔
4317
        }
4318

4319

4320
        /**
4321
         * Returns a map with the slice from the original map.
4322
         *
4323
         * Examples:
4324
         *  Map::from( ['a', 'b', 'c'] )->slice( 1 );
4325
         *  Map::from( ['a', 'b', 'c'] )->slice( 1, 1 );
4326
         *  Map::from( ['a', 'b', 'c', 'd'] )->slice( -2, -1 );
4327
         *
4328
         * Results:
4329
         * The first example will return ['b', 'c'] and the second one ['b'] only.
4330
         * The third example returns ['c'] because the slice starts at the second
4331
         * last value and ends before the last value.
4332
         *
4333
         * The rules for offsets are:
4334
         * - If offset is non-negative, the sequence will start at that offset
4335
         * - If offset is negative, the sequence will start that far from the end
4336
         *
4337
         * Similar for the length:
4338
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4339
         * - If the array is shorter than the length, then only the available array elements will be present
4340
         * - If length is given and is negative then the sequence will stop that many elements from the end
4341
         * - If it is omitted, then the sequence will have everything from offset up until the end
4342
         *
4343
         * The keys of the items returned in the new map are the same as in the original one.
4344
         *
4345
         * @param int $offset Number of elements to start from
4346
         * @param int|null $length Number of elements to return or NULL for no limit
4347
         * @return self<int|string,mixed> New map
4348
         */
4349
        public function slice( int $offset, ?int $length = null ) : self
4350
        {
4351
                return new static( array_slice( $this->list(), $offset, $length, true ) );
48✔
4352
        }
4353

4354

4355
        /**
4356
         * Tests if at least one element passes the test or is part of the map.
4357
         *
4358
         * Examples:
4359
         *  Map::from( ['a', 'b'] )->some( 'a' );
4360
         *  Map::from( ['a', 'b'] )->some( ['a', 'c'] );
4361
         *  Map::from( ['a', 'b'] )->some( function( $item, $key ) {
4362
         *    return $item === 'a';
4363
         *  } );
4364
         *  Map::from( ['a', 'b'] )->some( ['c', 'd'] );
4365
         *  Map::from( ['1', '2'] )->some( [2], true );
4366
         *
4367
         * Results:
4368
         * The first three examples will return TRUE while the fourth and fifth will return FALSE
4369
         *
4370
         * @param \Closure|iterable|mixed $values Anonymous function with (item, key) parameter, element or list of elements to test against
4371
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
4372
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
4373
         */
4374
        public function some( $values, bool $strict = false ) : bool
4375
        {
4376
                $list = $this->list();
48✔
4377

4378
                if( is_iterable( $values ) )
48✔
4379
                {
4380
                        foreach( $values as $entry )
24✔
4381
                        {
4382
                                if( in_array( $entry, $list, $strict ) === true ) {
24✔
4383
                                        return true;
24✔
4384
                                }
4385
                        }
4386

4387
                        return false;
16✔
4388
                }
4389
                elseif( is_callable( $values ) )
32✔
4390
                {
4391
                        foreach( $list as $key => $item )
16✔
4392
                        {
4393
                                if( $values( $item, $key ) ) {
16✔
4394
                                        return true;
16✔
4395
                                }
4396
                        }
4397
                }
4398
                elseif( in_array( $values, $list, $strict ) === true )
24✔
4399
                {
4400
                        return true;
24✔
4401
                }
4402

4403
                return false;
24✔
4404
        }
4405

4406

4407
        /**
4408
         * Sorts all elements in-place using new keys.
4409
         *
4410
         * Examples:
4411
         *  Map::from( ['a' => 1, 'b' => 0] )->sort();
4412
         *  Map::from( [0 => 'b', 1 => 'a'] )->sort();
4413
         *
4414
         * Results:
4415
         *  [0 => 0, 1 => 1]
4416
         *  [0 => 'a', 1 => 'b']
4417
         *
4418
         * The parameter modifies how the values are compared. Possible parameter values are:
4419
         * - SORT_REGULAR : compare elements normally (don't change types)
4420
         * - SORT_NUMERIC : compare elements numerically
4421
         * - SORT_STRING : compare elements as strings
4422
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4423
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4424
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4425
         *
4426
         * The keys aren't preserved and elements get a new index. No new map is created.
4427
         *
4428
         * @param int $options Sort options for PHP sort()
4429
         * @return self<int|string,mixed> Updated map for fluid interface
4430
         * @see sorted() - Sorts elements in a copy of the map
4431
         */
4432
        public function sort( int $options = SORT_REGULAR ) : self
4433
        {
4434
                sort( $this->list(), $options );
40✔
4435
                return $this;
40✔
4436
        }
4437

4438

4439
        /**
4440
         * Sorts the elements in a copy of the map using new keys.
4441
         *
4442
         * Examples:
4443
         *  Map::from( ['a' => 1, 'b' => 0] )->sorted();
4444
         *  Map::from( [0 => 'b', 1 => 'a'] )->sorted();
4445
         *
4446
         * Results:
4447
         *  [0 => 0, 1 => 1]
4448
         *  [0 => 'a', 1 => 'b']
4449
         *
4450
         * The parameter modifies how the values are compared. Possible parameter values are:
4451
         * - SORT_REGULAR : compare elements normally (don't change types)
4452
         * - SORT_NUMERIC : compare elements numerically
4453
         * - SORT_STRING : compare elements as strings
4454
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4455
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4456
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4457
         *
4458
         * The keys aren't preserved and elements get a new index and a new map is created before sorting the elements.
4459
         * Thus, sort() should be preferred for performance reasons if possible. A new map is created by calling this method.
4460
         *
4461
         * @param int $options Sort options for PHP sort()
4462
         * @return self<int|string,mixed> New map with a sorted copy of the elements
4463
         * @see sort() - Sorts elements in-place in the original map
4464
         */
4465
        public function sorted( int $options = SORT_REGULAR ) : self
4466
        {
4467
                return ( clone $this )->sort( $options );
16✔
4468
        }
4469

4470

4471
        /**
4472
         * Removes a portion of the map and replace it with the given replacement, then return the updated map.
4473
         *
4474
         * Examples:
4475
         *  Map::from( ['a', 'b', 'c'] )->splice( 1 );
4476
         *  Map::from( ['a', 'b', 'c'] )->splice( 1, 1, ['x', 'y'] );
4477
         *
4478
         * Results:
4479
         * The first example removes all entries after "a", so only ['a'] will be left
4480
         * in the map and ['b', 'c'] is returned. The second example replaces/returns "b"
4481
         * (start at 1, length 1) with ['x', 'y'] so the new map will contain
4482
         * ['a', 'x', 'y', 'c'] afterwards.
4483
         *
4484
         * The rules for offsets are:
4485
         * - If offset is non-negative, the sequence will start at that offset
4486
         * - If offset is negative, the sequence will start that far from the end
4487
         *
4488
         * Similar for the length:
4489
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4490
         * - If the array is shorter than the length, then only the available array elements will be present
4491
         * - If length is given and is negative then the sequence will stop that many elements from the end
4492
         * - If it is omitted, then the sequence will have everything from offset up until the end
4493
         *
4494
         * Numerical array indexes are NOT preserved.
4495
         *
4496
         * @param int $offset Number of elements to start from
4497
         * @param int|null $length Number of elements to remove, NULL for all
4498
         * @param mixed $replacement List of elements to insert
4499
         * @return self<int|string,mixed> New map
4500
         */
4501
        public function splice( int $offset, ?int $length = null, $replacement = [] ) : self
4502
        {
4503
                if( $length === null ) {
40✔
4504
                        $length = count( $this->list() );
16✔
4505
                }
4506

4507
                return new static( array_splice( $this->list(), $offset, $length, (array) $replacement ) );
40✔
4508
        }
4509

4510

4511
        /**
4512
         * Returns the strings after the passed value.
4513
         *
4514
         * Examples:
4515
         *  Map::from( ['äöüß'] )->strAfter( 'ö' );
4516
         *  Map::from( ['abc'] )->strAfter( '' );
4517
         *  Map::from( ['abc'] )->strAfter( 'b' );
4518
         *  Map::from( ['abc'] )->strAfter( 'c' );
4519
         *  Map::from( ['abc'] )->strAfter( 'x' );
4520
         *  Map::from( [''] )->strAfter( '' );
4521
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4522
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4523
         *
4524
         * Results:
4525
         *  ['üß']
4526
         *  ['abc']
4527
         *  ['c']
4528
         *  ['']
4529
         *  []
4530
         *  []
4531
         *  ['1', '1', '1']
4532
         *  ['0', '0']
4533
         *
4534
         * All scalar values (bool, int, float, string) will be converted to strings.
4535
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4536
         *
4537
         * @param string $value Character or string to search for
4538
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4539
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4540
         * @return self<int|string,mixed> New map
4541
         */
4542
        public function strAfter( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4543
        {
4544
                $list = [];
8✔
4545
                $len = mb_strlen( $value );
8✔
4546
                $fcn = $case ? 'mb_stripos' : 'mb_strpos';
8✔
4547

4548
                foreach( $this->list() as $key => $entry )
8✔
4549
                {
4550
                        if( is_scalar( $entry ) )
8✔
4551
                        {
4552
                                $pos = null;
8✔
4553
                                $str = (string) $entry;
8✔
4554

4555
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
8✔
4556
                                        $list[$key] = mb_substr( $str, $pos + $len, null, $encoding );
8✔
4557
                                } elseif( $str !== '' && $pos !== false ) {
8✔
4558
                                        $list[$key] = $str;
8✔
4559
                                }
4560
                        }
4561
                }
4562

4563
                return new static( $list );
8✔
4564
        }
4565

4566

4567
        /**
4568
         * Returns the strings before the passed value.
4569
         *
4570
         * Examples:
4571
         *  Map::from( ['äöüß'] )->strBefore( 'ü' );
4572
         *  Map::from( ['abc'] )->strBefore( '' );
4573
         *  Map::from( ['abc'] )->strBefore( 'b' );
4574
         *  Map::from( ['abc'] )->strBefore( 'a' );
4575
         *  Map::from( ['abc'] )->strBefore( 'x' );
4576
         *  Map::from( [''] )->strBefore( '' );
4577
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4578
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4579
         *
4580
         * Results:
4581
         *  ['äö']
4582
         *  ['abc']
4583
         *  ['a']
4584
         *  ['']
4585
         *  []
4586
         *  []
4587
         *  ['1', '1', '1']
4588
         *  ['0', '0']
4589
         *
4590
         * All scalar values (bool, int, float, string) will be converted to strings.
4591
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4592
         *
4593
         * @param string $value Character or string to search for
4594
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4595
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4596
         * @return self<int|string,mixed> New map
4597
         */
4598
        public function strBefore( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4599
        {
4600
                $list = [];
8✔
4601
                $fcn = $case ? 'mb_strripos' : 'mb_strrpos';
8✔
4602

4603
                foreach( $this->list() as $key => $entry )
8✔
4604
                {
4605
                        if( is_scalar( $entry ) )
8✔
4606
                        {
4607
                                $pos = null;
8✔
4608
                                $str = (string) $entry;
8✔
4609

4610
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
8✔
4611
                                        $list[$key] = mb_substr( $str, 0, $pos, $encoding );
8✔
4612
                                } elseif( $str !== '' && $pos !== false ) {
8✔
4613
                                        $list[$key] = $str;
8✔
4614
                                } else {
1✔
4615
                                }
4616
                        }
4617
                }
4618

4619
                return new static( $list );
8✔
4620
        }
4621

4622

4623
        /**
4624
         * Tests if at least one of the passed strings is part of at least one entry.
4625
         *
4626
         * Examples:
4627
         *  Map::from( ['abc'] )->strContains( '' );
4628
         *  Map::from( ['abc'] )->strContains( 'a' );
4629
         *  Map::from( ['abc'] )->strContains( 'bc' );
4630
         *  Map::from( [12345] )->strContains( '23' );
4631
         *  Map::from( [123.4] )->strContains( 23.4 );
4632
         *  Map::from( [12345] )->strContains( false );
4633
         *  Map::from( [12345] )->strContains( true );
4634
         *  Map::from( [false] )->strContains( false );
4635
         *  Map::from( [''] )->strContains( false );
4636
         *  Map::from( ['abc'] )->strContains( ['b', 'd'] );
4637
         *  Map::from( ['abc'] )->strContains( 'c', 'ASCII' );
4638
         *
4639
         *  Map::from( ['abc'] )->strContains( 'd' );
4640
         *  Map::from( ['abc'] )->strContains( 'cb' );
4641
         *  Map::from( [23456] )->strContains( true );
4642
         *  Map::from( [false] )->strContains( 0 );
4643
         *  Map::from( ['abc'] )->strContains( ['d', 'e'] );
4644
         *  Map::from( ['abc'] )->strContains( 'cb', 'ASCII' );
4645
         *
4646
         * Results:
4647
         * The first eleven examples will return TRUE while the last six will return FALSE.
4648
         *
4649
         * @param array|string $value The string or list of strings to search for in each entry
4650
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4651
         * @return bool TRUE if one of the entries contains one of the strings, FALSE if not
4652
         * @todo 4.0 Add $case parameter at second position
4653
         */
4654
        public function strContains( $value, string $encoding = 'UTF-8' ) : bool
4655
        {
4656
                foreach( $this->list() as $entry )
8✔
4657
                {
4658
                        $entry = (string) $entry;
8✔
4659

4660
                        foreach( (array) $value as $str )
8✔
4661
                        {
4662
                                $str = (string) $str;
8✔
4663

4664
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
8✔
4665
                                        return true;
8✔
4666
                                }
4667
                        }
4668
                }
4669

4670
                return false;
8✔
4671
        }
4672

4673

4674
        /**
4675
         * Tests if all of the entries contains one of the passed strings.
4676
         *
4677
         * Examples:
4678
         *  Map::from( ['abc', 'def'] )->strContainsAll( '' );
4679
         *  Map::from( ['abc', 'cba'] )->strContainsAll( 'a' );
4680
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'bc' );
4681
         *  Map::from( [12345, '230'] )->strContainsAll( '23' );
4682
         *  Map::from( [123.4, 23.42] )->strContainsAll( 23.4 );
4683
         *  Map::from( [12345, '234'] )->strContainsAll( [true, false] );
4684
         *  Map::from( ['', false] )->strContainsAll( false );
4685
         *  Map::from( ['abc', 'def'] )->strContainsAll( ['b', 'd'] );
4686
         *  Map::from( ['abc', 'ecf'] )->strContainsAll( 'c', 'ASCII' );
4687
         *
4688
         *  Map::from( ['abc', 'def'] )->strContainsAll( 'd' );
4689
         *  Map::from( ['abc', 'cab'] )->strContainsAll( 'cb' );
4690
         *  Map::from( [23456, '123'] )->strContainsAll( true );
4691
         *  Map::from( [false, '000'] )->strContainsAll( 0 );
4692
         *  Map::from( ['abc', 'acf'] )->strContainsAll( ['d', 'e'] );
4693
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'cb', 'ASCII' );
4694
         *
4695
         * Results:
4696
         * The first nine examples will return TRUE while the last six will return FALSE.
4697
         *
4698
         * @param array|string $value The string or list of strings to search for in each entry
4699
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4700
         * @return bool TRUE if all of the entries contains at least one of the strings, FALSE if not
4701
         * @todo 4.0 Add $case parameter at second position
4702
         */
4703
        public function strContainsAll( $value, string $encoding = 'UTF-8' ) : bool
4704
        {
4705
                $list = [];
8✔
4706

4707
                foreach( $this->list() as $entry )
8✔
4708
                {
4709
                        $entry = (string) $entry;
8✔
4710
                        $list[$entry] = 0;
8✔
4711

4712
                        foreach( (array) $value as $str )
8✔
4713
                        {
4714
                                $str = (string) $str;
8✔
4715

4716
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
8✔
4717
                                        $list[$entry] = 1; break;
8✔
4718
                                }
4719
                        }
4720
                }
4721

4722
                return array_sum( $list ) === count( $list );
8✔
4723
        }
4724

4725

4726
        /**
4727
         * Tests if at least one of the entries ends with one of the passed strings.
4728
         *
4729
         * Examples:
4730
         *  Map::from( ['abc'] )->strEnds( '' );
4731
         *  Map::from( ['abc'] )->strEnds( 'c' );
4732
         *  Map::from( ['abc'] )->strEnds( 'bc' );
4733
         *  Map::from( ['abc'] )->strEnds( ['b', 'c'] );
4734
         *  Map::from( ['abc'] )->strEnds( 'c', 'ASCII' );
4735
         *  Map::from( ['abc'] )->strEnds( 'a' );
4736
         *  Map::from( ['abc'] )->strEnds( 'cb' );
4737
         *  Map::from( ['abc'] )->strEnds( ['d', 'b'] );
4738
         *  Map::from( ['abc'] )->strEnds( 'cb', 'ASCII' );
4739
         *
4740
         * Results:
4741
         * The first five examples will return TRUE while the last four will return FALSE.
4742
         *
4743
         * @param array|string $value The string or strings to search for in each entry
4744
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4745
         * @return bool TRUE if one of the entries ends with one of the strings, FALSE if not
4746
         * @todo 4.0 Add $case parameter at second position
4747
         */
4748
        public function strEnds( $value, string $encoding = 'UTF-8' ) : bool
4749
        {
4750
                foreach( $this->list() as $entry )
8✔
4751
                {
4752
                        $entry = (string) $entry;
8✔
4753

4754
                        foreach( (array) $value as $str )
8✔
4755
                        {
4756
                                $len = mb_strlen( (string) $str );
8✔
4757

4758
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
8✔
4759
                                        return true;
8✔
4760
                                }
4761
                        }
4762
                }
4763

4764
                return false;
8✔
4765
        }
4766

4767

4768
        /**
4769
         * Tests if all of the entries ends with at least one of the passed strings.
4770
         *
4771
         * Examples:
4772
         *  Map::from( ['abc', 'def'] )->strEndsAll( '' );
4773
         *  Map::from( ['abc', 'bac'] )->strEndsAll( 'c' );
4774
         *  Map::from( ['abc', 'cbc'] )->strEndsAll( 'bc' );
4775
         *  Map::from( ['abc', 'def'] )->strEndsAll( ['c', 'f'] );
4776
         *  Map::from( ['abc', 'efc'] )->strEndsAll( 'c', 'ASCII' );
4777
         *  Map::from( ['abc', 'fed'] )->strEndsAll( 'd' );
4778
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca' );
4779
         *  Map::from( ['abc', 'acf'] )->strEndsAll( ['a', 'c'] );
4780
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca', 'ASCII' );
4781
         *
4782
         * Results:
4783
         * The first five examples will return TRUE while the last four will return FALSE.
4784
         *
4785
         * @param array|string $value The string or strings to search for in each entry
4786
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4787
         * @return bool TRUE if all of the entries ends with at least one of the strings, FALSE if not
4788
         * @todo 4.0 Add $case parameter at second position
4789
         */
4790
        public function strEndsAll( $value, string $encoding = 'UTF-8' ) : bool
4791
        {
4792
                $list = [];
8✔
4793

4794
                foreach( $this->list() as $entry )
8✔
4795
                {
4796
                        $entry = (string) $entry;
8✔
4797
                        $list[$entry] = 0;
8✔
4798

4799
                        foreach( (array) $value as $str )
8✔
4800
                        {
4801
                                $len = mb_strlen( (string) $str );
8✔
4802

4803
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
8✔
4804
                                        $list[$entry] = 1; break;
8✔
4805
                                }
4806
                        }
4807
                }
4808

4809
                return array_sum( $list ) === count( $list );
8✔
4810
        }
4811

4812

4813
        /**
4814
         * Returns an element by key and casts it to string if possible.
4815
         *
4816
         * Examples:
4817
         *  Map::from( ['a' => true] )->string( 'a' );
4818
         *  Map::from( ['a' => 1] )->string( 'a' );
4819
         *  Map::from( ['a' => 1.1] )->string( 'a' );
4820
         *  Map::from( ['a' => 'abc'] )->string( 'a' );
4821
         *  Map::from( ['a' => ['b' => ['c' => 'yes']]] )->string( 'a/b/c' );
4822
         *  Map::from( [] )->string( 'a', function() { return 'no'; } );
4823
         *
4824
         *  Map::from( [] )->string( 'b' );
4825
         *  Map::from( ['b' => ''] )->string( 'b' );
4826
         *  Map::from( ['b' => null] )->string( 'b' );
4827
         *  Map::from( ['b' => [true]] )->string( 'b' );
4828
         *  Map::from( ['b' => resource] )->string( 'b' );
4829
         *  Map::from( ['b' => new \stdClass] )->string( 'b' );
4830
         *
4831
         *  Map::from( [] )->string( 'c', new \Exception( 'error' ) );
4832
         *
4833
         * Results:
4834
         * The first six examples will return the value as string while the 9th to 12th
4835
         * example returns an empty string. The last example will throw an exception.
4836
         *
4837
         * This does also work for multi-dimensional arrays by passing the keys
4838
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
4839
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
4840
         * public properties of objects or objects implementing __isset() and __get() methods.
4841
         *
4842
         * @param int|string $key Key or path to the requested item
4843
         * @param mixed $default Default value if key isn't found (will be casted to bool)
4844
         * @return string Value from map or default value
4845
         */
4846
        public function string( $key, $default = '' ) : string
4847
        {
4848
                return (string) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
24✔
4849
        }
4850

4851

4852
        /**
4853
         * Converts all alphabetic characters in strings to lower case.
4854
         *
4855
         * Examples:
4856
         *  Map::from( ['My String'] )->strLower();
4857
         *  Map::from( ['Τάχιστη'] )->strLower();
4858
         *  Map::from( ['Äpfel', 'Birnen'] )->strLower( 'ISO-8859-1' );
4859
         *  Map::from( [123] )->strLower();
4860
         *  Map::from( [new stdClass] )->strLower();
4861
         *
4862
         * Results:
4863
         * The first example will return ["my string"], the second one ["τάχιστη"] and
4864
         * the third one ["äpfel", "birnen"]. The last two strings will be unchanged.
4865
         *
4866
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4867
         * @return self<int|string,mixed> Updated map for fluid interface
4868
         */
4869
        public function strLower( string $encoding = 'UTF-8' ) : self
4870
        {
4871
                foreach( $this->list() as &$entry )
8✔
4872
                {
4873
                        if( is_string( $entry ) ) {
8✔
4874
                                $entry = mb_strtolower( $entry, $encoding );
8✔
4875
                        }
4876
                }
4877

4878
                return $this;
8✔
4879
        }
4880

4881

4882
        /**
4883
         * Replaces all occurrences of the search string with the replacement string.
4884
         *
4885
         * Examples:
4886
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( '.com', '.de' );
4887
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], '.de' );
4888
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.de'] );
4889
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.fr', '.de'] );
4890
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( ['.com', '.co'], ['.co', '.de', '.fr'] );
4891
         * Map::from( ['google.com', 'aimeos.com', 123] )->strReplace( '.com', '.de' );
4892
         * Map::from( ['GOOGLE.COM', 'AIMEOS.COM'] )->strReplace( '.com', '.de', true );
4893
         *
4894
         * Restults:
4895
         * ['google.de', 'aimeos.de']
4896
         * ['google.de', 'aimeos.de']
4897
         * ['google.de', 'aimeos']
4898
         * ['google.fr', 'aimeos.de']
4899
         * ['google.de', 'aimeos.de']
4900
         * ['google.de', 'aimeos.de', 123]
4901
         * ['GOOGLE.de', 'AIMEOS.de']
4902
         *
4903
         * If you use an array of strings for search or search/replacement, the order of
4904
         * the strings matters! Each search string found is replaced by the corresponding
4905
         * replacement string at the same position.
4906
         *
4907
         * In case of array parameters and if the number of replacement strings is less
4908
         * than the number of search strings, the search strings with no corresponding
4909
         * replacement string are replaced with empty strings. Replacement strings with
4910
         * no corresponding search string are ignored.
4911
         *
4912
         * An array parameter for the replacements is only allowed if the search parameter
4913
         * is an array of strings too!
4914
         *
4915
         * Because the method replaces from left to right, it might replace a previously
4916
         * inserted value when doing multiple replacements. Entries which are non-string
4917
         * values are left untouched.
4918
         *
4919
         * @param array|string $search String or list of strings to search for
4920
         * @param array|string $replace String or list of strings of replacement strings
4921
         * @param bool $case TRUE if replacements should be case insensitive, FALSE if case-sensitive
4922
         * @return self<int|string,mixed> Updated map for fluid interface
4923
         */
4924
        public function strReplace( $search, $replace, bool $case = false ) : self
4925
        {
4926
                $fcn = $case ? 'str_ireplace' : 'str_replace';
8✔
4927

4928
                foreach( $this->list() as &$entry )
8✔
4929
                {
4930
                        if( is_string( $entry ) ) {
8✔
4931
                                $entry = $fcn( $search, $replace, $entry );
8✔
4932
                        }
4933
                }
4934

4935
                return $this;
8✔
4936
        }
4937

4938

4939
        /**
4940
         * Tests if at least one of the entries starts with at least one of the passed strings.
4941
         *
4942
         * Examples:
4943
         *  Map::from( ['abc'] )->strStarts( '' );
4944
         *  Map::from( ['abc'] )->strStarts( 'a' );
4945
         *  Map::from( ['abc'] )->strStarts( 'ab' );
4946
         *  Map::from( ['abc'] )->strStarts( ['a', 'b'] );
4947
         *  Map::from( ['abc'] )->strStarts( 'ab', 'ASCII' );
4948
         *  Map::from( ['abc'] )->strStarts( 'b' );
4949
         *  Map::from( ['abc'] )->strStarts( 'bc' );
4950
         *  Map::from( ['abc'] )->strStarts( ['b', 'c'] );
4951
         *  Map::from( ['abc'] )->strStarts( 'bc', 'ASCII' );
4952
         *
4953
         * Results:
4954
         * The first five examples will return TRUE while the last four will return FALSE.
4955
         *
4956
         * @param array|string $value The string or strings to search for in each entry
4957
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4958
         * @return bool TRUE if all of the entries ends with at least one of the strings, FALSE if not
4959
         * @todo 4.0 Add $case parameter at second position
4960
         */
4961
        public function strStarts( $value, string $encoding = 'UTF-8' ) : bool
4962
        {
4963
                foreach( $this->list() as $entry )
8✔
4964
                {
4965
                        $entry = (string) $entry;
8✔
4966

4967
                        foreach( (array) $value as $str )
8✔
4968
                        {
4969
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
8✔
4970
                                        return true;
8✔
4971
                                }
4972
                        }
4973
                }
4974

4975
                return false;
8✔
4976
        }
4977

4978

4979
        /**
4980
         * Tests if all of the entries starts with one of the passed strings.
4981
         *
4982
         * Examples:
4983
         *  Map::from( ['abc', 'def'] )->strStartsAll( '' );
4984
         *  Map::from( ['abc', 'acb'] )->strStartsAll( 'a' );
4985
         *  Map::from( ['abc', 'aba'] )->strStartsAll( 'ab' );
4986
         *  Map::from( ['abc', 'def'] )->strStartsAll( ['a', 'd'] );
4987
         *  Map::from( ['abc', 'acf'] )->strStartsAll( 'a', 'ASCII' );
4988
         *  Map::from( ['abc', 'def'] )->strStartsAll( 'd' );
4989
         *  Map::from( ['abc', 'bca'] )->strStartsAll( 'ab' );
4990
         *  Map::from( ['abc', 'bac'] )->strStartsAll( ['a', 'c'] );
4991
         *  Map::from( ['abc', 'cab'] )->strStartsAll( 'ab', 'ASCII' );
4992
         *
4993
         * Results:
4994
         * The first five examples will return TRUE while the last four will return FALSE.
4995
         *
4996
         * @param array|string $value The string or strings to search for in each entry
4997
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4998
         * @return bool TRUE if one of the entries starts with one of the strings, FALSE if not
4999
         * @todo 4.0 Add $case parameter at second position
5000
         */
5001
        public function strStartsAll( $value, string $encoding = 'UTF-8' ) : bool
5002
        {
5003
                $list = [];
8✔
5004

5005
                foreach( $this->list() as $entry )
8✔
5006
                {
5007
                        $entry = (string) $entry;
8✔
5008
                        $list[$entry] = 0;
8✔
5009

5010
                        foreach( (array) $value as $str )
8✔
5011
                        {
5012
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
8✔
5013
                                        $list[$entry] = 1; break;
8✔
5014
                                }
5015
                        }
5016
                }
5017

5018
                return array_sum( $list ) === count( $list );
8✔
5019
        }
5020

5021

5022
        /**
5023
         * Converts all alphabetic characters in strings to upper case.
5024
         *
5025
         * Examples:
5026
         *  Map::from( ['My String'] )->strUpper();
5027
         *  Map::from( ['τάχιστη'] )->strUpper();
5028
         *  Map::from( ['äpfel', 'birnen'] )->strUpper( 'ISO-8859-1' );
5029
         *  Map::from( [123] )->strUpper();
5030
         *  Map::from( [new stdClass] )->strUpper();
5031
         *
5032
         * Results:
5033
         * The first example will return ["MY STRING"], the second one ["ΤΆΧΙΣΤΗ"] and
5034
         * the third one ["ÄPFEL", "BIRNEN"]. The last two strings will be unchanged.
5035
         *
5036
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5037
         * @return self<int|string,mixed> Updated map for fluid interface
5038
         */
5039
        public function strUpper( string $encoding = 'UTF-8' ) :self
5040
        {
5041
                foreach( $this->list() as &$entry )
8✔
5042
                {
5043
                        if( is_string( $entry ) ) {
8✔
5044
                                $entry = mb_strtoupper( $entry, $encoding );
8✔
5045
                        }
5046
                }
5047

5048
                return $this;
8✔
5049
        }
5050

5051

5052
        /**
5053
         * Adds a suffix at the end of each map entry.
5054
         *
5055
         * By defaul, nested arrays are walked recusively so all entries at all levels are suffixed.
5056
         *
5057
         * Examples:
5058
         *  Map::from( ['a', 'b'] )->suffix( '-1' );
5059
         *  Map::from( ['a', ['b']] )->suffix( '-1' );
5060
         *  Map::from( ['a', ['b']] )->suffix( '-1', 1 );
5061
         *  Map::from( ['a', 'b'] )->suffix( function( $item, $key ) {
5062
         *      return '-' . ( ord( $item ) + ord( $key ) );
5063
         *  } );
5064
         *
5065
         * Results:
5066
         *  The first example returns ['a-1', 'b-1'] while the second one will return
5067
         *  ['a-1', ['b-1']]. In the third example, the depth is limited to the first
5068
         *  level only so it will return ['a-1', ['b']]. The forth example passing
5069
         *  the closure will return ['a-145', 'b-147'].
5070
         *
5071
         * The keys are preserved using this method.
5072
         *
5073
         * @param \Closure|string $suffix Suffix string or anonymous function with ($item, $key) as parameters
5074
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
5075
         * @return self<int|string,mixed> Updated map for fluid interface
5076
         */
5077
        public function suffix( $suffix, ?int $depth = null ) : self
5078
        {
5079
                $fcn = function( $list, $suffix, $depth ) use ( &$fcn ) {
6✔
5080

5081
                        foreach( $list as $key => $item )
8✔
5082
                        {
5083
                                if( is_array( $item ) ) {
8✔
5084
                                        $list[$key] = $depth > 1 ? $fcn( $item, $suffix, $depth - 1 ) : $item;
8✔
5085
                                } else {
5086
                                        $list[$key] = $item . ( is_callable( $suffix ) ? $suffix( $item, $key ) : $suffix );
8✔
5087
                                }
5088
                        }
5089

5090
                        return $list;
8✔
5091
                };
8✔
5092

5093
                $this->list = $fcn( $this->list(), $suffix, $depth ?? 0x7fffffff );
8✔
5094
                return $this;
8✔
5095
        }
5096

5097

5098
        /**
5099
         * Returns the sum of all integer and float values in the map.
5100
         *
5101
         * Examples:
5102
         *  Map::from( [1, 3, 5] )->sum();
5103
         *  Map::from( [1, 'sum', 5] )->sum();
5104
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->sum( 'p' );
5105
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( 'i/p' );
5106
         *  Map::from( [30, 50, 10] )->sum( fn( $val, $key ) => $val < 50 );
5107
         *
5108
         * Results:
5109
         * The first line will return "9", the second one "6", the third one "90"
5110
         * the forth on "80" and the last one "40".
5111
         *
5112
         * NULL values are treated as 0, non-numeric values will generate an error.
5113
         *
5114
         * This does also work for multi-dimensional arrays by passing the keys
5115
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5116
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5117
         * public properties of objects or objects implementing __isset() and __get() methods.
5118
         *
5119
         * @param Closure|string|null $col Closure, key or path to the values in the nested array or object to sum up
5120
         * @return float Sum of all elements or 0 if there are no elements in the map
5121
         */
5122
        public function sum( $col = null ) : float
5123
        {
5124
                if( $col instanceof \Closure ) {
24✔
5125
                        $vals = array_filter( $this->list(), $col, ARRAY_FILTER_USE_BOTH );
8✔
5126
                } elseif( is_string( $col ) ) {
16✔
5127
                        $vals = $this->col( $col )->toArray();
8✔
5128
                } elseif( is_null( $col ) ) {
8✔
5129
                        $vals = $this->list();
8✔
5130
                } else {
UNCOV
5131
                        throw new \InvalidArgumentException( 'Parameter is no closure or string' );
×
5132
                }
5133

5134
                return array_sum( $vals );
24✔
5135
        }
5136

5137

5138
        /**
5139
         * Returns a new map with the given number of items.
5140
         *
5141
         * The keys of the items returned in the new map are the same as in the original one.
5142
         *
5143
         * Examples:
5144
         *  Map::from( [1, 2, 3, 4] )->take( 2 );
5145
         *  Map::from( [1, 2, 3, 4] )->take( 2, 1 );
5146
         *  Map::from( [1, 2, 3, 4] )->take( 2, -2 );
5147
         *  Map::from( [1, 2, 3, 4] )->take( 2, function( $item, $key ) {
5148
         *      return $item < 2;
5149
         *  } );
5150
         *
5151
         * Results:
5152
         *  [0 => 1, 1 => 2]
5153
         *  [1 => 2, 2 => 3]
5154
         *  [2 => 3, 3 => 4]
5155
         *  [1 => 2, 2 => 3]
5156
         *
5157
         * The keys of the items returned in the new map are the same as in the original one.
5158
         *
5159
         * @param int $size Number of items to return
5160
         * @param \Closure|int $offset Number of items to skip or function($item, $key) returning true for skipped items
5161
         * @return self<int|string,mixed> New map
5162
         */
5163
        public function take( int $size, $offset = 0 ) : self
5164
        {
5165
                $list = $this->list();
40✔
5166

5167
                if( is_scalar( $offset ) ) {
40✔
5168
                        return new static( array_slice( $list, (int) $offset, $size, true ) );
24✔
5169
                }
5170

5171
                if( is_callable( $offset ) )
16✔
5172
                {
5173
                        $idx = 0;
8✔
5174

5175
                        foreach( $list as $key => $item )
8✔
5176
                        {
5177
                                if( !$offset( $item, $key ) ) {
8✔
5178
                                        break;
8✔
5179
                                }
5180

5181
                                ++$idx;
8✔
5182
                        }
5183

5184
                        return new static( array_slice( $list, $idx, $size, true ) );
8✔
5185
                }
5186

5187
                throw new \InvalidArgumentException( 'Only an integer or a closure is allowed as second argument for take()' );
8✔
5188
        }
5189

5190

5191
        /**
5192
         * Passes a clone of the map to the given callback.
5193
         *
5194
         * Use it to "tap" into a chain of methods to check the state between two
5195
         * method calls. The original map is not altered by anything done in the
5196
         * callback.
5197
         *
5198
         * Examples:
5199
         *  Map::from( [3, 2, 1] )->rsort()->tap( function( $map ) {
5200
         *    print_r( $map->remove( 0 )->toArray() );
5201
         *  } )->first();
5202
         *
5203
         * Results:
5204
         * It will sort the list in reverse order (`[1, 2, 3]`) while keeping the keys,
5205
         * then prints the items without the first (`[2, 3]`) in the function passed
5206
         * to `tap()` and returns the first item ("1") at the end.
5207
         *
5208
         * @param callable $callback Function receiving ($map) parameter
5209
         * @return self<int|string,mixed> Same map for fluid interface
5210
         */
5211
        public function tap( callable $callback ) : self
5212
        {
5213
                $callback( clone $this );
8✔
5214
                return $this;
8✔
5215
        }
5216

5217

5218
        /**
5219
         * Returns the elements as a plain array.
5220
         *
5221
         * @return array<int|string,mixed> Plain array
5222
         */
5223
        public function to() : array
5224
        {
5225
                return $this->list = $this->array( $this->list );
8✔
5226
        }
5227

5228

5229
        /**
5230
         * Returns the elements as a plain array.
5231
         *
5232
         * @return array<int|string,mixed> Plain array
5233
         */
5234
        public function toArray() : array
5235
        {
5236
                return $this->list = $this->array( $this->list );
1,944✔
5237
        }
5238

5239

5240
        /**
5241
         * Returns the elements encoded as JSON string.
5242
         *
5243
         * There are several options available to modify the JSON output:
5244
         * {@link https://www.php.net/manual/en/function.json-encode.php}
5245
         * The parameter can be a single JSON_* constant or a bitmask of several
5246
         * constants combine by bitwise OR (|), e.g.:
5247
         *
5248
         *  JSON_FORCE_OBJECT|JSON_HEX_QUOT
5249
         *
5250
         * @param int $options Combination of JSON_* constants
5251
         * @return string|null Array encoded as JSON string or NULL on failure
5252
         */
5253
        public function toJson( int $options = 0 ) : ?string
5254
        {
5255
                $result = json_encode( $this->list(), $options );
16✔
5256
                return $result !== false ? $result : null;
16✔
5257
        }
5258

5259

5260
        /**
5261
         * Reverses the element order in a copy of the map (alias).
5262
         *
5263
         * This method is an alias for reversed(). For performance reasons, reversed() should be
5264
         * preferred because it uses one method call less than toReversed().
5265
         *
5266
         * @return self<int|string,mixed> New map with a reversed copy of the elements
5267
         * @see reversed() - Underlying method with same parameters and return value but better performance
5268
         */
5269
        public function toReversed() : self
5270
        {
5271
                return $this->reversed();
8✔
5272
        }
5273

5274

5275
        /**
5276
         * Sorts the elements in a copy of the map using new keys (alias).
5277
         *
5278
         * This method is an alias for sorted(). For performance reasons, sorted() should be
5279
         * preferred because it uses one method call less than toSorted().
5280
         *
5281
         * @param int $options Sort options for PHP sort()
5282
         * @return self<int|string,mixed> New map with a sorted copy of the elements
5283
         * @see sorted() - Underlying method with same parameters and return value but better performance
5284
         */
5285
        public function toSorted( int $options = SORT_REGULAR ) : self
5286
        {
5287
                return $this->sorted( $options );
8✔
5288
        }
5289

5290

5291
        /**
5292
         * Creates a HTTP query string from the map elements.
5293
         *
5294
         * Examples:
5295
         *  Map::from( ['a' => 1, 'b' => 2] )->toUrl();
5296
         *  Map::from( ['a' => ['b' => 'abc', 'c' => 'def'], 'd' => 123] )->toUrl();
5297
         *
5298
         * Results:
5299
         *  a=1&b=2
5300
         *  a%5Bb%5D=abc&a%5Bc%5D=def&d=123
5301
         *
5302
         * @return string Parameter string for GET requests
5303
         */
5304
        public function toUrl() : string
5305
        {
5306
                return http_build_query( $this->list(), '', '&', PHP_QUERY_RFC3986 );
16✔
5307
        }
5308

5309

5310
        /**
5311
         * Creates new key/value pairs using the passed function and returns a new map for the result.
5312
         *
5313
         * Examples:
5314
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5315
         *      return [$key . '-2' => $value * 2];
5316
         *  } );
5317
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5318
         *      return [$key => $value * 2, $key . $key => $value * 4];
5319
         *  } );
5320
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5321
         *      return $key < 'b' ? [$key => $value * 2] : null;
5322
         *  } );
5323
         *  Map::from( ['la' => 2, 'le' => 4, 'li' => 6] )->transform( function( $value, $key ) {
5324
         *      return [$key[0] => $value * 2];
5325
         *  } );
5326
         *
5327
         * Results:
5328
         *  ['a-2' => 4, 'b-2' => 8]
5329
         *  ['a' => 4, 'aa' => 8, 'b' => 8, 'bb' => 16]
5330
         *  ['a' => 4]
5331
         *  ['l' => 12]
5332
         *
5333
         * If a key is returned twice, the last value will overwrite previous values.
5334
         *
5335
         * @param \Closure $callback Function with (value, key) parameters and returns an array of new key/value pair(s)
5336
         * @return self<int|string,mixed> New map with the new key/value pairs
5337
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
5338
         * @see rekey() - Changes the keys according to the passed function
5339
         */
5340
        public function transform( \Closure $callback ) : self
5341
        {
5342
                $result = [];
32✔
5343

5344
                foreach( $this->list() as $key => $value )
32✔
5345
                {
5346
                        foreach( (array) $callback( $value, $key ) as $newkey => $newval ) {
32✔
5347
                                $result[$newkey] = $newval;
32✔
5348
                        }
5349
                }
5350

5351
                return new static( $result );
32✔
5352
        }
5353

5354

5355
        /**
5356
         * Exchanges rows and columns for a two dimensional map.
5357
         *
5358
         * Examples:
5359
         *  Map::from( [
5360
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
5361
         *    ['name' => 'B', 2020 => 300, 2021 => 200, 2022 => 100],
5362
         *    ['name' => 'C', 2020 => 400, 2021 => 300, 2022 => 200],
5363
         *  ] )->transpose();
5364
         *
5365
         *  Map::from( [
5366
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
5367
         *    ['name' => 'B', 2020 => 300, 2021 => 200],
5368
         *    ['name' => 'C', 2020 => 400]
5369
         *  ] );
5370
         *
5371
         * Results:
5372
         *  [
5373
         *    'name' => ['A', 'B', 'C'],
5374
         *    2020 => [200, 300, 400],
5375
         *    2021 => [100, 200, 300],
5376
         *    2022 => [50, 100, 200]
5377
         *  ]
5378
         *
5379
         *  [
5380
         *    'name' => ['A', 'B', 'C'],
5381
         *    2020 => [200, 300, 400],
5382
         *    2021 => [100, 200],
5383
         *    2022 => [50]
5384
         *  ]
5385
         *
5386
         * @return self<int|string,mixed> New map
5387
         */
5388
        public function transpose() : self
5389
        {
5390
                $result = [];
16✔
5391

5392
                foreach( (array) $this->first( [] ) as $key => $col ) {
16✔
5393
                        $result[$key] = array_column( $this->list(), $key );
16✔
5394
                }
5395

5396
                return new static( $result );
16✔
5397
        }
5398

5399

5400
        /**
5401
         * Traverses trees of nested items passing each item to the callback.
5402
         *
5403
         * This does work for nested arrays and objects with public properties or
5404
         * objects implementing __isset() and __get() methods. To build trees
5405
         * of nested items, use the tree() method.
5406
         *
5407
         * Examples:
5408
         *   Map::from( [[
5409
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5410
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5411
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5412
         *     ]
5413
         *   ]] )->traverse();
5414
         *
5415
         *   Map::from( [[
5416
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5417
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5418
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5419
         *     ]
5420
         *   ]] )->traverse( function( $entry, $key, $level, $parent ) {
5421
         *     return str_repeat( '-', $level ) . '- ' . $entry['name'];
5422
         *   } );
5423
         *
5424
         *   Map::from( [[
5425
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5426
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5427
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5428
         *     ]
5429
         *   ]] )->traverse( function( &$entry, $key, $level, $parent ) {
5430
         *     $entry['path'] = isset( $parent['path'] ) ? $parent['path'] . '/' . $entry['name'] : $entry['name'];
5431
         *     return $entry;
5432
         *   } );
5433
         *
5434
         *   Map::from( [[
5435
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [
5436
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []]
5437
         *     ]
5438
         *   ]] )->traverse( null, 'nodes' );
5439
         *
5440
         * Results:
5441
         *   [
5442
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...]],
5443
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5444
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []],
5445
         *   ]
5446
         *
5447
         *   ['- n1', '-- n2', '-- n3']
5448
         *
5449
         *   [
5450
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...], 'path' => 'n1'],
5451
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => [], 'path' => 'n1/n2'],
5452
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => [], 'path' => 'n1/n3'],
5453
         *   ]
5454
         *
5455
         *   [
5456
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [...]],
5457
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []],
5458
         *   ]
5459
         *
5460
         * @param \Closure|null $callback Callback with (entry, key, level, $parent) arguments, returns the entry added to result
5461
         * @param string $nestKey Key to the children of each item
5462
         * @return self<int|string,mixed> New map with all items as flat list
5463
         */
5464
        public function traverse( ?\Closure $callback = null, string $nestKey = 'children' ) : self
5465
        {
5466
                $result = [];
40✔
5467
                $this->visit( $this->list(), $result, 0, $callback, $nestKey );
40✔
5468

5469
                return map( $result );
40✔
5470
        }
5471

5472

5473
        /**
5474
         * Creates a tree structure from the list items.
5475
         *
5476
         * Use this method to rebuild trees e.g. from database records. To traverse
5477
         * trees, use the traverse() method.
5478
         *
5479
         * Examples:
5480
         *  Map::from( [
5481
         *    ['id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1'],
5482
         *    ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2'],
5483
         *    ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3'],
5484
         *    ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4'],
5485
         *    ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5'],
5486
         *    ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6'],
5487
         *  ] )->tree( 'id', 'pid' );
5488
         *
5489
         * Results:
5490
         *   [1 => [
5491
         *     'id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1', 'children' => [
5492
         *       2 => ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2', 'children' => [
5493
         *         3 => ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3', 'children' => []]
5494
         *       ]],
5495
         *       4 => ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4', 'children' => [
5496
         *         5 => ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5', 'children' => []]
5497
         *       ]],
5498
         *       6 => ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6', 'children' => []]
5499
         *     ]
5500
         *   ]]
5501
         *
5502
         * To build the tree correctly, the items must be in order or at least the
5503
         * nodes of the lower levels must come first. For a tree like this:
5504
         * n1
5505
         * |- n2
5506
         * |  |- n3
5507
         * |- n4
5508
         * |  |- n5
5509
         * |- n6
5510
         *
5511
         * Accepted item order:
5512
         * - in order: n1, n2, n3, n4, n5, n6
5513
         * - lower levels first: n1, n2, n4, n6, n3, n5
5514
         *
5515
         * If your items are unordered, apply usort() first to the map entries, e.g.
5516
         *   Map::from( [['id' => 3, 'lvl' => 2], ...] )->usort( function( $item1, $item2 ) {
5517
         *     return $item1['lvl'] <=> $item2['lvl'];
5518
         *   } );
5519
         *
5520
         * @param string $idKey Name of the key with the unique ID of the node
5521
         * @param string $parentKey Name of the key with the ID of the parent node
5522
         * @param string $nestKey Name of the key with will contain the children of the node
5523
         * @return self<int|string,mixed> New map with one or more root tree nodes
5524
         */
5525
        public function tree( string $idKey, string $parentKey, string $nestKey = 'children' ) : self
5526
        {
5527
                $this->list();
8✔
5528
                $trees = $refs = [];
8✔
5529

5530
                foreach( $this->list as &$node )
8✔
5531
                {
5532
                        $node[$nestKey] = [];
8✔
5533
                        $refs[$node[$idKey]] = &$node;
8✔
5534

5535
                        if( $node[$parentKey] ) {
8✔
5536
                                $refs[$node[$parentKey]][$nestKey][$node[$idKey]] = &$node;
8✔
5537
                        } else {
5538
                                $trees[$node[$idKey]] = &$node;
8✔
5539
                        }
5540
                }
5541

5542
                return map( $trees );
8✔
5543
        }
5544

5545

5546
        /**
5547
         * Removes the passed characters from the left/right of all strings.
5548
         *
5549
         * Examples:
5550
         *  Map::from( [" abc\n", "\tcde\r\n"] )->trim();
5551
         *  Map::from( ["a b c", "cbax"] )->trim( 'abc' );
5552
         *
5553
         * Results:
5554
         * The first example will return ["abc", "cde"] while the second one will return [" b ", "x"].
5555
         *
5556
         * @param string $chars List of characters to trim
5557
         * @return self<int|string,mixed> Updated map for fluid interface
5558
         */
5559
        public function trim( string $chars = " \n\r\t\v\x00" ) : self
5560
        {
5561
                foreach( $this->list() as &$entry )
8✔
5562
                {
5563
                        if( is_string( $entry ) ) {
8✔
5564
                                $entry = trim( $entry, $chars );
8✔
5565
                        }
5566
                }
5567

5568
                return $this;
8✔
5569
        }
5570

5571

5572
        /**
5573
         * Sorts all elements using a callback and maintains the key association.
5574
         *
5575
         * The given callback will be used to compare the values. The callback must accept
5576
         * two parameters (item A and B) and must return -1 if item A is smaller than
5577
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5578
         * method name and an anonymous function can be passed.
5579
         *
5580
         * Examples:
5581
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( 'strcasecmp' );
5582
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( function( $itemA, $itemB ) {
5583
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5584
         *  } );
5585
         *
5586
         * Results:
5587
         *  ['b' => 'a', 'a' => 'B']
5588
         *  ['b' => 'a', 'a' => 'B']
5589
         *
5590
         * The keys are preserved using this method and no new map is created.
5591
         *
5592
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5593
         * @return self<int|string,mixed> Updated map for fluid interface
5594
         */
5595
        public function uasort( callable $callback ) : self
5596
        {
5597
                uasort( $this->list(), $callback );
16✔
5598
                return $this;
16✔
5599
        }
5600

5601

5602
        /**
5603
         * Sorts all elements using a callback and maintains the key association.
5604
         *
5605
         * The given callback will be used to compare the values. The callback must accept
5606
         * two parameters (item A and B) and must return -1 if item A is smaller than
5607
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5608
         * method name and an anonymous function can be passed.
5609
         *
5610
         * Examples:
5611
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( 'strcasecmp' );
5612
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( function( $itemA, $itemB ) {
5613
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5614
         *  } );
5615
         *
5616
         * Results:
5617
         *  ['b' => 'a', 'a' => 'B']
5618
         *  ['b' => 'a', 'a' => 'B']
5619
         *
5620
         * The keys are preserved using this method and a new map is created.
5621
         *
5622
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5623
         * @return self<int|string,mixed> Updated map for fluid interface
5624
         */
5625
        public function uasorted( callable $callback ) : self
5626
        {
5627
                return ( clone $this )->uasort( $callback );
8✔
5628
        }
5629

5630

5631
        /**
5632
         * Sorts the map elements by their keys using a callback.
5633
         *
5634
         * The given callback will be used to compare the keys. The callback must accept
5635
         * two parameters (key A and B) and must return -1 if key A is smaller than
5636
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
5637
         * method name and an anonymous function can be passed.
5638
         *
5639
         * Examples:
5640
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( 'strcasecmp' );
5641
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( function( $keyA, $keyB ) {
5642
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
5643
         *  } );
5644
         *
5645
         * Results:
5646
         *  ['a' => 'b', 'B' => 'a']
5647
         *  ['a' => 'b', 'B' => 'a']
5648
         *
5649
         * The keys are preserved using this method and no new map is created.
5650
         *
5651
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
5652
         * @return self<int|string,mixed> Updated map for fluid interface
5653
         */
5654
        public function uksort( callable $callback ) : self
5655
        {
5656
                uksort( $this->list(), $callback );
16✔
5657
                return $this;
16✔
5658
        }
5659

5660

5661
        /**
5662
         * Sorts a copy of the map elements by their keys using a callback.
5663
         *
5664
         * The given callback will be used to compare the keys. The callback must accept
5665
         * two parameters (key A and B) and must return -1 if key A is smaller than
5666
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
5667
         * method name and an anonymous function can be passed.
5668
         *
5669
         * Examples:
5670
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( 'strcasecmp' );
5671
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( function( $keyA, $keyB ) {
5672
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
5673
         *  } );
5674
         *
5675
         * Results:
5676
         *  ['a' => 'b', 'B' => 'a']
5677
         *  ['a' => 'b', 'B' => 'a']
5678
         *
5679
         * The keys are preserved using this method and a new map is created.
5680
         *
5681
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
5682
         * @return self<int|string,mixed> Updated map for fluid interface
5683
         */
5684
        public function uksorted( callable $callback ) : self
5685
        {
5686
                return ( clone $this )->uksort( $callback );
8✔
5687
        }
5688

5689

5690
        /**
5691
         * Builds a union of the elements and the given elements without overwriting existing ones.
5692
         * Existing keys in the map will not be overwritten
5693
         *
5694
         * Examples:
5695
         *  Map::from( [0 => 'a', 1 => 'b'] )->union( [0 => 'c'] );
5696
         *  Map::from( ['a' => 1, 'b' => 2] )->union( ['c' => 1] );
5697
         *
5698
         * Results:
5699
         * The first example will result in [0 => 'a', 1 => 'b'] because the key 0
5700
         * isn't overwritten. In the second example, the result will be a combined
5701
         * list: ['a' => 1, 'b' => 2, 'c' => 1].
5702
         *
5703
         * If list entries should be overwritten,  please use merge() instead!
5704
         * The keys are preserved using this method and no new map is created.
5705
         *
5706
         * @param iterable<int|string,mixed> $elements List of elements
5707
         * @return self<int|string,mixed> Updated map for fluid interface
5708
         */
5709
        public function union( iterable $elements ) : self
5710
        {
5711
                $this->list = $this->list() + $this->array( $elements );
16✔
5712
                return $this;
16✔
5713
        }
5714

5715

5716
        /**
5717
         * Returns only unique elements from the map incl. their keys.
5718
         *
5719
         * Examples:
5720
         *  Map::from( [0 => 'a', 1 => 'b', 2 => 'b', 3 => 'c'] )->unique();
5721
         *  Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->unique( 'p' )
5722
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( 'i/p' )
5723
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( fn( $item, $key ) => $item['i']['p'] )
5724
         *
5725
         * Results:
5726
         * [0 => 'a', 1 => 'b', 3 => 'c']
5727
         * [['p' => 1], ['p' => 2]]
5728
         * [['i' => ['p' => '1']]]
5729
         * [['i' => ['p' => '1']]]
5730
         *
5731
         * Two elements are considered equal if comparing their string representions returns TRUE:
5732
         * (string) $elem1 === (string) $elem2
5733
         *
5734
         * The keys of the elements are only preserved in the new map if no key is passed.
5735
         *
5736
         * @param \Closure|string|null $col Key, path of the nested array or anonymous function with ($item, $key) parameters returning the value for comparison
5737
         * @return self<int|string,mixed> New map
5738
         */
5739
        public function unique( $col = null ) : self
5740
        {
5741
                if( $col === null ) {
40✔
5742
                        return new static( array_unique( $this->list() ) );
16✔
5743
                }
5744

5745
                $list = $this->list();
24✔
5746
                $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
24✔
5747

5748
                return new static( array_intersect_key( $list, array_unique( $map ) ) );
24✔
5749
        }
5750

5751

5752
        /**
5753
         * Pushes an element onto the beginning of the map without returning a new map.
5754
         *
5755
         * Examples:
5756
         *  Map::from( ['a', 'b'] )->unshift( 'd' );
5757
         *  Map::from( ['a', 'b'] )->unshift( 'd', 'first' );
5758
         *
5759
         * Results:
5760
         *  ['d', 'a', 'b']
5761
         *  ['first' => 'd', 0 => 'a', 1 => 'b']
5762
         *
5763
         * The keys of the elements are only preserved in the new map if no key is passed.
5764
         *
5765
         * Performance note:
5766
         * The bigger the list, the higher the performance impact because unshift()
5767
         * needs to create a new list and copies all existing elements to the new
5768
         * array. Usually, it's better to push() new entries at the end and reverse()
5769
         * the list afterwards:
5770
         *
5771
         *  $map->push( 'a' )->push( 'b' )->reverse();
5772
         * instead of
5773
         *  $map->unshift( 'a' )->unshift( 'b' );
5774
         *
5775
         * @param mixed $value Item to add at the beginning
5776
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
5777
         * @return self<int|string,mixed> Updated map for fluid interface
5778
         */
5779
        public function unshift( $value, $key = null ) : self
5780
        {
5781
                if( $key === null ) {
24✔
5782
                        array_unshift( $this->list(), $value );
16✔
5783
                } else {
5784
                        $this->list = [$key => $value] + $this->list();
8✔
5785
                }
5786

5787
                return $this;
24✔
5788
        }
5789

5790

5791
        /**
5792
         * Sorts all elements using a callback using new keys.
5793
         *
5794
         * The given callback will be used to compare the values. The callback must accept
5795
         * two parameters (item A and B) and must return -1 if item A is smaller than
5796
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5797
         * method name and an anonymous function can be passed.
5798
         *
5799
         * Examples:
5800
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usort( 'strcasecmp' );
5801
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usort( function( $itemA, $itemB ) {
5802
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5803
         *  } );
5804
         *
5805
         * Results:
5806
         *  [0 => 'a', 1 => 'B']
5807
         *  [0 => 'a', 1 => 'B']
5808
         *
5809
         * The keys aren't preserved and elements get a new index. No new map is created.
5810
         *
5811
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5812
         * @return self<int|string,mixed> Updated map for fluid interface
5813
         */
5814
        public function usort( callable $callback ) : self
5815
        {
5816
                usort( $this->list(), $callback );
16✔
5817
                return $this;
16✔
5818
        }
5819

5820

5821
        /**
5822
         * Sorts a copy of all elements using a callback using new keys.
5823
         *
5824
         * The given callback will be used to compare the values. The callback must accept
5825
         * two parameters (item A and B) and must return -1 if item A is smaller than
5826
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5827
         * method name and an anonymous function can be passed.
5828
         *
5829
         * Examples:
5830
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usorted( 'strcasecmp' );
5831
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->usorted( function( $itemA, $itemB ) {
5832
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5833
         *  } );
5834
         *
5835
         * Results:
5836
         *  [0 => 'a', 1 => 'B']
5837
         *  [0 => 'a', 1 => 'B']
5838
         *
5839
         * The keys aren't preserved, elements get a new index and a new map is created.
5840
         *
5841
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5842
         * @return self<int|string,mixed> Updated map for fluid interface
5843
         */
5844
        public function usorted( callable $callback ) : self
5845
        {
5846
                return ( clone $this )->usort( $callback );
8✔
5847
        }
5848

5849

5850
        /**
5851
         * Resets the keys and return the values in a new map.
5852
         *
5853
         * Examples:
5854
         *  Map::from( ['x' => 'b', 2 => 'a', 'c'] )->values();
5855
         *
5856
         * Results:
5857
         * A new map with [0 => 'b', 1 => 'a', 2 => 'c'] as content
5858
         *
5859
         * @return self<int|string,mixed> New map of the values
5860
         */
5861
        public function values() : self
5862
        {
5863
                return new static( array_values( $this->list() ) );
80✔
5864
        }
5865

5866

5867
        /**
5868
         * Applies the given callback to all elements.
5869
         *
5870
         * To change the values of the Map, specify the value parameter as reference
5871
         * (&$value). You can only change the values but not the keys nor the array
5872
         * structure.
5873
         *
5874
         * Examples:
5875
         *  Map::from( ['a', 'B', ['c', 'd'], 'e'] )->walk( function( &$value ) {
5876
         *    $value = strtoupper( $value );
5877
         *  } );
5878
         *  Map::from( [66 => 'B', 97 => 'a'] )->walk( function( $value, $key ) {
5879
         *    echo 'ASCII ' . $key . ' is ' . $value . "\n";
5880
         *  } );
5881
         *  Map::from( [1, 2, 3] )->walk( function( &$value, $key, $data ) {
5882
         *    $value = $data[$value] ?? $value;
5883
         *  }, [1 => 'one', 2 => 'two'] );
5884
         *
5885
         * Results:
5886
         * The first example will change the Map elements to:
5887
         *   ['A', 'B', ['C', 'D'], 'E']
5888
         * The output of the second one will be:
5889
         *  ASCII 66 is B
5890
         *  ASCII 97 is a
5891
         * The last example changes the Map elements to:
5892
         *  ['one', 'two', 3]
5893
         *
5894
         * By default, Map elements which are arrays will be traversed recursively.
5895
         * To iterate over the Map elements only, pass FALSE as third parameter.
5896
         *
5897
         * @param callable $callback Function with (item, key, data) parameters
5898
         * @param mixed $data Arbitrary data that will be passed to the callback as third parameter
5899
         * @param bool $recursive TRUE to traverse sub-arrays recursively (default), FALSE to iterate Map elements only
5900
         * @return self<int|string,mixed> Updated map for fluid interface
5901
         */
5902
        public function walk( callable $callback, $data = null, bool $recursive = true ) : self
5903
        {
5904
                if( $recursive ) {
24✔
5905
                        array_walk_recursive( $this->list(), $callback, $data );
16✔
5906
                } else {
5907
                        array_walk( $this->list(), $callback, $data );
8✔
5908
                }
5909

5910
                return $this;
24✔
5911
        }
5912

5913

5914
        /**
5915
         * Filters the list of elements by a given condition.
5916
         *
5917
         * Examples:
5918
         *  Map::from( [
5919
         *    ['id' => 1, 'type' => 'name'],
5920
         *    ['id' => 2, 'type' => 'short'],
5921
         *  ] )->where( 'type', '==', 'name' );
5922
         *
5923
         *  Map::from( [
5924
         *    ['id' => 3, 'price' => 10],
5925
         *    ['id' => 4, 'price' => 50],
5926
         *  ] )->where( 'price', '>', 20 );
5927
         *
5928
         *  Map::from( [
5929
         *    ['id' => 3, 'price' => 10],
5930
         *    ['id' => 4, 'price' => 50],
5931
         *  ] )->where( 'price', 'in', [10, 25] );
5932
         *
5933
         *  Map::from( [
5934
         *    ['id' => 3, 'price' => 10],
5935
         *    ['id' => 4, 'price' => 50],
5936
         *  ] )->where( 'price', '-', [10, 100] );
5937
         *
5938
         *  Map::from( [
5939
         *    ['item' => ['id' => 3, 'price' => 10]],
5940
         *    ['item' => ['id' => 4, 'price' => 50]],
5941
         *  ] )->where( 'item/price', '>', 30 );
5942
         *
5943
         * Results:
5944
         *  [0 => ['id' => 1, 'type' => 'name']]
5945
         *  [1 => ['id' => 4, 'price' => 50]]
5946
         *  [0 => ['id' => 3, 'price' => 10]]
5947
         *  [0 => ['id' => 3, 'price' => 10], ['id' => 4, 'price' => 50]]
5948
         *  [1 => ['item' => ['id' => 4, 'price' => 50]]]
5949
         *
5950
         * Available operators are:
5951
         * * '==' : Equal
5952
         * * '===' : Equal and same type
5953
         * * '!=' : Not equal
5954
         * * '!==' : Not equal and same type
5955
         * * '<=' : Smaller than an equal
5956
         * * '>=' : Greater than an equal
5957
         * * '<' : Smaller
5958
         * * '>' : Greater
5959
         * 'in' : Array of value which are in the list of values
5960
         * '-' : Values between array of start and end value, e.g. [10, 100] (inclusive)
5961
         *
5962
         * This does also work for multi-dimensional arrays by passing the keys
5963
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5964
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5965
         * public properties of objects or objects implementing __isset() and __get() methods.
5966
         *
5967
         * The keys of the original map are preserved in the returned map.
5968
         *
5969
         * @param string $key Key or path of the value in the array or object used for comparison
5970
         * @param string $op Operator used for comparison
5971
         * @param mixed $value Value used for comparison
5972
         * @return self<int|string,mixed> New map for fluid interface
5973
         */
5974
        public function where( string $key, string $op, $value ) : self
5975
        {
5976
                return $this->filter( function( $item ) use ( $key, $op, $value ) {
36✔
5977

5978
                        if( ( $val = $this->val( $item, explode( $this->sep, $key ) ) ) !== null )
48✔
5979
                        {
5980
                                switch( $op )
5✔
5981
                                {
5982
                                        case '-':
40✔
5983
                                                $list = (array) $value;
8✔
5984
                                                return $val >= current( $list ) && $val <= end( $list );
8✔
5985
                                        case 'in': return in_array( $val, (array) $value );
32✔
5986
                                        case '<': return $val < $value;
24✔
5987
                                        case '>': return $val > $value;
24✔
5988
                                        case '<=': return $val <= $value;
16✔
5989
                                        case '>=': return $val >= $value;
16✔
5990
                                        case '===': return $val === $value;
16✔
5991
                                        case '!==': return $val !== $value;
16✔
5992
                                        case '!=': return $val != $value;
16✔
5993
                                        default: return $val == $value;
16✔
5994
                                }
5995
                        }
5996

5997
                        return false;
8✔
5998
                } );
48✔
5999
        }
6000

6001

6002
        /**
6003
         * Returns a copy of the map with the element at the given index replaced with the given value.
6004
         *
6005
         * Examples:
6006
         *  $m = Map::from( ['a' => 1] );
6007
         *  $m->with( 2, 'b' );
6008
         *  $m->with( 'a', 2 );
6009
         *
6010
         * Results:
6011
         *  ['a' => 1, 2 => 'b']
6012
         *  ['a' => 2]
6013
         *
6014
         * The original map ($m) stays untouched!
6015
         * This method is a shortcut for calling the copy() and set() methods.
6016
         *
6017
         * @param int|string $key Array key to set or replace
6018
         * @param mixed $value New value for the given key
6019
         * @return self<int|string,mixed> New map
6020
         */
6021
        public function with( $key, $value ) : self
6022
        {
6023
                return ( clone $this )->set( $key, $value );
8✔
6024
        }
6025

6026

6027
        /**
6028
         * Merges the values of all arrays at the corresponding index.
6029
         *
6030
         * Examples:
6031
         *  $en = ['one', 'two', 'three'];
6032
         *  $es = ['uno', 'dos', 'tres'];
6033
         *  $m = Map::from( [1, 2, 3] )->zip( $en, $es );
6034
         *
6035
         * Results:
6036
         *  [
6037
         *    [1, 'one', 'uno'],
6038
         *    [2, 'two', 'dos'],
6039
         *    [3, 'three', 'tres'],
6040
         *  ]
6041
         *
6042
         * @param array<int|string,mixed>|\Traversable<int|string,mixed>|\Iterator<int|string,mixed> $arrays List of arrays to merge with at the same position
6043
         * @return self<int|string,mixed> New map of arrays
6044
         */
6045
        public function zip( ...$arrays ) : self
6046
        {
6047
                $args = array_map( function( $items ) {
6✔
6048
                        return $this->array( $items );
8✔
6049
                }, $arrays );
8✔
6050

6051
                return new static( array_map( null, $this->list(), ...$args ) );
8✔
6052
        }
6053

6054

6055
        /**
6056
         * Returns a plain array of the given elements.
6057
         *
6058
         * @param mixed $elements List of elements or single value
6059
         * @return array<int|string,mixed> Plain array
6060
         */
6061
        protected function array( $elements ) : array
6062
        {
6063
                if( is_array( $elements ) ) {
2,064✔
6064
                        return $elements;
1,984✔
6065
                }
6066

6067
                if( $elements instanceof \Closure ) {
312✔
UNCOV
6068
                        return (array) $elements();
×
6069
                }
6070

6071
                if( $elements instanceof \Aimeos\Map ) {
312✔
6072
                        return $elements->toArray();
184✔
6073
                }
6074

6075
                if( is_iterable( $elements ) ) {
136✔
6076
                        return iterator_to_array( $elements, true );
24✔
6077
                }
6078

6079
                return $elements !== null ? [$elements] : [];
112✔
6080
        }
6081

6082

6083
        /**
6084
         * Flattens a multi-dimensional array or map into a single level array.
6085
         *
6086
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
6087
         * @param array<mixed> &$result Will contain all elements from the multi-dimensional arrays afterwards
6088
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
6089
         */
6090
        protected function flatten( iterable $entries, array &$result, int $depth ) : void
6091
        {
6092
                foreach( $entries as $entry )
40✔
6093
                {
6094
                        if( is_iterable( $entry ) && $depth > 0 ) {
40✔
6095
                                $this->flatten( $entry, $result, $depth - 1 );
32✔
6096
                        } else {
6097
                                $result[] = $entry;
40✔
6098
                        }
6099
                }
6100
        }
10✔
6101

6102

6103
        /**
6104
         * Flattens a multi-dimensional array or map into a single level array.
6105
         *
6106
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
6107
         * @param array<int|string,mixed> $result Will contain all elements from the multi-dimensional arrays afterwards
6108
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
6109
         */
6110
        protected function kflatten( iterable $entries, array &$result, int $depth ) : void
6111
        {
6112
                foreach( $entries as $key => $entry )
40✔
6113
                {
6114
                        if( is_iterable( $entry ) && $depth > 0 ) {
40✔
6115
                                $this->kflatten( $entry, $result, $depth - 1 );
40✔
6116
                        } else {
6117
                                $result[$key] = $entry;
40✔
6118
                        }
6119
                }
6120
        }
10✔
6121

6122

6123
        /**
6124
         * Returns a reference to the array of elements
6125
         *
6126
         * @return array Reference to the array of elements
6127
         */
6128
        protected function &list() : array
6129
        {
6130
                if( !is_array( $this->list ) ) {
2,800✔
UNCOV
6131
                        $this->list = $this->array( $this->list );
×
6132
                }
6133

6134
                return $this->list;
2,800✔
6135
        }
6136

6137

6138
        /**
6139
         * Returns a closure that retrieves the value for the passed key
6140
         *
6141
         * @param \Closure|string|null $key Closure or key (e.g. "key1/key2/key3") to retrieve the value for
6142
         * @return \Closure Closure that retrieves the value for the passed key
6143
         */
6144
        protected function mapper( $key = null, bool $cast = false ) : \Closure
6145
        {
6146
                if( $key instanceof \Closure ) {
48✔
6147
                        return $key;
16✔
6148
                }
6149

6150
                $parts = $key ? explode( $this->sep, (string) $key ) : [];
32✔
6151

6152
                return function( $item ) use ( $cast, $parts ) {
24✔
6153
                        $val = $this->val( $item, $parts );
32✔
6154
                        return $cast ? (string) $val : $val;
32✔
6155
                };
32✔
6156
        }
6157

6158

6159
        /**
6160
         * Returns a configuration value from an array.
6161
         *
6162
         * @param array<mixed>|object $entry The array or object to look at
6163
         * @param array<string> $parts Path parts to look for inside the array or object
6164
         * @return mixed Found value or null if no value is available
6165
         */
6166
        protected function val( $entry, array $parts )
6167
        {
6168
                foreach( $parts as $part )
328✔
6169
                {
6170
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$part] ) ) {
328✔
6171
                                $entry = $entry[$part];
192✔
6172
                        } elseif( is_object( $entry ) && isset( $entry->{$part} ) ) {
200✔
6173
                                $entry = $entry->{$part};
8✔
6174
                        } else {
6175
                                return null;
209✔
6176
                        }
6177
                }
6178

6179
                return $entry;
192✔
6180
        }
6181

6182

6183
        /**
6184
         * Visits each entry, calls the callback and returns the items in the result argument
6185
         *
6186
         * @param iterable<int|string,mixed> $entries List of entries with children (optional)
6187
         * @param array<mixed> $result Numerically indexed list of all visited entries
6188
         * @param int $level Current depth of the nodes in the tree
6189
         * @param \Closure|null $callback Callback with ($entry, $key, $level) arguments, returns the entry added to result
6190
         * @param string $nestKey Key to the children of each entry
6191
         * @param array<mixed>|object|null $parent Parent entry
6192
         */
6193
        protected function visit( iterable $entries, array &$result, int $level, ?\Closure $callback, string $nestKey, $parent = null ) : void
6194
        {
6195
                foreach( $entries as $key => $entry )
40✔
6196
                {
6197
                        $result[] = $callback ? $callback( $entry, $key, $level, $parent ) : $entry;
40✔
6198

6199
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$nestKey] ) ) {
40✔
6200
                                $this->visit( $entry[$nestKey], $result, $level + 1, $callback, $nestKey, $entry );
32✔
6201
                        } elseif( is_object( $entry ) && isset( $entry->{$nestKey} ) ) {
8✔
6202
                                $this->visit( $entry->{$nestKey}, $result, $level + 1, $callback, $nestKey, $entry );
12✔
6203
                        }
6204
                }
6205
        }
10✔
6206
}
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