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

aimeos / map / 13589590503

28 Feb 2025 01:55PM UTC coverage: 97.653% (+0.4%) from 97.205%
13589590503

push

github

aimeos
Fixed tests for PHP 7.x

749 of 767 relevant lines covered (97.65%)

50.22 hits per line

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

97.64
/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,160✔
53
                $this->list = $elements;
3,160✔
54
        }
790✔
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,472✔
274
                        return $elements;
24✔
275
                }
276

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

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

666

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

694

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

735

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

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

769
                return new static( $result );
8✔
770
        }
771

772

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

813
                return $this;
8✔
814
        }
815

816

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

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

847

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

859

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

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

884
                return new static( $list );
8✔
885
        }
886

887

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

927
                if( count( $vparts ) === 1 && count( $iparts ) === 1 ) {
72✔
928
                        return new static( array_column( $this->list(), $valuecol, $indexcol ) );
48✔
929
                }
930

931
                $list = [];
24✔
932

933
                foreach( $this->list() as $item )
24✔
934
                {
935
                        $v = $valuecol !== null ? $this->val( $item, $vparts ) : $item;
24✔
936

937
                        if( $indexcol !== null && ( $key = $this->val( $item, $iparts ) ) !== null ) {
24✔
938
                                $list[(string) $key] = $v;
16✔
939
                        } else {
940
                                $list[] = $v;
10✔
941
                        }
942
                }
943

944
                return new static( $list );
24✔
945
        }
946

947

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

982
                $result = [];
40✔
983
                $this->kflatten( $this->list(), $result, $depth ?? 0x7fffffff );
40✔
984
                return new static( $result );
40✔
985
        }
986

987

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

1005

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

1021

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

1040
                foreach( $elements as $item ) {
16✔
1041
                        $this->list[] = $item;
16✔
1042
                }
1043

1044
                return $this;
16✔
1045
        }
1046

1047

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

1081
                if( $value === null ) {
8✔
1082
                        return !$this->where( $key, '==', $operator )->isEmpty();
8✔
1083
                }
1084

1085
                return !$this->where( $key, $operator, $value )->isEmpty();
8✔
1086
        }
1087

1088

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

1102

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

1113

1114
        /**
1115
         * Counts how often the same values are in the map.
1116
         *
1117
         * Examples:
1118
         *  Map::from( [1, 'foo', 2, 'foo', 1] )->countBy();
1119
         *  Map::from( [1.11, 3.33, 3.33, 9.99] )->countBy();
1120
         *  Map::from( [['i' => ['p' => 1.11]], ['i' => ['p' => 3.33]], ['i' => ['p' => 3.33]]] )->countBy( 'i/p' );
1121
         *  Map::from( ['a@gmail.com', 'b@yahoo.com', 'c@gmail.com'] )->countBy( function( $email ) {
1122
         *    return substr( strrchr( $email, '@' ), 1 );
1123
         *  } );
1124
         *
1125
         * Results:
1126
         *  [1 => 2, 'foo' => 2, 2 => 1]
1127
         *  ['1.11' => 1, '3.33' => 2, '9.99' => 1]
1128
         *  ['1.11' => 1, '3.33' => 2]
1129
         *  ['gmail.com' => 2, 'yahoo.com' => 1]
1130
         *
1131
         * Counting values does only work for integers and strings because these are
1132
         * the only types allowed as array keys. All elements are casted to strings
1133
         * if no callback is passed. Custom callbacks need to make sure that only
1134
         * string or integer values are returned!
1135
         *
1136
         * @param \Closure|string|null $col Key as "key1/key2/key3" or function with (value, key) parameters returning the values for counting
1137
         * @return self<int|string,mixed> New map with values as keys and their count as value
1138
         */
1139
        public function countBy( $col = null ) : self
1140
        {
1141
                if( !( $col instanceof \Closure ) )
32✔
1142
                {
1143
                        $parts = $col ? explode( $this->sep, (string) $col ) : [];
24✔
1144

1145
                        $col = function( $item ) use ( $parts ) {
18✔
1146
                                return (string) $this->val( $item, $parts );
24✔
1147
                        };
24✔
1148
                }
1149

1150
                return new static( array_count_values( array_map( $col, $this->list() ) ) );
32✔
1151
        }
1152

1153

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

1179

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

1215
                return new static( array_diff( $this->list(), $this->array( $elements ) ) );
24✔
1216
        }
1217

1218

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

1256
                return new static( array_diff_assoc( $this->list(), $this->array( $elements ) ) );
16✔
1257
        }
1258

1259

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

1296
                return new static( array_diff_key( $this->list(), $this->array( $elements ) ) );
16✔
1297
        }
1298

1299

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

1331

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

1364
                if( $col !== null ) {
32✔
1365
                        $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
24✔
1366
                }
1367

1368
                return new static( array_diff_key( $list, array_unique( $map ) ) );
32✔
1369
        }
1370

1371

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

1397
                return $this;
16✔
1398
        }
1399

1400

1401
        /**
1402
         * Determines if the map is empty or not.
1403
         *
1404
         * Examples:
1405
         *  Map::from( [] )->empty();
1406
         *  Map::from( ['a'] )->empty();
1407
         *
1408
         * Results:
1409
         *  The first example returns TRUE while the second returns FALSE
1410
         *
1411
         * The method is equivalent to isEmpty().
1412
         *
1413
         * @return bool TRUE if map is empty, FALSE if not
1414
         */
1415
        public function empty() : bool
1416
        {
1417
                return empty( $this->list() );
16✔
1418
        }
1419

1420

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

1446
                return array_diff( $list, $elements ) === [] && array_diff( $elements, $list ) === [];
48✔
1447
        }
1448

1449

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

1477
                return true;
8✔
1478
        }
1479

1480

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

1502

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

1531
                return new static( array_filter( $this->list() ) );
8✔
1532
        }
1533

1534

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

1570
                if( $default instanceof \Throwable ) {
16✔
1571
                        throw $default;
8✔
1572
                }
1573

1574
                return $default;
8✔
1575
        }
1576

1577

1578
        /**
1579
         * Returns the first/last key where the callback returns TRUE.
1580
         *
1581
         * Examples:
1582
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1583
         *      return $value >= 'b';
1584
         *  } );
1585
         *  Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
1586
         *      return $value >= 'b';
1587
         *  }, null, true );
1588
         *  Map::from( [] )->findKey( function( $value, $key ) {
1589
         *      return $value >= 'b';
1590
         *  }, 'none' );
1591
         *  Map::from( [] )->findKey( function( $value, $key ) {
1592
         *      return $value >= 'b';
1593
         *  }, new \Exception( 'error' ) );
1594
         *
1595
         * Results:
1596
         * The first example will return '1' while the second will return '2' (last element).
1597
         * The third one will return "none" and the last one will throw the exception.
1598
         *
1599
         * @param \Closure $callback Function with (value, key) parameters and returns TRUE/FALSE
1600
         * @param mixed $default Default value or exception if the map contains no elements
1601
         * @param bool $reverse TRUE to test elements from back to front, FALSE for front to back (default)
1602
         * @return mixed Key of first matching element, passed default value or an exception
1603
         */
1604
        public function findKey( \Closure $callback, $default = null, bool $reverse = false )
1605
        {
1606
                foreach( ( $reverse ? array_reverse( $this->list(), true ) : $this->list() ) as $key => $value )
32✔
1607
                {
1608
                        if( $callback( $value, $key ) ) {
16✔
1609
                                return $key;
16✔
1610
                        }
1611
                }
1612

1613
                if( $default instanceof \Throwable ) {
16✔
1614
                        throw $default;
8✔
1615
                }
1616

1617
                return $default;
8✔
1618
        }
1619

1620

1621
        /**
1622
         * Returns the first element from the map.
1623
         *
1624
         * Examples:
1625
         *  Map::from( ['a', 'b'] )->first();
1626
         *  Map::from( [] )->first( 'x' );
1627
         *  Map::from( [] )->first( new \Exception( 'error' ) );
1628
         *  Map::from( [] )->first( function() { return rand(); } );
1629
         *
1630
         * Results:
1631
         * The first example will return 'b' and the second one 'x'. The third example
1632
         * will throw the exception passed if the map contains no elements. In the
1633
         * fourth example, a random value generated by the closure function will be
1634
         * returned.
1635
         *
1636
         * @param mixed $default Default value or exception if the map contains no elements
1637
         * @return mixed First value of map, (generated) default value or an exception
1638
         */
1639
        public function first( $default = null )
1640
        {
1641
                if( ( $value = reset( $this->list() ) ) !== false ) {
64✔
1642
                        return $value;
40✔
1643
                }
1644

1645
                if( $default instanceof \Closure ) {
32✔
1646
                        return $default();
8✔
1647
                }
1648

1649
                if( $default instanceof \Throwable ) {
24✔
1650
                        throw $default;
8✔
1651
                }
1652

1653
                return $default;
16✔
1654
        }
1655

1656

1657
        /**
1658
         * Returns the first key from the map.
1659
         *
1660
         * Examples:
1661
         *  Map::from( ['a' => 1, 'b' => 2] )->firstKey();
1662
         *  Map::from( [] )->firstKey();
1663
         *
1664
         * Results:
1665
         * The first example will return 'a' and the second one NULL.
1666
         *
1667
         * @return mixed First key of map or NULL if empty
1668
         */
1669
        public function firstKey()
1670
        {
1671
                $list = $this->list();
16✔
1672

1673
                if( function_exists( 'array_key_first' ) ) {
16✔
1674
                        return array_key_first( $list );
16✔
1675
                }
1676

1677
                reset( $list );
×
1678
                return key( $list );
×
1679
        }
1680

1681

1682
        /**
1683
         * Creates a new map with all sub-array elements added recursively withput overwriting existing keys.
1684
         *
1685
         * Examples:
1686
         *  Map::from( [[0, 1], [2, 3]] )->flat();
1687
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat();
1688
         *  Map::from( [[0, 1], [[2, 3], 4]] )->flat( 1 );
1689
         *  Map::from( [[0, 1], Map::from( [[2, 3], 4] )] )->flat();
1690
         *
1691
         * Results:
1692
         *  [0, 1, 2, 3]
1693
         *  [0, 1, 2, 3, 4]
1694
         *  [0, 1, [2, 3], 4]
1695
         *  [0, 1, 2, 3, 4]
1696
         *
1697
         * The keys are not preserved and the new map elements will be numbered from
1698
         * 0-n. A value smaller than 1 for depth will return the same map elements
1699
         * indexed from 0-n. Flattening does also work if elements implement the
1700
         * "Traversable" interface (which the Map object does).
1701
         *
1702
         * This method is similar than collapse() but doesn't replace existing elements.
1703
         * Keys are NOT preserved using this method!
1704
         *
1705
         * @param int|null $depth Number of levels to flatten multi-dimensional arrays or NULL for all
1706
         * @return self<int|string,mixed> New map with all sub-array elements added into it recursively, up to the specified depth
1707
         * @throws \InvalidArgumentException If depth must be greater or equal than 0 or NULL
1708
         */
1709
        public function flat( ?int $depth = null ) : self
1710
        {
1711
                if( $depth < 0 ) {
48✔
1712
                        throw new \InvalidArgumentException( 'Depth must be greater or equal than 0 or NULL' );
8✔
1713
                }
1714

1715
                $result = [];
40✔
1716
                $this->flatten( $this->list(), $result, $depth ?? 0x7fffffff );
40✔
1717
                return new static( $result );
40✔
1718
        }
1719

1720

1721
        /**
1722
         * Exchanges the keys with their values and vice versa.
1723
         *
1724
         * Examples:
1725
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->flip();
1726
         *
1727
         * Results:
1728
         *  ['X' => 'a', 'Y' => 'b']
1729
         *
1730
         * @return self<int|string,mixed> New map with keys as values and values as keys
1731
         */
1732
        public function flip() : self
1733
        {
1734
                return new static( array_flip( $this->list() ) );
8✔
1735
        }
1736

1737

1738
        /**
1739
         * Returns an element by key and casts it to float if possible.
1740
         *
1741
         * Examples:
1742
         *  Map::from( ['a' => true] )->float( 'a' );
1743
         *  Map::from( ['a' => 1] )->float( 'a' );
1744
         *  Map::from( ['a' => '1.1'] )->float( 'a' );
1745
         *  Map::from( ['a' => '10'] )->float( 'a' );
1746
         *  Map::from( ['a' => ['b' => ['c' => 1.1]]] )->float( 'a/b/c' );
1747
         *  Map::from( [] )->float( 'c', function() { return 1.1; } );
1748
         *  Map::from( [] )->float( 'a', 1.1 );
1749
         *
1750
         *  Map::from( [] )->float( 'b' );
1751
         *  Map::from( ['b' => ''] )->float( 'b' );
1752
         *  Map::from( ['b' => null] )->float( 'b' );
1753
         *  Map::from( ['b' => 'abc'] )->float( 'b' );
1754
         *  Map::from( ['b' => [1]] )->float( 'b' );
1755
         *  Map::from( ['b' => #resource] )->float( 'b' );
1756
         *  Map::from( ['b' => new \stdClass] )->float( 'b' );
1757
         *
1758
         *  Map::from( [] )->float( 'c', new \Exception( 'error' ) );
1759
         *
1760
         * Results:
1761
         * The first eight examples will return the float values for the passed keys
1762
         * while the 9th to 14th example returns 0. The last example will throw an exception.
1763
         *
1764
         * This does also work for multi-dimensional arrays by passing the keys
1765
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1766
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1767
         * public properties of objects or objects implementing __isset() and __get() methods.
1768
         *
1769
         * @param int|string $key Key or path to the requested item
1770
         * @param mixed $default Default value if key isn't found (will be casted to float)
1771
         * @return float Value from map or default value
1772
         */
1773
        public function float( $key, $default = 0.0 ) : float
1774
        {
1775
                return (float) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
24✔
1776
        }
1777

1778

1779
        /**
1780
         * Returns an element from the map by key.
1781
         *
1782
         * Examples:
1783
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'a' );
1784
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'c', 'Z' );
1785
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->get( 'a/b/c' );
1786
         *  Map::from( [] )->get( 'Y', new \Exception( 'error' ) );
1787
         *  Map::from( [] )->get( 'Y', function() { return rand(); } );
1788
         *
1789
         * Results:
1790
         * The first example will return 'X', the second 'Z' and the third 'Y'. The forth
1791
         * example will throw the exception passed if the map contains no elements. In
1792
         * the fifth example, a random value generated by the closure function will be
1793
         * returned.
1794
         *
1795
         * This does also work for multi-dimensional arrays by passing the keys
1796
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1797
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1798
         * public properties of objects or objects implementing __isset() and __get() methods.
1799
         *
1800
         * @param int|string $key Key or path to the requested item
1801
         * @param mixed $default Default value if no element matches
1802
         * @return mixed Value from map or default value
1803
         */
1804
        public function get( $key, $default = null )
1805
        {
1806
                $list = $this->list();
184✔
1807

1808
                if( array_key_exists( $key, $list ) ) {
184✔
1809
                        return $list[$key];
48✔
1810
                }
1811

1812
                if( ( $v = $this->val( $list, explode( $this->sep, (string) $key ) ) ) !== null ) {
168✔
1813
                        return $v;
56✔
1814
                }
1815

1816
                if( $default instanceof \Closure ) {
144✔
1817
                        return $default();
48✔
1818
                }
1819

1820
                if( $default instanceof \Throwable ) {
96✔
1821
                        throw $default;
48✔
1822
                }
1823

1824
                return $default;
48✔
1825
        }
1826

1827

1828
        /**
1829
         * Returns an iterator for the elements.
1830
         *
1831
         * This method will be used by e.g. foreach() to loop over all entries:
1832
         *  foreach( Map::from( ['a', 'b'] ) as $value )
1833
         *
1834
         * @return \ArrayIterator<int|string,mixed> Iterator for map elements
1835
         */
1836
        public function getIterator() : \ArrayIterator
1837
        {
1838
                return new \ArrayIterator( $this->list() );
40✔
1839
        }
1840

1841

1842
        /**
1843
         * Returns only items which matches the regular expression.
1844
         *
1845
         * All items are converted to string first before they are compared to the
1846
         * regular expression. Thus, fractions of ".0" will be removed in float numbers
1847
         * which may result in unexpected results.
1848
         *
1849
         * Examples:
1850
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/b/' );
1851
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/a/', PREG_GREP_INVERT );
1852
         *  Map::from( [1.5, 0, 1.0, 'a'] )->grep( '/^(\d+)?\.\d+$/' );
1853
         *
1854
         * Results:
1855
         *  ['ab', 'bc']
1856
         *  ['bc', 'cd']
1857
         *  [1.5] // float 1.0 is converted to string "1"
1858
         *
1859
         * The keys are preserved using this method.
1860
         *
1861
         * @param string $pattern Regular expression pattern, e.g. "/ab/"
1862
         * @param int $flags PREG_GREP_INVERT to return elements not matching the pattern
1863
         * @return self<int|string,mixed> New map containing only the matched elements
1864
         */
1865
        public function grep( string $pattern, int $flags = 0 ) : self
1866
        {
1867
                if( ( $result = preg_grep( $pattern, $this->list(), $flags ) ) === false )
32✔
1868
                {
1869
                        switch( preg_last_error() )
8✔
1870
                        {
1871
                                case PREG_INTERNAL_ERROR: $msg = 'Internal error'; break;
8✔
1872
                                case PREG_BACKTRACK_LIMIT_ERROR: $msg = 'Backtrack limit error'; break;
×
1873
                                case PREG_RECURSION_LIMIT_ERROR: $msg = 'Recursion limit error'; break;
×
1874
                                case PREG_BAD_UTF8_ERROR: $msg = 'Bad UTF8 error'; break;
×
1875
                                case PREG_BAD_UTF8_OFFSET_ERROR: $msg = 'Bad UTF8 offset error'; break;
×
1876
                                case PREG_JIT_STACKLIMIT_ERROR: $msg = 'JIT stack limit error'; break;
×
1877
                                default: $msg = 'Unknown error';
×
1878
                        }
1879

1880
                        throw new \RuntimeException( 'Regular expression error: ' . $msg );
8✔
1881
                }
1882

1883
                return new static( $result );
24✔
1884
        }
1885

1886

1887
        /**
1888
         * Groups associative array elements or objects by the passed key or closure.
1889
         *
1890
         * Instead of overwriting items with the same keys like to the col() method
1891
         * does, groupBy() keeps all entries in sub-arrays. It's preserves the keys
1892
         * of the orignal map entries too.
1893
         *
1894
         * Examples:
1895
         *  $list = [
1896
         *    10 => ['aid' => 123, 'code' => 'x-abc'],
1897
         *    20 => ['aid' => 123, 'code' => 'x-def'],
1898
         *    30 => ['aid' => 456, 'code' => 'x-def']
1899
         *  ];
1900
         *  Map::from( $list )->groupBy( 'aid' );
1901
         *  Map::from( $list )->groupBy( function( $item, $key ) {
1902
         *    return substr( $item['code'], -3 );
1903
         *  } );
1904
         *  Map::from( $list )->groupBy( 'xid' );
1905
         *
1906
         * Results:
1907
         *  [
1908
         *    123 => [10 => ['aid' => 123, 'code' => 'x-abc'], 20 => ['aid' => 123, 'code' => 'x-def']],
1909
         *    456 => [30 => ['aid' => 456, 'code' => 'x-def']]
1910
         *  ]
1911
         *  [
1912
         *    'abc' => [10 => ['aid' => 123, 'code' => 'x-abc']],
1913
         *    'def' => [20 => ['aid' => 123, 'code' => 'x-def'], 30 => ['aid' => 456, 'code' => 'x-def']]
1914
         *  ]
1915
         *  [
1916
         *    '' => [
1917
         *      10 => ['aid' => 123, 'code' => 'x-abc'],
1918
         *      20 => ['aid' => 123, 'code' => 'x-def'],
1919
         *      30 => ['aid' => 456, 'code' => 'x-def']
1920
         *    ]
1921
         *  ]
1922
         *
1923
         * In case the passed key doesn't exist in one or more items, these items
1924
         * are stored in a sub-array using an empty string as key.
1925
         *
1926
         * @param  \Closure|string|int $key Closure function with (item, idx) parameters returning the key or the key itself to group by
1927
         * @return self<int|string,mixed> New map with elements grouped by the given key
1928
         */
1929
        public function groupBy( $key ) : self
1930
        {
1931
                $result = [];
32✔
1932

1933
                foreach( $this->list() as $idx => $item )
32✔
1934
                {
1935
                        if( is_callable( $key ) ) {
32✔
1936
                                $keyval = $key( $item, $idx );
8✔
1937
                        } elseif( ( is_array( $item ) || $item instanceof \ArrayAccess ) && isset( $item[$key] ) ) {
24✔
1938
                                $keyval = $item[$key];
8✔
1939
                        } elseif( is_object( $item ) && isset( $item->{$key} ) ) {
16✔
1940
                                $keyval = $item->{$key};
8✔
1941
                        } else {
1942
                                $keyval = '';
8✔
1943
                        }
1944

1945
                        $result[$keyval][$idx] = $item;
32✔
1946
                }
1947

1948
                return new static( $result );
32✔
1949
        }
1950

1951

1952
        /**
1953
         * Determines if a key or several keys exists in the map.
1954
         *
1955
         * If several keys are passed as array, all keys must exist in the map for
1956
         * TRUE to be returned.
1957
         *
1958
         * Examples:
1959
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'a' );
1960
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'b'] );
1961
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->has( 'a/b/c' );
1962
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'c' );
1963
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'c'] );
1964
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'X' );
1965
         *
1966
         * Results:
1967
         * The first three examples will return TRUE while the other ones will return FALSE
1968
         *
1969
         * This does also work for multi-dimensional arrays by passing the keys
1970
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1971
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1972
         * public properties of objects or objects implementing __isset() and __get() methods.
1973
         *
1974
         * @param array<int|string>|int|string $key Key of the requested item or list of keys
1975
         * @return bool TRUE if key or keys are available in map, FALSE if not
1976
         */
1977
        public function has( $key ) : bool
1978
        {
1979
                $list = $this->list();
24✔
1980

1981
                foreach( (array) $key as $entry )
24✔
1982
                {
1983
                        if( array_key_exists( $entry, $list ) === false
24✔
1984
                                && $this->val( $list, explode( $this->sep, (string) $entry ) ) === null
24✔
1985
                        ) {
1986
                                return false;
24✔
1987
                        }
1988
                }
1989

1990
                return true;
24✔
1991
        }
1992

1993

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

2051
                if( $condition ) {
64✔
2052
                        return $then ? static::from( $then( $this, $condition ) ) : $this;
40✔
2053
                } elseif( $else ) {
24✔
2054
                        return static::from( $else( $this, $condition ) );
24✔
2055
                }
2056

2057
                return $this;
×
2058
        }
2059

2060

2061
        /**
2062
         * Executes callbacks depending if the map contains elements or not.
2063
         *
2064
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2065
         * executed and their returned value is passed back within a Map object. In
2066
         * case no "then" or "else" closure is given, the method will return the same
2067
         * map object.
2068
         *
2069
         * Examples:
2070
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2071
         *    $map->push( 'b' );
2072
         *  } );
2073
         *
2074
         *  Map::from( [] )->ifAny( null, function( $map ) {
2075
         *    return $map->push( 'b' );
2076
         *  } );
2077
         *
2078
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2079
         *    return 'c';
2080
         *  } );
2081
         *
2082
         * Results:
2083
         * The first example returns a Map containing ['a', 'b'] because the the initial
2084
         * Map is not empty. The second one returns  a Map with ['b'] because the initial
2085
         * Map is empty and the "else" closure is used. The last example returns ['c']
2086
         * as new map content.
2087
         *
2088
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2089
         * (a short form for anonymous closures) as parameters. The automatically have access
2090
         * to previously defined variables but can not modify them. Also, they can not have
2091
         * a void return type and must/will always return something. Details about
2092
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2093
         *
2094
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2095
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2096
         * @return self<int|string,mixed> New map
2097
         */
2098
        public function ifAny( ?\Closure $then = null, ?\Closure $else = null ) : self
2099
        {
2100
                return $this->if( !empty( $this->list() ), $then, $else );
24✔
2101
        }
2102

2103

2104
        /**
2105
         * Executes callbacks depending if the map is empty or not.
2106
         *
2107
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2108
         * executed and their returned value is passed back within a Map object. In
2109
         * case no "then" or "else" closure is given, the method will return the same
2110
         * map object.
2111
         *
2112
         * Examples:
2113
         *  Map::from( [] )->ifEmpty( function( $map ) {
2114
         *    $map->push( 'a' );
2115
         *  } );
2116
         *
2117
         *  Map::from( ['a'] )->ifEmpty( null, function( $map ) {
2118
         *    return $map->push( 'b' );
2119
         *  } );
2120
         *
2121
         * Results:
2122
         * The first example returns a Map containing ['a'] because the the initial Map
2123
         * is empty. The second one returns  a Map with ['a', 'b'] because the initial
2124
         * Map is not empty and the "else" closure is used.
2125
         *
2126
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2127
         * (a short form for anonymous closures) as parameters. The automatically have access
2128
         * to previously defined variables but can not modify them. Also, they can not have
2129
         * a void return type and must/will always return something. Details about
2130
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2131
         *
2132
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2133
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2134
         * @return self<int|string,mixed> New map
2135
         */
2136
        public function ifEmpty( ?\Closure $then = null, ?\Closure $else = null ) : self
2137
        {
2138
                return $this->if( empty( $this->list() ), $then, $else );
×
2139
        }
2140

2141

2142
        /**
2143
         * Tests if all entries in the map are objects implementing the given interface.
2144
         *
2145
         * Examples:
2146
         *  Map::from( [new Map(), new Map()] )->implements( '\Countable' );
2147
         *  Map::from( [new Map(), new stdClass()] )->implements( '\Countable' );
2148
         *  Map::from( [new Map(), 123] )->implements( '\Countable' );
2149
         *  Map::from( [new Map(), 123] )->implements( '\Countable', true );
2150
         *  Map::from( [new Map(), 123] )->implements( '\Countable', '\RuntimeException' );
2151
         *
2152
         * Results:
2153
         *  The first example returns TRUE while the second and third one return FALSE.
2154
         *  The forth example will throw an UnexpectedValueException while the last one
2155
         *  throws a RuntimeException.
2156
         *
2157
         * @param string $interface Name of the interface that must be implemented
2158
         * @param \Throwable|bool $throw Passing TRUE or an exception name will throw the exception instead of returning FALSE
2159
         * @return bool TRUE if all entries implement the interface or FALSE if at least one doesn't
2160
         * @throws \UnexpectedValueException|\Throwable If one entry doesn't implement the interface
2161
         */
2162
        public function implements( string $interface, $throw = false ) : bool
2163
        {
2164
                foreach( $this->list() as $entry )
24✔
2165
                {
2166
                        if( !( $entry instanceof $interface ) )
24✔
2167
                        {
2168
                                if( $throw )
24✔
2169
                                {
2170
                                        $name = is_string( $throw ) ? $throw : '\UnexpectedValueException';
16✔
2171
                                        throw new $name( "Does not implement $interface: " . print_r( $entry, true ) );
16✔
2172
                                }
2173

2174
                                return false;
10✔
2175
                        }
2176
                }
2177

2178
                return true;
8✔
2179
        }
2180

2181

2182
        /**
2183
         * Tests if the passed element or elements are part of the map.
2184
         *
2185
         * Examples:
2186
         *  Map::from( ['a', 'b'] )->in( 'a' );
2187
         *  Map::from( ['a', 'b'] )->in( ['a', 'b'] );
2188
         *  Map::from( ['a', 'b'] )->in( 'x' );
2189
         *  Map::from( ['a', 'b'] )->in( ['a', 'x'] );
2190
         *  Map::from( ['1', '2'] )->in( 2, true );
2191
         *
2192
         * Results:
2193
         * The first and second example will return TRUE while the other ones will return FALSE
2194
         *
2195
         * @param mixed|array $element Element or elements to search for in the map
2196
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2197
         * @return bool TRUE if all elements are available in map, FALSE if not
2198
         */
2199
        public function in( $element, bool $strict = false ) : bool
2200
        {
2201
                if( !is_array( $element ) ) {
32✔
2202
                        return in_array( $element, $this->list(), $strict );
32✔
2203
                };
2204

2205
                foreach( $element as $entry )
8✔
2206
                {
2207
                        if( in_array( $entry, $this->list(), $strict ) === false ) {
8✔
2208
                                return false;
8✔
2209
                        }
2210
                }
2211

2212
                return true;
8✔
2213
        }
2214

2215

2216
        /**
2217
         * Tests if the passed element or elements are part of the map.
2218
         *
2219
         * This method is an alias for in(). For performance reasons, in() should be
2220
         * preferred because it uses one method call less than includes().
2221
         *
2222
         * @param mixed|array $element Element or elements to search for in the map
2223
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2224
         * @return bool TRUE if all elements are available in map, FALSE if not
2225
         * @see in() - Underlying method with same parameters and return value but better performance
2226
         */
2227
        public function includes( $element, bool $strict = false ) : bool
2228
        {
2229
                return $this->in( $element, $strict );
8✔
2230
        }
2231

2232

2233
        /**
2234
         * Returns the numerical index of the given key.
2235
         *
2236
         * Examples:
2237
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( '8' );
2238
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( function( $key ) {
2239
         *      return $key == '8';
2240
         *  } );
2241
         *
2242
         * Results:
2243
         * Both examples will return "1" because the value "b" is at the second position
2244
         * and the returned index is zero based so the first item has the index "0".
2245
         *
2246
         * @param \Closure|string|int $value Key to search for or function with (key) parameters return TRUE if key is found
2247
         * @return int|null Position of the found value (zero based) or NULL if not found
2248
         */
2249
        public function index( $value ) : ?int
2250
        {
2251
                if( $value instanceof \Closure )
32✔
2252
                {
2253
                        $pos = 0;
16✔
2254

2255
                        foreach( $this->list() as $key => $item )
16✔
2256
                        {
2257
                                if( $value( $key ) ) {
8✔
2258
                                        return $pos;
8✔
2259
                                }
2260

2261
                                ++$pos;
8✔
2262
                        }
2263

2264
                        return null;
8✔
2265
                }
2266

2267
                $pos = array_search( $value, array_keys( $this->list() ) );
16✔
2268
                return $pos !== false ? $pos : null;
16✔
2269
        }
2270

2271

2272
        /**
2273
         * Inserts the value or values after the given element.
2274
         *
2275
         * Examples:
2276
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAfter( 'foo', 'baz' );
2277
         *  Map::from( ['foo', 'bar'] )->insertAfter( 'foo', ['baz', 'boo'] );
2278
         *  Map::from( ['foo', 'bar'] )->insertAfter( null, 'baz' );
2279
         *
2280
         * Results:
2281
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2282
         *  ['foo', 'baz', 'boo', 'bar']
2283
         *  ['foo', 'bar', 'baz']
2284
         *
2285
         * Numerical array indexes are not preserved.
2286
         *
2287
         * @param mixed $element Element after the value is inserted
2288
         * @param mixed $value Element or list of elements to insert
2289
         * @return self<int|string,mixed> Updated map for fluid interface
2290
         */
2291
        public function insertAfter( $element, $value ) : self
2292
        {
2293
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
24✔
2294
                array_splice( $this->list(), $position + 1, 0, $this->array( $value ) );
24✔
2295

2296
                return $this;
24✔
2297
        }
2298

2299

2300
        /**
2301
         * Inserts the item at the given position in the map.
2302
         *
2303
         * Examples:
2304
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 0, 'baz' );
2305
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 1, 'baz', 'c' );
2306
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 4, 'baz' );
2307
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( -1, 'baz', 'c' );
2308
         *
2309
         * Results:
2310
         *  [0 => 'baz', 'a' => 'foo', 'b' => 'bar']
2311
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2312
         *  ['a' => 'foo', 'b' => 'bar', 'c' => 'baz']
2313
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2314
         *
2315
         * @param int $pos Position the element it should be inserted at
2316
         * @param mixed $element Element to be inserted
2317
         * @param mixed|null $key Element key or NULL to assign an integer key automatically
2318
         * @return self<int|string,mixed> Updated map for fluid interface
2319
         */
2320
        public function insertAt( int $pos, $element, $key = null ) : self
2321
        {
2322
                if( $key !== null )
40✔
2323
                {
2324
                        $list = $this->list();
16✔
2325

2326
                        $this->list = array_merge(
16✔
2327
                                array_slice( $list, 0, $pos, true ),
16✔
2328
                                [$key => $element],
16✔
2329
                                array_slice( $list, $pos, null, true )
16✔
2330
                        );
12✔
2331
                }
2332
                else
2333
                {
2334
                        array_splice( $this->list(), $pos, 0, [$element] );
24✔
2335
                }
2336

2337
                return $this;
40✔
2338
        }
2339

2340

2341
        /**
2342
         * Inserts the value or values before the given element.
2343
         *
2344
         * Examples:
2345
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertBefore( 'bar', 'baz' );
2346
         *  Map::from( ['foo', 'bar'] )->insertBefore( 'bar', ['baz', 'boo'] );
2347
         *  Map::from( ['foo', 'bar'] )->insertBefore( null, 'baz' );
2348
         *
2349
         * Results:
2350
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2351
         *  ['foo', 'baz', 'boo', 'bar']
2352
         *  ['foo', 'bar', 'baz']
2353
         *
2354
         * Numerical array indexes are not preserved.
2355
         *
2356
         * @param mixed $element Element before the value is inserted
2357
         * @param mixed $value Element or list of elements to insert
2358
         * @return self<int|string,mixed> Updated map for fluid interface
2359
         */
2360
        public function insertBefore( $element, $value ) : self
2361
        {
2362
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
24✔
2363
                array_splice( $this->list(), $position, 0, $this->array( $value ) );
24✔
2364

2365
                return $this;
24✔
2366
        }
2367

2368

2369
        /**
2370
         * Tests if the passed value or values are part of the strings in the map.
2371
         *
2372
         * Examples:
2373
         *  Map::from( ['abc'] )->inString( 'c' );
2374
         *  Map::from( ['abc'] )->inString( 'bc' );
2375
         *  Map::from( [12345] )->inString( '23' );
2376
         *  Map::from( [123.4] )->inString( 23.4 );
2377
         *  Map::from( [12345] )->inString( false );
2378
         *  Map::from( [12345] )->inString( true );
2379
         *  Map::from( [false] )->inString( false );
2380
         *  Map::from( ['abc'] )->inString( '' );
2381
         *  Map::from( [''] )->inString( false );
2382
         *  Map::from( ['abc'] )->inString( 'BC', false );
2383
         *  Map::from( ['abc', 'def'] )->inString( ['de', 'xy'] );
2384
         *  Map::from( ['abc', 'def'] )->inString( ['E', 'x'] );
2385
         *  Map::from( ['abc', 'def'] )->inString( 'E' );
2386
         *  Map::from( [23456] )->inString( true );
2387
         *  Map::from( [false] )->inString( 0 );
2388
         *
2389
         * Results:
2390
         * The first eleven examples will return TRUE while the last four will return FALSE
2391
         *
2392
         * All scalar values (bool, float, int and string) are casted to string values before
2393
         * comparing to the given value. Non-scalar values in the map are ignored.
2394
         *
2395
         * @param array|string $value Value or values to compare the map elements, will be casted to string type
2396
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
2397
         * @return bool TRUE If at least one element matches, FALSE if value is not in any string of the map
2398
         * @deprecated Use multi-byte aware strContains() instead
2399
         */
2400
        public function inString( $value, bool $case = true ) : bool
2401
        {
2402
                $fcn = $case ? 'strpos' : 'stripos';
8✔
2403

2404
                foreach( (array) $value as $val )
8✔
2405
                {
2406
                        if( (string) $val === '' ) {
8✔
2407
                                return true;
8✔
2408
                        }
2409

2410
                        foreach( $this->list() as $item )
8✔
2411
                        {
2412
                                if( is_scalar( $item ) && $fcn( (string) $item, (string) $val ) !== false ) {
8✔
2413
                                        return true;
8✔
2414
                                }
2415
                        }
2416
                }
2417

2418
                return false;
8✔
2419
        }
2420

2421

2422
        /**
2423
         * Returns an element by key and casts it to integer if possible.
2424
         *
2425
         * Examples:
2426
         *  Map::from( ['a' => true] )->int( 'a' );
2427
         *  Map::from( ['a' => '1'] )->int( 'a' );
2428
         *  Map::from( ['a' => 1.1] )->int( 'a' );
2429
         *  Map::from( ['a' => '10'] )->int( 'a' );
2430
         *  Map::from( ['a' => ['b' => ['c' => 1]]] )->int( 'a/b/c' );
2431
         *  Map::from( [] )->int( 'c', function() { return rand( 1, 1 ); } );
2432
         *  Map::from( [] )->int( 'a', 1 );
2433
         *
2434
         *  Map::from( [] )->int( 'b' );
2435
         *  Map::from( ['b' => ''] )->int( 'b' );
2436
         *  Map::from( ['b' => 'abc'] )->int( 'b' );
2437
         *  Map::from( ['b' => null] )->int( 'b' );
2438
         *  Map::from( ['b' => [1]] )->int( 'b' );
2439
         *  Map::from( ['b' => #resource] )->int( 'b' );
2440
         *  Map::from( ['b' => new \stdClass] )->int( 'b' );
2441
         *
2442
         *  Map::from( [] )->int( 'c', new \Exception( 'error' ) );
2443
         *
2444
         * Results:
2445
         * The first seven examples will return 1 while the 8th to 14th example
2446
         * returns 0. The last example will throw an exception.
2447
         *
2448
         * This does also work for multi-dimensional arrays by passing the keys
2449
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2450
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2451
         * public properties of objects or objects implementing __isset() and __get() methods.
2452
         *
2453
         * @param int|string $key Key or path to the requested item
2454
         * @param mixed $default Default value if key isn't found (will be casted to integer)
2455
         * @return int Value from map or default value
2456
         */
2457
        public function int( $key, $default = 0 ) : int
2458
        {
2459
                return (int) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
24✔
2460
        }
2461

2462

2463
        /**
2464
         * Returns all values in a new map that are available in both, the map and the given elements.
2465
         *
2466
         * Examples:
2467
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersect( ['bar'] );
2468
         *
2469
         * Results:
2470
         *  ['b' => 'bar']
2471
         *
2472
         * If a callback is passed, the given function will be used to compare the values.
2473
         * The function must accept two parameters (value A and B) and must return
2474
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2475
         * greater than value B. Both, a method name and an anonymous function can be passed:
2476
         *
2477
         *  Map::from( [0 => 'a'] )->intersect( [0 => 'A'], 'strcasecmp' );
2478
         *  Map::from( ['b' => 'a'] )->intersect( ['B' => 'A'], 'strcasecmp' );
2479
         *  Map::from( ['b' => 'a'] )->intersect( ['c' => 'A'], function( $valA, $valB ) {
2480
         *      return strtolower( $valA ) <=> strtolower( $valB );
2481
         *  } );
2482
         *
2483
         * All examples will return a map containing ['a'] because both contain the same
2484
         * values when compared case insensitive.
2485
         *
2486
         * The keys are preserved using this method.
2487
         *
2488
         * @param iterable<int|string,mixed> $elements List of elements
2489
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2490
         * @return self<int|string,mixed> New map
2491
         */
2492
        public function intersect( iterable $elements, ?callable $callback = null ) : self
2493
        {
2494
                $list = $this->list();
16✔
2495
                $elements = $this->array( $elements );
16✔
2496

2497
                if( $callback ) {
16✔
2498
                        return new static( array_uintersect( $list, $elements, $callback ) );
8✔
2499
                }
2500

2501
                return new static( array_intersect( $list, $elements ) );
8✔
2502
        }
2503

2504

2505
        /**
2506
         * Returns all values in a new map that are available in both, the map and the given elements while comparing the keys too.
2507
         *
2508
         * Examples:
2509
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectAssoc( new Map( ['foo', 'b' => 'bar'] ) );
2510
         *
2511
         * Results:
2512
         *  ['a' => 'foo']
2513
         *
2514
         * If a callback is passed, the given function will be used to compare the values.
2515
         * The function must accept two parameters (value A and B) and must return
2516
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2517
         * greater than value B. Both, a method name and an anonymous function can be passed:
2518
         *
2519
         *  Map::from( [0 => 'a'] )->intersectAssoc( [0 => 'A'], 'strcasecmp' );
2520
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['B' => 'A'], 'strcasecmp' );
2521
         *  Map::from( ['b' => 'a'] )->intersectAssoc( ['c' => 'A'], function( $valA, $valB ) {
2522
         *      return strtolower( $valA ) <=> strtolower( $valB );
2523
         *  } );
2524
         *
2525
         * The first example will return [0 => 'a'] because both contain the same
2526
         * values when compared case insensitive. The second and third example will return
2527
         * an empty map because the keys doesn't match ("b" vs. "B" and "b" vs. "c").
2528
         *
2529
         * The keys are preserved using this method.
2530
         *
2531
         * @param iterable<int|string,mixed> $elements List of elements
2532
         * @param  callable|null $callback Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2533
         * @return self<int|string,mixed> New map
2534
         */
2535
        public function intersectAssoc( iterable $elements, ?callable $callback = null ) : self
2536
        {
2537
                $elements = $this->array( $elements );
40✔
2538

2539
                if( $callback ) {
40✔
2540
                        return new static( array_uintersect_assoc( $this->list(), $elements, $callback ) );
8✔
2541
                }
2542

2543
                return new static( array_intersect_assoc( $this->list(), $elements ) );
32✔
2544
        }
2545

2546

2547
        /**
2548
         * Returns all values in a new map that are available in both, the map and the given elements by comparing the keys only.
2549
         *
2550
         * Examples:
2551
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersectKeys( new Map( ['foo', 'b' => 'baz'] ) );
2552
         *
2553
         * Results:
2554
         *  ['b' => 'bar']
2555
         *
2556
         * If a callback is passed, the given function will be used to compare the keys.
2557
         * The function must accept two parameters (key A and B) and must return
2558
         * -1 if key A is smaller than key B, 0 if both are equal and 1 if key A is
2559
         * greater than key B. Both, a method name and an anonymous function can be passed:
2560
         *
2561
         *  Map::from( [0 => 'a'] )->intersectKeys( [0 => 'A'], 'strcasecmp' );
2562
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['B' => 'X'], 'strcasecmp' );
2563
         *  Map::from( ['b' => 'a'] )->intersectKeys( ['c' => 'a'], function( $keyA, $keyB ) {
2564
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
2565
         *  } );
2566
         *
2567
         * The first example will return a map with [0 => 'a'] and the second one will
2568
         * return a map with ['b' => 'a'] because both contain the same keys when compared
2569
         * case insensitive. The third example will return an empty map because the keys
2570
         * doesn't match ("b" vs. "c").
2571
         *
2572
         * The keys are preserved using this method.
2573
         *
2574
         * @param iterable<int|string,mixed> $elements List of elements
2575
         * @param  callable|null $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
2576
         * @return self<int|string,mixed> New map
2577
         */
2578
        public function intersectKeys( iterable $elements, ?callable $callback = null ) : self
2579
        {
2580
                $elements = $this->array( $elements );
24✔
2581

2582
                if( $callback ) {
24✔
2583
                        return new static( array_intersect_ukey( $this->list(), $elements, $callback ) );
8✔
2584
                }
2585

2586
                return new static( array_intersect_key( $this->list(), $elements ) );
16✔
2587
        }
2588

2589

2590
        /**
2591
         * Tests if the map consists of the same keys and values
2592
         *
2593
         * Examples:
2594
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'] );
2595
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'], true );
2596
         *  Map::from( [1, 2] )->is( ['1', '2'] );
2597
         *
2598
         * Results:
2599
         *  The first example returns TRUE while the second and third one returns FALSE
2600
         *
2601
         * @param iterable<int|string,mixed> $list List of key/value pairs to compare with
2602
         * @param bool $strict TRUE for comparing order of elements too, FALSE for key/values only
2603
         * @return bool TRUE if given list is equal, FALSE if not
2604
         */
2605
        public function is( iterable $list, bool $strict = false ) : bool
2606
        {
2607
                $list = $this->array( $list );
24✔
2608

2609
                if( $strict ) {
24✔
2610
                        return $this->list() === $list;
16✔
2611
                }
2612

2613
                return $this->list() == $list;
8✔
2614
        }
2615

2616

2617
        /**
2618
         * Determines if the map is empty or not.
2619
         *
2620
         * Examples:
2621
         *  Map::from( [] )->isEmpty();
2622
         *  Map::from( ['a'] )->isEmpty();
2623
         *
2624
         * Results:
2625
         *  The first example returns TRUE while the second returns FALSE
2626
         *
2627
         * The method is equivalent to empty().
2628
         *
2629
         * @return bool TRUE if map is empty, FALSE if not
2630
         */
2631
        public function isEmpty() : bool
2632
        {
2633
                return empty( $this->list() );
32✔
2634
        }
2635

2636

2637
        /**
2638
         * Checks if the map contains a list of subsequentially numbered keys.
2639
         *
2640
         * Examples:
2641
         * Map::from( [] )->isList();
2642
         * Map::from( [1, 3, 2] )->isList();
2643
         * Map::from( [0 => 1, 1 => 2, 2 => 3] )->isList();
2644
         * Map::from( [1 => 1, 2 => 2, 3 => 3] )->isList();
2645
         * Map::from( [0 => 1, 2 => 2, 3 => 3] )->isList();
2646
         * Map::from( ['a' => 1, 1 => 2, 'c' => 3] )->isList();
2647
         *
2648
         * Results:
2649
         * The first three examples return TRUE while the last three return FALSE
2650
         *
2651
         * @return bool TRUE if the map is a list, FALSE if not
2652
         */
2653
        public function isList() : bool
2654
        {
2655
                $i = -1;
8✔
2656

2657
                foreach( $this->list() as $k => $v )
8✔
2658
                {
2659
                        if( $k !== ++$i ) {
8✔
2660
                                return false;
8✔
2661
                        }
2662
                }
2663

2664
                return true;
8✔
2665
        }
2666

2667

2668
        /**
2669
         * Determines if all entries are numeric values.
2670
         *
2671
         * Examples:
2672
         *  Map::from( [] )->isNumeric();
2673
         *  Map::from( [1] )->isNumeric();
2674
         *  Map::from( [1.1] )->isNumeric();
2675
         *  Map::from( [010] )->isNumeric();
2676
         *  Map::from( [0x10] )->isNumeric();
2677
         *  Map::from( [0b10] )->isNumeric();
2678
         *  Map::from( ['010'] )->isNumeric();
2679
         *  Map::from( ['10'] )->isNumeric();
2680
         *  Map::from( ['10.1'] )->isNumeric();
2681
         *  Map::from( [' 10 '] )->isNumeric();
2682
         *  Map::from( ['10e2'] )->isNumeric();
2683
         *  Map::from( ['0b10'] )->isNumeric();
2684
         *  Map::from( ['0x10'] )->isNumeric();
2685
         *  Map::from( ['null'] )->isNumeric();
2686
         *  Map::from( [null] )->isNumeric();
2687
         *  Map::from( [true] )->isNumeric();
2688
         *  Map::from( [[]] )->isNumeric();
2689
         *  Map::from( [''] )->isNumeric();
2690
         *
2691
         * Results:
2692
         *  The first eleven examples return TRUE while the last seven return FALSE
2693
         *
2694
         * @return bool TRUE if all map entries are numeric values, FALSE if not
2695
         */
2696
        public function isNumeric() : bool
2697
        {
2698
                foreach( $this->list() as $val )
8✔
2699
                {
2700
                        if( !is_numeric( $val ) ) {
8✔
2701
                                return false;
8✔
2702
                        }
2703
                }
2704

2705
                return true;
8✔
2706
        }
2707

2708

2709
        /**
2710
         * Determines if all entries are objects.
2711
         *
2712
         * Examples:
2713
         *  Map::from( [] )->isObject();
2714
         *  Map::from( [new stdClass] )->isObject();
2715
         *  Map::from( [1] )->isObject();
2716
         *
2717
         * Results:
2718
         *  The first two examples return TRUE while the last one return FALSE
2719
         *
2720
         * @return bool TRUE if all map entries are objects, FALSE if not
2721
         */
2722
        public function isObject() : bool
2723
        {
2724
                foreach( $this->list() as $val )
8✔
2725
                {
2726
                        if( !is_object( $val ) ) {
8✔
2727
                                return false;
8✔
2728
                        }
2729
                }
2730

2731
                return true;
8✔
2732
        }
2733

2734

2735
        /**
2736
         * Determines if all entries are scalar values.
2737
         *
2738
         * Examples:
2739
         *  Map::from( [] )->isScalar();
2740
         *  Map::from( [1] )->isScalar();
2741
         *  Map::from( [1.1] )->isScalar();
2742
         *  Map::from( ['abc'] )->isScalar();
2743
         *  Map::from( [true, false] )->isScalar();
2744
         *  Map::from( [new stdClass] )->isScalar();
2745
         *  Map::from( [#resource] )->isScalar();
2746
         *  Map::from( [null] )->isScalar();
2747
         *  Map::from( [[1]] )->isScalar();
2748
         *
2749
         * Results:
2750
         *  The first five examples return TRUE while the others return FALSE
2751
         *
2752
         * @return bool TRUE if all map entries are scalar values, FALSE if not
2753
         */
2754
        public function isScalar() : bool
2755
        {
2756
                foreach( $this->list() as $val )
8✔
2757
                {
2758
                        if( !is_scalar( $val ) ) {
8✔
2759
                                return false;
8✔
2760
                        }
2761
                }
2762

2763
                return true;
8✔
2764
        }
2765

2766

2767
        /**
2768
         * Determines if all entries are string values.
2769
         *
2770
         * Examples:
2771
         *  Map::from( ['abc'] )->isString();
2772
         *  Map::from( [] )->isString();
2773
         *  Map::from( [1] )->isString();
2774
         *  Map::from( [1.1] )->isString();
2775
         *  Map::from( [true, false] )->isString();
2776
         *  Map::from( [new stdClass] )->isString();
2777
         *  Map::from( [#resource] )->isString();
2778
         *  Map::from( [null] )->isString();
2779
         *  Map::from( [[1]] )->isString();
2780
         *
2781
         * Results:
2782
         *  The first two examples return TRUE while the others return FALSE
2783
         *
2784
         * @return bool TRUE if all map entries are string values, FALSE if not
2785
         */
2786
        public function isString() : bool
2787
        {
2788
                foreach( $this->list() as $val )
8✔
2789
                {
2790
                        if( !is_string( $val ) ) {
8✔
2791
                                return false;
8✔
2792
                        }
2793
                }
2794

2795
                return true;
8✔
2796
        }
2797

2798

2799
        /**
2800
         * Concatenates the string representation of all elements.
2801
         *
2802
         * Objects that implement __toString() does also work, otherwise (and in case
2803
         * of arrays) a PHP notice is generated. NULL and FALSE values are treated as
2804
         * empty strings.
2805
         *
2806
         * Examples:
2807
         *  Map::from( ['a', 'b', false] )->join();
2808
         *  Map::from( ['a', 'b', null, false] )->join( '-' );
2809
         *
2810
         * Results:
2811
         * The first example will return "ab" while the second one will return "a-b--"
2812
         *
2813
         * @param string $glue Character or string added between elements
2814
         * @return string String of concatenated map elements
2815
         */
2816
        public function join( string $glue = '' ) : string
2817
        {
2818
                return implode( $glue, $this->list() );
8✔
2819
        }
2820

2821

2822
        /**
2823
         * Specifies the data which should be serialized to JSON by json_encode().
2824
         *
2825
         * Examples:
2826
         *   json_encode( Map::from( ['a', 'b'] ) );
2827
         *   json_encode( Map::from( ['a' => 0, 'b' => 1] ) );
2828
         *
2829
         * Results:
2830
         *   ["a", "b"]
2831
         *   {"a":0,"b":1}
2832
         *
2833
         * @return array<int|string,mixed> Data to serialize to JSON
2834
         */
2835
        #[\ReturnTypeWillChange]
2836
        public function jsonSerialize()
2837
        {
2838
                return $this->list = $this->array( $this->list );
8✔
2839
        }
2840

2841

2842
        /**
2843
         * Returns the keys of the all elements in a new map object.
2844
         *
2845
         * Examples:
2846
         *  Map::from( ['a', 'b'] );
2847
         *  Map::from( ['a' => 0, 'b' => 1] );
2848
         *
2849
         * Results:
2850
         * The first example returns a map containing [0, 1] while the second one will
2851
         * return a map with ['a', 'b'].
2852
         *
2853
         * @return self<int|string,mixed> New map
2854
         */
2855
        public function keys() : self
2856
        {
2857
                return new static( array_keys( $this->list() ) );
8✔
2858
        }
2859

2860

2861
        /**
2862
         * Sorts the elements by their keys in reverse order.
2863
         *
2864
         * Examples:
2865
         *  Map::from( ['b' => 0, 'a' => 1] )->krsort();
2866
         *  Map::from( [1 => 'a', 0 => 'b'] )->krsort();
2867
         *
2868
         * Results:
2869
         *  ['a' => 1, 'b' => 0]
2870
         *  [0 => 'b', 1 => 'a']
2871
         *
2872
         * The parameter modifies how the keys are compared. Possible values are:
2873
         * - SORT_REGULAR : compare elements normally (don't change types)
2874
         * - SORT_NUMERIC : compare elements numerically
2875
         * - SORT_STRING : compare elements as strings
2876
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
2877
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
2878
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
2879
         *
2880
         * The keys are preserved using this method and no new map is created.
2881
         *
2882
         * @param int $options Sort options for krsort()
2883
         * @return self<int|string,mixed> Updated map for fluid interface
2884
         */
2885
        public function krsort( int $options = SORT_REGULAR ) : self
2886
        {
2887
                krsort( $this->list(), $options );
24✔
2888
                return $this;
24✔
2889
        }
2890

2891

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

2921

2922
        /**
2923
         * Sorts the elements by their keys.
2924
         *
2925
         * Examples:
2926
         *  Map::from( ['b' => 0, 'a' => 1] )->ksort();
2927
         *  Map::from( [1 => 'a', 0 => 'b'] )->ksort();
2928
         *
2929
         * Results:
2930
         *  ['a' => 1, 'b' => 0]
2931
         *  [0 => 'b', 1 => 'a']
2932
         *
2933
         * The parameter modifies how the keys are compared. Possible values are:
2934
         * - SORT_REGULAR : compare elements normally (don't change types)
2935
         * - SORT_NUMERIC : compare elements numerically
2936
         * - SORT_STRING : compare elements as strings
2937
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
2938
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
2939
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
2940
         *
2941
         * The keys are preserved using this method and no new map is created.
2942
         *
2943
         * @param int $options Sort options for ksort()
2944
         * @return self<int|string,mixed> Updated map for fluid interface
2945
         */
2946
        public function ksort( int $options = SORT_REGULAR ) : self
2947
        {
2948
                ksort( $this->list(), $options );
24✔
2949
                return $this;
24✔
2950
        }
2951

2952

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

2982

2983
        /**
2984
         * Returns the last element from the map.
2985
         *
2986
         * Examples:
2987
         *  Map::from( ['a', 'b'] )->last();
2988
         *  Map::from( [] )->last( 'x' );
2989
         *  Map::from( [] )->last( new \Exception( 'error' ) );
2990
         *  Map::from( [] )->last( function() { return rand(); } );
2991
         *
2992
         * Results:
2993
         * The first example will return 'b' and the second one 'x'. The third example
2994
         * will throw the exception passed if the map contains no elements. In the
2995
         * fourth example, a random value generated by the closure function will be
2996
         * returned.
2997
         *
2998
         * @param mixed $default Default value or exception if the map contains no elements
2999
         * @return mixed Last value of map, (generated) default value or an exception
3000
         */
3001
        public function last( $default = null )
3002
        {
3003
                if( ( $value = end( $this->list() ) ) !== false ) {
40✔
3004
                        return $value;
16✔
3005
                }
3006

3007
                if( $default instanceof \Closure ) {
24✔
3008
                        return $default();
8✔
3009
                }
3010

3011
                if( $default instanceof \Throwable ) {
16✔
3012
                        throw $default;
8✔
3013
                }
3014

3015
                return $default;
8✔
3016
        }
3017

3018

3019
        /**
3020
         * Returns the last key from the map.
3021
         *
3022
         * Examples:
3023
         *  Map::from( ['a' => 1, 'b' => 2] )->lastKey();
3024
         *  Map::from( [] )->lastKey();
3025
         *
3026
         * Results:
3027
         * The first example will return 'b' and the second one NULL.
3028
         *
3029
         * @return mixed Last key of map or NULL if empty
3030
         */
3031
        public function lastKey()
3032
        {
3033
                $list = $this->list();
16✔
3034

3035
                if( function_exists( 'array_key_last' ) ) {
16✔
3036
                        return array_key_last( $list );
16✔
3037
                }
3038

3039
                end( $list );
×
3040
                return key( $list );
×
3041
        }
3042

3043

3044
        /**
3045
         * Removes the passed characters from the left of all strings.
3046
         *
3047
         * Examples:
3048
         *  Map::from( [" abc\n", "\tcde\r\n"] )->ltrim();
3049
         *  Map::from( ["a b c", "cbxa"] )->ltrim( 'abc' );
3050
         *
3051
         * Results:
3052
         * The first example will return ["abc\n", "cde\r\n"] while the second one will return [" b c", "xa"].
3053
         *
3054
         * @param string $chars List of characters to trim
3055
         * @return self<int|string,mixed> Updated map for fluid interface
3056
         */
3057
        public function ltrim( string $chars = " \n\r\t\v\x00" ) : self
3058
        {
3059
                foreach( $this->list() as &$entry )
8✔
3060
                {
3061
                        if( is_string( $entry ) ) {
8✔
3062
                                $entry = ltrim( $entry, $chars );
8✔
3063
                        }
3064
                }
3065

3066
                return $this;
8✔
3067
        }
3068

3069

3070
        /**
3071
         * Maps new values to the existing keys using the passed function and returns a new map for the result.
3072
         *
3073
         * Examples:
3074
         *  Map::from( ['a' => 2, 'b' => 4] )->map( function( $value, $key ) {
3075
         *      return $value * 2;
3076
         *  } );
3077
         *
3078
         * Results:
3079
         *  ['a' => 4, 'b' => 8]
3080
         *
3081
         * The keys are preserved using this method.
3082
         *
3083
         * @param callable $callback Function with (value, key) parameters and returns computed result
3084
         * @return self<int|string,mixed> New map with the original keys and the computed values
3085
         * @see rekey() - Changes the keys according to the passed function
3086
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
3087
         */
3088
        public function map( callable $callback ) : self
3089
        {
3090
                $list = $this->list();
8✔
3091
                $keys = array_keys( $list );
8✔
3092
                $map = array_map( $callback, array_values( $list ), $keys );
8✔
3093

3094
                return new static( array_combine( $keys, $map ) );
8✔
3095
        }
3096

3097

3098
        /**
3099
         * Returns the maximum value of all elements.
3100
         *
3101
         * Examples:
3102
         *  Map::from( [1, 3, 2, 5, 4] )->max()
3103
         *  Map::from( ['bar', 'foo', 'baz'] )->max()
3104
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->max( 'p' )
3105
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( 'i/p' )
3106
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( fn( $val, $key ) => $val['i']['p'] ?? null )
3107
         *  Map::from( [50, 10, 30] )->max( fn( $val, $key ) => $key > 0 ? $val : null )
3108
         *
3109
         * Results:
3110
         * The first line will return "5", the second one "foo" and the third to fitfh
3111
         * one return 50 while the last one will return 30.
3112
         *
3113
         * NULL values are removed before the comparison. If there are no values or all
3114
         * values are NULL, NULL is returned.
3115
         *
3116
         * This does also work for multi-dimensional arrays by passing the keys
3117
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3118
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3119
         * public properties of objects or objects implementing __isset() and __get() methods.
3120
         *
3121
         * Be careful comparing elements of different types because this can have
3122
         * unpredictable results due to the PHP comparison rules:
3123
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3124
         *
3125
         * @param Closure|string|null $col Closure, key or path to the value of the nested array or object
3126
         * @return mixed Maximum value or NULL if there are no elements in the map
3127
         */
3128
        public function max( $col = null )
3129
        {
3130
                $list = $this->list();
32✔
3131
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list );
32✔
3132

3133
                return !empty( $vals ) ? max( $vals ) : null;
32✔
3134
        }
3135

3136

3137
        /**
3138
         * Merges the map with the given elements without returning a new map.
3139
         *
3140
         * Elements with the same non-numeric keys will be overwritten, elements
3141
         * with the same numeric keys will be added.
3142
         *
3143
         * Examples:
3144
         *  Map::from( ['a', 'b'] )->merge( ['b', 'c'] );
3145
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6] );
3146
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6], true );
3147
         *
3148
         * Results:
3149
         *  ['a', 'b', 'b', 'c']
3150
         *  ['a' => 1, 'b' => 4, 'c' => 6]
3151
         *  ['a' => 1, 'b' => [2, 4], 'c' => 6]
3152
         *
3153
         * The method is similar to replace() but doesn't replace elements with
3154
         * the same numeric keys. If you want to be sure that all passed elements
3155
         * are added without replacing existing ones, use concat() instead.
3156
         *
3157
         * The keys are preserved using this method.
3158
         *
3159
         * @param iterable<int|string,mixed> $elements List of elements
3160
         * @param bool $recursive TRUE to merge nested arrays too, FALSE for first level elements only
3161
         * @return self<int|string,mixed> Updated map for fluid interface
3162
         */
3163
        public function merge( iterable $elements, bool $recursive = false ) : self
3164
        {
3165
                if( $recursive ) {
24✔
3166
                        $this->list = array_merge_recursive( $this->list(), $this->array( $elements ) );
8✔
3167
                } else {
3168
                        $this->list = array_merge( $this->list(), $this->array( $elements ) );
16✔
3169
                }
3170

3171
                return $this;
24✔
3172
        }
3173

3174

3175
        /**
3176
         * Returns the minimum value of all elements.
3177
         *
3178
         * Examples:
3179
         *  Map::from( [2, 3, 1, 5, 4] )->min()
3180
         *  Map::from( ['baz', 'foo', 'bar'] )->min()
3181
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->min( 'p' )
3182
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->min( 'i/p' )
3183
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->min( fn( $val, $key ) => $val['i']['p'] ?? null )
3184
         *  Map::from( [10, 50, 30] )->min( fn( $val, $key ) => $key > 0 ? $val : null )
3185
         *
3186
         * Results:
3187
         * The first line will return "1", the second one "bar", the third one
3188
         * 10, and the forth to the last one 30.
3189
         *
3190
         * NULL values are removed before the comparison. If there are no values or all
3191
         * values are NULL, NULL is returned.
3192
         *
3193
         * This does also work for multi-dimensional arrays by passing the keys
3194
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3195
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3196
         * public properties of objects or objects implementing __isset() and __get() methods.
3197
         *
3198
         * Be careful comparing elements of different types because this can have
3199
         * unpredictable results due to the PHP comparison rules:
3200
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3201
         *
3202
         * @param Closure|string|null $key Closure, key or path to the value of the nested array or object
3203
         * @return mixed Minimum value or NULL if there are no elements in the map
3204
         */
3205
        public function min( $col = null )
3206
        {
3207
                $list = $this->list();
32✔
3208
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list );
32✔
3209

3210
                return !empty( $vals ) ? min( $vals ) : null;
32✔
3211
        }
3212

3213

3214
        /**
3215
         * Tests if none of the elements are part of the map.
3216
         *
3217
         * Examples:
3218
         *  Map::from( ['a', 'b'] )->none( 'x' );
3219
         *  Map::from( ['a', 'b'] )->none( ['x', 'y'] );
3220
         *  Map::from( ['1', '2'] )->none( 2, true );
3221
         *  Map::from( ['a', 'b'] )->none( 'a' );
3222
         *  Map::from( ['a', 'b'] )->none( ['a', 'b'] );
3223
         *  Map::from( ['a', 'b'] )->none( ['a', 'x'] );
3224
         *
3225
         * Results:
3226
         * The first three examples will return TRUE while the other ones will return FALSE
3227
         *
3228
         * @param mixed|array $element Element or elements to search for in the map
3229
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
3230
         * @return bool TRUE if none of the elements is part of the map, FALSE if at least one is
3231
         */
3232
        public function none( $element, bool $strict = false ) : bool
3233
        {
3234
                $list = $this->list();
8✔
3235

3236
                if( !is_array( $element ) ) {
8✔
3237
                        return !in_array( $element, $list, $strict );
8✔
3238
                };
3239

3240
                foreach( $element as $entry )
8✔
3241
                {
3242
                        if( in_array( $entry, $list, $strict ) === true ) {
8✔
3243
                                return false;
8✔
3244
                        }
3245
                }
3246

3247
                return true;
8✔
3248
        }
3249

3250

3251
        /**
3252
         * Returns every nth element from the map.
3253
         *
3254
         * Examples:
3255
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2 );
3256
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2, 1 );
3257
         *
3258
         * Results:
3259
         *  ['a', 'c', 'e']
3260
         *  ['b', 'd', 'f']
3261
         *
3262
         * @param int $step Step width
3263
         * @param int $offset Number of element to start from (0-based)
3264
         * @return self<int|string,mixed> New map
3265
         */
3266
        public function nth( int $step, int $offset = 0 ) : self
3267
        {
3268
                if( $step < 1 ) {
24✔
3269
                        throw new \InvalidArgumentException( 'Step width must be greater than zero' );
8✔
3270
                }
3271

3272
                if( $step === 1 ) {
16✔
3273
                        return clone $this;
8✔
3274
                }
3275

3276
                $result = [];
8✔
3277
                $list = $this->list();
8✔
3278

3279
                while( !empty( $pair = array_slice( $list, $offset, 1, true ) ) )
8✔
3280
                {
3281
                        $result += $pair;
8✔
3282
                        $offset += $step;
8✔
3283
                }
3284

3285
                return new static( $result );
8✔
3286
        }
3287

3288

3289
        /**
3290
         * Determines if an element exists at an offset.
3291
         *
3292
         * Examples:
3293
         *  $map = Map::from( ['a' => 1, 'b' => 3, 'c' => null] );
3294
         *  isset( $map['b'] );
3295
         *  isset( $map['c'] );
3296
         *  isset( $map['d'] );
3297
         *
3298
         * Results:
3299
         *  The first isset() will return TRUE while the second and third one will return FALSE
3300
         *
3301
         * @param int|string $key Key to check for
3302
         * @return bool TRUE if key exists, FALSE if not
3303
         */
3304
        public function offsetExists( $key ) : bool
3305
        {
3306
                return isset( $this->list()[$key] );
56✔
3307
        }
3308

3309

3310
        /**
3311
         * Returns an element at a given offset.
3312
         *
3313
         * Examples:
3314
         *  $map = Map::from( ['a' => 1, 'b' => 3] );
3315
         *  $map['b'];
3316
         *
3317
         * Results:
3318
         *  $map['b'] will return 3
3319
         *
3320
         * @param int|string $key Key to return the element for
3321
         * @return mixed Value associated to the given key
3322
         */
3323
        #[\ReturnTypeWillChange]
3324
        public function offsetGet( $key )
3325
        {
3326
                return $this->list()[$key] ?? null;
40✔
3327
        }
3328

3329

3330
        /**
3331
         * Sets the element at a given offset.
3332
         *
3333
         * Examples:
3334
         *  $map = Map::from( ['a' => 1] );
3335
         *  $map['b'] = 2;
3336
         *  $map[0] = 4;
3337
         *
3338
         * Results:
3339
         *  ['a' => 1, 'b' => 2, 0 => 4]
3340
         *
3341
         * @param int|string|null $key Key to set the element for or NULL to append value
3342
         * @param mixed $value New value set for the key
3343
         */
3344
        public function offsetSet( $key, $value ) : void
3345
        {
3346
                if( $key !== null ) {
24✔
3347
                        $this->list()[$key] = $value;
16✔
3348
                } else {
3349
                        $this->list()[] = $value;
16✔
3350
                }
3351
        }
6✔
3352

3353

3354
        /**
3355
         * Unsets the element at a given offset.
3356
         *
3357
         * Examples:
3358
         *  $map = Map::from( ['a' => 1] );
3359
         *  unset( $map['a'] );
3360
         *
3361
         * Results:
3362
         *  The map will be empty
3363
         *
3364
         * @param int|string $key Key for unsetting the item
3365
         */
3366
        public function offsetUnset( $key ) : void
3367
        {
3368
                unset( $this->list()[$key] );
16✔
3369
        }
4✔
3370

3371

3372
        /**
3373
         * Returns a new map with only those elements specified by the given keys.
3374
         *
3375
         * Examples:
3376
         *  Map::from( ['a' => 1, 0 => 'b'] )->only( 'a' );
3377
         *  Map::from( ['a' => 1, 0 => 'b', 1 => 'c'] )->only( [0, 1] );
3378
         *
3379
         * Results:
3380
         *  ['a' => 1]
3381
         *  [0 => 'b', 1 => 'c']
3382
         *
3383
         * The keys are preserved using this method.
3384
         *
3385
         * @param iterable<mixed>|array<mixed>|string|int $keys Keys of the elements that should be returned
3386
         * @return self<int|string,mixed> New map with only the elements specified by the keys
3387
         */
3388
        public function only( $keys ) : self
3389
        {
3390
                return $this->intersectKeys( array_flip( $this->array( $keys ) ) );
8✔
3391
        }
3392

3393

3394
        /**
3395
         * Returns a new map with elements ordered by the passed keys.
3396
         *
3397
         * If there are less keys passed than available in the map, the remaining
3398
         * elements are removed. Otherwise, if keys are passed that are not in the
3399
         * map, they will be also available in the returned map but their value is
3400
         * NULL.
3401
         *
3402
         * Examples:
3403
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 'a'] );
3404
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 2] );
3405
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1] );
3406
         *
3407
         * Results:
3408
         *  [0 => 'b', 1 => 'c', 'a' => 1]
3409
         *  [0 => 'b', 1 => 'c', 2 => null]
3410
         *  [0 => 'b', 1 => 'c']
3411
         *
3412
         * The keys are preserved using this method.
3413
         *
3414
         * @param iterable<mixed> $keys Keys of the elements in the required order
3415
         * @return self<int|string,mixed> New map with elements ordered by the passed keys
3416
         */
3417
        public function order( iterable $keys ) : self
3418
        {
3419
                $result = [];
8✔
3420
                $list = $this->list();
8✔
3421

3422
                foreach( $keys as $key ) {
8✔
3423
                        $result[$key] = $list[$key] ?? null;
8✔
3424
                }
3425

3426
                return new static( $result );
8✔
3427
        }
3428

3429

3430
        /**
3431
         * Fill up to the specified length with the given value
3432
         *
3433
         * In case the given number is smaller than the number of element that are
3434
         * already in the list, the map is unchanged. If the size is positive, the
3435
         * new elements are padded on the right, if it's negative then the elements
3436
         * are padded on the left.
3437
         *
3438
         * Examples:
3439
         *  Map::from( [1, 2, 3] )->pad( 5 );
3440
         *  Map::from( [1, 2, 3] )->pad( -5 );
3441
         *  Map::from( [1, 2, 3] )->pad( 5, '0' );
3442
         *  Map::from( [1, 2, 3] )->pad( 2 );
3443
         *  Map::from( [10 => 1, 20 => 2] )->pad( 3 );
3444
         *  Map::from( ['a' => 1, 'b' => 2] )->pad( 3, 3 );
3445
         *
3446
         * Results:
3447
         *  [1, 2, 3, null, null]
3448
         *  [null, null, 1, 2, 3]
3449
         *  [1, 2, 3, '0', '0']
3450
         *  [1, 2, 3]
3451
         *  [0 => 1, 1 => 2, 2 => null]
3452
         *  ['a' => 1, 'b' => 2, 0 => 3]
3453
         *
3454
         * Associative keys are preserved, numerical keys are replaced and numerical
3455
         * keys are used for the new elements.
3456
         *
3457
         * @param int $size Total number of elements that should be in the list
3458
         * @param mixed $value Value to fill up with if the map length is smaller than the given size
3459
         * @return self<int|string,mixed> New map
3460
         */
3461
        public function pad( int $size, $value = null ) : self
3462
        {
3463
                return new static( array_pad( $this->list(), $size, $value ) );
8✔
3464
        }
3465

3466

3467
        /**
3468
         * Breaks the list of elements into the given number of groups.
3469
         *
3470
         * Examples:
3471
         *  Map::from( [1, 2, 3, 4, 5] )->partition( 3 );
3472
         *  Map::from( [1, 2, 3, 4, 5] )->partition( function( $val, $idx ) {
3473
         *                return $idx % 3;
3474
         *        } );
3475
         *
3476
         * Results:
3477
         *  [[0 => 1, 1 => 2], [2 => 3, 3 => 4], [4 => 5]]
3478
         *  [0 => [0 => 1, 3 => 4], 1 => [1 => 2, 4 => 5], 2 => [2 => 3]]
3479
         *
3480
         * The keys of the original map are preserved in the returned map.
3481
         *
3482
         * @param \Closure|int $number Function with (value, index) as arguments returning the bucket key or number of groups
3483
         * @return self<int|string,mixed> New map
3484
         */
3485
        public function partition( $number ) : self
3486
        {
3487
                $list = $this->list();
32✔
3488

3489
                if( empty( $list ) ) {
32✔
3490
                        return new static();
8✔
3491
                }
3492

3493
                $result = [];
24✔
3494

3495
                if( $number instanceof \Closure )
24✔
3496
                {
3497
                        foreach( $list as $idx => $item ) {
8✔
3498
                                $result[$number( $item, $idx )][$idx] = $item;
8✔
3499
                        }
3500

3501
                        return new static( $result );
8✔
3502
                }
3503
                elseif( is_int( $number ) )
16✔
3504
                {
3505
                        $start = 0;
8✔
3506
                        $size = (int) ceil( count( $list ) / $number );
8✔
3507

3508
                        for( $i = 0; $i < $number; $i++ )
8✔
3509
                        {
3510
                                $result[] = array_slice( $list, $start, $size, true );
8✔
3511
                                $start += $size;
8✔
3512
                        }
3513

3514
                        return new static( $result );
8✔
3515
                }
3516

3517
                throw new \InvalidArgumentException( 'Parameter is no closure or integer' );
8✔
3518
        }
3519

3520

3521
        /**
3522
         * Returns the percentage of all elements passing the test in the map.
3523
         *
3524
         * Examples:
3525
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50 );
3526
         *  Map::from( [] )->percentage( fn( $val, $key ) => true );
3527
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 100 );
3528
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 3 );
3529
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 0 );
3530
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50, -1 );
3531
         *
3532
         * Results:
3533
         * The first line will return "66.67", the second and third one "0.0", the forth
3534
         * one "33.333", the fifth one "33.0" and the last one "70.0" (66 rounded up).
3535
         *
3536
         * @param Closure $fcn Closure to filter the values in the nested array or object to compute the percentage
3537
         * @param int $precision Number of decimal digits use by the result value
3538
         * @return float Percentage of all elements passing the test in the map
3539
         */
3540
        public function percentage( \Closure $fcn, int $precision = 2 ) : float
3541
        {
3542
                $vals = array_filter( $this->list(), $fcn, ARRAY_FILTER_USE_BOTH );
8✔
3543

3544
                $cnt = count( $this->list() );
8✔
3545
                return $cnt > 0 ? round( count( $vals ) * 100 / $cnt, $precision ) : 0;
8✔
3546
        }
3547

3548

3549
        /**
3550
         * Passes the map to the given callback and return the result.
3551
         *
3552
         * Examples:
3553
         *  Map::from( ['a', 'b'] )->pipe( function( $map ) {
3554
         *      return join( '-', $map->toArray() );
3555
         *  } );
3556
         *
3557
         * Results:
3558
         *  "a-b" will be returned
3559
         *
3560
         * @param \Closure $callback Function with map as parameter which returns arbitrary result
3561
         * @return mixed Result returned by the callback
3562
         */
3563
        public function pipe( \Closure $callback )
3564
        {
3565
                return $callback( $this );
8✔
3566
        }
3567

3568

3569
        /**
3570
         * Returns the values of a single column/property from an array of arrays or objects in a new map.
3571
         *
3572
         * This method is an alias for col(). For performance reasons, col() should
3573
         * be preferred because it uses one method call less than pluck().
3574
         *
3575
         * @param string|null $valuecol Name or path of the value property
3576
         * @param string|null $indexcol Name or path of the index property
3577
         * @return self<int|string,mixed> New map with mapped entries
3578
         * @see col() - Underlying method with same parameters and return value but better performance
3579
         */
3580
        public function pluck( ?string $valuecol = null, ?string $indexcol = null ) : self
3581
        {
3582
                return $this->col( $valuecol, $indexcol );
8✔
3583
        }
3584

3585

3586
        /**
3587
         * Returns and removes the last element from the map.
3588
         *
3589
         * Examples:
3590
         *  Map::from( ['a', 'b'] )->pop();
3591
         *
3592
         * Results:
3593
         *  "b" will be returned and the map only contains ['a'] afterwards
3594
         *
3595
         * @return mixed Last element of the map or null if empty
3596
         */
3597
        public function pop()
3598
        {
3599
                return array_pop( $this->list() );
16✔
3600
        }
3601

3602

3603
        /**
3604
         * Returns the numerical index of the value.
3605
         *
3606
         * Examples:
3607
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( 'b' );
3608
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( function( $item, $key ) {
3609
         *      return $item === 'b';
3610
         *  } );
3611
         *
3612
         * Results:
3613
         * Both examples will return "1" because the value "b" is at the second position
3614
         * and the returned index is zero based so the first item has the index "0".
3615
         *
3616
         * @param \Closure|mixed $value Value to search for or function with (item, key) parameters return TRUE if value is found
3617
         * @return int|null Position of the found value (zero based) or NULL if not found
3618
         */
3619
        public function pos( $value ) : ?int
3620
        {
3621
                $pos = 0;
120✔
3622
                $list = $this->list();
120✔
3623

3624
                if( $value instanceof \Closure )
120✔
3625
                {
3626
                        foreach( $list as $key => $item )
24✔
3627
                        {
3628
                                if( $value( $item, $key ) ) {
24✔
3629
                                        return $pos;
24✔
3630
                                }
3631

3632
                                ++$pos;
24✔
3633
                        }
3634
                }
3635

3636
                if( ( $key = array_search( $value, $list, true ) ) !== false
96✔
3637
                        && ( $pos = array_search( $key, array_keys( $list ), true ) ) !== false
96✔
3638
                ) {
3639
                        return $pos;
80✔
3640
                }
3641

3642
                return null;
16✔
3643
        }
3644

3645

3646
        /**
3647
         * Adds a prefix in front of each map entry.
3648
         *
3649
         * By defaul, nested arrays are walked recusively so all entries at all levels are prefixed.
3650
         *
3651
         * Examples:
3652
         *  Map::from( ['a', 'b'] )->prefix( '1-' );
3653
         *  Map::from( ['a', ['b']] )->prefix( '1-' );
3654
         *  Map::from( ['a', ['b']] )->prefix( '1-', 1 );
3655
         *  Map::from( ['a', 'b'] )->prefix( function( $item, $key ) {
3656
         *      return ( ord( $item ) + ord( $key ) ) . '-';
3657
         *  } );
3658
         *
3659
         * Results:
3660
         *  The first example returns ['1-a', '1-b'] while the second one will return
3661
         *  ['1-a', ['1-b']]. In the third example, the depth is limited to the first
3662
         *  level only so it will return ['1-a', ['b']]. The forth example passing
3663
         *  the closure will return ['145-a', '147-b'].
3664
         *
3665
         * The keys of the original map are preserved in the returned map.
3666
         *
3667
         * @param \Closure|string $prefix Prefix string or anonymous function with ($item, $key) as parameters
3668
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
3669
         * @return self<int|string,mixed> Updated map for fluid interface
3670
         */
3671
        public function prefix( $prefix, ?int $depth = null ) : self
3672
        {
3673
                $fcn = function( array $list, $prefix, int $depth ) use ( &$fcn ) {
6✔
3674

3675
                        foreach( $list as $key => $item )
8✔
3676
                        {
3677
                                if( is_array( $item ) ) {
8✔
3678
                                        $list[$key] = $depth > 1 ? $fcn( $item, $prefix, $depth - 1 ) : $item;
8✔
3679
                                } else {
3680
                                        $list[$key] = ( is_callable( $prefix ) ? $prefix( $item, $key ) : $prefix ) . $item;
8✔
3681
                                }
3682
                        }
3683

3684
                        return $list;
8✔
3685
                };
8✔
3686

3687
                $this->list = $fcn( $this->list(), $prefix, $depth ?? 0x7fffffff );
8✔
3688
                return $this;
8✔
3689
        }
3690

3691

3692
        /**
3693
         * Pushes an element onto the beginning of the map without returning a new map.
3694
         *
3695
         * This method is an alias for unshift().
3696
         *
3697
         * @param mixed $value Item to add at the beginning
3698
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
3699
         * @return self<int|string,mixed> Updated map for fluid interface
3700
         * @see unshift() - Underlying method with same parameters and return value but better performance
3701
         */
3702
        public function prepend( $value, $key = null ) : self
3703
        {
3704
                return $this->unshift( $value, $key );
8✔
3705
        }
3706

3707

3708
        /**
3709
         * Returns and removes an element from the map by its key.
3710
         *
3711
         * Examples:
3712
         *  Map::from( ['a', 'b', 'c'] )->pull( 1 );
3713
         *  Map::from( ['a', 'b', 'c'] )->pull( 'x', 'none' );
3714
         *  Map::from( [] )->pull( 'Y', new \Exception( 'error' ) );
3715
         *  Map::from( [] )->pull( 'Z', function() { return rand(); } );
3716
         *
3717
         * Results:
3718
         * The first example will return "b" and the map contains ['a', 'c'] afterwards.
3719
         * The second one will return "none" and the map content stays untouched. If you
3720
         * pass an exception as default value, it will throw that exception if the map
3721
         * contains no elements. In the fourth example, a random value generated by the
3722
         * closure function will be returned.
3723
         *
3724
         * @param int|string $key Key to retrieve the value for
3725
         * @param mixed $default Default value if key isn't available
3726
         * @return mixed Value from map or default value
3727
         */
3728
        public function pull( $key, $default = null )
3729
        {
3730
                $value = $this->get( $key, $default );
32✔
3731
                unset( $this->list()[$key] );
24✔
3732

3733
                return $value;
24✔
3734
        }
3735

3736

3737
        /**
3738
         * Pushes an element onto the end of the map without returning a new map.
3739
         *
3740
         * Examples:
3741
         *  Map::from( ['a', 'b'] )->push( 'aa' );
3742
         *
3743
         * Results:
3744
         *  ['a', 'b', 'aa']
3745
         *
3746
         * @param mixed $value Value to add to the end
3747
         * @return self<int|string,mixed> Updated map for fluid interface
3748
         */
3749
        public function push( $value ) : self
3750
        {
3751
                $this->list()[] = $value;
24✔
3752
                return $this;
24✔
3753
        }
3754

3755

3756
        /**
3757
         * Sets the given key and value in the map without returning a new map.
3758
         *
3759
         * This method is an alias for set(). For performance reasons, set() should be
3760
         * preferred because it uses one method call less than put().
3761
         *
3762
         * @param int|string $key Key to set the new value for
3763
         * @param mixed $value New element that should be set
3764
         * @return self<int|string,mixed> Updated map for fluid interface
3765
         * @see set() - Underlying method with same parameters and return value but better performance
3766
         */
3767
        public function put( $key, $value ) : self
3768
        {
3769
                return $this->set( $key, $value );
8✔
3770
        }
3771

3772

3773
        /**
3774
         * Returns one or more random element from the map incl. their keys.
3775
         *
3776
         * Examples:
3777
         *  Map::from( [2, 4, 8, 16] )->random();
3778
         *  Map::from( [2, 4, 8, 16] )->random( 2 );
3779
         *  Map::from( [2, 4, 8, 16] )->random( 5 );
3780
         *
3781
         * Results:
3782
         * The first example will return a map including [0 => 8] or any other value,
3783
         * the second one will return a map with [0 => 16, 1 => 2] or any other values
3784
         * and the third example will return a map of the whole list in random order. The
3785
         * less elements are in the map, the less random the order will be, especially if
3786
         * the maximum number of values is high or close to the number of elements.
3787
         *
3788
         * The keys of the original map are preserved in the returned map.
3789
         *
3790
         * @param int $max Maximum number of elements that should be returned
3791
         * @return self<int|string,mixed> New map with key/element pairs from original map in random order
3792
         * @throws \InvalidArgumentException If requested number of elements is less than 1
3793
         */
3794
        public function random( int $max = 1 ) : self
3795
        {
3796
                if( $max < 1 ) {
40✔
3797
                        throw new \InvalidArgumentException( 'Requested number of elements must be greater or equal than 1' );
8✔
3798
                }
3799

3800
                $list = $this->list();
32✔
3801

3802
                if( empty( $list ) ) {
32✔
3803
                        return new static();
8✔
3804
                }
3805

3806
                if( ( $num = count( $list ) ) < $max ) {
24✔
3807
                        $max = $num;
8✔
3808
                }
3809

3810
                $keys = array_rand( $list, $max );
24✔
3811

3812
                return new static( array_intersect_key( $list, array_flip( (array) $keys ) ) );
24✔
3813
        }
3814

3815

3816
        /**
3817
         * Iteratively reduces the array to a single value using a callback function.
3818
         * Afterwards, the map will be empty.
3819
         *
3820
         * Examples:
3821
         *  Map::from( [2, 8] )->reduce( function( $result, $value ) {
3822
         *      return $result += $value;
3823
         *  }, 10 );
3824
         *
3825
         * Results:
3826
         *  "20" will be returned because the sum is computed by 10 (initial value) + 2 + 8
3827
         *
3828
         * @param callable $callback Function with (result, value) parameters and returns result
3829
         * @param mixed $initial Initial value when computing the result
3830
         * @return mixed Value computed by the callback function
3831
         */
3832
        public function reduce( callable $callback, $initial = null )
3833
        {
3834
                return array_reduce( $this->list(), $callback, $initial );
8✔
3835
        }
3836

3837

3838
        /**
3839
         * Removes all matched elements and returns a new map.
3840
         *
3841
         * Examples:
3842
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->reject( function( $value, $key ) {
3843
         *      return $value < 'm';
3844
         *  } );
3845
         *  Map::from( [2 => 'a', 13 => 'm', 30 => 'z'] )->reject( 'm' );
3846
         *  Map::from( [2 => 'a', 6 => null, 13 => 'm'] )->reject();
3847
         *
3848
         * Results:
3849
         *  [13 => 'm', 30 => 'z']
3850
         *  [2 => 'a', 30 => 'z']
3851
         *  [6 => null]
3852
         *
3853
         * This method is the inverse of the filter() and should return TRUE if the
3854
         * item should be removed from the returned map.
3855
         *
3856
         * If no callback is passed, all values which are NOT empty, null or false will be
3857
         * removed. The keys of the original map are preserved in the returned map.
3858
         *
3859
         * @param Closure|mixed $callback Function with (item) parameter which returns TRUE/FALSE or value to compare with
3860
         * @return self<int|string,mixed> New map
3861
         */
3862
        public function reject( $callback = true ) : self
3863
        {
3864
                $isCallable = $callback instanceof \Closure;
24✔
3865

3866
                return new static( array_filter( $this->list(), function( $value, $key ) use ( $callback, $isCallable ) {
18✔
3867
                        return $isCallable ? !$callback( $value, $key ) : $value != $callback;
24✔
3868
                }, ARRAY_FILTER_USE_BOTH ) );
24✔
3869
        }
3870

3871

3872
        /**
3873
         * Changes the keys according to the passed function.
3874
         *
3875
         * Examples:
3876
         *  Map::from( ['a' => 2, 'b' => 4] )->rekey( function( $value, $key ) {
3877
         *      return 'key-' . $key;
3878
         *  } );
3879
         *
3880
         * Results:
3881
         *  ['key-a' => 2, 'key-b' => 4]
3882
         *
3883
         * @param callable $callback Function with (value, key) parameters and returns new key
3884
         * @return self<int|string,mixed> New map with new keys and original values
3885
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
3886
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
3887
         */
3888
        public function rekey( callable $callback ) : self
3889
        {
3890
                $list = $this->list();
8✔
3891
                $keys = array_keys( $list );
8✔
3892
                $newKeys = array_map( $callback, $list, $keys );
8✔
3893

3894
                return new static( array_combine( $newKeys, $list ) ?: [] );
8✔
3895
        }
3896

3897

3898
        /**
3899
         * Removes one or more elements from the map by its keys without returning a new map.
3900
         *
3901
         * Examples:
3902
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( 'a' );
3903
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( [2, 'a'] );
3904
         *
3905
         * Results:
3906
         * The first example will result in [2 => 'b'] while the second one resulting
3907
         * in an empty list
3908
         *
3909
         * @param iterable<string|int>|array<string|int>|string|int $keys List of keys to remove
3910
         * @return self<int|string,mixed> Updated map for fluid interface
3911
         */
3912
        public function remove( $keys ) : self
3913
        {
3914
                foreach( $this->array( $keys ) as $key ) {
40✔
3915
                        unset( $this->list()[$key] );
40✔
3916
                }
3917

3918
                return $this;
40✔
3919
        }
3920

3921

3922
        /**
3923
         * Replaces elements in the map with the given elements without returning a new map.
3924
         *
3925
         * Examples:
3926
         *  Map::from( ['a' => 1, 2 => 'b'] )->replace( ['a' => 2] );
3927
         *  Map::from( ['a' => 1, 'b' => ['c' => 3, 'd' => 4]] )->replace( ['b' => ['c' => 9]] );
3928
         *
3929
         * Results:
3930
         *  ['a' => 2, 2 => 'b']
3931
         *  ['a' => 1, 'b' => ['c' => 9, 'd' => 4]]
3932
         *
3933
         * The method is similar to merge() but it also replaces elements with numeric
3934
         * keys. These would be added by merge() with a new numeric key.
3935
         *
3936
         * The keys are preserved using this method.
3937
         *
3938
         * @param iterable<int|string,mixed> $elements List of elements
3939
         * @param bool $recursive TRUE to replace recursively (default), FALSE to replace elements only
3940
         * @return self<int|string,mixed> Updated map for fluid interface
3941
         */
3942
        public function replace( iterable $elements, bool $recursive = true ) : self
3943
        {
3944
                if( $recursive ) {
40✔
3945
                        $this->list = array_replace_recursive( $this->list(), $this->array( $elements ) );
32✔
3946
                } else {
3947
                        $this->list = array_replace( $this->list(), $this->array( $elements ) );
8✔
3948
                }
3949

3950
                return $this;
40✔
3951
        }
3952

3953

3954
        /**
3955
         * Reverses the element order with keys without returning a new map.
3956
         *
3957
         * Examples:
3958
         *  Map::from( ['a', 'b'] )->reverse();
3959
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reverse();
3960
         *
3961
         * Results:
3962
         *  ['b', 'a']
3963
         *  ['last' => 'user', 'name' => 'test']
3964
         *
3965
         * The keys are preserved using this method.
3966
         *
3967
         * @return self<int|string,mixed> Updated map for fluid interface
3968
         * @see reversed() - Reverses the element order in a copy of the map
3969
         */
3970
        public function reverse() : self
3971
        {
3972
                $this->list = array_reverse( $this->list(), true );
32✔
3973
                return $this;
32✔
3974
        }
3975

3976

3977
        /**
3978
         * Reverses the element order in a copy of the map.
3979
         *
3980
         * Examples:
3981
         *  Map::from( ['a', 'b'] )->reversed();
3982
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reversed();
3983
         *
3984
         * Results:
3985
         *  ['b', 'a']
3986
         *  ['last' => 'user', 'name' => 'test']
3987
         *
3988
         * The keys are preserved using this method and a new map is created before reversing the elements.
3989
         * Thus, reverse() should be preferred for performance reasons if possible.
3990
         *
3991
         * @return self<int|string,mixed> New map with a reversed copy of the elements
3992
         * @see reverse() - Reverses the element order with keys without returning a new map
3993
         */
3994
        public function reversed() : self
3995
        {
3996
                return ( clone $this )->reverse();
16✔
3997
        }
3998

3999

4000
        /**
4001
         * Sorts all elements in reverse order using new keys.
4002
         *
4003
         * Examples:
4004
         *  Map::from( ['a' => 1, 'b' => 0] )->rsort();
4005
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsort();
4006
         *
4007
         * Results:
4008
         *  [0 => 1, 1 => 0]
4009
         *  [0 => 'b', 1 => 'a']
4010
         *
4011
         * The parameter modifies how the values are compared. Possible parameter values are:
4012
         * - SORT_REGULAR : compare elements normally (don't change types)
4013
         * - SORT_NUMERIC : compare elements numerically
4014
         * - SORT_STRING : compare elements as strings
4015
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4016
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4017
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4018
         *
4019
         * The keys aren't preserved and elements get a new index. No new map is created
4020
         *
4021
         * @param int $options Sort options for rsort()
4022
         * @return self<int|string,mixed> Updated map for fluid interface
4023
         */
4024
        public function rsort( int $options = SORT_REGULAR ) : self
4025
        {
4026
                rsort( $this->list(), $options );
24✔
4027
                return $this;
24✔
4028
        }
4029

4030

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

4060

4061
        /**
4062
         * Removes the passed characters from the right of all strings.
4063
         *
4064
         * Examples:
4065
         *  Map::from( [" abc\n", "\tcde\r\n"] )->rtrim();
4066
         *  Map::from( ["a b c", "cbxa"] )->rtrim( 'abc' );
4067
         *
4068
         * Results:
4069
         * The first example will return [" abc", "\tcde"] while the second one will return ["a b ", "cbx"].
4070
         *
4071
         * @param string $chars List of characters to trim
4072
         * @return self<int|string,mixed> Updated map for fluid interface
4073
         */
4074
        public function rtrim( string $chars = " \n\r\t\v\x00" ) : self
4075
        {
4076
                foreach( $this->list() as &$entry )
8✔
4077
                {
4078
                        if( is_string( $entry ) ) {
8✔
4079
                                $entry = rtrim( $entry, $chars );
8✔
4080
                        }
4081
                }
4082

4083
                return $this;
8✔
4084
        }
4085

4086

4087
        /**
4088
         * Searches the map for a given value and return the corresponding key if successful.
4089
         *
4090
         * Examples:
4091
         *  Map::from( ['a', 'b', 'c'] )->search( 'b' );
4092
         *  Map::from( [1, 2, 3] )->search( '2', true );
4093
         *
4094
         * Results:
4095
         * The first example will return 1 (array index) while the second one will
4096
         * return NULL because the types doesn't match (int vs. string)
4097
         *
4098
         * @param mixed $value Item to search for
4099
         * @param bool $strict TRUE if type of the element should be checked too
4100
         * @return int|string|null Key associated to the value or null if not found
4101
         */
4102
        public function search( $value, $strict = true )
4103
        {
4104
                if( ( $result = array_search( $value, $this->list(), $strict ) ) !== false ) {
8✔
4105
                        return $result;
8✔
4106
                }
4107

4108
                return null;
8✔
4109
        }
4110

4111

4112
        /**
4113
         * Sets the seperator for paths to values in multi-dimensional arrays or objects.
4114
         *
4115
         * This method only changes the separator for the current map instance. To
4116
         * change the separator for all maps created afterwards, use the static
4117
         * delimiter() method instead.
4118
         *
4119
         * Examples:
4120
         *  Map::from( ['foo' => ['bar' => 'baz']] )->sep( '/' )->get( 'foo/bar' );
4121
         *
4122
         * Results:
4123
         *  'baz'
4124
         *
4125
         * @param string $char Separator character, e.g. "." for "key.to.value" instead of "key/to/value"
4126
         * @return self<int|string,mixed> Same map for fluid interface
4127
         */
4128
        public function sep( string $char ) : self
4129
        {
4130
                $this->sep = $char;
8✔
4131
                return $this;
8✔
4132
        }
4133

4134

4135
        /**
4136
         * Sets an element in the map by key without returning a new map.
4137
         *
4138
         * Examples:
4139
         *  Map::from( ['a'] )->set( 1, 'b' );
4140
         *  Map::from( ['a'] )->set( 0, 'b' );
4141
         *
4142
         * Results:
4143
         *  ['a', 'b']
4144
         *  ['b']
4145
         *
4146
         * @param int|string $key Key to set the new value for
4147
         * @param mixed $value New element that should be set
4148
         * @return self<int|string,mixed> Updated map for fluid interface
4149
         */
4150
        public function set( $key, $value ) : self
4151
        {
4152
                $this->list()[(string) $key] = $value;
40✔
4153
                return $this;
40✔
4154
        }
4155

4156

4157
        /**
4158
         * Returns and removes the first element from the map.
4159
         *
4160
         * Examples:
4161
         *  Map::from( ['a', 'b'] )->shift();
4162
         *  Map::from( [] )->shift();
4163
         *
4164
         * Results:
4165
         * The first example returns "a" and shortens the map to ['b'] only while the
4166
         * second example will return NULL
4167
         *
4168
         * Performance note:
4169
         * The bigger the list, the higher the performance impact because shift()
4170
         * reindexes all existing elements. Usually, it's better to reverse() the list
4171
         * and pop() entries from the list afterwards if a significant number of elements
4172
         * should be removed from the list:
4173
         *
4174
         *  $map->reverse()->pop();
4175
         * instead of
4176
         *  $map->shift( 'a' );
4177
         *
4178
         * @return mixed|null Value from map or null if not found
4179
         */
4180
        public function shift()
4181
        {
4182
                return array_shift( $this->list() );
8✔
4183
        }
4184

4185

4186
        /**
4187
         * Shuffles the elements in the map without returning a new map.
4188
         *
4189
         * Examples:
4190
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle();
4191
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle( true );
4192
         *
4193
         * Results:
4194
         * The map in the first example will contain "a" and "b" in random order and
4195
         * with new keys assigned. The second call will also return all values in
4196
         * random order but preserves the keys of the original list.
4197
         *
4198
         * @param bool $assoc True to preserve keys, false to assign new keys
4199
         * @return self<int|string,mixed> Updated map for fluid interface
4200
         * @see shuffled() - Shuffles the elements in a copy of the map
4201
         */
4202
        public function shuffle( bool $assoc = false ) : self
4203
        {
4204
                if( $assoc )
24✔
4205
                {
4206
                        $list = $this->list();
8✔
4207
                        $keys = array_keys( $list );
8✔
4208
                        shuffle( $keys );
8✔
4209
                        $items = [];
8✔
4210

4211
                        foreach( $keys as $key ) {
8✔
4212
                                $items[$key] = $list[$key];
8✔
4213
                        }
4214

4215
                        $this->list = $items;
8✔
4216
                }
4217
                else
4218
                {
4219
                        shuffle( $this->list() );
16✔
4220
                }
4221

4222
                return $this;
24✔
4223
        }
4224

4225

4226
        /**
4227
         * Shuffles the elements in a copy of the map.
4228
         *
4229
         * Examples:
4230
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled();
4231
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled( true );
4232
         *
4233
         * Results:
4234
         * The map in the first example will contain "a" and "b" in random order and
4235
         * with new keys assigned. The second call will also return all values in
4236
         * random order but preserves the keys of the original list.
4237
         *
4238
         * @param bool $assoc True to preserve keys, false to assign new keys
4239
         * @return self<int|string,mixed> New map with a shuffled copy of the elements
4240
         * @see shuffle() - Shuffles the elements in the map without returning a new map
4241
         */
4242
        public function shuffled( bool $assoc = false ) : self
4243
        {
4244
                return ( clone $this )->shuffle( $assoc );
8✔
4245
        }
4246

4247

4248
        /**
4249
         * Returns a new map with the given number of items skipped.
4250
         *
4251
         * Examples:
4252
         *  Map::from( [1, 2, 3, 4] )->skip( 2 );
4253
         *  Map::from( [1, 2, 3, 4] )->skip( function( $item, $key ) {
4254
         *      return $item < 4;
4255
         *  } );
4256
         *
4257
         * Results:
4258
         *  [2 => 3, 3 => 4]
4259
         *  [3 => 4]
4260
         *
4261
         * The keys of the items returned in the new map are the same as in the original one.
4262
         *
4263
         * @param \Closure|int $offset Number of items to skip or function($item, $key) returning true for skipped items
4264
         * @return self<int|string,mixed> New map
4265
         */
4266
        public function skip( $offset ) : self
4267
        {
4268
                if( is_scalar( $offset ) ) {
24✔
4269
                        return new static( array_slice( $this->list(), (int) $offset, null, true ) );
8✔
4270
                }
4271

4272
                if( is_callable( $offset ) )
16✔
4273
                {
4274
                        $idx = 0;
8✔
4275
                        $list = $this->list();
8✔
4276

4277
                        foreach( $list as $key => $item )
8✔
4278
                        {
4279
                                if( !$offset( $item, $key ) ) {
8✔
4280
                                        break;
8✔
4281
                                }
4282

4283
                                ++$idx;
8✔
4284
                        }
4285

4286
                        return new static( array_slice( $list, $idx, null, true ) );
8✔
4287
                }
4288

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

4292

4293
        /**
4294
         * Returns a map with the slice from the original map.
4295
         *
4296
         * Examples:
4297
         *  Map::from( ['a', 'b', 'c'] )->slice( 1 );
4298
         *  Map::from( ['a', 'b', 'c'] )->slice( 1, 1 );
4299
         *  Map::from( ['a', 'b', 'c', 'd'] )->slice( -2, -1 );
4300
         *
4301
         * Results:
4302
         * The first example will return ['b', 'c'] and the second one ['b'] only.
4303
         * The third example returns ['c'] because the slice starts at the second
4304
         * last value and ends before the last value.
4305
         *
4306
         * The rules for offsets are:
4307
         * - If offset is non-negative, the sequence will start at that offset
4308
         * - If offset is negative, the sequence will start that far from the end
4309
         *
4310
         * Similar for the length:
4311
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4312
         * - If the array is shorter than the length, then only the available array elements will be present
4313
         * - If length is given and is negative then the sequence will stop that many elements from the end
4314
         * - If it is omitted, then the sequence will have everything from offset up until the end
4315
         *
4316
         * The keys of the items returned in the new map are the same as in the original one.
4317
         *
4318
         * @param int $offset Number of elements to start from
4319
         * @param int|null $length Number of elements to return or NULL for no limit
4320
         * @return self<int|string,mixed> New map
4321
         */
4322
        public function slice( int $offset, ?int $length = null ) : self
4323
        {
4324
                return new static( array_slice( $this->list(), $offset, $length, true ) );
48✔
4325
        }
4326

4327

4328
        /**
4329
         * Tests if at least one element passes the test or is part of the map.
4330
         *
4331
         * Examples:
4332
         *  Map::from( ['a', 'b'] )->some( 'a' );
4333
         *  Map::from( ['a', 'b'] )->some( ['a', 'c'] );
4334
         *  Map::from( ['a', 'b'] )->some( function( $item, $key ) {
4335
         *    return $item === 'a';
4336
         *  } );
4337
         *  Map::from( ['a', 'b'] )->some( ['c', 'd'] );
4338
         *  Map::from( ['1', '2'] )->some( [2], true );
4339
         *
4340
         * Results:
4341
         * The first three examples will return TRUE while the fourth and fifth will return FALSE
4342
         *
4343
         * @param \Closure|iterable|mixed $values Anonymous function with (item, key) parameter, element or list of elements to test against
4344
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
4345
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
4346
         */
4347
        public function some( $values, bool $strict = false ) : bool
4348
        {
4349
                $list = $this->list();
48✔
4350

4351
                if( is_iterable( $values ) )
48✔
4352
                {
4353
                        foreach( $values as $entry )
24✔
4354
                        {
4355
                                if( in_array( $entry, $list, $strict ) === true ) {
24✔
4356
                                        return true;
24✔
4357
                                }
4358
                        }
4359

4360
                        return false;
16✔
4361
                }
4362
                elseif( is_callable( $values ) )
32✔
4363
                {
4364
                        foreach( $list as $key => $item )
16✔
4365
                        {
4366
                                if( $values( $item, $key ) ) {
16✔
4367
                                        return true;
16✔
4368
                                }
4369
                        }
4370
                }
4371
                elseif( in_array( $values, $list, $strict ) === true )
24✔
4372
                {
4373
                        return true;
24✔
4374
                }
4375

4376
                return false;
24✔
4377
        }
4378

4379

4380
        /**
4381
         * Sorts all elements in-place using new keys.
4382
         *
4383
         * Examples:
4384
         *  Map::from( ['a' => 1, 'b' => 0] )->sort();
4385
         *  Map::from( [0 => 'b', 1 => 'a'] )->sort();
4386
         *
4387
         * Results:
4388
         *  [0 => 0, 1 => 1]
4389
         *  [0 => 'a', 1 => 'b']
4390
         *
4391
         * The parameter modifies how the values are compared. Possible parameter values are:
4392
         * - SORT_REGULAR : compare elements normally (don't change types)
4393
         * - SORT_NUMERIC : compare elements numerically
4394
         * - SORT_STRING : compare elements as strings
4395
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4396
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4397
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4398
         *
4399
         * The keys aren't preserved and elements get a new index. No new map is created.
4400
         *
4401
         * @param int $options Sort options for PHP sort()
4402
         * @return self<int|string,mixed> Updated map for fluid interface
4403
         * @see sorted() - Sorts elements in a copy of the map
4404
         */
4405
        public function sort( int $options = SORT_REGULAR ) : self
4406
        {
4407
                sort( $this->list(), $options );
40✔
4408
                return $this;
40✔
4409
        }
4410

4411

4412
        /**
4413
         * Sorts the elements in a copy of the map using new keys.
4414
         *
4415
         * Examples:
4416
         *  Map::from( ['a' => 1, 'b' => 0] )->sorted();
4417
         *  Map::from( [0 => 'b', 1 => 'a'] )->sorted();
4418
         *
4419
         * Results:
4420
         *  [0 => 0, 1 => 1]
4421
         *  [0 => 'a', 1 => 'b']
4422
         *
4423
         * The parameter modifies how the values are compared. Possible parameter values are:
4424
         * - SORT_REGULAR : compare elements normally (don't change types)
4425
         * - SORT_NUMERIC : compare elements numerically
4426
         * - SORT_STRING : compare elements as strings
4427
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4428
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4429
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4430
         *
4431
         * The keys aren't preserved and elements get a new index and a new map is created before sorting the elements.
4432
         * Thus, sort() should be preferred for performance reasons if possible. A new map is created by calling this method.
4433
         *
4434
         * @param int $options Sort options for PHP sort()
4435
         * @return self<int|string,mixed> New map with a sorted copy of the elements
4436
         * @see sort() - Sorts elements in-place in the original map
4437
         */
4438
        public function sorted( int $options = SORT_REGULAR ) : self
4439
        {
4440
                return ( clone $this )->sort( $options );
16✔
4441
        }
4442

4443

4444
        /**
4445
         * Removes a portion of the map and replace it with the given replacement, then return the updated map.
4446
         *
4447
         * Examples:
4448
         *  Map::from( ['a', 'b', 'c'] )->splice( 1 );
4449
         *  Map::from( ['a', 'b', 'c'] )->splice( 1, 1, ['x', 'y'] );
4450
         *
4451
         * Results:
4452
         * The first example removes all entries after "a", so only ['a'] will be left
4453
         * in the map and ['b', 'c'] is returned. The second example replaces/returns "b"
4454
         * (start at 1, length 1) with ['x', 'y'] so the new map will contain
4455
         * ['a', 'x', 'y', 'c'] afterwards.
4456
         *
4457
         * The rules for offsets are:
4458
         * - If offset is non-negative, the sequence will start at that offset
4459
         * - If offset is negative, the sequence will start that far from the end
4460
         *
4461
         * Similar for the length:
4462
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4463
         * - If the array is shorter than the length, then only the available array elements will be present
4464
         * - If length is given and is negative then the sequence will stop that many elements from the end
4465
         * - If it is omitted, then the sequence will have everything from offset up until the end
4466
         *
4467
         * Numerical array indexes are NOT preserved.
4468
         *
4469
         * @param int $offset Number of elements to start from
4470
         * @param int|null $length Number of elements to remove, NULL for all
4471
         * @param mixed $replacement List of elements to insert
4472
         * @return self<int|string,mixed> New map
4473
         */
4474
        public function splice( int $offset, ?int $length = null, $replacement = [] ) : self
4475
        {
4476
                if( $length === null ) {
40✔
4477
                        $length = count( $this->list() );
16✔
4478
                }
4479

4480
                return new static( array_splice( $this->list(), $offset, $length, (array) $replacement ) );
40✔
4481
        }
4482

4483

4484
        /**
4485
         * Returns the strings after the passed value.
4486
         *
4487
         * Examples:
4488
         *  Map::from( ['äöüß'] )->strAfter( 'ö' );
4489
         *  Map::from( ['abc'] )->strAfter( '' );
4490
         *  Map::from( ['abc'] )->strAfter( 'b' );
4491
         *  Map::from( ['abc'] )->strAfter( 'c' );
4492
         *  Map::from( ['abc'] )->strAfter( 'x' );
4493
         *  Map::from( [''] )->strAfter( '' );
4494
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4495
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4496
         *
4497
         * Results:
4498
         *  ['üß']
4499
         *  ['abc']
4500
         *  ['c']
4501
         *  ['']
4502
         *  []
4503
         *  []
4504
         *  ['1', '1', '1']
4505
         *  ['0', '0']
4506
         *
4507
         * All scalar values (bool, int, float, string) will be converted to strings.
4508
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4509
         *
4510
         * @param string $value Character or string to search for
4511
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4512
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4513
         * @return self<int|string,mixed> New map
4514
         */
4515
        public function strAfter( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4516
        {
4517
                $list = [];
8✔
4518
                $len = mb_strlen( $value );
8✔
4519
                $fcn = $case ? 'mb_stripos' : 'mb_strpos';
8✔
4520

4521
                foreach( $this->list() as $key => $entry )
8✔
4522
                {
4523
                        if( is_scalar( $entry ) )
8✔
4524
                        {
4525
                                $pos = null;
8✔
4526
                                $str = (string) $entry;
8✔
4527

4528
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
8✔
4529
                                        $list[$key] = mb_substr( $str, $pos + $len, null, $encoding );
8✔
4530
                                } elseif( $str !== '' && $pos !== false ) {
8✔
4531
                                        $list[$key] = $str;
8✔
4532
                                }
4533
                        }
4534
                }
4535

4536
                return new static( $list );
8✔
4537
        }
4538

4539

4540
        /**
4541
         * Returns the strings before the passed value.
4542
         *
4543
         * Examples:
4544
         *  Map::from( ['äöüß'] )->strBefore( 'ü' );
4545
         *  Map::from( ['abc'] )->strBefore( '' );
4546
         *  Map::from( ['abc'] )->strBefore( 'b' );
4547
         *  Map::from( ['abc'] )->strBefore( 'a' );
4548
         *  Map::from( ['abc'] )->strBefore( 'x' );
4549
         *  Map::from( [''] )->strBefore( '' );
4550
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4551
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4552
         *
4553
         * Results:
4554
         *  ['äö']
4555
         *  ['abc']
4556
         *  ['a']
4557
         *  ['']
4558
         *  []
4559
         *  []
4560
         *  ['1', '1', '1']
4561
         *  ['0', '0']
4562
         *
4563
         * All scalar values (bool, int, float, string) will be converted to strings.
4564
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4565
         *
4566
         * @param string $value Character or string to search for
4567
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4568
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4569
         * @return self<int|string,mixed> New map
4570
         */
4571
        public function strBefore( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4572
        {
4573
                $list = [];
8✔
4574
                $fcn = $case ? 'mb_strripos' : 'mb_strrpos';
8✔
4575

4576
                foreach( $this->list() as $key => $entry )
8✔
4577
                {
4578
                        if( is_scalar( $entry ) )
8✔
4579
                        {
4580
                                $pos = null;
8✔
4581
                                $str = (string) $entry;
8✔
4582

4583
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
8✔
4584
                                        $list[$key] = mb_substr( $str, 0, $pos, $encoding );
8✔
4585
                                } elseif( $str !== '' && $pos !== false ) {
8✔
4586
                                        $list[$key] = $str;
8✔
4587
                                } else {
1✔
4588
                                }
4589
                        }
4590
                }
4591

4592
                return new static( $list );
8✔
4593
        }
4594

4595

4596
        /**
4597
         * Compares the value against all map elements.
4598
         *
4599
         * Examples:
4600
         *  Map::from( ['foo', 'bar'] )->compare( 'foo' );
4601
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo', false );
4602
         *  Map::from( [123, 12.3] )->compare( '12.3' );
4603
         *  Map::from( [false, true] )->compare( '1' );
4604
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo' );
4605
         *  Map::from( ['foo', 'bar'] )->compare( 'baz' );
4606
         *  Map::from( [new \stdClass(), 'bar'] )->compare( 'foo' );
4607
         *
4608
         * Results:
4609
         * The first four examples return TRUE, the last three examples will return FALSE.
4610
         *
4611
         * All scalar values (bool, float, int and string) are casted to string values before
4612
         * comparing to the given value. Non-scalar values in the map are ignored.
4613
         *
4614
         * @param string $value Value to compare map elements to
4615
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
4616
         * @return bool TRUE If at least one element matches, FALSE if value is not in map
4617
         */
4618
        public function strCompare( string $value, bool $case = true ) : bool
4619
        {
4620
                $fcn = $case ? 'strcmp' : 'strcasecmp';
16✔
4621

4622
                foreach( $this->list() as $item )
16✔
4623
                {
4624
                        if( is_scalar( $item ) && !$fcn( (string) $item, $value ) ) {
16✔
4625
                                return true;
16✔
4626
                        }
4627
                }
4628

4629
                return false;
16✔
4630
        }
4631

4632

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

4670
                        foreach( (array) $value as $str )
8✔
4671
                        {
4672
                                $str = (string) $str;
8✔
4673

4674
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
8✔
4675
                                        return true;
8✔
4676
                                }
4677
                        }
4678
                }
4679

4680
                return false;
8✔
4681
        }
4682

4683

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

4717
                foreach( $this->list() as $entry )
8✔
4718
                {
4719
                        $entry = (string) $entry;
8✔
4720
                        $list[$entry] = 0;
8✔
4721

4722
                        foreach( (array) $value as $str )
8✔
4723
                        {
4724
                                $str = (string) $str;
8✔
4725

4726
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
8✔
4727
                                        $list[$entry] = 1; break;
8✔
4728
                                }
4729
                        }
4730
                }
4731

4732
                return array_sum( $list ) === count( $list );
8✔
4733
        }
4734

4735

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

4764
                        foreach( (array) $value as $str )
8✔
4765
                        {
4766
                                $len = mb_strlen( (string) $str );
8✔
4767

4768
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
8✔
4769
                                        return true;
8✔
4770
                                }
4771
                        }
4772
                }
4773

4774
                return false;
8✔
4775
        }
4776

4777

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

4804
                foreach( $this->list() as $entry )
8✔
4805
                {
4806
                        $entry = (string) $entry;
8✔
4807
                        $list[$entry] = 0;
8✔
4808

4809
                        foreach( (array) $value as $str )
8✔
4810
                        {
4811
                                $len = mb_strlen( (string) $str );
8✔
4812

4813
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
8✔
4814
                                        $list[$entry] = 1; break;
8✔
4815
                                }
4816
                        }
4817
                }
4818

4819
                return array_sum( $list ) === count( $list );
8✔
4820
        }
4821

4822

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

4861

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

4888
                return $this;
8✔
4889
        }
4890

4891

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

4938
                foreach( $this->list() as &$entry )
8✔
4939
                {
4940
                        if( is_string( $entry ) ) {
8✔
4941
                                $entry = $fcn( $search, $replace, $entry );
8✔
4942
                        }
4943
                }
4944

4945
                return $this;
8✔
4946
        }
4947

4948

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

4977
                        foreach( (array) $value as $str )
8✔
4978
                        {
4979
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
8✔
4980
                                        return true;
8✔
4981
                                }
4982
                        }
4983
                }
4984

4985
                return false;
8✔
4986
        }
4987

4988

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

5015
                foreach( $this->list() as $entry )
8✔
5016
                {
5017
                        $entry = (string) $entry;
8✔
5018
                        $list[$entry] = 0;
8✔
5019

5020
                        foreach( (array) $value as $str )
8✔
5021
                        {
5022
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
8✔
5023
                                        $list[$entry] = 1; break;
8✔
5024
                                }
5025
                        }
5026
                }
5027

5028
                return array_sum( $list ) === count( $list );
8✔
5029
        }
5030

5031

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

5058
                return $this;
8✔
5059
        }
5060

5061

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

5091
                        foreach( $list as $key => $item )
8✔
5092
                        {
5093
                                if( is_array( $item ) ) {
8✔
5094
                                        $list[$key] = $depth > 1 ? $fcn( $item, $suffix, $depth - 1 ) : $item;
8✔
5095
                                } else {
5096
                                        $list[$key] = $item . ( is_callable( $suffix ) ? $suffix( $item, $key ) : $suffix );
8✔
5097
                                }
5098
                        }
5099

5100
                        return $list;
8✔
5101
                };
8✔
5102

5103
                $this->list = $fcn( $this->list(), $suffix, $depth ?? 0x7fffffff );
8✔
5104
                return $this;
8✔
5105
        }
5106

5107

5108
        /**
5109
         * Returns the sum of all integer and float values in the map.
5110
         *
5111
         * Examples:
5112
         *  Map::from( [1, 3, 5] )->sum();
5113
         *  Map::from( [1, 'sum', 5] )->sum();
5114
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->sum( 'p' );
5115
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( 'i/p' );
5116
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( fn( $val, $key ) => $val['i']['p'] ?? null )
5117
         *  Map::from( [30, 50, 10] )->sum( fn( $val, $key ) => $val < 50 ? $val : null )
5118
         *
5119
         * Results:
5120
         * The first line will return "9", the second one "6", the third one "90"
5121
         * the forth/fifth "80" and the last one "40".
5122
         *
5123
         * Non-numeric values will be removed before calculation.
5124
         *
5125
         * This does also work for multi-dimensional arrays by passing the keys
5126
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5127
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5128
         * public properties of objects or objects implementing __isset() and __get() methods.
5129
         *
5130
         * @param Closure|string|null $col Closure, key or path to the values in the nested array or object to sum up
5131
         * @return float Sum of all elements or 0 if there are no elements in the map
5132
         */
5133
        public function sum( $col = null ) : float
5134
        {
5135
                $list = $this->list();
24✔
5136
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list, 'is_numeric' );
24✔
5137

5138
                return array_sum( $vals );
24✔
5139
        }
5140

5141

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

5171
                if( is_scalar( $offset ) ) {
40✔
5172
                        return new static( array_slice( $list, (int) $offset, $size, true ) );
24✔
5173
                }
5174

5175
                if( is_callable( $offset ) )
16✔
5176
                {
5177
                        $idx = 0;
8✔
5178

5179
                        foreach( $list as $key => $item )
8✔
5180
                        {
5181
                                if( !$offset( $item, $key ) ) {
8✔
5182
                                        break;
8✔
5183
                                }
5184

5185
                                ++$idx;
8✔
5186
                        }
5187

5188
                        return new static( array_slice( $list, $idx, $size, true ) );
8✔
5189
                }
5190

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

5194

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

5221

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

5232

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

5243

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

5263

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

5278

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

5294

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

5313

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

5348
                foreach( $this->list() as $key => $value )
32✔
5349
                {
5350
                        foreach( (array) $callback( $value, $key ) as $newkey => $newval ) {
32✔
5351
                                $result[$newkey] = $newval;
32✔
5352
                        }
5353
                }
5354

5355
                return new static( $result );
32✔
5356
        }
5357

5358

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

5396
                foreach( (array) $this->first( [] ) as $key => $col ) {
16✔
5397
                        $result[$key] = array_column( $this->list(), $key );
16✔
5398
                }
5399

5400
                return new static( $result );
16✔
5401
        }
5402

5403

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

5473
                return map( $result );
40✔
5474
        }
5475

5476

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

5534
                foreach( $this->list as &$node )
8✔
5535
                {
5536
                        $node[$nestKey] = [];
8✔
5537
                        $refs[$node[$idKey]] = &$node;
8✔
5538

5539
                        if( $node[$parentKey] ) {
8✔
5540
                                $refs[$node[$parentKey]][$nestKey][$node[$idKey]] = &$node;
8✔
5541
                        } else {
5542
                                $trees[$node[$idKey]] = &$node;
8✔
5543
                        }
5544
                }
5545

5546
                return map( $trees );
8✔
5547
        }
5548

5549

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

5572
                return $this;
8✔
5573
        }
5574

5575

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

5605

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

5634

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

5664

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

5693

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

5719

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

5749
                $list = $this->list();
24✔
5750
                $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
24✔
5751

5752
                return new static( array_intersect_key( $list, array_unique( $map ) ) );
24✔
5753
        }
5754

5755

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

5791
                return $this;
24✔
5792
        }
5793

5794

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

5824

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

5853

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

5870

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

5914
                return $this;
24✔
5915
        }
5916

5917

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

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

6001
                        return false;
8✔
6002
                } );
48✔
6003
        }
6004

6005

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

6030

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

6055
                return new static( array_map( null, $this->list(), ...$args ) );
8✔
6056
        }
6057

6058

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

6071
                if( $elements instanceof \Closure ) {
312✔
6072
                        return (array) $elements();
×
6073
                }
6074

6075
                if( $elements instanceof \Aimeos\Map ) {
312✔
6076
                        return $elements->toArray();
184✔
6077
                }
6078

6079
                if( is_iterable( $elements ) ) {
136✔
6080
                        return iterator_to_array( $elements, true );
24✔
6081
                }
6082

6083
                return $elements !== null ? [$elements] : [];
112✔
6084
        }
6085

6086

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

6106

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

6126

6127
        /**
6128
         * Returns a reference to the array of elements
6129
         *
6130
         * @return array Reference to the array of elements
6131
         */
6132
        protected function &list() : array
6133
        {
6134
                if( !is_array( $this->list ) ) {
2,816✔
6135
                        $this->list = $this->array( $this->list );
×
6136
                }
6137

6138
                return $this->list;
2,816✔
6139
        }
6140

6141

6142
        /**
6143
         * Returns a closure that retrieves the value for the passed key
6144
         *
6145
         * @param \Closure|string|null $key Closure or key (e.g. "key1/key2/key3") to retrieve the value for
6146
         * @return \Closure Closure that retrieves the value for the passed key
6147
         */
6148
        protected function mapper( $key = null ) : \Closure
6149
        {
6150
                if( $key instanceof \Closure ) {
112✔
6151
                        return $key;
48✔
6152
                }
6153

6154
                $parts = $key ? explode( $this->sep, (string) $key ) : [];
64✔
6155

6156
                return function( $item ) use ( $parts ) {
48✔
6157
                        return $this->val( $item, $parts );
64✔
6158
                };
64✔
6159
        }
6160

6161

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

6182
                return $entry;
216✔
6183
        }
6184

6185

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

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