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

aimeos / map / 13655342629

04 Mar 2025 01:58PM UTC coverage: 97.589% (+0.06%) from 97.526%
13655342629

push

github

aimeos
Minor improvments

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

17 existing lines in 1 file now uncovered.

769 of 788 relevant lines covered (97.59%)

12.36 hits per line

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

97.58
/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;
810✔
53
                $this->list = $elements;
810✔
54
        }
55

56

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

79
                return call_user_func_array( \Closure::bind( static::$methods[$name], null, static::class ), $params );
2✔
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] ) ) {
8✔
115
                        return call_user_func_array( static::$methods[$name]->bindTo( $this, static::class ), $params );
4✔
116
                }
117

118
                $result = [];
4✔
119

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

127
                return new static( $result );
4✔
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 );
2✔
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;
2✔
163

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

168
                return $old;
2✔
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 !== '' ) {
16✔
207
                        return new static( explode( $delimiter, $string, $limit ) );
8✔
208
                }
209

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

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

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

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

225
                return new static( $parts );
4✔
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 ) );
4✔
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 ) {
374✔
274
                        return $elements;
6✔
275
                }
276

277
                return new static( $elements );
374✔
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 ) {
8✔
312
                        return new static( $result );
6✔
313
                }
314

315
                throw new \RuntimeException( 'Not a valid JSON string: ' . $json );
2✔
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 ) {
6✔
342
                        self::$methods[$method] = $fcn;
6✔
343
                }
344

345
                return self::$methods[$method] ?? null;
6✔
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 = [];
6✔
380

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

386
                return new static( $list );
6✔
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 ) {
8✔
415
                        return new static();
2✔
416
                }
417

418
                return new static( array_slice( $this->list(), $pos + 1, null, true ) );
6✔
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' ) ) {
2✔
453
                        return array_any( $this->list(), $callback );
×
454
                }
455

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

463
                return false;
2✔
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 );
8✔
498
                return $this;
8✔
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 );
2✔
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 );
8✔
567
                return $this;
8✔
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 );
2✔
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 );
2✔
628
                return !empty( $pair ) ? current( $pair ) : null;
2✔
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();
6✔
661
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list, 'is_numeric' );
6✔
662

663
                return !empty( $vals ) ? array_sum( $vals ) / count( $vals ) : 0;
6✔
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 ) );
8✔
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 );
6✔
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 = [];
2✔
761

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

769
                return new static( $result );
2✔
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 )
2✔
801
                {
802
                        switch( $type )
803
                        {
804
                                case 'bool': $item = (bool) $item; break;
2✔
805
                                case 'int': $item = (int) $item; break;
2✔
806
                                case 'float': $item = (float) $item; break;
2✔
807
                                case 'string': $item = (string) $item; break;
2✔
808
                                case 'array': $item = (array) $item; break;
2✔
809
                                case 'object': $item = (object) $item; break;
2✔
810
                        }
811
                }
812

813
                return $this;
2✔
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 ) {
6✔
841
                        throw new \InvalidArgumentException( 'Chunk size must be greater or equal than 1' );
2✔
842
                }
843

844
                return new static( array_chunk( $this->list(), $size, $preserve ) );
4✔
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 = [];
8✔
856
                return $this;
8✔
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 = [];
2✔
879

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

884
                return new static( $list );
2✔
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 );
18✔
925
                $iparts = explode( $this->sep, (string) $indexcol );
18✔
926

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

933
                $list = [];
6✔
934

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

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

946
                return new static( $list );
6✔
947
        }
948

949

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

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

989

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

1007

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

1023

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

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

1046
                return $this;
4✔
1047
        }
1048

1049

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

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

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

1090

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

1104

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

1115

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

1147
                        $col = function( $item ) use ( $parts ) {
6✔
1148
                                return (string) $this->val( $item, $parts );
6✔
1149
                        };
6✔
1150
                }
1151

1152
                return new static( array_count_values( array_map( $col, $this->list() ) ) );
8✔
1153
        }
1154

1155

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

1181

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

1217
                return new static( array_diff( $this->list(), $this->array( $elements ) ) );
6✔
1218
        }
1219

1220

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

1258
                return new static( array_diff_assoc( $this->list(), $this->array( $elements ) ) );
4✔
1259
        }
1260

1261

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

1298
                return new static( array_diff_key( $this->list(), $this->array( $elements ) ) );
4✔
1299
        }
1300

1301

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

1333

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

1366
                if( $col !== null ) {
8✔
1367
                        $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
6✔
1368
                }
1369

1370
                return new static( array_diff_key( $list, array_unique( $map ) ) );
8✔
1371
        }
1372

1373

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

1399
                return $this;
4✔
1400
        }
1401

1402

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

1422

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

1448
                return array_diff( $list, $elements ) === [] && array_diff( $elements, $list ) === [];
12✔
1449
        }
1450

1451

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

1479
                return true;
2✔
1480
        }
1481

1482

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

1504

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

1532

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

1563
                if( !empty( $list ) )
10✔
1564
                {
1565
                        if( $reverse )
10✔
1566
                        {
1567
                                $value = end( $list );
4✔
1568
                                $key = key( $list );
4✔
1569

1570
                                do
1571
                                {
1572
                                        if( $callback( $value, $key ) ) {
4✔
1573
                                                return $value;
2✔
1574
                                        }
1575
                                }
1576
                                while( ( $value = prev( $list ) ) !== false && ( $key = key( $list ) ) !== null );
4✔
1577

1578
                                reset( $list );
2✔
1579
                        }
1580
                        else
1581
                        {
1582
                                foreach( $list as $key => $value )
6✔
1583
                                {
1584
                                        if( $callback( $value, $key ) ) {
6✔
1585
                                                return $value;
2✔
1586
                                        }
1587
                                }
1588
                        }
1589
                }
1590

1591
                if( $default instanceof \Closure ) {
6✔
1592
                        return $default();
2✔
1593
                }
1594

1595
                if( $default instanceof \Throwable ) {
4✔
1596
                        throw $default;
2✔
1597
                }
1598

1599
                return $default;
2✔
1600
        }
1601

1602

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

1636
                if( !empty( $list ) )
10✔
1637
                {
1638
                        if( $reverse )
4✔
1639
                        {
1640
                                $value = end( $list );
2✔
1641
                                $key = key( $list );
2✔
1642

1643
                                do
1644
                                {
1645
                                        if( $callback( $value, $key ) ) {
2✔
1646
                                                return $key;
2✔
1647
                                        }
1648
                                }
UNCOV
1649
                                while( ( $value = prev( $list ) ) !== false && ( $key = key( $list ) ) !== null );
×
1650

UNCOV
1651
                                reset( $list );
×
1652
                        }
1653
                        else
1654
                        {
1655
                                foreach( $list as $key => $value )
2✔
1656
                                {
1657
                                        if( $callback( $value, $key ) ) {
2✔
1658
                                                return $key;
2✔
1659
                                        }
1660
                                }
1661
                        }
1662
                }
1663

1664
                if( $default instanceof \Closure ) {
6✔
1665
                        return $default();
2✔
1666
                }
1667

1668
                if( $default instanceof \Throwable ) {
4✔
1669
                        throw $default;
2✔
1670
                }
1671

1672
                return $default;
2✔
1673
        }
1674

1675

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

1702
                if( $default instanceof \Closure ) {
10✔
1703
                        return $default();
2✔
1704
                }
1705

1706
                if( $default instanceof \Throwable ) {
8✔
1707
                        throw $default;
2✔
1708
                }
1709

1710
                return $default;
6✔
1711
        }
1712

1713

1714
        /**
1715
         * Returns the first key from the map.
1716
         *
1717
         * Examples:
1718
         *  Map::from( ['a' => 1, 'b' => 2] )->firstKey();
1719
         *  Map::from( [] )->firstKey( 'x' );
1720
         *  Map::from( [] )->firstKey( new \Exception( 'error' ) );
1721
         *  Map::from( [] )->firstKey( function() { return rand(); } );
1722
         *
1723
         * Results:
1724
         * The first example will return 'a' and the second one 'x', the third one will throw
1725
         * an exception and the last one will return a random value.
1726
         *
1727
         * Using this method doesn't affect the internal array pointer.
1728
         *
1729
         * @param mixed $default Default value, closure or exception if the map contains no elements
1730
         * @return mixed First key of map, (generated) default value or an exception
1731
         */
1732
        public function firstKey( $default = null )
1733
        {
1734
                $list = $this->list();
10✔
1735

1736
                // PHP 7.x compatibility
1737
                if( function_exists( 'array_key_first' ) ) {
10✔
1738
                        $key = array_key_first( $list );
10✔
1739
                } else {
UNCOV
1740
                        $key = key( array_slice( $list, 0, 1, true ) );
×
1741
                }
1742

1743
                if( $key !== null ) {
10✔
1744
                        return $key;
2✔
1745
                }
1746

1747
                if( $default instanceof \Closure ) {
8✔
1748
                        return $default();
2✔
1749
                }
1750

1751
                if( $default instanceof \Throwable ) {
6✔
1752
                        throw $default;
2✔
1753
                }
1754

1755
                return $default;
4✔
1756
        }
1757

1758

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

1792
                $result = [];
10✔
1793
                $this->flatten( $this->list(), $result, $depth ?? 0x7fffffff );
10✔
1794
                return new static( $result );
10✔
1795
        }
1796

1797

1798
        /**
1799
         * Exchanges the keys with their values and vice versa.
1800
         *
1801
         * Examples:
1802
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->flip();
1803
         *
1804
         * Results:
1805
         *  ['X' => 'a', 'Y' => 'b']
1806
         *
1807
         * @return self<int|string,mixed> New map with keys as values and values as keys
1808
         */
1809
        public function flip() : self
1810
        {
1811
                return new static( array_flip( $this->list() ) );
2✔
1812
        }
1813

1814

1815
        /**
1816
         * Returns an element by key and casts it to float if possible.
1817
         *
1818
         * Examples:
1819
         *  Map::from( ['a' => true] )->float( 'a' );
1820
         *  Map::from( ['a' => 1] )->float( 'a' );
1821
         *  Map::from( ['a' => '1.1'] )->float( 'a' );
1822
         *  Map::from( ['a' => '10'] )->float( 'a' );
1823
         *  Map::from( ['a' => ['b' => ['c' => 1.1]]] )->float( 'a/b/c' );
1824
         *  Map::from( [] )->float( 'c', function() { return 1.1; } );
1825
         *  Map::from( [] )->float( 'a', 1.1 );
1826
         *
1827
         *  Map::from( [] )->float( 'b' );
1828
         *  Map::from( ['b' => ''] )->float( 'b' );
1829
         *  Map::from( ['b' => null] )->float( 'b' );
1830
         *  Map::from( ['b' => 'abc'] )->float( 'b' );
1831
         *  Map::from( ['b' => [1]] )->float( 'b' );
1832
         *  Map::from( ['b' => #resource] )->float( 'b' );
1833
         *  Map::from( ['b' => new \stdClass] )->float( 'b' );
1834
         *
1835
         *  Map::from( [] )->float( 'c', new \Exception( 'error' ) );
1836
         *
1837
         * Results:
1838
         * The first eight examples will return the float values for the passed keys
1839
         * while the 9th to 14th example returns 0. The last example will throw an exception.
1840
         *
1841
         * This does also work for multi-dimensional arrays by passing the keys
1842
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1843
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1844
         * public properties of objects or objects implementing __isset() and __get() methods.
1845
         *
1846
         * @param int|string $key Key or path to the requested item
1847
         * @param mixed $default Default value if key isn't found (will be casted to float)
1848
         * @return float Value from map or default value
1849
         */
1850
        public function float( $key, $default = 0.0 ) : float
1851
        {
1852
                return (float) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
6✔
1853
        }
1854

1855

1856
        /**
1857
         * Returns an element from the map by key.
1858
         *
1859
         * Examples:
1860
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'a' );
1861
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'c', 'Z' );
1862
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->get( 'a/b/c' );
1863
         *  Map::from( [] )->get( 'Y', new \Exception( 'error' ) );
1864
         *  Map::from( [] )->get( 'Y', function() { return rand(); } );
1865
         *
1866
         * Results:
1867
         * The first example will return 'X', the second 'Z' and the third 'Y'. The forth
1868
         * example will throw the exception passed if the map contains no elements. In
1869
         * the fifth example, a random value generated by the closure function will be
1870
         * returned.
1871
         *
1872
         * This does also work for multi-dimensional arrays by passing the keys
1873
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
1874
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
1875
         * public properties of objects or objects implementing __isset() and __get() methods.
1876
         *
1877
         * @param int|string $key Key or path to the requested item
1878
         * @param mixed $default Default value if no element matches
1879
         * @return mixed Value from map or default value
1880
         */
1881
        public function get( $key, $default = null )
1882
        {
1883
                $list = $this->list();
46✔
1884

1885
                if( array_key_exists( $key, $list ) ) {
46✔
1886
                        return $list[$key];
12✔
1887
                }
1888

1889
                if( ( $v = $this->val( $list, explode( $this->sep, (string) $key ) ) ) !== null ) {
42✔
1890
                        return $v;
14✔
1891
                }
1892

1893
                if( $default instanceof \Closure ) {
36✔
1894
                        return $default();
12✔
1895
                }
1896

1897
                if( $default instanceof \Throwable ) {
24✔
1898
                        throw $default;
12✔
1899
                }
1900

1901
                return $default;
12✔
1902
        }
1903

1904

1905
        /**
1906
         * Returns an iterator for the elements.
1907
         *
1908
         * This method will be used by e.g. foreach() to loop over all entries:
1909
         *  foreach( Map::from( ['a', 'b'] ) as $value )
1910
         *
1911
         * @return \ArrayIterator<int|string,mixed> Iterator for map elements
1912
         */
1913
        public function getIterator() : \ArrayIterator
1914
        {
1915
                return new \ArrayIterator( $this->list() );
10✔
1916
        }
1917

1918

1919
        /**
1920
         * Returns only items which matches the regular expression.
1921
         *
1922
         * All items are converted to string first before they are compared to the
1923
         * regular expression. Thus, fractions of ".0" will be removed in float numbers
1924
         * which may result in unexpected results.
1925
         *
1926
         * Examples:
1927
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/b/' );
1928
         *  Map::from( ['ab', 'bc', 'cd'] )->grep( '/a/', PREG_GREP_INVERT );
1929
         *  Map::from( [1.5, 0, 1.0, 'a'] )->grep( '/^(\d+)?\.\d+$/' );
1930
         *
1931
         * Results:
1932
         *  ['ab', 'bc']
1933
         *  ['bc', 'cd']
1934
         *  [1.5] // float 1.0 is converted to string "1"
1935
         *
1936
         * The keys are preserved using this method.
1937
         *
1938
         * @param string $pattern Regular expression pattern, e.g. "/ab/"
1939
         * @param int $flags PREG_GREP_INVERT to return elements not matching the pattern
1940
         * @return self<int|string,mixed> New map containing only the matched elements
1941
         */
1942
        public function grep( string $pattern, int $flags = 0 ) : self
1943
        {
1944
                if( ( $result = preg_grep( $pattern, $this->list(), $flags ) ) === false )
8✔
1945
                {
1946
                        switch( preg_last_error() )
2✔
1947
                        {
1948
                                case PREG_INTERNAL_ERROR: $msg = 'Internal error'; break;
2✔
UNCOV
1949
                                case PREG_BACKTRACK_LIMIT_ERROR: $msg = 'Backtrack limit error'; break;
×
UNCOV
1950
                                case PREG_RECURSION_LIMIT_ERROR: $msg = 'Recursion limit error'; break;
×
UNCOV
1951
                                case PREG_BAD_UTF8_ERROR: $msg = 'Bad UTF8 error'; break;
×
UNCOV
1952
                                case PREG_BAD_UTF8_OFFSET_ERROR: $msg = 'Bad UTF8 offset error'; break;
×
UNCOV
1953
                                case PREG_JIT_STACKLIMIT_ERROR: $msg = 'JIT stack limit error'; break;
×
UNCOV
1954
                                default: $msg = 'Unknown error';
×
1955
                        }
1956

1957
                        throw new \RuntimeException( 'Regular expression error: ' . $msg );
2✔
1958
                }
1959

1960
                return new static( $result );
6✔
1961
        }
1962

1963

1964
        /**
1965
         * Groups associative array elements or objects by the passed key or closure.
1966
         *
1967
         * Instead of overwriting items with the same keys like to the col() method
1968
         * does, groupBy() keeps all entries in sub-arrays. It's preserves the keys
1969
         * of the orignal map entries too.
1970
         *
1971
         * Examples:
1972
         *  $list = [
1973
         *    10 => ['aid' => 123, 'code' => 'x-abc'],
1974
         *    20 => ['aid' => 123, 'code' => 'x-def'],
1975
         *    30 => ['aid' => 456, 'code' => 'x-def']
1976
         *  ];
1977
         *  Map::from( $list )->groupBy( 'aid' );
1978
         *  Map::from( $list )->groupBy( function( $item, $key ) {
1979
         *    return substr( $item['code'], -3 );
1980
         *  } );
1981
         *  Map::from( $list )->groupBy( 'xid' );
1982
         *
1983
         * Results:
1984
         *  [
1985
         *    123 => [10 => ['aid' => 123, 'code' => 'x-abc'], 20 => ['aid' => 123, 'code' => 'x-def']],
1986
         *    456 => [30 => ['aid' => 456, 'code' => 'x-def']]
1987
         *  ]
1988
         *  [
1989
         *    'abc' => [10 => ['aid' => 123, 'code' => 'x-abc']],
1990
         *    'def' => [20 => ['aid' => 123, 'code' => 'x-def'], 30 => ['aid' => 456, 'code' => 'x-def']]
1991
         *  ]
1992
         *  [
1993
         *    '' => [
1994
         *      10 => ['aid' => 123, 'code' => 'x-abc'],
1995
         *      20 => ['aid' => 123, 'code' => 'x-def'],
1996
         *      30 => ['aid' => 456, 'code' => 'x-def']
1997
         *    ]
1998
         *  ]
1999
         *
2000
         * In case the passed key doesn't exist in one or more items, these items
2001
         * are stored in a sub-array using an empty string as key.
2002
         *
2003
         * This does also work for multi-dimensional arrays by passing the keys
2004
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2005
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2006
         * public properties of objects or objects implementing __isset() and __get() methods.
2007
         *
2008
         * @param  \Closure|string|int $key Closure function with (item, idx) parameters returning the key or the key itself to group by
2009
         * @return self<int|string,mixed> New map with elements grouped by the given key
2010
         */
2011
        public function groupBy( $key ) : self
2012
        {
2013
                $result = [];
8✔
2014

2015
                if( is_callable( $key ) )
8✔
2016
                {
2017
                        foreach( $this->list() as $idx => $item )
2✔
2018
                        {
2019
                                $keyval = (string) $key( $item, $idx );
2✔
2020
                                $result[$keyval][$idx] = $item;
2✔
2021
                        }
2022
                }
2023
                else
2024
                {
2025
                        $parts = explode( $this->sep, (string) $key );
6✔
2026

2027
                        foreach( $this->list() as $idx => $item )
6✔
2028
                        {
2029
                                $keyval = (string) $this->val( $item, $parts );
6✔
2030
                                $result[$keyval][$idx] = $item;
6✔
2031
                        }
2032
                }
2033

2034
                return new static( $result );
8✔
2035
        }
2036

2037

2038
        /**
2039
         * Determines if a key or several keys exists in the map.
2040
         *
2041
         * If several keys are passed as array, all keys must exist in the map for
2042
         * TRUE to be returned.
2043
         *
2044
         * Examples:
2045
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'a' );
2046
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'b'] );
2047
         *  Map::from( ['a' => ['b' => ['c' => 'Y']]] )->has( 'a/b/c' );
2048
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'c' );
2049
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'c'] );
2050
         *  Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'X' );
2051
         *
2052
         * Results:
2053
         * The first three examples will return TRUE while the other ones will return FALSE
2054
         *
2055
         * This does also work for multi-dimensional arrays by passing the keys
2056
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2057
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2058
         * public properties of objects or objects implementing __isset() and __get() methods.
2059
         *
2060
         * @param array<int|string>|int|string $key Key of the requested item or list of keys
2061
         * @return bool TRUE if key or keys are available in map, FALSE if not
2062
         */
2063
        public function has( $key ) : bool
2064
        {
2065
                $list = $this->list();
6✔
2066

2067
                foreach( (array) $key as $entry )
6✔
2068
                {
2069
                        if( array_key_exists( $entry, $list ) === false
6✔
2070
                                && $this->val( $list, explode( $this->sep, (string) $entry ) ) === null
6✔
2071
                        ) {
2072
                                return false;
6✔
2073
                        }
2074
                }
2075

2076
                return true;
6✔
2077
        }
2078

2079

2080
        /**
2081
         * Executes callbacks depending on the condition.
2082
         *
2083
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2084
         * executed and their returned value is passed back within a Map object. In
2085
         * case no "then" or "else" closure is given, the method will return the same
2086
         * map object.
2087
         *
2088
         * Examples:
2089
         *  Map::from( [] )->if( strpos( 'abc', 'b' ) !== false, function( $map ) {
2090
         *    echo 'found';
2091
         *  } );
2092
         *
2093
         *  Map::from( [] )->if( function( $map ) {
2094
         *    return $map->empty();
2095
         *  }, function( $map ) {
2096
         *    echo 'then';
2097
         *  } );
2098
         *
2099
         *  Map::from( ['a'] )->if( function( $map ) {
2100
         *    return $map->empty();
2101
         *  }, function( $map ) {
2102
         *    echo 'then';
2103
         *  }, function( $map ) {
2104
         *    echo 'else';
2105
         *  } );
2106
         *
2107
         *  Map::from( ['a', 'b'] )->if( true, function( $map ) {
2108
         *    return $map->push( 'c' );
2109
         *  } );
2110
         *
2111
         *  Map::from( ['a', 'b'] )->if( false, null, function( $map ) {
2112
         *    return $map->pop();
2113
         *  } );
2114
         *
2115
         * Results:
2116
         * The first example returns "found" while the second one returns "then" and
2117
         * the third one "else". The forth one will return ['a', 'b', 'c'] while the
2118
         * fifth one will return 'b', which is turned into a map of ['b'] again.
2119
         *
2120
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2121
         * (a short form for anonymous closures) as parameters. The automatically have access
2122
         * to previously defined variables but can not modify them. Also, they can not have
2123
         * a void return type and must/will always return something. Details about
2124
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2125
         *
2126
         * @param \Closure|bool $condition Boolean or function with (map) parameter returning a boolean
2127
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2128
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2129
         * @return self<int|string,mixed> New map
2130
         */
2131
        public function if( $condition, ?\Closure $then = null, ?\Closure $else = null ) : self
2132
        {
2133
                if( $condition instanceof \Closure ) {
16✔
2134
                        $condition = $condition( $this );
4✔
2135
                }
2136

2137
                if( $condition ) {
16✔
2138
                        return $then ? static::from( $then( $this, $condition ) ) : $this;
10✔
2139
                } elseif( $else ) {
6✔
2140
                        return static::from( $else( $this, $condition ) );
6✔
2141
                }
2142

UNCOV
2143
                return $this;
×
2144
        }
2145

2146

2147
        /**
2148
         * Executes callbacks depending if the map contains elements or not.
2149
         *
2150
         * If callbacks for "then" and/or "else" are passed, these callbacks will be
2151
         * executed and their returned value is passed back within a Map object. In
2152
         * case no "then" or "else" closure is given, the method will return the same
2153
         * map object.
2154
         *
2155
         * Examples:
2156
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2157
         *    $map->push( 'b' );
2158
         *  } );
2159
         *
2160
         *  Map::from( [] )->ifAny( null, function( $map ) {
2161
         *    return $map->push( 'b' );
2162
         *  } );
2163
         *
2164
         *  Map::from( ['a'] )->ifAny( function( $map ) {
2165
         *    return 'c';
2166
         *  } );
2167
         *
2168
         * Results:
2169
         * The first example returns a Map containing ['a', 'b'] because the the initial
2170
         * Map is not empty. The second one returns  a Map with ['b'] because the initial
2171
         * Map is empty and the "else" closure is used. The last example returns ['c']
2172
         * as new map content.
2173
         *
2174
         * Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
2175
         * (a short form for anonymous closures) as parameters. The automatically have access
2176
         * to previously defined variables but can not modify them. Also, they can not have
2177
         * a void return type and must/will always return something. Details about
2178
         * [PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
2179
         *
2180
         * @param \Closure|null $then Function with (map, condition) parameter (optional)
2181
         * @param \Closure|null $else Function with (map, condition) parameter (optional)
2182
         * @return self<int|string,mixed> New map
2183
         */
2184
        public function ifAny( ?\Closure $then = null, ?\Closure $else = null ) : self
2185
        {
2186
                return $this->if( !empty( $this->list() ), $then, $else );
6✔
2187
        }
2188

2189

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

2227

2228
        /**
2229
         * Tests if all entries in the map are objects implementing the given interface.
2230
         *
2231
         * Examples:
2232
         *  Map::from( [new Map(), new Map()] )->implements( '\Countable' );
2233
         *  Map::from( [new Map(), new stdClass()] )->implements( '\Countable' );
2234
         *  Map::from( [new Map(), 123] )->implements( '\Countable' );
2235
         *  Map::from( [new Map(), 123] )->implements( '\Countable', true );
2236
         *  Map::from( [new Map(), 123] )->implements( '\Countable', '\RuntimeException' );
2237
         *
2238
         * Results:
2239
         *  The first example returns TRUE while the second and third one return FALSE.
2240
         *  The forth example will throw an UnexpectedValueException while the last one
2241
         *  throws a RuntimeException.
2242
         *
2243
         * @param string $interface Name of the interface that must be implemented
2244
         * @param \Throwable|bool $throw Passing TRUE or an exception name will throw the exception instead of returning FALSE
2245
         * @return bool TRUE if all entries implement the interface or FALSE if at least one doesn't
2246
         * @throws \UnexpectedValueException|\Throwable If one entry doesn't implement the interface
2247
         */
2248
        public function implements( string $interface, $throw = false ) : bool
2249
        {
2250
                foreach( $this->list() as $entry )
6✔
2251
                {
2252
                        if( !( $entry instanceof $interface ) )
6✔
2253
                        {
2254
                                if( $throw )
6✔
2255
                                {
2256
                                        $name = is_string( $throw ) ? $throw : '\UnexpectedValueException';
4✔
2257
                                        throw new $name( "Does not implement $interface: " . print_r( $entry, true ) );
4✔
2258
                                }
2259

2260
                                return false;
2✔
2261
                        }
2262
                }
2263

2264
                return true;
2✔
2265
        }
2266

2267

2268
        /**
2269
         * Tests if the passed element or elements are part of the map.
2270
         *
2271
         * Examples:
2272
         *  Map::from( ['a', 'b'] )->in( 'a' );
2273
         *  Map::from( ['a', 'b'] )->in( ['a', 'b'] );
2274
         *  Map::from( ['a', 'b'] )->in( 'x' );
2275
         *  Map::from( ['a', 'b'] )->in( ['a', 'x'] );
2276
         *  Map::from( ['1', '2'] )->in( 2, true );
2277
         *
2278
         * Results:
2279
         * The first and second example will return TRUE while the other ones will return FALSE
2280
         *
2281
         * @param mixed|array $element Element or elements to search for in the map
2282
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2283
         * @return bool TRUE if all elements are available in map, FALSE if not
2284
         */
2285
        public function in( $element, bool $strict = false ) : bool
2286
        {
2287
                if( !is_array( $element ) ) {
8✔
2288
                        return in_array( $element, $this->list(), $strict );
8✔
2289
                };
2290

2291
                foreach( $element as $entry )
2✔
2292
                {
2293
                        if( in_array( $entry, $this->list(), $strict ) === false ) {
2✔
2294
                                return false;
2✔
2295
                        }
2296
                }
2297

2298
                return true;
2✔
2299
        }
2300

2301

2302
        /**
2303
         * Tests if the passed element or elements are part of the map.
2304
         *
2305
         * This method is an alias for in(). For performance reasons, in() should be
2306
         * preferred because it uses one method call less than includes().
2307
         *
2308
         * @param mixed|array $element Element or elements to search for in the map
2309
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
2310
         * @return bool TRUE if all elements are available in map, FALSE if not
2311
         * @see in() - Underlying method with same parameters and return value but better performance
2312
         */
2313
        public function includes( $element, bool $strict = false ) : bool
2314
        {
2315
                return $this->in( $element, $strict );
2✔
2316
        }
2317

2318

2319
        /**
2320
         * Returns the numerical index of the given key.
2321
         *
2322
         * Examples:
2323
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( '8' );
2324
         *  Map::from( [4 => 'a', 8 => 'b'] )->index( function( $key ) {
2325
         *      return $key == '8';
2326
         *  } );
2327
         *
2328
         * Results:
2329
         * Both examples will return "1" because the value "b" is at the second position
2330
         * and the returned index is zero based so the first item has the index "0".
2331
         *
2332
         * @param \Closure|string|int $value Key to search for or function with (key) parameters return TRUE if key is found
2333
         * @return int|null Position of the found value (zero based) or NULL if not found
2334
         */
2335
        public function index( $value ) : ?int
2336
        {
2337
                if( $value instanceof \Closure )
8✔
2338
                {
2339
                        $pos = 0;
4✔
2340

2341
                        foreach( $this->list() as $key => $item )
4✔
2342
                        {
2343
                                if( $value( $key ) ) {
2✔
2344
                                        return $pos;
2✔
2345
                                }
2346

2347
                                ++$pos;
2✔
2348
                        }
2349

2350
                        return null;
2✔
2351
                }
2352

2353
                $pos = array_search( $value, array_keys( $this->list() ) );
4✔
2354
                return $pos !== false ? $pos : null;
4✔
2355
        }
2356

2357

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

2382
                return $this;
6✔
2383
        }
2384

2385

2386
        /**
2387
         * Inserts the item at the given position in the map.
2388
         *
2389
         * Examples:
2390
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 0, 'baz' );
2391
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 1, 'baz', 'c' );
2392
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 4, 'baz' );
2393
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( -1, 'baz', 'c' );
2394
         *
2395
         * Results:
2396
         *  [0 => 'baz', 'a' => 'foo', 'b' => 'bar']
2397
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2398
         *  ['a' => 'foo', 'b' => 'bar', 'c' => 'baz']
2399
         *  ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
2400
         *
2401
         * @param int $pos Position the element it should be inserted at
2402
         * @param mixed $element Element to be inserted
2403
         * @param mixed|null $key Element key or NULL to assign an integer key automatically
2404
         * @return self<int|string,mixed> Updated map for fluid interface
2405
         */
2406
        public function insertAt( int $pos, $element, $key = null ) : self
2407
        {
2408
                if( $key !== null )
10✔
2409
                {
2410
                        $list = $this->list();
4✔
2411

2412
                        $this->list = array_merge(
4✔
2413
                                array_slice( $list, 0, $pos, true ),
4✔
2414
                                [$key => $element],
4✔
2415
                                array_slice( $list, $pos, null, true )
4✔
2416
                        );
4✔
2417
                }
2418
                else
2419
                {
2420
                        array_splice( $this->list(), $pos, 0, [$element] );
6✔
2421
                }
2422

2423
                return $this;
10✔
2424
        }
2425

2426

2427
        /**
2428
         * Inserts the value or values before the given element.
2429
         *
2430
         * Examples:
2431
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertBefore( 'bar', 'baz' );
2432
         *  Map::from( ['foo', 'bar'] )->insertBefore( 'bar', ['baz', 'boo'] );
2433
         *  Map::from( ['foo', 'bar'] )->insertBefore( null, 'baz' );
2434
         *
2435
         * Results:
2436
         *  ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
2437
         *  ['foo', 'baz', 'boo', 'bar']
2438
         *  ['foo', 'bar', 'baz']
2439
         *
2440
         * Numerical array indexes are not preserved.
2441
         *
2442
         * @param mixed $element Element before the value is inserted
2443
         * @param mixed $value Element or list of elements to insert
2444
         * @return self<int|string,mixed> Updated map for fluid interface
2445
         */
2446
        public function insertBefore( $element, $value ) : self
2447
        {
2448
                $position = ( $element !== null && ( $pos = $this->pos( $element ) ) !== null ? $pos : count( $this->list() ) );
6✔
2449
                array_splice( $this->list(), $position, 0, $this->array( $value ) );
6✔
2450

2451
                return $this;
6✔
2452
        }
2453

2454

2455
        /**
2456
         * Tests if the passed value or values are part of the strings in the map.
2457
         *
2458
         * Examples:
2459
         *  Map::from( ['abc'] )->inString( 'c' );
2460
         *  Map::from( ['abc'] )->inString( 'bc' );
2461
         *  Map::from( [12345] )->inString( '23' );
2462
         *  Map::from( [123.4] )->inString( 23.4 );
2463
         *  Map::from( [12345] )->inString( false );
2464
         *  Map::from( [12345] )->inString( true );
2465
         *  Map::from( [false] )->inString( false );
2466
         *  Map::from( ['abc'] )->inString( '' );
2467
         *  Map::from( [''] )->inString( false );
2468
         *  Map::from( ['abc'] )->inString( 'BC', false );
2469
         *  Map::from( ['abc', 'def'] )->inString( ['de', 'xy'] );
2470
         *  Map::from( ['abc', 'def'] )->inString( ['E', 'x'] );
2471
         *  Map::from( ['abc', 'def'] )->inString( 'E' );
2472
         *  Map::from( [23456] )->inString( true );
2473
         *  Map::from( [false] )->inString( 0 );
2474
         *
2475
         * Results:
2476
         * The first eleven examples will return TRUE while the last four will return FALSE
2477
         *
2478
         * All scalar values (bool, float, int and string) are casted to string values before
2479
         * comparing to the given value. Non-scalar values in the map are ignored.
2480
         *
2481
         * @param array|string $value Value or values to compare the map elements, will be casted to string type
2482
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
2483
         * @return bool TRUE If at least one element matches, FALSE if value is not in any string of the map
2484
         * @deprecated Use multi-byte aware strContains() instead
2485
         */
2486
        public function inString( $value, bool $case = true ) : bool
2487
        {
2488
                $fcn = $case ? 'strpos' : 'stripos';
2✔
2489

2490
                foreach( (array) $value as $val )
2✔
2491
                {
2492
                        if( (string) $val === '' ) {
2✔
2493
                                return true;
2✔
2494
                        }
2495

2496
                        foreach( $this->list() as $item )
2✔
2497
                        {
2498
                                if( is_scalar( $item ) && $fcn( (string) $item, (string) $val ) !== false ) {
2✔
2499
                                        return true;
2✔
2500
                                }
2501
                        }
2502
                }
2503

2504
                return false;
2✔
2505
        }
2506

2507

2508
        /**
2509
         * Returns an element by key and casts it to integer if possible.
2510
         *
2511
         * Examples:
2512
         *  Map::from( ['a' => true] )->int( 'a' );
2513
         *  Map::from( ['a' => '1'] )->int( 'a' );
2514
         *  Map::from( ['a' => 1.1] )->int( 'a' );
2515
         *  Map::from( ['a' => '10'] )->int( 'a' );
2516
         *  Map::from( ['a' => ['b' => ['c' => 1]]] )->int( 'a/b/c' );
2517
         *  Map::from( [] )->int( 'c', function() { return rand( 1, 1 ); } );
2518
         *  Map::from( [] )->int( 'a', 1 );
2519
         *
2520
         *  Map::from( [] )->int( 'b' );
2521
         *  Map::from( ['b' => ''] )->int( 'b' );
2522
         *  Map::from( ['b' => 'abc'] )->int( 'b' );
2523
         *  Map::from( ['b' => null] )->int( 'b' );
2524
         *  Map::from( ['b' => [1]] )->int( 'b' );
2525
         *  Map::from( ['b' => #resource] )->int( 'b' );
2526
         *  Map::from( ['b' => new \stdClass] )->int( 'b' );
2527
         *
2528
         *  Map::from( [] )->int( 'c', new \Exception( 'error' ) );
2529
         *
2530
         * Results:
2531
         * The first seven examples will return 1 while the 8th to 14th example
2532
         * returns 0. The last example will throw an exception.
2533
         *
2534
         * This does also work for multi-dimensional arrays by passing the keys
2535
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
2536
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
2537
         * public properties of objects or objects implementing __isset() and __get() methods.
2538
         *
2539
         * @param int|string $key Key or path to the requested item
2540
         * @param mixed $default Default value if key isn't found (will be casted to integer)
2541
         * @return int Value from map or default value
2542
         */
2543
        public function int( $key, $default = 0 ) : int
2544
        {
2545
                return (int) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
6✔
2546
        }
2547

2548

2549
        /**
2550
         * Returns all values in a new map that are available in both, the map and the given elements.
2551
         *
2552
         * Examples:
2553
         *  Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersect( ['bar'] );
2554
         *
2555
         * Results:
2556
         *  ['b' => 'bar']
2557
         *
2558
         * If a callback is passed, the given function will be used to compare the values.
2559
         * The function must accept two parameters (value A and B) and must return
2560
         * -1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
2561
         * greater than value B. Both, a method name and an anonymous function can be passed:
2562
         *
2563
         *  Map::from( [0 => 'a'] )->intersect( [0 => 'A'], 'strcasecmp' );
2564
         *  Map::from( ['b' => 'a'] )->intersect( ['B' => 'A'], 'strcasecmp' );
2565
         *  Map::from( ['b' => 'a'] )->intersect( ['c' => 'A'], function( $valA, $valB ) {
2566
         *      return strtolower( $valA ) <=> strtolower( $valB );
2567
         *  } );
2568
         *
2569
         * All examples will return a map containing ['a'] because both contain the same
2570
         * values when compared case insensitive.
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 (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
2576
         * @return self<int|string,mixed> New map
2577
         */
2578
        public function intersect( iterable $elements, ?callable $callback = null ) : self
2579
        {
2580
                $list = $this->list();
4✔
2581
                $elements = $this->array( $elements );
4✔
2582

2583
                if( $callback ) {
4✔
2584
                        return new static( array_uintersect( $list, $elements, $callback ) );
2✔
2585
                }
2586

2587
                return new static( array_intersect( $list, $elements ) );
2✔
2588
        }
2589

2590

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

2625
                if( $callback ) {
10✔
2626
                        return new static( array_uintersect_assoc( $this->list(), $elements, $callback ) );
2✔
2627
                }
2628

2629
                return new static( array_intersect_assoc( $this->list(), $elements ) );
8✔
2630
        }
2631

2632

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

2668
                if( $callback ) {
6✔
2669
                        return new static( array_intersect_ukey( $this->list(), $elements, $callback ) );
2✔
2670
                }
2671

2672
                return new static( array_intersect_key( $this->list(), $elements ) );
4✔
2673
        }
2674

2675

2676
        /**
2677
         * Tests if the map consists of the same keys and values
2678
         *
2679
         * Examples:
2680
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'] );
2681
         *  Map::from( ['a', 'b'] )->is( ['b', 'a'], true );
2682
         *  Map::from( [1, 2] )->is( ['1', '2'] );
2683
         *
2684
         * Results:
2685
         *  The first example returns TRUE while the second and third one returns FALSE
2686
         *
2687
         * @param iterable<int|string,mixed> $list List of key/value pairs to compare with
2688
         * @param bool $strict TRUE for comparing order of elements too, FALSE for key/values only
2689
         * @return bool TRUE if given list is equal, FALSE if not
2690
         */
2691
        public function is( iterable $list, bool $strict = false ) : bool
2692
        {
2693
                $list = $this->array( $list );
6✔
2694

2695
                if( $strict ) {
6✔
2696
                        return $this->list() === $list;
4✔
2697
                }
2698

2699
                return $this->list() == $list;
2✔
2700
        }
2701

2702

2703
        /**
2704
         * Determines if the map is empty or not.
2705
         *
2706
         * Examples:
2707
         *  Map::from( [] )->isEmpty();
2708
         *  Map::from( ['a'] )->isEmpty();
2709
         *
2710
         * Results:
2711
         *  The first example returns TRUE while the second returns FALSE
2712
         *
2713
         * The method is equivalent to empty().
2714
         *
2715
         * @return bool TRUE if map is empty, FALSE if not
2716
         */
2717
        public function isEmpty() : bool
2718
        {
2719
                return empty( $this->list() );
8✔
2720
        }
2721

2722

2723
        /**
2724
         * Checks if the map contains a list of subsequentially numbered keys.
2725
         *
2726
         * Examples:
2727
         * Map::from( [] )->isList();
2728
         * Map::from( [1, 3, 2] )->isList();
2729
         * Map::from( [0 => 1, 1 => 2, 2 => 3] )->isList();
2730
         * Map::from( [1 => 1, 2 => 2, 3 => 3] )->isList();
2731
         * Map::from( [0 => 1, 2 => 2, 3 => 3] )->isList();
2732
         * Map::from( ['a' => 1, 1 => 2, 'c' => 3] )->isList();
2733
         *
2734
         * Results:
2735
         * The first three examples return TRUE while the last three return FALSE
2736
         *
2737
         * @return bool TRUE if the map is a list, FALSE if not
2738
         */
2739
        public function isList() : bool
2740
        {
2741
                $i = -1;
2✔
2742

2743
                foreach( $this->list() as $k => $v )
2✔
2744
                {
2745
                        if( $k !== ++$i ) {
2✔
2746
                                return false;
2✔
2747
                        }
2748
                }
2749

2750
                return true;
2✔
2751
        }
2752

2753

2754
        /**
2755
         * Determines if all entries are numeric values.
2756
         *
2757
         * Examples:
2758
         *  Map::from( [] )->isNumeric();
2759
         *  Map::from( [1] )->isNumeric();
2760
         *  Map::from( [1.1] )->isNumeric();
2761
         *  Map::from( [010] )->isNumeric();
2762
         *  Map::from( [0x10] )->isNumeric();
2763
         *  Map::from( [0b10] )->isNumeric();
2764
         *  Map::from( ['010'] )->isNumeric();
2765
         *  Map::from( ['10'] )->isNumeric();
2766
         *  Map::from( ['10.1'] )->isNumeric();
2767
         *  Map::from( [' 10 '] )->isNumeric();
2768
         *  Map::from( ['10e2'] )->isNumeric();
2769
         *  Map::from( ['0b10'] )->isNumeric();
2770
         *  Map::from( ['0x10'] )->isNumeric();
2771
         *  Map::from( ['null'] )->isNumeric();
2772
         *  Map::from( [null] )->isNumeric();
2773
         *  Map::from( [true] )->isNumeric();
2774
         *  Map::from( [[]] )->isNumeric();
2775
         *  Map::from( [''] )->isNumeric();
2776
         *
2777
         * Results:
2778
         *  The first eleven examples return TRUE while the last seven return FALSE
2779
         *
2780
         * @return bool TRUE if all map entries are numeric values, FALSE if not
2781
         */
2782
        public function isNumeric() : bool
2783
        {
2784
                foreach( $this->list() as $val )
2✔
2785
                {
2786
                        if( !is_numeric( $val ) ) {
2✔
2787
                                return false;
2✔
2788
                        }
2789
                }
2790

2791
                return true;
2✔
2792
        }
2793

2794

2795
        /**
2796
         * Determines if all entries are objects.
2797
         *
2798
         * Examples:
2799
         *  Map::from( [] )->isObject();
2800
         *  Map::from( [new stdClass] )->isObject();
2801
         *  Map::from( [1] )->isObject();
2802
         *
2803
         * Results:
2804
         *  The first two examples return TRUE while the last one return FALSE
2805
         *
2806
         * @return bool TRUE if all map entries are objects, FALSE if not
2807
         */
2808
        public function isObject() : bool
2809
        {
2810
                foreach( $this->list() as $val )
2✔
2811
                {
2812
                        if( !is_object( $val ) ) {
2✔
2813
                                return false;
2✔
2814
                        }
2815
                }
2816

2817
                return true;
2✔
2818
        }
2819

2820

2821
        /**
2822
         * Determines if all entries are scalar values.
2823
         *
2824
         * Examples:
2825
         *  Map::from( [] )->isScalar();
2826
         *  Map::from( [1] )->isScalar();
2827
         *  Map::from( [1.1] )->isScalar();
2828
         *  Map::from( ['abc'] )->isScalar();
2829
         *  Map::from( [true, false] )->isScalar();
2830
         *  Map::from( [new stdClass] )->isScalar();
2831
         *  Map::from( [#resource] )->isScalar();
2832
         *  Map::from( [null] )->isScalar();
2833
         *  Map::from( [[1]] )->isScalar();
2834
         *
2835
         * Results:
2836
         *  The first five examples return TRUE while the others return FALSE
2837
         *
2838
         * @return bool TRUE if all map entries are scalar values, FALSE if not
2839
         */
2840
        public function isScalar() : bool
2841
        {
2842
                foreach( $this->list() as $val )
2✔
2843
                {
2844
                        if( !is_scalar( $val ) ) {
2✔
2845
                                return false;
2✔
2846
                        }
2847
                }
2848

2849
                return true;
2✔
2850
        }
2851

2852

2853
        /**
2854
         * Determines if all entries are string values.
2855
         *
2856
         * Examples:
2857
         *  Map::from( ['abc'] )->isString();
2858
         *  Map::from( [] )->isString();
2859
         *  Map::from( [1] )->isString();
2860
         *  Map::from( [1.1] )->isString();
2861
         *  Map::from( [true, false] )->isString();
2862
         *  Map::from( [new stdClass] )->isString();
2863
         *  Map::from( [#resource] )->isString();
2864
         *  Map::from( [null] )->isString();
2865
         *  Map::from( [[1]] )->isString();
2866
         *
2867
         * Results:
2868
         *  The first two examples return TRUE while the others return FALSE
2869
         *
2870
         * @return bool TRUE if all map entries are string values, FALSE if not
2871
         */
2872
        public function isString() : bool
2873
        {
2874
                foreach( $this->list() as $val )
2✔
2875
                {
2876
                        if( !is_string( $val ) ) {
2✔
2877
                                return false;
2✔
2878
                        }
2879
                }
2880

2881
                return true;
2✔
2882
        }
2883

2884

2885
        /**
2886
         * Concatenates the string representation of all elements.
2887
         *
2888
         * Objects that implement __toString() does also work, otherwise (and in case
2889
         * of arrays) a PHP notice is generated. NULL and FALSE values are treated as
2890
         * empty strings.
2891
         *
2892
         * Examples:
2893
         *  Map::from( ['a', 'b', false] )->join();
2894
         *  Map::from( ['a', 'b', null, false] )->join( '-' );
2895
         *
2896
         * Results:
2897
         * The first example will return "ab" while the second one will return "a-b--"
2898
         *
2899
         * @param string $glue Character or string added between elements
2900
         * @return string String of concatenated map elements
2901
         */
2902
        public function join( string $glue = '' ) : string
2903
        {
2904
                return implode( $glue, $this->list() );
2✔
2905
        }
2906

2907

2908
        /**
2909
         * Specifies the data which should be serialized to JSON by json_encode().
2910
         *
2911
         * Examples:
2912
         *   json_encode( Map::from( ['a', 'b'] ) );
2913
         *   json_encode( Map::from( ['a' => 0, 'b' => 1] ) );
2914
         *
2915
         * Results:
2916
         *   ["a", "b"]
2917
         *   {"a":0,"b":1}
2918
         *
2919
         * @return array<int|string,mixed> Data to serialize to JSON
2920
         */
2921
        #[\ReturnTypeWillChange]
2922
        public function jsonSerialize()
2923
        {
2924
                return $this->list = $this->array( $this->list );
2✔
2925
        }
2926

2927

2928
        /**
2929
         * Returns the keys of the all elements in a new map object.
2930
         *
2931
         * Examples:
2932
         *  Map::from( ['a', 'b'] );
2933
         *  Map::from( ['a' => 0, 'b' => 1] );
2934
         *
2935
         * Results:
2936
         * The first example returns a map containing [0, 1] while the second one will
2937
         * return a map with ['a', 'b'].
2938
         *
2939
         * @return self<int|string,mixed> New map
2940
         */
2941
        public function keys() : self
2942
        {
2943
                return new static( array_keys( $this->list() ) );
2✔
2944
        }
2945

2946

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

2977

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

3007

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

3038

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

3068

3069
        /**
3070
         * Returns the last element from the map.
3071
         *
3072
         * Examples:
3073
         *  Map::from( ['a', 'b'] )->last();
3074
         *  Map::from( [] )->last( 'x' );
3075
         *  Map::from( [] )->last( new \Exception( 'error' ) );
3076
         *  Map::from( [] )->last( function() { return rand(); } );
3077
         *
3078
         * Results:
3079
         * The first example will return 'b' and the second one 'x'. The third example
3080
         * will throw the exception passed if the map contains no elements. In the
3081
         * fourth example, a random value generated by the closure function will be
3082
         * returned.
3083
         *
3084
         * Using this method doesn't affect the internal array pointer.
3085
         *
3086
         * @param mixed $default Default value or exception if the map contains no elements
3087
         * @return mixed Last value of map, (generated) default value or an exception
3088
         */
3089
        public function last( $default = null )
3090
        {
3091
                if( !empty( $this->list() ) ) {
12✔
3092
                        return current( array_slice( $this->list(), -1, 1 ) );
4✔
3093
                }
3094

3095
                if( $default instanceof \Closure ) {
8✔
3096
                        return $default();
2✔
3097
                }
3098

3099
                if( $default instanceof \Throwable ) {
6✔
3100
                        throw $default;
2✔
3101
                }
3102

3103
                return $default;
4✔
3104
        }
3105

3106

3107
        /**
3108
         * Returns the last key from the map.
3109
         *
3110
         * Examples:
3111
         *  Map::from( ['a' => 1, 'b' => 2] )->lastKey();
3112
         *  Map::from( [] )->lastKey( 'x' );
3113
         *  Map::from( [] )->lastKey( new \Exception( 'error' ) );
3114
         *  Map::from( [] )->lastKey( function() { return rand(); } );
3115
         *
3116
         * Results:
3117
         * The first example will return 'a' and the second one 'x', the third one will throw
3118
         * an exception and the last one will return a random value.
3119
         *
3120
         * Using this method doesn't affect the internal array pointer.
3121
         *
3122
         * @param mixed $default Default value, closure or exception if the map contains no elements
3123
         * @return mixed Last key of map, (generated) default value or an exception
3124
         */
3125
        public function lastKey( $default = null )
3126
        {
3127
                $list = $this->list();
10✔
3128

3129
                // PHP 7.x compatibility
3130
                if( function_exists( 'array_key_last' ) ) {
10✔
3131
                        $key = array_key_last( $list );
10✔
3132
                } else {
UNCOV
3133
                        $key = key( array_slice( $list, -1, 1, true ) );
×
3134
                }
3135

3136
                if( $key !== null ) {
10✔
3137
                        return $key;
2✔
3138
                }
3139

3140
                if( $default instanceof \Closure ) {
8✔
3141
                        return $default();
2✔
3142
                }
3143

3144
                if( $default instanceof \Throwable ) {
6✔
3145
                        throw $default;
2✔
3146
                }
3147

3148
                return $default;
4✔
3149
        }
3150

3151

3152
        /**
3153
         * Removes the passed characters from the left of all strings.
3154
         *
3155
         * Examples:
3156
         *  Map::from( [" abc\n", "\tcde\r\n"] )->ltrim();
3157
         *  Map::from( ["a b c", "cbxa"] )->ltrim( 'abc' );
3158
         *
3159
         * Results:
3160
         * The first example will return ["abc\n", "cde\r\n"] while the second one will return [" b c", "xa"].
3161
         *
3162
         * @param string $chars List of characters to trim
3163
         * @return self<int|string,mixed> Updated map for fluid interface
3164
         */
3165
        public function ltrim( string $chars = " \n\r\t\v\x00" ) : self
3166
        {
3167
                foreach( $this->list() as &$entry )
2✔
3168
                {
3169
                        if( is_string( $entry ) ) {
2✔
3170
                                $entry = ltrim( $entry, $chars );
2✔
3171
                        }
3172
                }
3173

3174
                return $this;
2✔
3175
        }
3176

3177

3178
        /**
3179
         * Maps new values to the existing keys using the passed function and returns a new map for the result.
3180
         *
3181
         * Examples:
3182
         *  Map::from( ['a' => 2, 'b' => 4] )->map( function( $value, $key ) {
3183
         *      return $value * 2;
3184
         *  } );
3185
         *
3186
         * Results:
3187
         *  ['a' => 4, 'b' => 8]
3188
         *
3189
         * The keys are preserved using this method.
3190
         *
3191
         * @param callable $callback Function with (value, key) parameters and returns computed result
3192
         * @return self<int|string,mixed> New map with the original keys and the computed values
3193
         * @see rekey() - Changes the keys according to the passed function
3194
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
3195
         */
3196
        public function map( callable $callback ) : self
3197
        {
3198
                $list = $this->list();
2✔
3199
                $keys = array_keys( $list );
2✔
3200
                $map = array_map( $callback, array_values( $list ), $keys );
2✔
3201

3202
                return new static( array_combine( $keys, $map ) );
2✔
3203
        }
3204

3205

3206
        /**
3207
         * Returns the maximum value of all elements.
3208
         *
3209
         * Examples:
3210
         *  Map::from( [1, 3, 2, 5, 4] )->max()
3211
         *  Map::from( ['bar', 'foo', 'baz'] )->max()
3212
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->max( 'p' )
3213
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( 'i/p' )
3214
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->max( fn( $val, $key ) => $val['i']['p'] ?? null )
3215
         *  Map::from( [50, 10, 30] )->max( fn( $val, $key ) => $key > 0 ? $val : null )
3216
         *
3217
         * Results:
3218
         * The first line will return "5", the second one "foo" and the third to fitfh
3219
         * one return 50 while the last one will return 30.
3220
         *
3221
         * NULL values are removed before the comparison. If there are no values or all
3222
         * values are NULL, NULL is returned.
3223
         *
3224
         * This does also work for multi-dimensional arrays by passing the keys
3225
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
3226
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
3227
         * public properties of objects or objects implementing __isset() and __get() methods.
3228
         *
3229
         * Be careful comparing elements of different types because this can have
3230
         * unpredictable results due to the PHP comparison rules:
3231
         * {@link https://www.php.net/manual/en/language.operators.comparison.php}
3232
         *
3233
         * @param Closure|string|null $col Closure, key or path to the value of the nested array or object
3234
         * @return mixed Maximum value or NULL if there are no elements in the map
3235
         */
3236
        public function max( $col = null )
3237
        {
3238
                $list = $this->list();
8✔
3239
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list );
8✔
3240

3241
                return !empty( $vals ) ? max( $vals ) : null;
8✔
3242
        }
3243

3244

3245
        /**
3246
         * Merges the map with the given elements without returning a new map.
3247
         *
3248
         * Elements with the same non-numeric keys will be overwritten, elements
3249
         * with the same numeric keys will be added.
3250
         *
3251
         * Examples:
3252
         *  Map::from( ['a', 'b'] )->merge( ['b', 'c'] );
3253
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6] );
3254
         *  Map::from( ['a' => 1, 'b' => 2] )->merge( ['b' => 4, 'c' => 6], true );
3255
         *
3256
         * Results:
3257
         *  ['a', 'b', 'b', 'c']
3258
         *  ['a' => 1, 'b' => 4, 'c' => 6]
3259
         *  ['a' => 1, 'b' => [2, 4], 'c' => 6]
3260
         *
3261
         * The method is similar to replace() but doesn't replace elements with
3262
         * the same numeric keys. If you want to be sure that all passed elements
3263
         * are added without replacing existing ones, use concat() instead.
3264
         *
3265
         * The keys are preserved using this method.
3266
         *
3267
         * @param iterable<int|string,mixed> $elements List of elements
3268
         * @param bool $recursive TRUE to merge nested arrays too, FALSE for first level elements only
3269
         * @return self<int|string,mixed> Updated map for fluid interface
3270
         */
3271
        public function merge( iterable $elements, bool $recursive = false ) : self
3272
        {
3273
                if( $recursive ) {
6✔
3274
                        $this->list = array_merge_recursive( $this->list(), $this->array( $elements ) );
2✔
3275
                } else {
3276
                        $this->list = array_merge( $this->list(), $this->array( $elements ) );
4✔
3277
                }
3278

3279
                return $this;
6✔
3280
        }
3281

3282

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

3318
                return !empty( $vals ) ? min( $vals ) : null;
8✔
3319
        }
3320

3321

3322
        /**
3323
         * Tests if none of the elements are part of the map.
3324
         *
3325
         * Examples:
3326
         *  Map::from( ['a', 'b'] )->none( 'x' );
3327
         *  Map::from( ['a', 'b'] )->none( ['x', 'y'] );
3328
         *  Map::from( ['1', '2'] )->none( 2, true );
3329
         *  Map::from( ['a', 'b'] )->none( 'a' );
3330
         *  Map::from( ['a', 'b'] )->none( ['a', 'b'] );
3331
         *  Map::from( ['a', 'b'] )->none( ['a', 'x'] );
3332
         *
3333
         * Results:
3334
         * The first three examples will return TRUE while the other ones will return FALSE
3335
         *
3336
         * @param mixed|array $element Element or elements to search for in the map
3337
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
3338
         * @return bool TRUE if none of the elements is part of the map, FALSE if at least one is
3339
         */
3340
        public function none( $element, bool $strict = false ) : bool
3341
        {
3342
                $list = $this->list();
2✔
3343

3344
                if( !is_array( $element ) ) {
2✔
3345
                        return !in_array( $element, $list, $strict );
2✔
3346
                };
3347

3348
                foreach( $element as $entry )
2✔
3349
                {
3350
                        if( in_array( $entry, $list, $strict ) === true ) {
2✔
3351
                                return false;
2✔
3352
                        }
3353
                }
3354

3355
                return true;
2✔
3356
        }
3357

3358

3359
        /**
3360
         * Returns every nth element from the map.
3361
         *
3362
         * Examples:
3363
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2 );
3364
         *  Map::from( ['a', 'b', 'c', 'd', 'e', 'f'] )->nth( 2, 1 );
3365
         *
3366
         * Results:
3367
         *  ['a', 'c', 'e']
3368
         *  ['b', 'd', 'f']
3369
         *
3370
         * @param int $step Step width
3371
         * @param int $offset Number of element to start from (0-based)
3372
         * @return self<int|string,mixed> New map
3373
         */
3374
        public function nth( int $step, int $offset = 0 ) : self
3375
        {
3376
                if( $step < 1 ) {
6✔
3377
                        throw new \InvalidArgumentException( 'Step width must be greater than zero' );
2✔
3378
                }
3379

3380
                if( $step === 1 ) {
4✔
3381
                        return clone $this;
2✔
3382
                }
3383

3384
                $result = [];
2✔
3385
                $list = $this->list();
2✔
3386

3387
                while( !empty( $pair = array_slice( $list, $offset, 1, true ) ) )
2✔
3388
                {
3389
                        $result += $pair;
2✔
3390
                        $offset += $step;
2✔
3391
                }
3392

3393
                return new static( $result );
2✔
3394
        }
3395

3396

3397
        /**
3398
         * Determines if an element exists at an offset.
3399
         *
3400
         * Examples:
3401
         *  $map = Map::from( ['a' => 1, 'b' => 3, 'c' => null] );
3402
         *  isset( $map['b'] );
3403
         *  isset( $map['c'] );
3404
         *  isset( $map['d'] );
3405
         *
3406
         * Results:
3407
         *  The first isset() will return TRUE while the second and third one will return FALSE
3408
         *
3409
         * @param int|string $key Key to check for
3410
         * @return bool TRUE if key exists, FALSE if not
3411
         */
3412
        public function offsetExists( $key ) : bool
3413
        {
3414
                return isset( $this->list()[$key] );
14✔
3415
        }
3416

3417

3418
        /**
3419
         * Returns an element at a given offset.
3420
         *
3421
         * Examples:
3422
         *  $map = Map::from( ['a' => 1, 'b' => 3] );
3423
         *  $map['b'];
3424
         *
3425
         * Results:
3426
         *  $map['b'] will return 3
3427
         *
3428
         * @param int|string $key Key to return the element for
3429
         * @return mixed Value associated to the given key
3430
         */
3431
        #[\ReturnTypeWillChange]
3432
        public function offsetGet( $key )
3433
        {
3434
                return $this->list()[$key] ?? null;
10✔
3435
        }
3436

3437

3438
        /**
3439
         * Sets the element at a given offset.
3440
         *
3441
         * Examples:
3442
         *  $map = Map::from( ['a' => 1] );
3443
         *  $map['b'] = 2;
3444
         *  $map[0] = 4;
3445
         *
3446
         * Results:
3447
         *  ['a' => 1, 'b' => 2, 0 => 4]
3448
         *
3449
         * @param int|string|null $key Key to set the element for or NULL to append value
3450
         * @param mixed $value New value set for the key
3451
         */
3452
        public function offsetSet( $key, $value ) : void
3453
        {
3454
                if( $key !== null ) {
6✔
3455
                        $this->list()[$key] = $value;
4✔
3456
                } else {
3457
                        $this->list()[] = $value;
4✔
3458
                }
3459
        }
3460

3461

3462
        /**
3463
         * Unsets the element at a given offset.
3464
         *
3465
         * Examples:
3466
         *  $map = Map::from( ['a' => 1] );
3467
         *  unset( $map['a'] );
3468
         *
3469
         * Results:
3470
         *  The map will be empty
3471
         *
3472
         * @param int|string $key Key for unsetting the item
3473
         */
3474
        public function offsetUnset( $key ) : void
3475
        {
3476
                unset( $this->list()[$key] );
4✔
3477
        }
3478

3479

3480
        /**
3481
         * Returns a new map with only those elements specified by the given keys.
3482
         *
3483
         * Examples:
3484
         *  Map::from( ['a' => 1, 0 => 'b'] )->only( 'a' );
3485
         *  Map::from( ['a' => 1, 0 => 'b', 1 => 'c'] )->only( [0, 1] );
3486
         *
3487
         * Results:
3488
         *  ['a' => 1]
3489
         *  [0 => 'b', 1 => 'c']
3490
         *
3491
         * The keys are preserved using this method.
3492
         *
3493
         * @param iterable<mixed>|array<mixed>|string|int $keys Keys of the elements that should be returned
3494
         * @return self<int|string,mixed> New map with only the elements specified by the keys
3495
         */
3496
        public function only( $keys ) : self
3497
        {
3498
                return $this->intersectKeys( array_flip( $this->array( $keys ) ) );
2✔
3499
        }
3500

3501

3502
        /**
3503
         * Returns a new map with elements ordered by the passed keys.
3504
         *
3505
         * If there are less keys passed than available in the map, the remaining
3506
         * elements are removed. Otherwise, if keys are passed that are not in the
3507
         * map, they will be also available in the returned map but their value is
3508
         * NULL.
3509
         *
3510
         * Examples:
3511
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 'a'] );
3512
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 2] );
3513
         *  Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1] );
3514
         *
3515
         * Results:
3516
         *  [0 => 'b', 1 => 'c', 'a' => 1]
3517
         *  [0 => 'b', 1 => 'c', 2 => null]
3518
         *  [0 => 'b', 1 => 'c']
3519
         *
3520
         * The keys are preserved using this method.
3521
         *
3522
         * @param iterable<mixed> $keys Keys of the elements in the required order
3523
         * @return self<int|string,mixed> New map with elements ordered by the passed keys
3524
         */
3525
        public function order( iterable $keys ) : self
3526
        {
3527
                $result = [];
2✔
3528
                $list = $this->list();
2✔
3529

3530
                foreach( $keys as $key ) {
2✔
3531
                        $result[$key] = $list[$key] ?? null;
2✔
3532
                }
3533

3534
                return new static( $result );
2✔
3535
        }
3536

3537

3538
        /**
3539
         * Fill up to the specified length with the given value
3540
         *
3541
         * In case the given number is smaller than the number of element that are
3542
         * already in the list, the map is unchanged. If the size is positive, the
3543
         * new elements are padded on the right, if it's negative then the elements
3544
         * are padded on the left.
3545
         *
3546
         * Examples:
3547
         *  Map::from( [1, 2, 3] )->pad( 5 );
3548
         *  Map::from( [1, 2, 3] )->pad( -5 );
3549
         *  Map::from( [1, 2, 3] )->pad( 5, '0' );
3550
         *  Map::from( [1, 2, 3] )->pad( 2 );
3551
         *  Map::from( [10 => 1, 20 => 2] )->pad( 3 );
3552
         *  Map::from( ['a' => 1, 'b' => 2] )->pad( 3, 3 );
3553
         *
3554
         * Results:
3555
         *  [1, 2, 3, null, null]
3556
         *  [null, null, 1, 2, 3]
3557
         *  [1, 2, 3, '0', '0']
3558
         *  [1, 2, 3]
3559
         *  [0 => 1, 1 => 2, 2 => null]
3560
         *  ['a' => 1, 'b' => 2, 0 => 3]
3561
         *
3562
         * Associative keys are preserved, numerical keys are replaced and numerical
3563
         * keys are used for the new elements.
3564
         *
3565
         * @param int $size Total number of elements that should be in the list
3566
         * @param mixed $value Value to fill up with if the map length is smaller than the given size
3567
         * @return self<int|string,mixed> New map
3568
         */
3569
        public function pad( int $size, $value = null ) : self
3570
        {
3571
                return new static( array_pad( $this->list(), $size, $value ) );
2✔
3572
        }
3573

3574

3575
        /**
3576
         * Breaks the list of elements into the given number of groups.
3577
         *
3578
         * Examples:
3579
         *  Map::from( [1, 2, 3, 4, 5] )->partition( 3 );
3580
         *  Map::from( [1, 2, 3, 4, 5] )->partition( function( $val, $idx ) {
3581
         *                return $idx % 3;
3582
         *        } );
3583
         *
3584
         * Results:
3585
         *  [[0 => 1, 1 => 2], [2 => 3, 3 => 4], [4 => 5]]
3586
         *  [0 => [0 => 1, 3 => 4], 1 => [1 => 2, 4 => 5], 2 => [2 => 3]]
3587
         *
3588
         * The keys of the original map are preserved in the returned map.
3589
         *
3590
         * @param \Closure|int $number Function with (value, index) as arguments returning the bucket key or number of groups
3591
         * @return self<int|string,mixed> New map
3592
         */
3593
        public function partition( $number ) : self
3594
        {
3595
                $list = $this->list();
8✔
3596

3597
                if( empty( $list ) ) {
8✔
3598
                        return new static();
2✔
3599
                }
3600

3601
                $result = [];
6✔
3602

3603
                if( $number instanceof \Closure )
6✔
3604
                {
3605
                        foreach( $list as $idx => $item ) {
2✔
3606
                                $result[$number( $item, $idx )][$idx] = $item;
2✔
3607
                        }
3608

3609
                        return new static( $result );
2✔
3610
                }
3611

3612
                if( is_int( $number ) )
4✔
3613
                {
3614
                        $start = 0;
2✔
3615
                        $size = (int) ceil( count( $list ) / $number );
2✔
3616

3617
                        for( $i = 0; $i < $number; $i++ )
2✔
3618
                        {
3619
                                $result[] = array_slice( $list, $start, $size, true );
2✔
3620
                                $start += $size;
2✔
3621
                        }
3622

3623
                        return new static( $result );
2✔
3624
                }
3625

3626
                throw new \InvalidArgumentException( 'Parameter is no closure or integer' );
2✔
3627
        }
3628

3629

3630
        /**
3631
         * Returns the percentage of all elements passing the test in the map.
3632
         *
3633
         * Examples:
3634
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50 );
3635
         *  Map::from( [] )->percentage( fn( $val, $key ) => true );
3636
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 100 );
3637
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 3 );
3638
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val > 30, 0 );
3639
         *  Map::from( [30, 50, 10] )->percentage( fn( $val, $key ) => $val < 50, -1 );
3640
         *
3641
         * Results:
3642
         * The first line will return "66.67", the second and third one "0.0", the forth
3643
         * one "33.333", the fifth one "33.0" and the last one "70.0" (66 rounded up).
3644
         *
3645
         * @param Closure $fcn Closure to filter the values in the nested array or object to compute the percentage
3646
         * @param int $precision Number of decimal digits use by the result value
3647
         * @return float Percentage of all elements passing the test in the map
3648
         */
3649
        public function percentage( \Closure $fcn, int $precision = 2 ) : float
3650
        {
3651
                $vals = array_filter( $this->list(), $fcn, ARRAY_FILTER_USE_BOTH );
2✔
3652

3653
                $cnt = count( $this->list() );
2✔
3654
                return $cnt > 0 ? round( count( $vals ) * 100 / $cnt, $precision ) : 0;
2✔
3655
        }
3656

3657

3658
        /**
3659
         * Passes the map to the given callback and return the result.
3660
         *
3661
         * Examples:
3662
         *  Map::from( ['a', 'b'] )->pipe( function( $map ) {
3663
         *      return join( '-', $map->toArray() );
3664
         *  } );
3665
         *
3666
         * Results:
3667
         *  "a-b" will be returned
3668
         *
3669
         * @param \Closure $callback Function with map as parameter which returns arbitrary result
3670
         * @return mixed Result returned by the callback
3671
         */
3672
        public function pipe( \Closure $callback )
3673
        {
3674
                return $callback( $this );
2✔
3675
        }
3676

3677

3678
        /**
3679
         * Returns the values of a single column/property from an array of arrays or objects in a new map.
3680
         *
3681
         * This method is an alias for col(). For performance reasons, col() should
3682
         * be preferred because it uses one method call less than pluck().
3683
         *
3684
         * @param string|null $valuecol Name or path of the value property
3685
         * @param string|null $indexcol Name or path of the index property
3686
         * @return self<int|string,mixed> New map with mapped entries
3687
         * @see col() - Underlying method with same parameters and return value but better performance
3688
         */
3689
        public function pluck( ?string $valuecol = null, ?string $indexcol = null ) : self
3690
        {
3691
                return $this->col( $valuecol, $indexcol );
2✔
3692
        }
3693

3694

3695
        /**
3696
         * Returns and removes the last element from the map.
3697
         *
3698
         * Examples:
3699
         *  Map::from( ['a', 'b'] )->pop();
3700
         *
3701
         * Results:
3702
         *  "b" will be returned and the map only contains ['a'] afterwards
3703
         *
3704
         * @return mixed Last element of the map or null if empty
3705
         */
3706
        public function pop()
3707
        {
3708
                return array_pop( $this->list() );
4✔
3709
        }
3710

3711

3712
        /**
3713
         * Returns the numerical index of the value.
3714
         *
3715
         * Examples:
3716
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( 'b' );
3717
         *  Map::from( [4 => 'a', 8 => 'b'] )->pos( function( $item, $key ) {
3718
         *      return $item === 'b';
3719
         *  } );
3720
         *
3721
         * Results:
3722
         * Both examples will return "1" because the value "b" is at the second position
3723
         * and the returned index is zero based so the first item has the index "0".
3724
         *
3725
         * @param \Closure|mixed $value Value to search for or function with (item, key) parameters return TRUE if value is found
3726
         * @return int|null Position of the found value (zero based) or NULL if not found
3727
         */
3728
        public function pos( $value ) : ?int
3729
        {
3730
                $pos = 0;
30✔
3731
                $list = $this->list();
30✔
3732

3733
                if( $value instanceof \Closure )
30✔
3734
                {
3735
                        foreach( $list as $key => $item )
6✔
3736
                        {
3737
                                if( $value( $item, $key ) ) {
6✔
3738
                                        return $pos;
6✔
3739
                                }
3740

3741
                                ++$pos;
6✔
3742
                        }
3743

UNCOV
3744
                        return null;
×
3745
                }
3746

3747
                if( ( $key = array_search( $value, $list, true ) ) !== false
24✔
3748
                        && ( $pos = array_search( $key, array_keys( $list ), true ) ) !== false
24✔
3749
                ) {
3750
                        return $pos;
20✔
3751
                }
3752

3753
                return null;
4✔
3754
        }
3755

3756

3757
        /**
3758
         * Adds a prefix in front of each map entry.
3759
         *
3760
         * By defaul, nested arrays are walked recusively so all entries at all levels are prefixed.
3761
         *
3762
         * Examples:
3763
         *  Map::from( ['a', 'b'] )->prefix( '1-' );
3764
         *  Map::from( ['a', ['b']] )->prefix( '1-' );
3765
         *  Map::from( ['a', ['b']] )->prefix( '1-', 1 );
3766
         *  Map::from( ['a', 'b'] )->prefix( function( $item, $key ) {
3767
         *      return ( ord( $item ) + ord( $key ) ) . '-';
3768
         *  } );
3769
         *
3770
         * Results:
3771
         *  The first example returns ['1-a', '1-b'] while the second one will return
3772
         *  ['1-a', ['1-b']]. In the third example, the depth is limited to the first
3773
         *  level only so it will return ['1-a', ['b']]. The forth example passing
3774
         *  the closure will return ['145-a', '147-b'].
3775
         *
3776
         * The keys of the original map are preserved in the returned map.
3777
         *
3778
         * @param \Closure|string $prefix Prefix string or anonymous function with ($item, $key) as parameters
3779
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
3780
         * @return self<int|string,mixed> Updated map for fluid interface
3781
         */
3782
        public function prefix( $prefix, ?int $depth = null ) : self
3783
        {
3784
                $fcn = function( array $list, $prefix, int $depth ) use ( &$fcn ) {
2✔
3785

3786
                        foreach( $list as $key => $item )
2✔
3787
                        {
3788
                                if( is_array( $item ) ) {
2✔
3789
                                        $list[$key] = $depth > 1 ? $fcn( $item, $prefix, $depth - 1 ) : $item;
2✔
3790
                                } else {
3791
                                        $list[$key] = ( is_callable( $prefix ) ? $prefix( $item, $key ) : $prefix ) . $item;
2✔
3792
                                }
3793
                        }
3794

3795
                        return $list;
2✔
3796
                };
2✔
3797

3798
                $this->list = $fcn( $this->list(), $prefix, $depth ?? 0x7fffffff );
2✔
3799
                return $this;
2✔
3800
        }
3801

3802

3803
        /**
3804
         * Pushes an element onto the beginning of the map without returning a new map.
3805
         *
3806
         * This method is an alias for unshift().
3807
         *
3808
         * @param mixed $value Item to add at the beginning
3809
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
3810
         * @return self<int|string,mixed> Updated map for fluid interface
3811
         * @see unshift() - Underlying method with same parameters and return value but better performance
3812
         */
3813
        public function prepend( $value, $key = null ) : self
3814
        {
3815
                return $this->unshift( $value, $key );
2✔
3816
        }
3817

3818

3819
        /**
3820
         * Returns and removes an element from the map by its key.
3821
         *
3822
         * Examples:
3823
         *  Map::from( ['a', 'b', 'c'] )->pull( 1 );
3824
         *  Map::from( ['a', 'b', 'c'] )->pull( 'x', 'none' );
3825
         *  Map::from( [] )->pull( 'Y', new \Exception( 'error' ) );
3826
         *  Map::from( [] )->pull( 'Z', function() { return rand(); } );
3827
         *
3828
         * Results:
3829
         * The first example will return "b" and the map contains ['a', 'c'] afterwards.
3830
         * The second one will return "none" and the map content stays untouched. If you
3831
         * pass an exception as default value, it will throw that exception if the map
3832
         * contains no elements. In the fourth example, a random value generated by the
3833
         * closure function will be returned.
3834
         *
3835
         * @param int|string $key Key to retrieve the value for
3836
         * @param mixed $default Default value if key isn't available
3837
         * @return mixed Value from map or default value
3838
         */
3839
        public function pull( $key, $default = null )
3840
        {
3841
                $value = $this->get( $key, $default );
8✔
3842
                unset( $this->list()[$key] );
6✔
3843

3844
                return $value;
6✔
3845
        }
3846

3847

3848
        /**
3849
         * Pushes an element onto the end of the map without returning a new map.
3850
         *
3851
         * Examples:
3852
         *  Map::from( ['a', 'b'] )->push( 'aa' );
3853
         *
3854
         * Results:
3855
         *  ['a', 'b', 'aa']
3856
         *
3857
         * @param mixed $value Value to add to the end
3858
         * @return self<int|string,mixed> Updated map for fluid interface
3859
         */
3860
        public function push( $value ) : self
3861
        {
3862
                $this->list()[] = $value;
6✔
3863
                return $this;
6✔
3864
        }
3865

3866

3867
        /**
3868
         * Sets the given key and value in the map without returning a new map.
3869
         *
3870
         * This method is an alias for set(). For performance reasons, set() should be
3871
         * preferred because it uses one method call less than put().
3872
         *
3873
         * @param int|string $key Key to set the new value for
3874
         * @param mixed $value New element that should be set
3875
         * @return self<int|string,mixed> Updated map for fluid interface
3876
         * @see set() - Underlying method with same parameters and return value but better performance
3877
         */
3878
        public function put( $key, $value ) : self
3879
        {
3880
                return $this->set( $key, $value );
2✔
3881
        }
3882

3883

3884
        /**
3885
         * Returns one or more random element from the map incl. their keys.
3886
         *
3887
         * Examples:
3888
         *  Map::from( [2, 4, 8, 16] )->random();
3889
         *  Map::from( [2, 4, 8, 16] )->random( 2 );
3890
         *  Map::from( [2, 4, 8, 16] )->random( 5 );
3891
         *
3892
         * Results:
3893
         * The first example will return a map including [0 => 8] or any other value,
3894
         * the second one will return a map with [0 => 16, 1 => 2] or any other values
3895
         * and the third example will return a map of the whole list in random order. The
3896
         * less elements are in the map, the less random the order will be, especially if
3897
         * the maximum number of values is high or close to the number of elements.
3898
         *
3899
         * The keys of the original map are preserved in the returned map.
3900
         *
3901
         * @param int $max Maximum number of elements that should be returned
3902
         * @return self<int|string,mixed> New map with key/element pairs from original map in random order
3903
         * @throws \InvalidArgumentException If requested number of elements is less than 1
3904
         */
3905
        public function random( int $max = 1 ) : self
3906
        {
3907
                if( $max < 1 ) {
10✔
3908
                        throw new \InvalidArgumentException( 'Requested number of elements must be greater or equal than 1' );
2✔
3909
                }
3910

3911
                $list = $this->list();
8✔
3912

3913
                if( empty( $list ) ) {
8✔
3914
                        return new static();
2✔
3915
                }
3916

3917
                if( ( $num = count( $list ) ) < $max ) {
6✔
3918
                        $max = $num;
2✔
3919
                }
3920

3921
                $keys = array_rand( $list, $max );
6✔
3922

3923
                return new static( array_intersect_key( $list, array_flip( (array) $keys ) ) );
6✔
3924
        }
3925

3926

3927
        /**
3928
         * Iteratively reduces the array to a single value using a callback function.
3929
         * Afterwards, the map will be empty.
3930
         *
3931
         * Examples:
3932
         *  Map::from( [2, 8] )->reduce( function( $result, $value ) {
3933
         *      return $result += $value;
3934
         *  }, 10 );
3935
         *
3936
         * Results:
3937
         *  "20" will be returned because the sum is computed by 10 (initial value) + 2 + 8
3938
         *
3939
         * @param callable $callback Function with (result, value) parameters and returns result
3940
         * @param mixed $initial Initial value when computing the result
3941
         * @return mixed Value computed by the callback function
3942
         */
3943
        public function reduce( callable $callback, $initial = null )
3944
        {
3945
                return array_reduce( $this->list(), $callback, $initial );
2✔
3946
        }
3947

3948

3949
        /**
3950
         * Removes all matched elements and returns a new map.
3951
         *
3952
         * Examples:
3953
         *  Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->reject( function( $value, $key ) {
3954
         *      return $value < 'm';
3955
         *  } );
3956
         *  Map::from( [2 => 'a', 13 => 'm', 30 => 'z'] )->reject( 'm' );
3957
         *  Map::from( [2 => 'a', 6 => null, 13 => 'm'] )->reject();
3958
         *
3959
         * Results:
3960
         *  [13 => 'm', 30 => 'z']
3961
         *  [2 => 'a', 30 => 'z']
3962
         *  [6 => null]
3963
         *
3964
         * This method is the inverse of the filter() and should return TRUE if the
3965
         * item should be removed from the returned map.
3966
         *
3967
         * If no callback is passed, all values which are NOT empty, null or false will be
3968
         * removed. The keys of the original map are preserved in the returned map.
3969
         *
3970
         * @param Closure|mixed $callback Function with (item, key) parameter which returns TRUE/FALSE
3971
         * @return self<int|string,mixed> New map
3972
         */
3973
        public function reject( $callback = true ) : self
3974
        {
3975
                $result = [];
6✔
3976

3977
                if( $callback instanceof \Closure )
6✔
3978
                {
3979
                        foreach( $this->list() as $key => $value )
2✔
3980
                        {
3981
                                if( !$callback( $value, $key ) ) {
2✔
3982
                                        $result[$key] = $value;
2✔
3983
                                }
3984
                        }
3985
                }
3986
                else
3987
                {
3988
                        foreach( $this->list() as $key => $value )
4✔
3989
                        {
3990
                                if( $value != $callback ) {
4✔
3991
                                        $result[$key] = $value;
4✔
3992
                                }
3993
                        }
3994
                }
3995

3996
                return new static( $result );
6✔
3997
        }
3998

3999

4000
        /**
4001
         * Changes the keys according to the passed function.
4002
         *
4003
         * Examples:
4004
         *  Map::from( ['a' => 2, 'b' => 4] )->rekey( function( $value, $key ) {
4005
         *      return 'key-' . $key;
4006
         *  } );
4007
         *
4008
         * Results:
4009
         *  ['key-a' => 2, 'key-b' => 4]
4010
         *
4011
         * @param callable $callback Function with (value, key) parameters and returns new key
4012
         * @return self<int|string,mixed> New map with new keys and original values
4013
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
4014
         * @see transform() - Creates new key/value pairs using the passed function and returns a new map for the result
4015
         */
4016
        public function rekey( callable $callback ) : self
4017
        {
4018
                $list = $this->list();
2✔
4019
                $newKeys = array_map( $callback, $list, array_keys( $list ) );
2✔
4020

4021
                return new static( array_combine( $newKeys, array_values( $list ) ) );
2✔
4022
        }
4023

4024

4025
        /**
4026
         * Removes one or more elements from the map by its keys without returning a new map.
4027
         *
4028
         * Examples:
4029
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( 'a' );
4030
         *  Map::from( ['a' => 1, 2 => 'b'] )->remove( [2, 'a'] );
4031
         *
4032
         * Results:
4033
         * The first example will result in [2 => 'b'] while the second one resulting
4034
         * in an empty list
4035
         *
4036
         * @param iterable<string|int>|array<string|int>|string|int $keys List of keys to remove
4037
         * @return self<int|string,mixed> Updated map for fluid interface
4038
         */
4039
        public function remove( $keys ) : self
4040
        {
4041
                foreach( $this->array( $keys ) as $key ) {
10✔
4042
                        unset( $this->list()[$key] );
10✔
4043
                }
4044

4045
                return $this;
10✔
4046
        }
4047

4048

4049
        /**
4050
         * Replaces elements in the map with the given elements without returning a new map.
4051
         *
4052
         * Examples:
4053
         *  Map::from( ['a' => 1, 2 => 'b'] )->replace( ['a' => 2] );
4054
         *  Map::from( ['a' => 1, 'b' => ['c' => 3, 'd' => 4]] )->replace( ['b' => ['c' => 9]] );
4055
         *
4056
         * Results:
4057
         *  ['a' => 2, 2 => 'b']
4058
         *  ['a' => 1, 'b' => ['c' => 9, 'd' => 4]]
4059
         *
4060
         * The method is similar to merge() but it also replaces elements with numeric
4061
         * keys. These would be added by merge() with a new numeric key.
4062
         *
4063
         * The keys are preserved using this method.
4064
         *
4065
         * @param iterable<int|string,mixed> $elements List of elements
4066
         * @param bool $recursive TRUE to replace recursively (default), FALSE to replace elements only
4067
         * @return self<int|string,mixed> Updated map for fluid interface
4068
         */
4069
        public function replace( iterable $elements, bool $recursive = true ) : self
4070
        {
4071
                if( $recursive ) {
10✔
4072
                        $this->list = array_replace_recursive( $this->list(), $this->array( $elements ) );
8✔
4073
                } else {
4074
                        $this->list = array_replace( $this->list(), $this->array( $elements ) );
2✔
4075
                }
4076

4077
                return $this;
10✔
4078
        }
4079

4080

4081
        /**
4082
         * Reverses the element order with keys without returning a new map.
4083
         *
4084
         * Examples:
4085
         *  Map::from( ['a', 'b'] )->reverse();
4086
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reverse();
4087
         *
4088
         * Results:
4089
         *  ['b', 'a']
4090
         *  ['last' => 'user', 'name' => 'test']
4091
         *
4092
         * The keys are preserved using this method.
4093
         *
4094
         * @return self<int|string,mixed> Updated map for fluid interface
4095
         * @see reversed() - Reverses the element order in a copy of the map
4096
         */
4097
        public function reverse() : self
4098
        {
4099
                $this->list = array_reverse( $this->list(), true );
8✔
4100
                return $this;
8✔
4101
        }
4102

4103

4104
        /**
4105
         * Reverses the element order in a copy of the map.
4106
         *
4107
         * Examples:
4108
         *  Map::from( ['a', 'b'] )->reversed();
4109
         *  Map::from( ['name' => 'test', 'last' => 'user'] )->reversed();
4110
         *
4111
         * Results:
4112
         *  ['b', 'a']
4113
         *  ['last' => 'user', 'name' => 'test']
4114
         *
4115
         * The keys are preserved using this method and a new map is created before reversing the elements.
4116
         * Thus, reverse() should be preferred for performance reasons if possible.
4117
         *
4118
         * @return self<int|string,mixed> New map with a reversed copy of the elements
4119
         * @see reverse() - Reverses the element order with keys without returning a new map
4120
         */
4121
        public function reversed() : self
4122
        {
4123
                return ( clone $this )->reverse();
4✔
4124
        }
4125

4126

4127
        /**
4128
         * Sorts all elements in reverse order using new keys.
4129
         *
4130
         * Examples:
4131
         *  Map::from( ['a' => 1, 'b' => 0] )->rsort();
4132
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsort();
4133
         *
4134
         * Results:
4135
         *  [0 => 1, 1 => 0]
4136
         *  [0 => 'b', 1 => 'a']
4137
         *
4138
         * The parameter modifies how the values are compared. Possible parameter values are:
4139
         * - SORT_REGULAR : compare elements normally (don't change types)
4140
         * - SORT_NUMERIC : compare elements numerically
4141
         * - SORT_STRING : compare elements as strings
4142
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4143
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4144
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4145
         *
4146
         * The keys aren't preserved and elements get a new index. No new map is created
4147
         *
4148
         * @param int $options Sort options for rsort()
4149
         * @return self<int|string,mixed> Updated map for fluid interface
4150
         */
4151
        public function rsort( int $options = SORT_REGULAR ) : self
4152
        {
4153
                rsort( $this->list(), $options );
6✔
4154
                return $this;
6✔
4155
        }
4156

4157

4158
        /**
4159
         * Sorts a copy of all elements in reverse order using new keys.
4160
         *
4161
         * Examples:
4162
         *  Map::from( ['a' => 1, 'b' => 0] )->rsorted();
4163
         *  Map::from( [0 => 'b', 1 => 'a'] )->rsorted();
4164
         *
4165
         * Results:
4166
         *  [0 => 1, 1 => 0]
4167
         *  [0 => 'b', 1 => 'a']
4168
         *
4169
         * The parameter modifies how the values are compared. Possible parameter values are:
4170
         * - SORT_REGULAR : compare elements normally (don't change types)
4171
         * - SORT_NUMERIC : compare elements numerically
4172
         * - SORT_STRING : compare elements as strings
4173
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4174
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4175
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4176
         *
4177
         * The keys aren't preserved, elements get a new index and a new map is created.
4178
         *
4179
         * @param int $options Sort options for rsort()
4180
         * @return self<int|string,mixed> Updated map for fluid interface
4181
         */
4182
        public function rsorted( int $options = SORT_REGULAR ) : self
4183
        {
4184
                return ( clone $this )->rsort( $options );
2✔
4185
        }
4186

4187

4188
        /**
4189
         * Removes the passed characters from the right of all strings.
4190
         *
4191
         * Examples:
4192
         *  Map::from( [" abc\n", "\tcde\r\n"] )->rtrim();
4193
         *  Map::from( ["a b c", "cbxa"] )->rtrim( 'abc' );
4194
         *
4195
         * Results:
4196
         * The first example will return [" abc", "\tcde"] while the second one will return ["a b ", "cbx"].
4197
         *
4198
         * @param string $chars List of characters to trim
4199
         * @return self<int|string,mixed> Updated map for fluid interface
4200
         */
4201
        public function rtrim( string $chars = " \n\r\t\v\x00" ) : self
4202
        {
4203
                foreach( $this->list() as &$entry )
2✔
4204
                {
4205
                        if( is_string( $entry ) ) {
2✔
4206
                                $entry = rtrim( $entry, $chars );
2✔
4207
                        }
4208
                }
4209

4210
                return $this;
2✔
4211
        }
4212

4213

4214
        /**
4215
         * Searches the map for a given value and return the corresponding key if successful.
4216
         *
4217
         * Examples:
4218
         *  Map::from( ['a', 'b', 'c'] )->search( 'b' );
4219
         *  Map::from( [1, 2, 3] )->search( '2', true );
4220
         *
4221
         * Results:
4222
         * The first example will return 1 (array index) while the second one will
4223
         * return NULL because the types doesn't match (int vs. string)
4224
         *
4225
         * @param mixed $value Item to search for
4226
         * @param bool $strict TRUE if type of the element should be checked too
4227
         * @return int|string|null Key associated to the value or null if not found
4228
         */
4229
        public function search( $value, $strict = true )
4230
        {
4231
                if( ( $result = array_search( $value, $this->list(), $strict ) ) !== false ) {
2✔
4232
                        return $result;
2✔
4233
                }
4234

4235
                return null;
2✔
4236
        }
4237

4238

4239
        /**
4240
         * Sets the seperator for paths to values in multi-dimensional arrays or objects.
4241
         *
4242
         * This method only changes the separator for the current map instance. To
4243
         * change the separator for all maps created afterwards, use the static
4244
         * delimiter() method instead.
4245
         *
4246
         * Examples:
4247
         *  Map::from( ['foo' => ['bar' => 'baz']] )->sep( '/' )->get( 'foo/bar' );
4248
         *
4249
         * Results:
4250
         *  'baz'
4251
         *
4252
         * @param string $char Separator character, e.g. "." for "key.to.value" instead of "key/to/value"
4253
         * @return self<int|string,mixed> Same map for fluid interface
4254
         */
4255
        public function sep( string $char ) : self
4256
        {
4257
                $this->sep = $char;
2✔
4258
                return $this;
2✔
4259
        }
4260

4261

4262
        /**
4263
         * Sets an element in the map by key without returning a new map.
4264
         *
4265
         * Examples:
4266
         *  Map::from( ['a'] )->set( 1, 'b' );
4267
         *  Map::from( ['a'] )->set( 0, 'b' );
4268
         *
4269
         * Results:
4270
         *  ['a', 'b']
4271
         *  ['b']
4272
         *
4273
         * @param int|string $key Key to set the new value for
4274
         * @param mixed $value New element that should be set
4275
         * @return self<int|string,mixed> Updated map for fluid interface
4276
         */
4277
        public function set( $key, $value ) : self
4278
        {
4279
                $this->list()[(string) $key] = $value;
10✔
4280
                return $this;
10✔
4281
        }
4282

4283

4284
        /**
4285
         * Returns and removes the first element from the map.
4286
         *
4287
         * Examples:
4288
         *  Map::from( ['a', 'b'] )->shift();
4289
         *  Map::from( [] )->shift();
4290
         *
4291
         * Results:
4292
         * The first example returns "a" and shortens the map to ['b'] only while the
4293
         * second example will return NULL
4294
         *
4295
         * Performance note:
4296
         * The bigger the list, the higher the performance impact because shift()
4297
         * reindexes all existing elements. Usually, it's better to reverse() the list
4298
         * and pop() entries from the list afterwards if a significant number of elements
4299
         * should be removed from the list:
4300
         *
4301
         *  $map->reverse()->pop();
4302
         * instead of
4303
         *  $map->shift( 'a' );
4304
         *
4305
         * @return mixed|null Value from map or null if not found
4306
         */
4307
        public function shift()
4308
        {
4309
                return array_shift( $this->list() );
2✔
4310
        }
4311

4312

4313
        /**
4314
         * Shuffles the elements in the map without returning a new map.
4315
         *
4316
         * Examples:
4317
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle();
4318
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffle( true );
4319
         *
4320
         * Results:
4321
         * The map in the first example will contain "a" and "b" in random order and
4322
         * with new keys assigned. The second call will also return all values in
4323
         * random order but preserves the keys of the original list.
4324
         *
4325
         * @param bool $assoc True to preserve keys, false to assign new keys
4326
         * @return self<int|string,mixed> Updated map for fluid interface
4327
         * @see shuffled() - Shuffles the elements in a copy of the map
4328
         */
4329
        public function shuffle( bool $assoc = false ) : self
4330
        {
4331
                if( $assoc )
6✔
4332
                {
4333
                        $list = $this->list();
2✔
4334
                        $keys = array_keys( $list );
2✔
4335
                        shuffle( $keys );
2✔
4336
                        $items = [];
2✔
4337

4338
                        foreach( $keys as $key ) {
2✔
4339
                                $items[$key] = $list[$key];
2✔
4340
                        }
4341

4342
                        $this->list = $items;
2✔
4343
                }
4344
                else
4345
                {
4346
                        shuffle( $this->list() );
4✔
4347
                }
4348

4349
                return $this;
6✔
4350
        }
4351

4352

4353
        /**
4354
         * Shuffles the elements in a copy of the map.
4355
         *
4356
         * Examples:
4357
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled();
4358
         *  Map::from( [2 => 'a', 4 => 'b'] )->shuffled( true );
4359
         *
4360
         * Results:
4361
         * The map in the first example will contain "a" and "b" in random order and
4362
         * with new keys assigned. The second call will also return all values in
4363
         * random order but preserves the keys of the original list.
4364
         *
4365
         * @param bool $assoc True to preserve keys, false to assign new keys
4366
         * @return self<int|string,mixed> New map with a shuffled copy of the elements
4367
         * @see shuffle() - Shuffles the elements in the map without returning a new map
4368
         */
4369
        public function shuffled( bool $assoc = false ) : self
4370
        {
4371
                return ( clone $this )->shuffle( $assoc );
2✔
4372
        }
4373

4374

4375
        /**
4376
         * Returns a new map with the given number of items skipped.
4377
         *
4378
         * Examples:
4379
         *  Map::from( [1, 2, 3, 4] )->skip( 2 );
4380
         *  Map::from( [1, 2, 3, 4] )->skip( function( $item, $key ) {
4381
         *      return $item < 4;
4382
         *  } );
4383
         *
4384
         * Results:
4385
         *  [2 => 3, 3 => 4]
4386
         *  [3 => 4]
4387
         *
4388
         * The keys of the items returned in the new map are the same as in the original one.
4389
         *
4390
         * @param \Closure|int $offset Number of items to skip or function($item, $key) returning true for skipped items
4391
         * @return self<int|string,mixed> New map
4392
         */
4393
        public function skip( $offset ) : self
4394
        {
4395
                if( is_numeric( $offset ) ) {
6✔
4396
                        return new static( array_slice( $this->list(), (int) $offset, null, true ) );
2✔
4397
                }
4398

4399
                if( $offset instanceof \Closure ) {
4✔
4400
                        return new static( array_slice( $this->list(), $this->until( $this->list(), $offset ), null, true ) );
2✔
4401
                }
4402

4403
                throw new \InvalidArgumentException( 'Only an integer or a closure is allowed as first argument for skip()' );
2✔
4404
        }
4405

4406

4407
        /**
4408
         * Returns a map with the slice from the original map.
4409
         *
4410
         * Examples:
4411
         *  Map::from( ['a', 'b', 'c'] )->slice( 1 );
4412
         *  Map::from( ['a', 'b', 'c'] )->slice( 1, 1 );
4413
         *  Map::from( ['a', 'b', 'c', 'd'] )->slice( -2, -1 );
4414
         *
4415
         * Results:
4416
         * The first example will return ['b', 'c'] and the second one ['b'] only.
4417
         * The third example returns ['c'] because the slice starts at the second
4418
         * last value and ends before the last value.
4419
         *
4420
         * The rules for offsets are:
4421
         * - If offset is non-negative, the sequence will start at that offset
4422
         * - If offset is negative, the sequence will start that far from the end
4423
         *
4424
         * Similar for the length:
4425
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4426
         * - If the array is shorter than the length, then only the available array elements will be present
4427
         * - If length is given and is negative then the sequence will stop that many elements from the end
4428
         * - If it is omitted, then the sequence will have everything from offset up until the end
4429
         *
4430
         * The keys of the items returned in the new map are the same as in the original one.
4431
         *
4432
         * @param int $offset Number of elements to start from
4433
         * @param int|null $length Number of elements to return or NULL for no limit
4434
         * @return self<int|string,mixed> New map
4435
         */
4436
        public function slice( int $offset, ?int $length = null ) : self
4437
        {
4438
                return new static( array_slice( $this->list(), $offset, $length, true ) );
12✔
4439
        }
4440

4441

4442
        /**
4443
         * Tests if at least one element passes the test or is part of the map.
4444
         *
4445
         * Examples:
4446
         *  Map::from( ['a', 'b'] )->some( 'a' );
4447
         *  Map::from( ['a', 'b'] )->some( ['a', 'c'] );
4448
         *  Map::from( ['a', 'b'] )->some( function( $item, $key ) {
4449
         *    return $item === 'a';
4450
         *  } );
4451
         *  Map::from( ['a', 'b'] )->some( ['c', 'd'] );
4452
         *  Map::from( ['1', '2'] )->some( [2], true );
4453
         *
4454
         * Results:
4455
         * The first three examples will return TRUE while the fourth and fifth will return FALSE
4456
         *
4457
         * @param \Closure|iterable|mixed $values Closure with (item, key) parameter, element or list of elements to test against
4458
         * @param bool $strict TRUE to check the type too, using FALSE '1' and 1 will be the same
4459
         * @return bool TRUE if at least one element is available in map, FALSE if the map contains none of them
4460
         */
4461
        public function some( $values, bool $strict = false ) : bool
4462
        {
4463
                $list = $this->list();
12✔
4464

4465
                if( is_iterable( $values ) )
12✔
4466
                {
4467
                        foreach( $values as $entry )
6✔
4468
                        {
4469
                                if( in_array( $entry, $list, $strict ) === true ) {
6✔
4470
                                        return true;
6✔
4471
                                }
4472
                        }
4473

4474
                        return false;
4✔
4475
                }
4476

4477
                if( $values instanceof \Closure )
8✔
4478
                {
4479
                        foreach( $list as $key => $item )
4✔
4480
                        {
4481
                                if( $values( $item, $key ) ) {
4✔
4482
                                        return true;
4✔
4483
                                }
4484
                        }
4485
                }
4486

4487
                return in_array( $values, $list, $strict );
8✔
4488
        }
4489

4490

4491
        /**
4492
         * Sorts all elements in-place using new keys.
4493
         *
4494
         * Examples:
4495
         *  Map::from( ['a' => 1, 'b' => 0] )->sort();
4496
         *  Map::from( [0 => 'b', 1 => 'a'] )->sort();
4497
         *
4498
         * Results:
4499
         *  [0 => 0, 1 => 1]
4500
         *  [0 => 'a', 1 => 'b']
4501
         *
4502
         * The parameter modifies how the values are compared. Possible parameter values are:
4503
         * - SORT_REGULAR : compare elements normally (don't change types)
4504
         * - SORT_NUMERIC : compare elements numerically
4505
         * - SORT_STRING : compare elements as strings
4506
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4507
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4508
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4509
         *
4510
         * The keys aren't preserved and elements get a new index. No new map is created.
4511
         *
4512
         * @param int $options Sort options for PHP sort()
4513
         * @return self<int|string,mixed> Updated map for fluid interface
4514
         * @see sorted() - Sorts elements in a copy of the map
4515
         */
4516
        public function sort( int $options = SORT_REGULAR ) : self
4517
        {
4518
                sort( $this->list(), $options );
10✔
4519
                return $this;
10✔
4520
        }
4521

4522

4523
        /**
4524
         * Sorts the elements in a copy of the map using new keys.
4525
         *
4526
         * Examples:
4527
         *  Map::from( ['a' => 1, 'b' => 0] )->sorted();
4528
         *  Map::from( [0 => 'b', 1 => 'a'] )->sorted();
4529
         *
4530
         * Results:
4531
         *  [0 => 0, 1 => 1]
4532
         *  [0 => 'a', 1 => 'b']
4533
         *
4534
         * The parameter modifies how the values are compared. Possible parameter values are:
4535
         * - SORT_REGULAR : compare elements normally (don't change types)
4536
         * - SORT_NUMERIC : compare elements numerically
4537
         * - SORT_STRING : compare elements as strings
4538
         * - SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by setlocale()
4539
         * - SORT_NATURAL : compare elements as strings using "natural ordering" like natsort()
4540
         * - SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURALSORT_FLAG_CASE to sort strings case-insensitively
4541
         *
4542
         * The keys aren't preserved and elements get a new index and a new map is created before sorting the elements.
4543
         * Thus, sort() should be preferred for performance reasons if possible. A new map is created by calling this method.
4544
         *
4545
         * @param int $options Sort options for PHP sort()
4546
         * @return self<int|string,mixed> New map with a sorted copy of the elements
4547
         * @see sort() - Sorts elements in-place in the original map
4548
         */
4549
        public function sorted( int $options = SORT_REGULAR ) : self
4550
        {
4551
                return ( clone $this )->sort( $options );
4✔
4552
        }
4553

4554

4555
        /**
4556
         * Removes a portion of the map and replace it with the given replacement, then return the updated map.
4557
         *
4558
         * Examples:
4559
         *  Map::from( ['a', 'b', 'c'] )->splice( 1 );
4560
         *  Map::from( ['a', 'b', 'c'] )->splice( 1, 1, ['x', 'y'] );
4561
         *
4562
         * Results:
4563
         * The first example removes all entries after "a", so only ['a'] will be left
4564
         * in the map and ['b', 'c'] is returned. The second example replaces/returns "b"
4565
         * (start at 1, length 1) with ['x', 'y'] so the new map will contain
4566
         * ['a', 'x', 'y', 'c'] afterwards.
4567
         *
4568
         * The rules for offsets are:
4569
         * - If offset is non-negative, the sequence will start at that offset
4570
         * - If offset is negative, the sequence will start that far from the end
4571
         *
4572
         * Similar for the length:
4573
         * - If length is given and is positive, then the sequence will have up to that many elements in it
4574
         * - If the array is shorter than the length, then only the available array elements will be present
4575
         * - If length is given and is negative then the sequence will stop that many elements from the end
4576
         * - If it is omitted, then the sequence will have everything from offset up until the end
4577
         *
4578
         * Numerical array indexes are NOT preserved.
4579
         *
4580
         * @param int $offset Number of elements to start from
4581
         * @param int|null $length Number of elements to remove, NULL for all
4582
         * @param mixed $replacement List of elements to insert
4583
         * @return self<int|string,mixed> New map
4584
         */
4585
        public function splice( int $offset, ?int $length = null, $replacement = [] ) : self
4586
        {
4587
                // PHP 7.x doesn't allow to pass NULL as replacement
4588
                if( $length === null ) {
10✔
4589
                        $length = count( $this->list() );
4✔
4590
                }
4591

4592
                return new static( array_splice( $this->list(), $offset, $length, (array) $replacement ) );
10✔
4593
        }
4594

4595

4596
        /**
4597
         * Returns the strings after the passed value.
4598
         *
4599
         * Examples:
4600
         *  Map::from( ['äöüß'] )->strAfter( 'ö' );
4601
         *  Map::from( ['abc'] )->strAfter( '' );
4602
         *  Map::from( ['abc'] )->strAfter( 'b' );
4603
         *  Map::from( ['abc'] )->strAfter( 'c' );
4604
         *  Map::from( ['abc'] )->strAfter( 'x' );
4605
         *  Map::from( [''] )->strAfter( '' );
4606
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4607
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4608
         *
4609
         * Results:
4610
         *  ['üß']
4611
         *  ['abc']
4612
         *  ['c']
4613
         *  ['']
4614
         *  []
4615
         *  []
4616
         *  ['1', '1', '1']
4617
         *  ['0', '0']
4618
         *
4619
         * All scalar values (bool, int, float, string) will be converted to strings.
4620
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4621
         *
4622
         * @param string $value Character or string to search for
4623
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4624
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4625
         * @return self<int|string,mixed> New map
4626
         */
4627
        public function strAfter( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4628
        {
4629
                $list = [];
2✔
4630
                $len = mb_strlen( $value );
2✔
4631
                $fcn = $case ? 'mb_stripos' : 'mb_strpos';
2✔
4632

4633
                foreach( $this->list() as $key => $entry )
2✔
4634
                {
4635
                        if( is_scalar( $entry ) )
2✔
4636
                        {
4637
                                $pos = null;
2✔
4638
                                $str = (string) $entry;
2✔
4639

4640
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
2✔
4641
                                        $list[$key] = mb_substr( $str, $pos + $len, null, $encoding );
2✔
4642
                                } elseif( $str !== '' && $pos !== false ) {
2✔
4643
                                        $list[$key] = $str;
2✔
4644
                                }
4645
                        }
4646
                }
4647

4648
                return new static( $list );
2✔
4649
        }
4650

4651

4652
        /**
4653
         * Returns the strings before the passed value.
4654
         *
4655
         * Examples:
4656
         *  Map::from( ['äöüß'] )->strBefore( 'ü' );
4657
         *  Map::from( ['abc'] )->strBefore( '' );
4658
         *  Map::from( ['abc'] )->strBefore( 'b' );
4659
         *  Map::from( ['abc'] )->strBefore( 'a' );
4660
         *  Map::from( ['abc'] )->strBefore( 'x' );
4661
         *  Map::from( [''] )->strBefore( '' );
4662
         *  Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
4663
         *  Map::from( [0, 0.0, false, []] )->strAfter( '' );
4664
         *
4665
         * Results:
4666
         *  ['äö']
4667
         *  ['abc']
4668
         *  ['a']
4669
         *  ['']
4670
         *  []
4671
         *  []
4672
         *  ['1', '1', '1']
4673
         *  ['0', '0']
4674
         *
4675
         * All scalar values (bool, int, float, string) will be converted to strings.
4676
         * Non-scalar values as well as empty strings will be skipped and are not part of the result.
4677
         *
4678
         * @param string $value Character or string to search for
4679
         * @param bool $case TRUE if search should be case insensitive, FALSE if case-sensitive
4680
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4681
         * @return self<int|string,mixed> New map
4682
         */
4683
        public function strBefore( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self
4684
        {
4685
                $list = [];
2✔
4686
                $fcn = $case ? 'mb_strripos' : 'mb_strrpos';
2✔
4687

4688
                foreach( $this->list() as $key => $entry )
2✔
4689
                {
4690
                        if( is_scalar( $entry ) )
2✔
4691
                        {
4692
                                $pos = null;
2✔
4693
                                $str = (string) $entry;
2✔
4694

4695
                                if( $str !== '' && $value !== '' && ( $pos = $fcn( $str, $value, 0, $encoding ) ) !== false ) {
2✔
4696
                                        $list[$key] = mb_substr( $str, 0, $pos, $encoding );
2✔
4697
                                } elseif( $str !== '' && $pos !== false ) {
2✔
4698
                                        $list[$key] = $str;
2✔
4699
                                }
4700
                        }
4701
                }
4702

4703
                return new static( $list );
2✔
4704
        }
4705

4706

4707
        /**
4708
         * Compares the value against all map elements.
4709
         *
4710
         * Examples:
4711
         *  Map::from( ['foo', 'bar'] )->compare( 'foo' );
4712
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo', false );
4713
         *  Map::from( [123, 12.3] )->compare( '12.3' );
4714
         *  Map::from( [false, true] )->compare( '1' );
4715
         *  Map::from( ['foo', 'bar'] )->compare( 'Foo' );
4716
         *  Map::from( ['foo', 'bar'] )->compare( 'baz' );
4717
         *  Map::from( [new \stdClass(), 'bar'] )->compare( 'foo' );
4718
         *
4719
         * Results:
4720
         * The first four examples return TRUE, the last three examples will return FALSE.
4721
         *
4722
         * All scalar values (bool, float, int and string) are casted to string values before
4723
         * comparing to the given value. Non-scalar values in the map are ignored.
4724
         *
4725
         * @param string $value Value to compare map elements to
4726
         * @param bool $case TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
4727
         * @return bool TRUE If at least one element matches, FALSE if value is not in map
4728
         */
4729
        public function strCompare( string $value, bool $case = true ) : bool
4730
        {
4731
                $fcn = $case ? 'strcmp' : 'strcasecmp';
4✔
4732

4733
                foreach( $this->list() as $item )
4✔
4734
                {
4735
                        if( is_scalar( $item ) && !$fcn( (string) $item, $value ) ) {
4✔
4736
                                return true;
4✔
4737
                        }
4738
                }
4739

4740
                return false;
4✔
4741
        }
4742

4743

4744
        /**
4745
         * Tests if at least one of the passed strings is part of at least one entry.
4746
         *
4747
         * Examples:
4748
         *  Map::from( ['abc'] )->strContains( '' );
4749
         *  Map::from( ['abc'] )->strContains( 'a' );
4750
         *  Map::from( ['abc'] )->strContains( 'bc' );
4751
         *  Map::from( [12345] )->strContains( '23' );
4752
         *  Map::from( [123.4] )->strContains( 23.4 );
4753
         *  Map::from( [12345] )->strContains( false );
4754
         *  Map::from( [12345] )->strContains( true );
4755
         *  Map::from( [false] )->strContains( false );
4756
         *  Map::from( [''] )->strContains( false );
4757
         *  Map::from( ['abc'] )->strContains( ['b', 'd'] );
4758
         *  Map::from( ['abc'] )->strContains( 'c', 'ASCII' );
4759
         *
4760
         *  Map::from( ['abc'] )->strContains( 'd' );
4761
         *  Map::from( ['abc'] )->strContains( 'cb' );
4762
         *  Map::from( [23456] )->strContains( true );
4763
         *  Map::from( [false] )->strContains( 0 );
4764
         *  Map::from( ['abc'] )->strContains( ['d', 'e'] );
4765
         *  Map::from( ['abc'] )->strContains( 'cb', 'ASCII' );
4766
         *
4767
         * Results:
4768
         * The first eleven examples will return TRUE while the last six will return FALSE.
4769
         *
4770
         * @param array|string $value The string or list of strings to search for in each entry
4771
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4772
         * @return bool TRUE if one of the entries contains one of the strings, FALSE if not
4773
         * @todo 4.0 Add $case parameter at second position
4774
         */
4775
        public function strContains( $value, string $encoding = 'UTF-8' ) : bool
4776
        {
4777
                foreach( $this->list() as $entry )
2✔
4778
                {
4779
                        $entry = (string) $entry;
2✔
4780

4781
                        foreach( (array) $value as $str )
2✔
4782
                        {
4783
                                $str = (string) $str;
2✔
4784

4785
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
2✔
4786
                                        return true;
2✔
4787
                                }
4788
                        }
4789
                }
4790

4791
                return false;
2✔
4792
        }
4793

4794

4795
        /**
4796
         * Tests if all of the entries contains one of the passed strings.
4797
         *
4798
         * Examples:
4799
         *  Map::from( ['abc', 'def'] )->strContainsAll( '' );
4800
         *  Map::from( ['abc', 'cba'] )->strContainsAll( 'a' );
4801
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'bc' );
4802
         *  Map::from( [12345, '230'] )->strContainsAll( '23' );
4803
         *  Map::from( [123.4, 23.42] )->strContainsAll( 23.4 );
4804
         *  Map::from( [12345, '234'] )->strContainsAll( [true, false] );
4805
         *  Map::from( ['', false] )->strContainsAll( false );
4806
         *  Map::from( ['abc', 'def'] )->strContainsAll( ['b', 'd'] );
4807
         *  Map::from( ['abc', 'ecf'] )->strContainsAll( 'c', 'ASCII' );
4808
         *
4809
         *  Map::from( ['abc', 'def'] )->strContainsAll( 'd' );
4810
         *  Map::from( ['abc', 'cab'] )->strContainsAll( 'cb' );
4811
         *  Map::from( [23456, '123'] )->strContainsAll( true );
4812
         *  Map::from( [false, '000'] )->strContainsAll( 0 );
4813
         *  Map::from( ['abc', 'acf'] )->strContainsAll( ['d', 'e'] );
4814
         *  Map::from( ['abc', 'bca'] )->strContainsAll( 'cb', 'ASCII' );
4815
         *
4816
         * Results:
4817
         * The first nine examples will return TRUE while the last six will return FALSE.
4818
         *
4819
         * @param array|string $value The string or list of strings to search for in each entry
4820
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4821
         * @return bool TRUE if all of the entries contains at least one of the strings, FALSE if not
4822
         * @todo 4.0 Add $case parameter at second position
4823
         */
4824
        public function strContainsAll( $value, string $encoding = 'UTF-8' ) : bool
4825
        {
4826
                $list = [];
2✔
4827

4828
                foreach( $this->list() as $entry )
2✔
4829
                {
4830
                        $entry = (string) $entry;
2✔
4831
                        $list[$entry] = 0;
2✔
4832

4833
                        foreach( (array) $value as $str )
2✔
4834
                        {
4835
                                $str = (string) $str;
2✔
4836

4837
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) !== false ) ) {
2✔
4838
                                        $list[$entry] = 1; break;
2✔
4839
                                }
4840
                        }
4841
                }
4842

4843
                return array_sum( $list ) === count( $list );
2✔
4844
        }
4845

4846

4847
        /**
4848
         * Tests if at least one of the entries ends with one of the passed strings.
4849
         *
4850
         * Examples:
4851
         *  Map::from( ['abc'] )->strEnds( '' );
4852
         *  Map::from( ['abc'] )->strEnds( 'c' );
4853
         *  Map::from( ['abc'] )->strEnds( 'bc' );
4854
         *  Map::from( ['abc'] )->strEnds( ['b', 'c'] );
4855
         *  Map::from( ['abc'] )->strEnds( 'c', 'ASCII' );
4856
         *  Map::from( ['abc'] )->strEnds( 'a' );
4857
         *  Map::from( ['abc'] )->strEnds( 'cb' );
4858
         *  Map::from( ['abc'] )->strEnds( ['d', 'b'] );
4859
         *  Map::from( ['abc'] )->strEnds( 'cb', 'ASCII' );
4860
         *
4861
         * Results:
4862
         * The first five examples will return TRUE while the last four will return FALSE.
4863
         *
4864
         * @param array|string $value The string or strings to search for in each entry
4865
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4866
         * @return bool TRUE if one of the entries ends with one of the strings, FALSE if not
4867
         * @todo 4.0 Add $case parameter at second position
4868
         */
4869
        public function strEnds( $value, string $encoding = 'UTF-8' ) : bool
4870
        {
4871
                foreach( $this->list() as $entry )
2✔
4872
                {
4873
                        $entry = (string) $entry;
2✔
4874

4875
                        foreach( (array) $value as $str )
2✔
4876
                        {
4877
                                $len = mb_strlen( (string) $str );
2✔
4878

4879
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
2✔
4880
                                        return true;
2✔
4881
                                }
4882
                        }
4883
                }
4884

4885
                return false;
2✔
4886
        }
4887

4888

4889
        /**
4890
         * Tests if all of the entries ends with at least one of the passed strings.
4891
         *
4892
         * Examples:
4893
         *  Map::from( ['abc', 'def'] )->strEndsAll( '' );
4894
         *  Map::from( ['abc', 'bac'] )->strEndsAll( 'c' );
4895
         *  Map::from( ['abc', 'cbc'] )->strEndsAll( 'bc' );
4896
         *  Map::from( ['abc', 'def'] )->strEndsAll( ['c', 'f'] );
4897
         *  Map::from( ['abc', 'efc'] )->strEndsAll( 'c', 'ASCII' );
4898
         *  Map::from( ['abc', 'fed'] )->strEndsAll( 'd' );
4899
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca' );
4900
         *  Map::from( ['abc', 'acf'] )->strEndsAll( ['a', 'c'] );
4901
         *  Map::from( ['abc', 'bca'] )->strEndsAll( 'ca', 'ASCII' );
4902
         *
4903
         * Results:
4904
         * The first five examples will return TRUE while the last four will return FALSE.
4905
         *
4906
         * @param array|string $value The string or strings to search for in each entry
4907
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4908
         * @return bool TRUE if all of the entries ends with at least one of the strings, FALSE if not
4909
         * @todo 4.0 Add $case parameter at second position
4910
         */
4911
        public function strEndsAll( $value, string $encoding = 'UTF-8' ) : bool
4912
        {
4913
                $list = [];
2✔
4914

4915
                foreach( $this->list() as $entry )
2✔
4916
                {
4917
                        $entry = (string) $entry;
2✔
4918
                        $list[$entry] = 0;
2✔
4919

4920
                        foreach( (array) $value as $str )
2✔
4921
                        {
4922
                                $len = mb_strlen( (string) $str );
2✔
4923

4924
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, -$len, $encoding ) !== false ) ) {
2✔
4925
                                        $list[$entry] = 1; break;
2✔
4926
                                }
4927
                        }
4928
                }
4929

4930
                return array_sum( $list ) === count( $list );
2✔
4931
        }
4932

4933

4934
        /**
4935
         * Returns an element by key and casts it to string if possible.
4936
         *
4937
         * Examples:
4938
         *  Map::from( ['a' => true] )->string( 'a' );
4939
         *  Map::from( ['a' => 1] )->string( 'a' );
4940
         *  Map::from( ['a' => 1.1] )->string( 'a' );
4941
         *  Map::from( ['a' => 'abc'] )->string( 'a' );
4942
         *  Map::from( ['a' => ['b' => ['c' => 'yes']]] )->string( 'a/b/c' );
4943
         *  Map::from( [] )->string( 'a', function() { return 'no'; } );
4944
         *
4945
         *  Map::from( [] )->string( 'b' );
4946
         *  Map::from( ['b' => ''] )->string( 'b' );
4947
         *  Map::from( ['b' => null] )->string( 'b' );
4948
         *  Map::from( ['b' => [true]] )->string( 'b' );
4949
         *  Map::from( ['b' => resource] )->string( 'b' );
4950
         *  Map::from( ['b' => new \stdClass] )->string( 'b' );
4951
         *
4952
         *  Map::from( [] )->string( 'c', new \Exception( 'error' ) );
4953
         *
4954
         * Results:
4955
         * The first six examples will return the value as string while the 9th to 12th
4956
         * example returns an empty string. The last example will throw an exception.
4957
         *
4958
         * This does also work for multi-dimensional arrays by passing the keys
4959
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
4960
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
4961
         * public properties of objects or objects implementing __isset() and __get() methods.
4962
         *
4963
         * @param int|string $key Key or path to the requested item
4964
         * @param mixed $default Default value if key isn't found (will be casted to bool)
4965
         * @return string Value from map or default value
4966
         */
4967
        public function string( $key, $default = '' ) : string
4968
        {
4969
                return (string) ( is_scalar( $val = $this->get( $key, $default ) ) ? $val : $default );
6✔
4970
        }
4971

4972

4973
        /**
4974
         * Converts all alphabetic characters in strings to lower case.
4975
         *
4976
         * Examples:
4977
         *  Map::from( ['My String'] )->strLower();
4978
         *  Map::from( ['Τάχιστη'] )->strLower();
4979
         *  Map::from( ['Äpfel', 'Birnen'] )->strLower( 'ISO-8859-1' );
4980
         *  Map::from( [123] )->strLower();
4981
         *  Map::from( [new stdClass] )->strLower();
4982
         *
4983
         * Results:
4984
         * The first example will return ["my string"], the second one ["τάχιστη"] and
4985
         * the third one ["äpfel", "birnen"]. The last two strings will be unchanged.
4986
         *
4987
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
4988
         * @return self<int|string,mixed> Updated map for fluid interface
4989
         */
4990
        public function strLower( string $encoding = 'UTF-8' ) : self
4991
        {
4992
                foreach( $this->list() as &$entry )
2✔
4993
                {
4994
                        if( is_string( $entry ) ) {
2✔
4995
                                $entry = mb_strtolower( $entry, $encoding );
2✔
4996
                        }
4997
                }
4998

4999
                return $this;
2✔
5000
        }
5001

5002

5003
        /**
5004
         * Replaces all occurrences of the search string with the replacement string.
5005
         *
5006
         * Examples:
5007
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( '.com', '.de' );
5008
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], '.de' );
5009
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.de'] );
5010
         * Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.fr', '.de'] );
5011
         * Map::from( ['google.com', 'aimeos.com'] )->strReplace( ['.com', '.co'], ['.co', '.de', '.fr'] );
5012
         * Map::from( ['google.com', 'aimeos.com', 123] )->strReplace( '.com', '.de' );
5013
         * Map::from( ['GOOGLE.COM', 'AIMEOS.COM'] )->strReplace( '.com', '.de', true );
5014
         *
5015
         * Restults:
5016
         * ['google.de', 'aimeos.de']
5017
         * ['google.de', 'aimeos.de']
5018
         * ['google.de', 'aimeos']
5019
         * ['google.fr', 'aimeos.de']
5020
         * ['google.de', 'aimeos.de']
5021
         * ['google.de', 'aimeos.de', 123]
5022
         * ['GOOGLE.de', 'AIMEOS.de']
5023
         *
5024
         * If you use an array of strings for search or search/replacement, the order of
5025
         * the strings matters! Each search string found is replaced by the corresponding
5026
         * replacement string at the same position.
5027
         *
5028
         * In case of array parameters and if the number of replacement strings is less
5029
         * than the number of search strings, the search strings with no corresponding
5030
         * replacement string are replaced with empty strings. Replacement strings with
5031
         * no corresponding search string are ignored.
5032
         *
5033
         * An array parameter for the replacements is only allowed if the search parameter
5034
         * is an array of strings too!
5035
         *
5036
         * Because the method replaces from left to right, it might replace a previously
5037
         * inserted value when doing multiple replacements. Entries which are non-string
5038
         * values are left untouched.
5039
         *
5040
         * @param array|string $search String or list of strings to search for
5041
         * @param array|string $replace String or list of strings of replacement strings
5042
         * @param bool $case TRUE if replacements should be case insensitive, FALSE if case-sensitive
5043
         * @return self<int|string,mixed> Updated map for fluid interface
5044
         */
5045
        public function strReplace( $search, $replace, bool $case = false ) : self
5046
        {
5047
                $fcn = $case ? 'str_ireplace' : 'str_replace';
2✔
5048

5049
                foreach( $this->list() as &$entry )
2✔
5050
                {
5051
                        if( is_string( $entry ) ) {
2✔
5052
                                $entry = $fcn( $search, $replace, $entry );
2✔
5053
                        }
5054
                }
5055

5056
                return $this;
2✔
5057
        }
5058

5059

5060
        /**
5061
         * Tests if at least one of the entries starts with at least one of the passed strings.
5062
         *
5063
         * Examples:
5064
         *  Map::from( ['abc'] )->strStarts( '' );
5065
         *  Map::from( ['abc'] )->strStarts( 'a' );
5066
         *  Map::from( ['abc'] )->strStarts( 'ab' );
5067
         *  Map::from( ['abc'] )->strStarts( ['a', 'b'] );
5068
         *  Map::from( ['abc'] )->strStarts( 'ab', 'ASCII' );
5069
         *  Map::from( ['abc'] )->strStarts( 'b' );
5070
         *  Map::from( ['abc'] )->strStarts( 'bc' );
5071
         *  Map::from( ['abc'] )->strStarts( ['b', 'c'] );
5072
         *  Map::from( ['abc'] )->strStarts( 'bc', 'ASCII' );
5073
         *
5074
         * Results:
5075
         * The first five examples will return TRUE while the last four will return FALSE.
5076
         *
5077
         * @param array|string $value The string or strings to search for in each entry
5078
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5079
         * @return bool TRUE if all of the entries ends with at least one of the strings, FALSE if not
5080
         * @todo 4.0 Add $case parameter at second position
5081
         */
5082
        public function strStarts( $value, string $encoding = 'UTF-8' ) : bool
5083
        {
5084
                foreach( $this->list() as $entry )
2✔
5085
                {
5086
                        $entry = (string) $entry;
2✔
5087

5088
                        foreach( (array) $value as $str )
2✔
5089
                        {
5090
                                if( ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
2✔
5091
                                        return true;
2✔
5092
                                }
5093
                        }
5094
                }
5095

5096
                return false;
2✔
5097
        }
5098

5099

5100
        /**
5101
         * Tests if all of the entries starts with one of the passed strings.
5102
         *
5103
         * Examples:
5104
         *  Map::from( ['abc', 'def'] )->strStartsAll( '' );
5105
         *  Map::from( ['abc', 'acb'] )->strStartsAll( 'a' );
5106
         *  Map::from( ['abc', 'aba'] )->strStartsAll( 'ab' );
5107
         *  Map::from( ['abc', 'def'] )->strStartsAll( ['a', 'd'] );
5108
         *  Map::from( ['abc', 'acf'] )->strStartsAll( 'a', 'ASCII' );
5109
         *  Map::from( ['abc', 'def'] )->strStartsAll( 'd' );
5110
         *  Map::from( ['abc', 'bca'] )->strStartsAll( 'ab' );
5111
         *  Map::from( ['abc', 'bac'] )->strStartsAll( ['a', 'c'] );
5112
         *  Map::from( ['abc', 'cab'] )->strStartsAll( 'ab', 'ASCII' );
5113
         *
5114
         * Results:
5115
         * The first five examples will return TRUE while the last four will return FALSE.
5116
         *
5117
         * @param array|string $value The string or strings to search for in each entry
5118
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5119
         * @return bool TRUE if one of the entries starts with one of the strings, FALSE if not
5120
         * @todo 4.0 Add $case parameter at second position
5121
         */
5122
        public function strStartsAll( $value, string $encoding = 'UTF-8' ) : bool
5123
        {
5124
                $list = [];
2✔
5125

5126
                foreach( $this->list() as $entry )
2✔
5127
                {
5128
                        $entry = (string) $entry;
2✔
5129
                        $list[$entry] = 0;
2✔
5130

5131
                        foreach( (array) $value as $str )
2✔
5132
                        {
5133
                                if( (int) ( $str === '' || mb_strpos( $entry, (string) $str, 0, $encoding ) === 0 ) ) {
2✔
5134
                                        $list[$entry] = 1; break;
2✔
5135
                                }
5136
                        }
5137
                }
5138

5139
                return array_sum( $list ) === count( $list );
2✔
5140
        }
5141

5142

5143
        /**
5144
         * Converts all alphabetic characters in strings to upper case.
5145
         *
5146
         * Examples:
5147
         *  Map::from( ['My String'] )->strUpper();
5148
         *  Map::from( ['τάχιστη'] )->strUpper();
5149
         *  Map::from( ['äpfel', 'birnen'] )->strUpper( 'ISO-8859-1' );
5150
         *  Map::from( [123] )->strUpper();
5151
         *  Map::from( [new stdClass] )->strUpper();
5152
         *
5153
         * Results:
5154
         * The first example will return ["MY STRING"], the second one ["ΤΆΧΙΣΤΗ"] and
5155
         * the third one ["ÄPFEL", "BIRNEN"]. The last two strings will be unchanged.
5156
         *
5157
         * @param string $encoding Character encoding of the strings, e.g. "UTF-8" (default), "ASCII", "ISO-8859-1", etc.
5158
         * @return self<int|string,mixed> Updated map for fluid interface
5159
         */
5160
        public function strUpper( string $encoding = 'UTF-8' ) :self
5161
        {
5162
                foreach( $this->list() as &$entry )
2✔
5163
                {
5164
                        if( is_string( $entry ) ) {
2✔
5165
                                $entry = mb_strtoupper( $entry, $encoding );
2✔
5166
                        }
5167
                }
5168

5169
                return $this;
2✔
5170
        }
5171

5172

5173
        /**
5174
         * Adds a suffix at the end of each map entry.
5175
         *
5176
         * By defaul, nested arrays are walked recusively so all entries at all levels are suffixed.
5177
         *
5178
         * Examples:
5179
         *  Map::from( ['a', 'b'] )->suffix( '-1' );
5180
         *  Map::from( ['a', ['b']] )->suffix( '-1' );
5181
         *  Map::from( ['a', ['b']] )->suffix( '-1', 1 );
5182
         *  Map::from( ['a', 'b'] )->suffix( function( $item, $key ) {
5183
         *      return '-' . ( ord( $item ) + ord( $key ) );
5184
         *  } );
5185
         *
5186
         * Results:
5187
         *  The first example returns ['a-1', 'b-1'] while the second one will return
5188
         *  ['a-1', ['b-1']]. In the third example, the depth is limited to the first
5189
         *  level only so it will return ['a-1', ['b']]. The forth example passing
5190
         *  the closure will return ['a-145', 'b-147'].
5191
         *
5192
         * The keys are preserved using this method.
5193
         *
5194
         * @param \Closure|string $suffix Suffix string or anonymous function with ($item, $key) as parameters
5195
         * @param int|null $depth Maximum depth to dive into multi-dimensional arrays starting from "1"
5196
         * @return self<int|string,mixed> Updated map for fluid interface
5197
         */
5198
        public function suffix( $suffix, ?int $depth = null ) : self
5199
        {
5200
                $fcn = function( $list, $suffix, $depth ) use ( &$fcn ) {
2✔
5201

5202
                        foreach( $list as $key => $item )
2✔
5203
                        {
5204
                                if( is_array( $item ) ) {
2✔
5205
                                        $list[$key] = $depth > 1 ? $fcn( $item, $suffix, $depth - 1 ) : $item;
2✔
5206
                                } else {
5207
                                        $list[$key] = $item . ( is_callable( $suffix ) ? $suffix( $item, $key ) : $suffix );
2✔
5208
                                }
5209
                        }
5210

5211
                        return $list;
2✔
5212
                };
2✔
5213

5214
                $this->list = $fcn( $this->list(), $suffix, $depth ?? 0x7fffffff );
2✔
5215
                return $this;
2✔
5216
        }
5217

5218

5219
        /**
5220
         * Returns the sum of all integer and float values in the map.
5221
         *
5222
         * Examples:
5223
         *  Map::from( [1, 3, 5] )->sum();
5224
         *  Map::from( [1, 'sum', 5] )->sum();
5225
         *  Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->sum( 'p' );
5226
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( 'i/p' );
5227
         *  Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( fn( $val, $key ) => $val['i']['p'] ?? null )
5228
         *  Map::from( [30, 50, 10] )->sum( fn( $val, $key ) => $val < 50 ? $val : null )
5229
         *
5230
         * Results:
5231
         * The first line will return "9", the second one "6", the third one "90"
5232
         * the forth/fifth "80" and the last one "40".
5233
         *
5234
         * Non-numeric values will be removed before calculation.
5235
         *
5236
         * This does also work for multi-dimensional arrays by passing the keys
5237
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
5238
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
5239
         * public properties of objects or objects implementing __isset() and __get() methods.
5240
         *
5241
         * @param Closure|string|null $col Closure, key or path to the values in the nested array or object to sum up
5242
         * @return float Sum of all elements or 0 if there are no elements in the map
5243
         */
5244
        public function sum( $col = null ) : float
5245
        {
5246
                $list = $this->list();
6✔
5247
                $vals = array_filter( $col ? array_map( $this->mapper( $col ), $list, array_keys( $list ) ) : $list, 'is_numeric' );
6✔
5248

5249
                return array_sum( $vals );
6✔
5250
        }
5251

5252

5253
        /**
5254
         * Returns a new map with the given number of items.
5255
         *
5256
         * The keys of the items returned in the new map are the same as in the original one.
5257
         *
5258
         * Examples:
5259
         *  Map::from( [1, 2, 3, 4] )->take( 2 );
5260
         *  Map::from( [1, 2, 3, 4] )->take( 2, 1 );
5261
         *  Map::from( [1, 2, 3, 4] )->take( 2, -2 );
5262
         *  Map::from( [1, 2, 3, 4] )->take( 2, function( $item, $key ) {
5263
         *      return $item < 2;
5264
         *  } );
5265
         *
5266
         * Results:
5267
         *  [0 => 1, 1 => 2]
5268
         *  [1 => 2, 2 => 3]
5269
         *  [2 => 3, 3 => 4]
5270
         *  [1 => 2, 2 => 3]
5271
         *
5272
         * The keys of the items returned in the new map are the same as in the original one.
5273
         *
5274
         * @param int $size Number of items to return
5275
         * @param \Closure|int $offset Number of items to skip or function($item, $key) returning true for skipped items
5276
         * @return self<int|string,mixed> New map
5277
         */
5278
        public function take( int $size, $offset = 0 ) : self
5279
        {
5280
                $list = $this->list();
10✔
5281

5282
                if( is_numeric( $offset ) ) {
10✔
5283
                        return new static( array_slice( $list, (int) $offset, $size, true ) );
6✔
5284
                }
5285

5286
                if( $offset instanceof \Closure ) {
4✔
5287
                        return new static( array_slice( $list, $this->until( $list, $offset ), $size, true ) );
2✔
5288
                }
5289

5290
                throw new \InvalidArgumentException( 'Only an integer or a closure is allowed as second argument for take()' );
2✔
5291
        }
5292

5293

5294
        /**
5295
         * Passes a clone of the map to the given callback.
5296
         *
5297
         * Use it to "tap" into a chain of methods to check the state between two
5298
         * method calls. The original map is not altered by anything done in the
5299
         * callback.
5300
         *
5301
         * Examples:
5302
         *  Map::from( [3, 2, 1] )->rsort()->tap( function( $map ) {
5303
         *    print_r( $map->remove( 0 )->toArray() );
5304
         *  } )->first();
5305
         *
5306
         * Results:
5307
         * It will sort the list in reverse order (`[1, 2, 3]`) while keeping the keys,
5308
         * then prints the items without the first (`[2, 3]`) in the function passed
5309
         * to `tap()` and returns the first item ("1") at the end.
5310
         *
5311
         * @param callable $callback Function receiving ($map) parameter
5312
         * @return self<int|string,mixed> Same map for fluid interface
5313
         */
5314
        public function tap( callable $callback ) : self
5315
        {
5316
                $callback( clone $this );
2✔
5317
                return $this;
2✔
5318
        }
5319

5320

5321
        /**
5322
         * Returns the elements as a plain array.
5323
         *
5324
         * @return array<int|string,mixed> Plain array
5325
         */
5326
        public function to() : array
5327
        {
5328
                return $this->list = $this->array( $this->list );
2✔
5329
        }
5330

5331

5332
        /**
5333
         * Returns the elements as a plain array.
5334
         *
5335
         * @return array<int|string,mixed> Plain array
5336
         */
5337
        public function toArray() : array
5338
        {
5339
                return $this->list = $this->array( $this->list );
480✔
5340
        }
5341

5342

5343
        /**
5344
         * Returns the elements encoded as JSON string.
5345
         *
5346
         * There are several options available to modify the JSON output:
5347
         * {@link https://www.php.net/manual/en/function.json-encode.php}
5348
         * The parameter can be a single JSON_* constant or a bitmask of several
5349
         * constants combine by bitwise OR (|), e.g.:
5350
         *
5351
         *  JSON_FORCE_OBJECT|JSON_HEX_QUOT
5352
         *
5353
         * @param int $options Combination of JSON_* constants
5354
         * @return string|null Array encoded as JSON string or NULL on failure
5355
         */
5356
        public function toJson( int $options = 0 ) : ?string
5357
        {
5358
                $result = json_encode( $this->list(), $options );
4✔
5359
                return $result !== false ? $result : null;
4✔
5360
        }
5361

5362

5363
        /**
5364
         * Reverses the element order in a copy of the map (alias).
5365
         *
5366
         * This method is an alias for reversed(). For performance reasons, reversed() should be
5367
         * preferred because it uses one method call less than toReversed().
5368
         *
5369
         * @return self<int|string,mixed> New map with a reversed copy of the elements
5370
         * @see reversed() - Underlying method with same parameters and return value but better performance
5371
         */
5372
        public function toReversed() : self
5373
        {
5374
                return $this->reversed();
2✔
5375
        }
5376

5377

5378
        /**
5379
         * Sorts the elements in a copy of the map using new keys (alias).
5380
         *
5381
         * This method is an alias for sorted(). For performance reasons, sorted() should be
5382
         * preferred because it uses one method call less than toSorted().
5383
         *
5384
         * @param int $options Sort options for PHP sort()
5385
         * @return self<int|string,mixed> New map with a sorted copy of the elements
5386
         * @see sorted() - Underlying method with same parameters and return value but better performance
5387
         */
5388
        public function toSorted( int $options = SORT_REGULAR ) : self
5389
        {
5390
                return $this->sorted( $options );
2✔
5391
        }
5392

5393

5394
        /**
5395
         * Creates a HTTP query string from the map elements.
5396
         *
5397
         * Examples:
5398
         *  Map::from( ['a' => 1, 'b' => 2] )->toUrl();
5399
         *  Map::from( ['a' => ['b' => 'abc', 'c' => 'def'], 'd' => 123] )->toUrl();
5400
         *
5401
         * Results:
5402
         *  a=1&b=2
5403
         *  a%5Bb%5D=abc&a%5Bc%5D=def&d=123
5404
         *
5405
         * @return string Parameter string for GET requests
5406
         */
5407
        public function toUrl() : string
5408
        {
5409
                return http_build_query( $this->list(), '', '&', PHP_QUERY_RFC3986 );
4✔
5410
        }
5411

5412

5413
        /**
5414
         * Creates new key/value pairs using the passed function and returns a new map for the result.
5415
         *
5416
         * Examples:
5417
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5418
         *      return [$key . '-2' => $value * 2];
5419
         *  } );
5420
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5421
         *      return [$key => $value * 2, $key . $key => $value * 4];
5422
         *  } );
5423
         *  Map::from( ['a' => 2, 'b' => 4] )->transform( function( $value, $key ) {
5424
         *      return $key < 'b' ? [$key => $value * 2] : null;
5425
         *  } );
5426
         *  Map::from( ['la' => 2, 'le' => 4, 'li' => 6] )->transform( function( $value, $key ) {
5427
         *      return [$key[0] => $value * 2];
5428
         *  } );
5429
         *
5430
         * Results:
5431
         *  ['a-2' => 4, 'b-2' => 8]
5432
         *  ['a' => 4, 'aa' => 8, 'b' => 8, 'bb' => 16]
5433
         *  ['a' => 4]
5434
         *  ['l' => 12]
5435
         *
5436
         * If a key is returned twice, the last value will overwrite previous values.
5437
         *
5438
         * @param \Closure $callback Function with (value, key) parameters and returns an array of new key/value pair(s)
5439
         * @return self<int|string,mixed> New map with the new key/value pairs
5440
         * @see map() - Maps new values to the existing keys using the passed function and returns a new map for the result
5441
         * @see rekey() - Changes the keys according to the passed function
5442
         */
5443
        public function transform( \Closure $callback ) : self
5444
        {
5445
                $result = [];
8✔
5446

5447
                foreach( $this->list() as $key => $value )
8✔
5448
                {
5449
                        foreach( (array) $callback( $value, $key ) as $newkey => $newval ) {
8✔
5450
                                $result[$newkey] = $newval;
8✔
5451
                        }
5452
                }
5453

5454
                return new static( $result );
8✔
5455
        }
5456

5457

5458
        /**
5459
         * Exchanges rows and columns for a two dimensional map.
5460
         *
5461
         * Examples:
5462
         *  Map::from( [
5463
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
5464
         *    ['name' => 'B', 2020 => 300, 2021 => 200, 2022 => 100],
5465
         *    ['name' => 'C', 2020 => 400, 2021 => 300, 2022 => 200],
5466
         *  ] )->transpose();
5467
         *
5468
         *  Map::from( [
5469
         *    ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
5470
         *    ['name' => 'B', 2020 => 300, 2021 => 200],
5471
         *    ['name' => 'C', 2020 => 400]
5472
         *  ] );
5473
         *
5474
         * Results:
5475
         *  [
5476
         *    'name' => ['A', 'B', 'C'],
5477
         *    2020 => [200, 300, 400],
5478
         *    2021 => [100, 200, 300],
5479
         *    2022 => [50, 100, 200]
5480
         *  ]
5481
         *
5482
         *  [
5483
         *    'name' => ['A', 'B', 'C'],
5484
         *    2020 => [200, 300, 400],
5485
         *    2021 => [100, 200],
5486
         *    2022 => [50]
5487
         *  ]
5488
         *
5489
         * @return self<int|string,mixed> New map
5490
         */
5491
        public function transpose() : self
5492
        {
5493
                $result = [];
4✔
5494

5495
                foreach( (array) $this->first( [] ) as $key => $col ) {
4✔
5496
                        $result[$key] = array_column( $this->list(), $key );
4✔
5497
                }
5498

5499
                return new static( $result );
4✔
5500
        }
5501

5502

5503
        /**
5504
         * Traverses trees of nested items passing each item to the callback.
5505
         *
5506
         * This does work for nested arrays and objects with public properties or
5507
         * objects implementing __isset() and __get() methods. To build trees
5508
         * of nested items, use the tree() method.
5509
         *
5510
         * Examples:
5511
         *   Map::from( [[
5512
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5513
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5514
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5515
         *     ]
5516
         *   ]] )->traverse();
5517
         *
5518
         *   Map::from( [[
5519
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5520
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5521
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5522
         *     ]
5523
         *   ]] )->traverse( function( $entry, $key, $level, $parent ) {
5524
         *     return str_repeat( '-', $level ) . '- ' . $entry['name'];
5525
         *   } );
5526
         *
5527
         *   Map::from( [[
5528
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
5529
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5530
         *       ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
5531
         *     ]
5532
         *   ]] )->traverse( function( &$entry, $key, $level, $parent ) {
5533
         *     $entry['path'] = isset( $parent['path'] ) ? $parent['path'] . '/' . $entry['name'] : $entry['name'];
5534
         *     return $entry;
5535
         *   } );
5536
         *
5537
         *   Map::from( [[
5538
         *     'id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [
5539
         *       ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []]
5540
         *     ]
5541
         *   ]] )->traverse( null, 'nodes' );
5542
         *
5543
         * Results:
5544
         *   [
5545
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...]],
5546
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
5547
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []],
5548
         *   ]
5549
         *
5550
         *   ['- n1', '-- n2', '-- n3']
5551
         *
5552
         *   [
5553
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...], 'path' => 'n1'],
5554
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => [], 'path' => 'n1/n2'],
5555
         *     ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => [], 'path' => 'n1/n3'],
5556
         *   ]
5557
         *
5558
         *   [
5559
         *     ['id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [...]],
5560
         *     ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []],
5561
         *   ]
5562
         *
5563
         * @param \Closure|null $callback Callback with (entry, key, level, $parent) arguments, returns the entry added to result
5564
         * @param string $nestKey Key to the children of each item
5565
         * @return self<int|string,mixed> New map with all items as flat list
5566
         */
5567
        public function traverse( ?\Closure $callback = null, string $nestKey = 'children' ) : self
5568
        {
5569
                $result = [];
10✔
5570
                $this->visit( $this->list(), $result, 0, $callback, $nestKey );
10✔
5571

5572
                return map( $result );
10✔
5573
        }
5574

5575

5576
        /**
5577
         * Creates a tree structure from the list items.
5578
         *
5579
         * Use this method to rebuild trees e.g. from database records. To traverse
5580
         * trees, use the traverse() method.
5581
         *
5582
         * Examples:
5583
         *  Map::from( [
5584
         *    ['id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1'],
5585
         *    ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2'],
5586
         *    ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3'],
5587
         *    ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4'],
5588
         *    ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5'],
5589
         *    ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6'],
5590
         *  ] )->tree( 'id', 'pid' );
5591
         *
5592
         * Results:
5593
         *   [1 => [
5594
         *     'id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1', 'children' => [
5595
         *       2 => ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2', 'children' => [
5596
         *         3 => ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3', 'children' => []]
5597
         *       ]],
5598
         *       4 => ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4', 'children' => [
5599
         *         5 => ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5', 'children' => []]
5600
         *       ]],
5601
         *       6 => ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6', 'children' => []]
5602
         *     ]
5603
         *   ]]
5604
         *
5605
         * To build the tree correctly, the items must be in order or at least the
5606
         * nodes of the lower levels must come first. For a tree like this:
5607
         * n1
5608
         * |- n2
5609
         * |  |- n3
5610
         * |- n4
5611
         * |  |- n5
5612
         * |- n6
5613
         *
5614
         * Accepted item order:
5615
         * - in order: n1, n2, n3, n4, n5, n6
5616
         * - lower levels first: n1, n2, n4, n6, n3, n5
5617
         *
5618
         * If your items are unordered, apply usort() first to the map entries, e.g.
5619
         *   Map::from( [['id' => 3, 'lvl' => 2], ...] )->usort( function( $item1, $item2 ) {
5620
         *     return $item1['lvl'] <=> $item2['lvl'];
5621
         *   } );
5622
         *
5623
         * @param string $idKey Name of the key with the unique ID of the node
5624
         * @param string $parentKey Name of the key with the ID of the parent node
5625
         * @param string $nestKey Name of the key with will contain the children of the node
5626
         * @return self<int|string,mixed> New map with one or more root tree nodes
5627
         */
5628
        public function tree( string $idKey, string $parentKey, string $nestKey = 'children' ) : self
5629
        {
5630
                $this->list();
2✔
5631
                $trees = $refs = [];
2✔
5632

5633
                foreach( $this->list as &$node )
2✔
5634
                {
5635
                        $node[$nestKey] = [];
2✔
5636
                        $refs[$node[$idKey]] = &$node;
2✔
5637

5638
                        if( $node[$parentKey] ) {
2✔
5639
                                $refs[$node[$parentKey]][$nestKey][$node[$idKey]] = &$node;
2✔
5640
                        } else {
5641
                                $trees[$node[$idKey]] = &$node;
2✔
5642
                        }
5643
                }
5644

5645
                return map( $trees );
2✔
5646
        }
5647

5648

5649
        /**
5650
         * Removes the passed characters from the left/right of all strings.
5651
         *
5652
         * Examples:
5653
         *  Map::from( [" abc\n", "\tcde\r\n"] )->trim();
5654
         *  Map::from( ["a b c", "cbax"] )->trim( 'abc' );
5655
         *
5656
         * Results:
5657
         * The first example will return ["abc", "cde"] while the second one will return [" b ", "x"].
5658
         *
5659
         * @param string $chars List of characters to trim
5660
         * @return self<int|string,mixed> Updated map for fluid interface
5661
         */
5662
        public function trim( string $chars = " \n\r\t\v\x00" ) : self
5663
        {
5664
                foreach( $this->list() as &$entry )
2✔
5665
                {
5666
                        if( is_string( $entry ) ) {
2✔
5667
                                $entry = trim( $entry, $chars );
2✔
5668
                        }
5669
                }
5670

5671
                return $this;
2✔
5672
        }
5673

5674

5675
        /**
5676
         * Sorts all elements using a callback and maintains the key association.
5677
         *
5678
         * The given callback will be used to compare the values. The callback must accept
5679
         * two parameters (item A and B) and must return -1 if item A is smaller than
5680
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5681
         * method name and an anonymous function can be passed.
5682
         *
5683
         * Examples:
5684
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( 'strcasecmp' );
5685
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( function( $itemA, $itemB ) {
5686
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5687
         *  } );
5688
         *
5689
         * Results:
5690
         *  ['b' => 'a', 'a' => 'B']
5691
         *  ['b' => 'a', 'a' => 'B']
5692
         *
5693
         * The keys are preserved using this method and no new map is created.
5694
         *
5695
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5696
         * @return self<int|string,mixed> Updated map for fluid interface
5697
         */
5698
        public function uasort( callable $callback ) : self
5699
        {
5700
                uasort( $this->list(), $callback );
4✔
5701
                return $this;
4✔
5702
        }
5703

5704

5705
        /**
5706
         * Sorts all elements using a callback and maintains the key association.
5707
         *
5708
         * The given callback will be used to compare the values. The callback must accept
5709
         * two parameters (item A and B) and must return -1 if item A is smaller than
5710
         * item B, 0 if both are equal and 1 if item A is greater than item B. Both, a
5711
         * method name and an anonymous function can be passed.
5712
         *
5713
         * Examples:
5714
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( 'strcasecmp' );
5715
         *  Map::from( ['a' => 'B', 'b' => 'a'] )->uasorted( function( $itemA, $itemB ) {
5716
         *      return strtolower( $itemA ) <=> strtolower( $itemB );
5717
         *  } );
5718
         *
5719
         * Results:
5720
         *  ['b' => 'a', 'a' => 'B']
5721
         *  ['b' => 'a', 'a' => 'B']
5722
         *
5723
         * The keys are preserved using this method and a new map is created.
5724
         *
5725
         * @param callable $callback Function with (itemA, itemB) parameters and returns -1 (<), 0 (=) and 1 (>)
5726
         * @return self<int|string,mixed> Updated map for fluid interface
5727
         */
5728
        public function uasorted( callable $callback ) : self
5729
        {
5730
                return ( clone $this )->uasort( $callback );
2✔
5731
        }
5732

5733

5734
        /**
5735
         * Sorts the map elements by their keys using a callback.
5736
         *
5737
         * The given callback will be used to compare the keys. The callback must accept
5738
         * two parameters (key A and B) and must return -1 if key A is smaller than
5739
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
5740
         * method name and an anonymous function can be passed.
5741
         *
5742
         * Examples:
5743
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( 'strcasecmp' );
5744
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( function( $keyA, $keyB ) {
5745
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
5746
         *  } );
5747
         *
5748
         * Results:
5749
         *  ['a' => 'b', 'B' => 'a']
5750
         *  ['a' => 'b', 'B' => 'a']
5751
         *
5752
         * The keys are preserved using this method and no new map is created.
5753
         *
5754
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
5755
         * @return self<int|string,mixed> Updated map for fluid interface
5756
         */
5757
        public function uksort( callable $callback ) : self
5758
        {
5759
                uksort( $this->list(), $callback );
4✔
5760
                return $this;
4✔
5761
        }
5762

5763

5764
        /**
5765
         * Sorts a copy of the map elements by their keys using a callback.
5766
         *
5767
         * The given callback will be used to compare the keys. The callback must accept
5768
         * two parameters (key A and B) and must return -1 if key A is smaller than
5769
         * key B, 0 if both are equal and 1 if key A is greater than key B. Both, a
5770
         * method name and an anonymous function can be passed.
5771
         *
5772
         * Examples:
5773
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( 'strcasecmp' );
5774
         *  Map::from( ['B' => 'a', 'a' => 'b'] )->uksorted( function( $keyA, $keyB ) {
5775
         *      return strtolower( $keyA ) <=> strtolower( $keyB );
5776
         *  } );
5777
         *
5778
         * Results:
5779
         *  ['a' => 'b', 'B' => 'a']
5780
         *  ['a' => 'b', 'B' => 'a']
5781
         *
5782
         * The keys are preserved using this method and a new map is created.
5783
         *
5784
         * @param callable $callback Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
5785
         * @return self<int|string,mixed> Updated map for fluid interface
5786
         */
5787
        public function uksorted( callable $callback ) : self
5788
        {
5789
                return ( clone $this )->uksort( $callback );
2✔
5790
        }
5791

5792

5793
        /**
5794
         * Builds a union of the elements and the given elements without overwriting existing ones.
5795
         * Existing keys in the map will not be overwritten
5796
         *
5797
         * Examples:
5798
         *  Map::from( [0 => 'a', 1 => 'b'] )->union( [0 => 'c'] );
5799
         *  Map::from( ['a' => 1, 'b' => 2] )->union( ['c' => 1] );
5800
         *
5801
         * Results:
5802
         * The first example will result in [0 => 'a', 1 => 'b'] because the key 0
5803
         * isn't overwritten. In the second example, the result will be a combined
5804
         * list: ['a' => 1, 'b' => 2, 'c' => 1].
5805
         *
5806
         * If list entries should be overwritten,  please use merge() instead!
5807
         * The keys are preserved using this method and no new map is created.
5808
         *
5809
         * @param iterable<int|string,mixed> $elements List of elements
5810
         * @return self<int|string,mixed> Updated map for fluid interface
5811
         */
5812
        public function union( iterable $elements ) : self
5813
        {
5814
                $this->list = $this->list() + $this->array( $elements );
4✔
5815
                return $this;
4✔
5816
        }
5817

5818

5819
        /**
5820
         * Returns only unique elements from the map incl. their keys.
5821
         *
5822
         * Examples:
5823
         *  Map::from( [0 => 'a', 1 => 'b', 2 => 'b', 3 => 'c'] )->unique();
5824
         *  Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->unique( 'p' )
5825
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( 'i/p' )
5826
         *  Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( fn( $item, $key ) => $item['i']['p'] )
5827
         *
5828
         * Results:
5829
         * [0 => 'a', 1 => 'b', 3 => 'c']
5830
         * [['p' => 1], ['p' => 2]]
5831
         * [['i' => ['p' => '1']]]
5832
         * [['i' => ['p' => '1']]]
5833
         *
5834
         * Two elements are considered equal if comparing their string representions returns TRUE:
5835
         * (string) $elem1 === (string) $elem2
5836
         *
5837
         * The keys of the elements are only preserved in the new map if no key is passed.
5838
         *
5839
         * @param \Closure|string|null $col Key, path of the nested array or anonymous function with ($item, $key) parameters returning the value for comparison
5840
         * @return self<int|string,mixed> New map
5841
         */
5842
        public function unique( $col = null ) : self
5843
        {
5844
                if( $col === null ) {
10✔
5845
                        return new static( array_unique( $this->list() ) );
4✔
5846
                }
5847

5848
                $list = $this->list();
6✔
5849
                $map = array_map( $this->mapper( $col ), array_values( $list ), array_keys( $list ) );
6✔
5850

5851
                return new static( array_intersect_key( $list, array_unique( $map ) ) );
6✔
5852
        }
5853

5854

5855
        /**
5856
         * Pushes an element onto the beginning of the map without returning a new map.
5857
         *
5858
         * Examples:
5859
         *  Map::from( ['a', 'b'] )->unshift( 'd' );
5860
         *  Map::from( ['a', 'b'] )->unshift( 'd', 'first' );
5861
         *
5862
         * Results:
5863
         *  ['d', 'a', 'b']
5864
         *  ['first' => 'd', 0 => 'a', 1 => 'b']
5865
         *
5866
         * The keys of the elements are only preserved in the new map if no key is passed.
5867
         *
5868
         * Performance note:
5869
         * The bigger the list, the higher the performance impact because unshift()
5870
         * needs to create a new list and copies all existing elements to the new
5871
         * array. Usually, it's better to push() new entries at the end and reverse()
5872
         * the list afterwards:
5873
         *
5874
         *  $map->push( 'a' )->push( 'b' )->reverse();
5875
         * instead of
5876
         *  $map->unshift( 'a' )->unshift( 'b' );
5877
         *
5878
         * @param mixed $value Item to add at the beginning
5879
         * @param int|string|null $key Key for the item or NULL to reindex all numerical keys
5880
         * @return self<int|string,mixed> Updated map for fluid interface
5881
         */
5882
        public function unshift( $value, $key = null ) : self
5883
        {
5884
                if( $key === null ) {
6✔
5885
                        array_unshift( $this->list(), $value );
4✔
5886
                } else {
5887
                        $this->list = [$key => $value] + $this->list();
2✔
5888
                }
5889

5890
                return $this;
6✔
5891
        }
5892

5893

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

5923

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

5952

5953
        /**
5954
         * Resets the keys and return the values in a new map.
5955
         *
5956
         * Examples:
5957
         *  Map::from( ['x' => 'b', 2 => 'a', 'c'] )->values();
5958
         *
5959
         * Results:
5960
         * A new map with [0 => 'b', 1 => 'a', 2 => 'c'] as content
5961
         *
5962
         * @return self<int|string,mixed> New map of the values
5963
         */
5964
        public function values() : self
5965
        {
5966
                return new static( array_values( $this->list() ) );
20✔
5967
        }
5968

5969

5970
        /**
5971
         * Applies the given callback to all elements.
5972
         *
5973
         * To change the values of the Map, specify the value parameter as reference
5974
         * (&$value). You can only change the values but not the keys nor the array
5975
         * structure.
5976
         *
5977
         * Examples:
5978
         *  Map::from( ['a', 'B', ['c', 'd'], 'e'] )->walk( function( &$value ) {
5979
         *    $value = strtoupper( $value );
5980
         *  } );
5981
         *  Map::from( [66 => 'B', 97 => 'a'] )->walk( function( $value, $key ) {
5982
         *    echo 'ASCII ' . $key . ' is ' . $value . "\n";
5983
         *  } );
5984
         *  Map::from( [1, 2, 3] )->walk( function( &$value, $key, $data ) {
5985
         *    $value = $data[$value] ?? $value;
5986
         *  }, [1 => 'one', 2 => 'two'] );
5987
         *
5988
         * Results:
5989
         * The first example will change the Map elements to:
5990
         *   ['A', 'B', ['C', 'D'], 'E']
5991
         * The output of the second one will be:
5992
         *  ASCII 66 is B
5993
         *  ASCII 97 is a
5994
         * The last example changes the Map elements to:
5995
         *  ['one', 'two', 3]
5996
         *
5997
         * By default, Map elements which are arrays will be traversed recursively.
5998
         * To iterate over the Map elements only, pass FALSE as third parameter.
5999
         *
6000
         * @param callable $callback Function with (item, key, data) parameters
6001
         * @param mixed $data Arbitrary data that will be passed to the callback as third parameter
6002
         * @param bool $recursive TRUE to traverse sub-arrays recursively (default), FALSE to iterate Map elements only
6003
         * @return self<int|string,mixed> Updated map for fluid interface
6004
         */
6005
        public function walk( callable $callback, $data = null, bool $recursive = true ) : self
6006
        {
6007
                if( $recursive ) {
6✔
6008
                        array_walk_recursive( $this->list(), $callback, $data );
4✔
6009
                } else {
6010
                        array_walk( $this->list(), $callback, $data );
2✔
6011
                }
6012

6013
                return $this;
6✔
6014
        }
6015

6016

6017
        /**
6018
         * Filters the list of elements by a given condition.
6019
         *
6020
         * Examples:
6021
         *  Map::from( [
6022
         *    ['id' => 1, 'type' => 'name'],
6023
         *    ['id' => 2, 'type' => 'short'],
6024
         *  ] )->where( 'type', '==', 'name' );
6025
         *
6026
         *  Map::from( [
6027
         *    ['id' => 3, 'price' => 10],
6028
         *    ['id' => 4, 'price' => 50],
6029
         *  ] )->where( 'price', '>', 20 );
6030
         *
6031
         *  Map::from( [
6032
         *    ['id' => 3, 'price' => 10],
6033
         *    ['id' => 4, 'price' => 50],
6034
         *  ] )->where( 'price', 'in', [10, 25] );
6035
         *
6036
         *  Map::from( [
6037
         *    ['id' => 3, 'price' => 10],
6038
         *    ['id' => 4, 'price' => 50],
6039
         *  ] )->where( 'price', '-', [10, 100] );
6040
         *
6041
         *  Map::from( [
6042
         *    ['item' => ['id' => 3, 'price' => 10]],
6043
         *    ['item' => ['id' => 4, 'price' => 50]],
6044
         *  ] )->where( 'item/price', '>', 30 );
6045
         *
6046
         * Results:
6047
         *  [0 => ['id' => 1, 'type' => 'name']]
6048
         *  [1 => ['id' => 4, 'price' => 50]]
6049
         *  [0 => ['id' => 3, 'price' => 10]]
6050
         *  [0 => ['id' => 3, 'price' => 10], ['id' => 4, 'price' => 50]]
6051
         *  [1 => ['item' => ['id' => 4, 'price' => 50]]]
6052
         *
6053
         * Available operators are:
6054
         * * '==' : Equal
6055
         * * '===' : Equal and same type
6056
         * * '!=' : Not equal
6057
         * * '!==' : Not equal and same type
6058
         * * '<=' : Smaller than an equal
6059
         * * '>=' : Greater than an equal
6060
         * * '<' : Smaller
6061
         * * '>' : Greater
6062
         * 'in' : Array of value which are in the list of values
6063
         * '-' : Values between array of start and end value, e.g. [10, 100] (inclusive)
6064
         *
6065
         * This does also work for multi-dimensional arrays by passing the keys
6066
         * of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
6067
         * to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
6068
         * public properties of objects or objects implementing __isset() and __get() methods.
6069
         *
6070
         * The keys of the original map are preserved in the returned map.
6071
         *
6072
         * @param string $key Key or path of the value in the array or object used for comparison
6073
         * @param string $op Operator used for comparison
6074
         * @param mixed $value Value used for comparison
6075
         * @return self<int|string,mixed> New map for fluid interface
6076
         */
6077
        public function where( string $key, string $op, $value ) : self
6078
        {
6079
                return $this->filter( function( $item ) use ( $key, $op, $value ) {
12✔
6080

6081
                        if( ( $val = $this->val( $item, explode( $this->sep, $key ) ) ) !== null )
12✔
6082
                        {
6083
                                switch( $op )
6084
                                {
6085
                                        case '-':
10✔
6086
                                                $list = (array) $value;
2✔
6087
                                                return $val >= current( $list ) && $val <= end( $list );
2✔
6088
                                        case 'in': return in_array( $val, (array) $value );
8✔
6089
                                        case '<': return $val < $value;
6✔
6090
                                        case '>': return $val > $value;
6✔
6091
                                        case '<=': return $val <= $value;
4✔
6092
                                        case '>=': return $val >= $value;
4✔
6093
                                        case '===': return $val === $value;
4✔
6094
                                        case '!==': return $val !== $value;
4✔
6095
                                        case '!=': return $val != $value;
4✔
6096
                                        default: return $val == $value;
4✔
6097
                                }
6098
                        }
6099

6100
                        return false;
2✔
6101
                } );
12✔
6102
        }
6103

6104

6105
        /**
6106
         * Returns a copy of the map with the element at the given index replaced with the given value.
6107
         *
6108
         * Examples:
6109
         *  $m = Map::from( ['a' => 1] );
6110
         *  $m->with( 2, 'b' );
6111
         *  $m->with( 'a', 2 );
6112
         *
6113
         * Results:
6114
         *  ['a' => 1, 2 => 'b']
6115
         *  ['a' => 2]
6116
         *
6117
         * The original map ($m) stays untouched!
6118
         * This method is a shortcut for calling the copy() and set() methods.
6119
         *
6120
         * @param int|string $key Array key to set or replace
6121
         * @param mixed $value New value for the given key
6122
         * @return self<int|string,mixed> New map
6123
         */
6124
        public function with( $key, $value ) : self
6125
        {
6126
                return ( clone $this )->set( $key, $value );
2✔
6127
        }
6128

6129

6130
        /**
6131
         * Merges the values of all arrays at the corresponding index.
6132
         *
6133
         * Examples:
6134
         *  $en = ['one', 'two', 'three'];
6135
         *  $es = ['uno', 'dos', 'tres'];
6136
         *  $m = Map::from( [1, 2, 3] )->zip( $en, $es );
6137
         *
6138
         * Results:
6139
         *  [
6140
         *    [1, 'one', 'uno'],
6141
         *    [2, 'two', 'dos'],
6142
         *    [3, 'three', 'tres'],
6143
         *  ]
6144
         *
6145
         * @param array<int|string,mixed>|\Traversable<int|string,mixed>|\Iterator<int|string,mixed> $arrays List of arrays to merge with at the same position
6146
         * @return self<int|string,mixed> New map of arrays
6147
         */
6148
        public function zip( ...$arrays ) : self
6149
        {
6150
                $args = array_map( function( $items ) {
2✔
6151
                        return $this->array( $items );
2✔
6152
                }, $arrays );
2✔
6153

6154
                return new static( array_map( null, $this->list(), ...$args ) );
2✔
6155
        }
6156

6157

6158
        /**
6159
         * Returns a plain array of the given elements.
6160
         *
6161
         * @param mixed $elements List of elements or single value
6162
         * @return array<int|string,mixed> Plain array
6163
         */
6164
        protected function array( $elements ) : array
6165
        {
6166
                if( is_array( $elements ) ) {
510✔
6167
                        return $elements;
490✔
6168
                }
6169

6170
                if( $elements instanceof \Closure ) {
78✔
UNCOV
6171
                        return (array) $elements();
×
6172
                }
6173

6174
                if( $elements instanceof \Aimeos\Map ) {
78✔
6175
                        return $elements->toArray();
46✔
6176
                }
6177

6178
                if( is_iterable( $elements ) ) {
34✔
6179
                        return iterator_to_array( $elements, true );
6✔
6180
                }
6181

6182
                return $elements !== null ? [$elements] : [];
28✔
6183
        }
6184

6185

6186
        /**
6187
         * Flattens a multi-dimensional array or map into a single level array.
6188
         *
6189
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
6190
         * @param array<mixed> &$result Will contain all elements from the multi-dimensional arrays afterwards
6191
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
6192
         */
6193
        protected function flatten( iterable $entries, array &$result, int $depth ) : void
6194
        {
6195
                foreach( $entries as $entry )
10✔
6196
                {
6197
                        if( is_iterable( $entry ) && $depth > 0 ) {
10✔
6198
                                $this->flatten( $entry, $result, $depth - 1 );
8✔
6199
                        } else {
6200
                                $result[] = $entry;
10✔
6201
                        }
6202
                }
6203
        }
6204

6205

6206
        /**
6207
         * Flattens a multi-dimensional array or map into a single level array.
6208
         *
6209
         * @param iterable<int|string,mixed> $entries Single of multi-level array, map or everything foreach can be used with
6210
         * @param array<int|string,mixed> $result Will contain all elements from the multi-dimensional arrays afterwards
6211
         * @param int $depth Number of levels to flatten in multi-dimensional arrays
6212
         */
6213
        protected function kflatten( iterable $entries, array &$result, int $depth ) : void
6214
        {
6215
                foreach( $entries as $key => $entry )
10✔
6216
                {
6217
                        if( is_iterable( $entry ) && $depth > 0 ) {
10✔
6218
                                $this->kflatten( $entry, $result, $depth - 1 );
10✔
6219
                        } else {
6220
                                $result[$key] = $entry;
10✔
6221
                        }
6222
                }
6223
        }
6224

6225

6226
        /**
6227
         * Returns a reference to the array of elements
6228
         *
6229
         * @return array Reference to the array of elements
6230
         */
6231
        protected function &list() : array
6232
        {
6233
                if( !is_array( $this->list ) ) {
724✔
UNCOV
6234
                        $this->list = $this->array( $this->list );
×
6235
                }
6236

6237
                return $this->list;
724✔
6238
        }
6239

6240

6241
        /**
6242
         * Returns a closure that retrieves the value for the passed key
6243
         *
6244
         * @param \Closure|string|null $key Closure or key (e.g. "key1/key2/key3") to retrieve the value for
6245
         * @return \Closure Closure that retrieves the value for the passed key
6246
         */
6247
        protected function mapper( $key = null ) : \Closure
6248
        {
6249
                if( $key instanceof \Closure ) {
28✔
6250
                        return $key;
12✔
6251
                }
6252

6253
                $parts = $key ? explode( $this->sep, (string) $key ) : [];
16✔
6254

6255
                return function( $item ) use ( $parts ) {
16✔
6256
                        return $this->val( $item, $parts );
16✔
6257
                };
16✔
6258
        }
6259

6260

6261
        /**
6262
         * Returns the position of the first element that doesn't match the condition
6263
         *
6264
         * @param iterable<int|string,mixed> $list List of elements to check
6265
         * @param \Closure $callback Closure with ($item, $key) arguments to check the condition
6266
         * @return int Position of the first element that doesn't match the condition
6267
         */
6268
        protected function until( iterable $list, \Closure $callback ) : int
6269
        {
6270
                $idx = 0;
4✔
6271

6272
                foreach( $list as $key => $item )
4✔
6273
                {
6274
                        if( !$callback( $item, $key ) ) {
4✔
6275
                                break;
4✔
6276
                        }
6277

6278
                        ++$idx;
4✔
6279
                }
6280

6281
                return $idx;
4✔
6282
        }
6283

6284

6285
        /**
6286
         * Returns a configuration value from an array.
6287
         *
6288
         * @param array<mixed>|object $entry The array or object to look at
6289
         * @param array<string> $parts Path parts to look for inside the array or object
6290
         * @return mixed Found value or null if no value is available
6291
         */
6292
        protected function val( $entry, array $parts )
6293
        {
6294
                foreach( $parts as $part )
94✔
6295
                {
6296
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$part] ) ) {
90✔
6297
                                $entry = $entry[$part];
52✔
6298
                        } elseif( is_object( $entry ) && isset( $entry->{$part} ) ) {
54✔
6299
                                $entry = $entry->{$part};
4✔
6300
                        } else {
6301
                                return null;
50✔
6302
                        }
6303
                }
6304

6305
                return $entry;
58✔
6306
        }
6307

6308

6309
        /**
6310
         * Visits each entry, calls the callback and returns the items in the result argument
6311
         *
6312
         * @param iterable<int|string,mixed> $entries List of entries with children (optional)
6313
         * @param array<mixed> $result Numerically indexed list of all visited entries
6314
         * @param int $level Current depth of the nodes in the tree
6315
         * @param \Closure|null $callback Callback with ($entry, $key, $level) arguments, returns the entry added to result
6316
         * @param string $nestKey Key to the children of each entry
6317
         * @param array<mixed>|object|null $parent Parent entry
6318
         */
6319
        protected function visit( iterable $entries, array &$result, int $level, ?\Closure $callback, string $nestKey, $parent = null ) : void
6320
        {
6321
                foreach( $entries as $key => $entry )
10✔
6322
                {
6323
                        $result[] = $callback ? $callback( $entry, $key, $level, $parent ) : $entry;
10✔
6324

6325
                        if( ( is_array( $entry ) || $entry instanceof \ArrayAccess ) && isset( $entry[$nestKey] ) ) {
10✔
6326
                                $this->visit( $entry[$nestKey], $result, $level + 1, $callback, $nestKey, $entry );
8✔
6327
                        } elseif( is_object( $entry ) && isset( $entry->{$nestKey} ) ) {
2✔
6328
                                $this->visit( $entry->{$nestKey}, $result, $level + 1, $callback, $nestKey, $entry );
2✔
6329
                        }
6330
                }
6331
        }
6332
}
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