Completed
Push — master ( 44b075...095c19 )
by Lars
03:03
created

Arrayy::containsValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Arrayy;
4
5
use ArrayAccess;
6
use Closure;
7
use voku\helper\UTF8;
8
9
/**
10
 * Methods to manage arrays.
11
 *
12
 * For the full copyright and license information, please view the LICENSE
13
 * file that was distributed with this source code.
14
 */
15
class Arrayy extends \ArrayObject
16
{
17
  /**
18
   * @var array
19
   */
20
  protected $array = array();
21
22
  /** @noinspection MagicMethodsValidityInspection */
23
  /**
24
   * Initializes
25
   *
26
   * @param array $array
27
   */
28 723
  public function __construct($array = array())
29
  {
30 723
    $array = $this->fallbackForArray($array);
31
32 721
    $this->array = $array;
33 721
  }
34
35
  /**
36
   * Get a value by key.
37
   *
38
   * @param $key
39
   *
40
   * @return mixed Get a Value from the current array.
41
   */
42
  public function &__get($key)
43
  {
44
    return $this->array[$key];
45
  }
46
47
  /**
48
   * Call object as function.
49
   *
50
   * @param mixed $key
51
   *
52
   * @return mixed
53
   */
54
  public function __invoke($key = null)
55
  {
56
    if ($key !== null) {
57
      if (isset($this->array[$key])) {
58
        return $this->array[$key];
59
      } else {
60
        return false;
61
      }
62
    }
63
64
    return (array)$this->array;
65
  }
66
67
  /**
68
   * Whether or not an element exists by key.
69
   *
70
   * @param mixed $key
71
   *
72
   * @return bool True is the key/index exists, otherwise false.
73
   */
74
  public function __isset($key)
75
  {
76
    return isset($this->array[$key]);
77
  }
78
79
  /**
80
   * Assigns a value to the specified element.
81
   *
82
   * @param mixed $key
83
   * @param mixed $value
84
   */
85
  public function __set($key, $value)
86
  {
87
    $this->array[$key] = $value;
88
  }
89
90
  /**
91
   * magic to string
92
   *
93
   * @return string
94
   */
95 16
  public function __toString()
96
  {
97 16
    return $this->toString();
98
  }
99
100
  /**
101
   * Unset element by key.
102
   *
103
   * @param mixed $key
104
   */
105
  public function __unset($key)
106
  {
107
    unset($this->array[$key]);
108
  }
109
110
  /**
111
   * alias: for "Arrayy->append()"
112
   *
113
   * @see Arrayy::append()
114
   *
115
   * @param mixed $value
116
   *
117
   * @return self (Mutable) Return this Arrayy object, with the appended values.
118
   */
119 1
  public function add($value)
120
  {
121 1
    return $this->append($value);
122
  }
123
124
  /**
125
   * Append a value to the current array.
126
   *
127
   * @param mixed $value
128
   *
129
   * @return self (Mutable) Return this Arrayy object, with the appended values.
130
   */
131 9
  public function append($value)
132
  {
133 9
    $this->array[] = $value;
134
135 9
    return $this;
136
  }
137
138
  /**
139
   * Count the values from the current array.
140
   *
141
   * alias: for "Arrayy->size()"
142
   *
143
   * @see Arrayy::size()
144
   *
145
   * @return int
146
   */
147 110
  public function count()
148
  {
149 110
    return $this->size();
150
  }
151
152
  /**
153
   * Returns a new ArrayIterator, thus implementing the IteratorAggregate interface.
154
   *
155
   * @return \ArrayIterator An iterator for the values in the array.
156
   */
157 17
  public function getIterator()
158
  {
159 17
    return new \ArrayIterator($this->array);
160
  }
161
162
  /**
163
   * Whether or not an offset exists.
164
   *
165
   * @param mixed $offset
166
   *
167
   * @return bool
168
   */
169 35
  public function offsetExists($offset)
170
  {
171 35
    return isset($this->array[$offset]);
172
  }
173
174
  /**
175
   * Returns the value at specified offset.
176
   *
177
   * @param mixed $offset
178
   *
179
   * @return mixed return null if the offset did not exists
180
   */
181 22
  public function offsetGet($offset)
182
  {
183 22
    return $this->offsetExists($offset) ? $this->array[$offset] : null;
184
  }
185
186
  /**
187
   * Assigns a value to the specified offset.
188
   *
189
   * @param mixed $offset
190
   * @param mixed $value
191
   */
192 13
  public function offsetSet($offset, $value)
193
  {
194 13
    if (null === $offset) {
195 4
      $this->array[] = $value;
196 4
    } else {
197 9
      $this->array[$offset] = $value;
198
    }
199 13
  }
200
201
  /**
202
   * Unset an offset.
203
   *
204
   * @param mixed $offset
205
   */
206 5
  public function offsetUnset($offset)
207
  {
208 5
    if ($this->offsetExists($offset)) {
209 3
      unset($this->array[$offset]);
210 3
    }
211 5
  }
212
213
  /**
214
   * Serialize the current array.
215
   *
216
   * @return string
217
   */
218 2
  public function serialize()
219
  {
220 2
    return serialize($this->array);
221
  }
222
223
  /**
224
   * Unserialize an string and return this object.
225
   *
226
   * @param string $string
227
   *
228
   * @return self (Mutable)
229
   */
230 2
  public function unserialize($string)
231
  {
232 2
    $this->array = unserialize($string);
233
234 2
    return $this;
235
  }
236
237
  /**
238
   * Iterate over the current array and execute a callback for each loop.
239
   *
240
   * @param \Closure $closure
241
   *
242
   * @return Arrayy (Immutable)
243
   */
244 2 View Code Duplication
  public function at(\Closure $closure)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
  {
246 2
    $array = $this->array;
247
248 2
    foreach ($array as $key => $value) {
249 2
      $closure($value, $key);
250 2
    }
251
252 2
    return static::create($array);
253
  }
254
255
  /**
256
   * Returns the average value of the current array.
257
   *
258
   * @param int $decimals The number of decimals to return
259
   *
260
   * @return int|double The average value
261
   */
262 10
  public function average($decimals = null)
263
  {
264 10
    $count = $this->count();
265
266 10
    if (!$count) {
267 2
      return 0;
268
    }
269
270 8
    if (!is_int($decimals)) {
271 3
      $decimals = null;
272 3
    }
273
274 8
    return round(array_sum($this->array) / $count, $decimals);
275
  }
276
277
  /**
278
   * Create a chunked version of the current array.
279
   *
280
   * @param int  $size         Size of each chunk
281
   * @param bool $preserveKeys Whether array keys are preserved or no
282
   *
283
   * @return Arrayy (Immutable) A new array of chunks from the original array.
284
   */
285 4
  public function chunk($size, $preserveKeys = false)
286
  {
287 4
    $result = array_chunk($this->array, $size, $preserveKeys);
288
289 4
    return static::create($result);
290
  }
291
292
  /**
293
   * Clean all falsy values from the current array.
294
   *
295
   * @return Arrayy (Immutable)
296
   */
297 8
  public function clean()
298
  {
299 8
    return $this->filter(
300
        function ($value) {
301 7
          return (bool)$value;
302
        }
303 8
    );
304
  }
305
306
  /**
307
   * WARNING!!! -> Clear the current array.
308
   *
309
   * @return self (Mutable) Return this Arrayy object, with an empty array.
310
   */
311 4
  public function clear()
312
  {
313 4
    $this->array = array();
314
315 4
    return $this;
316
  }
317
318
  /**
319
   * Check if an item is in the current array.
320
   *
321
   * @param string|int|float $value
322
   *
323
   * @return bool
324
   */
325 13
  public function contains($value)
326
  {
327 13
    return in_array($value, $this->array, true);
328
  }
329
330
  /**
331
   * Check if an (case-insensitive) string is in the current array.
332
   *
333
   * @param string $value
334
   *
335
   * @return bool
336
   */
337 13
  public function containsCaseInsensitive($value)
338
  {
339 13
    return in_array(
340 13
        UTF8::strtolower($value),
341 13
        array_map(
342
            array(
343 13
                new UTF8(),
344 13
                'strtolower',
345 13
            ),
346 13
            $this->array
347 13
        ),
348
        true
349 13
    );
350
  }
351
352
  /**
353
   * Check if the given key/index exists in the array.
354
   *
355
   * @param string|int|float $key key/index to search for
356
   *
357
   * @return bool Returns true if the given key/index exists in the array, false otherwise
358
   */
359 4
  public function containsKey($key)
360
  {
361 4
    return $this->offsetExists($key);
362
  }
363
364
  /**
365
   * Check if all given needles are present in the array as key/index.
366
   *
367
   * @param array $needles
368
   *
369
   * @return bool Returns true if the given keys/indexes exists in the array, false otherwise
370
   */
371 1
  public function containsKeys(array $needles)
372
  {
373 1
    return count(array_intersect($needles, $this->keys()->getArray())) === count($needles);
374
  }
375
376
  /**
377
   * alias: for "Arrayy->contains()"
378
   *
379
   * @see Arrayy::contains()
380
   *
381
   * @param string|int|float $value
382
   *
383
   * @return bool
384
   */
385
  public function containsValue($value)
386
  {
387
    return $this->contains($value);
388
  }
389
390
  /**
391
   * Check if all given needles are present in the array.
392
   *
393
   * @param array $needles
394
   *
395
   * @return bool Returns true if the given values exists in the array, false otherwise
396
   */
397 1
  public function containsValues(array $needles)
398
  {
399 1
    return count(array_intersect($needles, $this->array)) === count($needles);
400
  }
401
402
  /** @noinspection ArrayTypeOfParameterByDefaultValueInspection */
403
  /**
404
   * Creates an Arrayy object.
405
   *
406
   * @param array $array
407
   *
408
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
409
   */
410 449
  public static function create($array = array())
411
  {
412 449
    return new static($array);
413
  }
414
415
  /** @noinspection ArrayTypeOfParameterByDefaultValueInspection */
416
  /**
417
   * WARNING: Creates an Arrayy object by reference.
418
   *
419
   * @param array $array
420
   *
421
   * @return self (Mutable) Return this Arrayy object.
422
   */
423
  public function createByReference(&$array = array())
424
  {
425
    $array = $this->fallbackForArray($array);
426
427
    $this->array = &$array;
428
429
    return $this;
430
  }
431
432
  /**
433
   * Create an new Arrayy object via JSON.
434
   *
435
   * @param string $json
436
   *
437
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
438
   */
439 5
  public static function createFromJson($json)
440
  {
441 5
    $array = UTF8::json_decode($json, true);
442
443 5
    return static::create($array);
444
  }
445
446
  /**
447
   * Create an new instance filled with values from an object that have implemented ArrayAccess.
448
   *
449
   * @param ArrayAccess $object Object that implements ArrayAccess
450
   *
451
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
452
   */
453 4
  public static function createFromObject(ArrayAccess $object)
454
  {
455 4
    $array = new static();
456 4
    foreach ($object as $key => $value) {
457
      /** @noinspection OffsetOperationsInspection */
458 3
      $array[$key] = $value;
459 4
    }
460
461 4
    return $array;
462
  }
463
464
  /**
465
   * Create an new Arrayy object via string.
466
   *
467
   * @param string      $str       The input string.
468
   * @param string|null $delimiter The boundary string.
469
   * @param string|null $regEx     Use the $delimiter or the $regEx, so if $pattern is null, $delimiter will be used.
470
   *
471
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
472
   */
473 8
  public static function createFromString($str, $delimiter, $regEx = null)
474
  {
475 8
    if ($regEx) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $regEx of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
476 1
      preg_match_all($regEx, $str, $array);
477
478 1
      if (count($array) > 0) {
479 1
        $array = $array[0];
480 1
      }
481
482 1
    } else {
483 7
      $array = explode($delimiter, $str);
484
    }
485
486
    // trim all string in the array
487 8
    array_walk(
488 8
        $array,
489
        function (&$val) {
490
          /** @noinspection ReferenceMismatchInspection */
491 8
          if (is_string($val)) {
492 8
            $val = trim($val);
493 8
          }
494 8
        }
495 8
    );
496
497 8
    return static::create($array);
498
  }
499
500
  /**
501
   * Create an new instance containing a range of elements.
502
   *
503
   * @param mixed $low  First value of the sequence
504
   * @param mixed $high The sequence is ended upon reaching the end value
505
   * @param int   $step Used as the increment between elements in the sequence
506
   *
507
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
508
   */
509 1
  public static function createWithRange($low, $high, $step = 1)
510
  {
511 1
    return static::create(range($low, $high, $step));
512
  }
513
514
  /**
515
   * Custom sort by index via "uksort".
516
   *
517
   * @link http://php.net/manual/en/function.uksort.php
518
   *
519
   * @param callable $function
520
   *
521
   * @return self (Mutable) Return this Arrayy object.
522
   */
523 5
  public function customSortKeys($function)
524
  {
525 5
    uksort($this->array, $function);
526
527 5
    return $this;
528
  }
529
530
  /**
531
   * Custom sort by value via "usort".
532
   *
533
   * @link http://php.net/manual/en/function.usort.php
534
   *
535
   * @param callable $function
536
   *
537
   * @return self (Mutable) Return this Arrayy object.
538
   */
539 4
  public function customSortValues($function)
540
  {
541 4
    usort($this->array, $function);
542
543 4
    return $this;
544
  }
545
546
  /**
547
   * Return values that are only in the current array.
548
   *
549
   * @param array $array
550
   *
551
   * @return Arrayy (Immutable)
552
   */
553 12
  public function diff(array $array = array())
554
  {
555 12
    $result = array_diff($this->array, $array);
556
557 12
    return static::create($result);
558
  }
559
560
  /**
561
   * Return values that are only in the current multi-dimensional array.
562
   *
563
   * @param array      $array
564
   * @param null|array $helperVariableForRecursion (only for internal usage)
565
   *
566
   * @return Arrayy (Immutable)
567
   */
568 1
  public function diffRecursive(array $array = array(), $helperVariableForRecursion = null)
569
  {
570 1
    $result = array();
571
572 1
    if ($helperVariableForRecursion !== null && is_array($helperVariableForRecursion) === true) {
573 1
      $arrayForTheLoop = $helperVariableForRecursion;
574 1
    } else {
575 1
      $arrayForTheLoop = $this->array;
576
    }
577
578 1
    foreach ($arrayForTheLoop as $key => $value) {
579 1
      if (array_key_exists($key, $array)) {
580 1
        if (is_array($value)) {
581 1
          $recursiveDiff = $this->diffRecursive($array[$key], $value);
582 1
          if (count($recursiveDiff)) {
583 1
            $result[$key] = $recursiveDiff;
584 1
          }
585 1
        } else {
586 1
          if ($value != $array[$key]) {
587 1
            $result[$key] = $value;
588 1
          }
589
        }
590 1
      } else {
591 1
        $result[$key] = $value;
592
      }
593 1
    }
594
595 1
    return static::create($result);
596
  }
597
598
  /**
599
   * Return values that are only in the new $array.
600
   *
601
   * @param array $array
602
   *
603
   * @return Arrayy (Immutable)
604
   */
605 8
  public function diffReverse(array $array = array())
606
  {
607 8
    $result = array_diff($array, $this->array);
608
609 8
    return static::create($result);
610
  }
611
612
  /**
613
   * Divide an array into two arrays. One with keys and the other with values.
614
   *
615
   * @return Arrayy (Immutable)
616
   */
617 1
  public function divide()
618
  {
619 1
    return static::create(
620
        array(
621 1
            $this->keys(),
622 1
            $this->values(),
623
        )
624 1
    );
625
  }
626
627
  /**
628
   * Iterate over the current array and modify the array's value.
629
   *
630
   * @param \Closure $closure
631
   *
632
   * @return Arrayy (Immutable)
633
   */
634 22 View Code Duplication
  public function each(\Closure $closure)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
635
  {
636 22
    $array = $this->array;
637
638 22
    foreach ($array as $key => &$value) {
639 18
      $value = $closure($value, $key);
640 22
    }
641
642 22
    return static::create($array);
643
  }
644
645
  /**
646
   * Check if a value is in the current array using a closure.
647
   *
648
   * @param \Closure $closure
649
   *
650
   * @return bool Returns true if the given value is found, false otherwise
651
   */
652 4
  public function exists(\Closure $closure)
653
  {
654 4
    $isExists = false;
655 4
    foreach ($this->array as $key => $value) {
656 3
      if ($closure($value, $key)) {
657 1
        $isExists = true;
658 1
        break;
659
      }
660 4
    }
661
662 4
    return $isExists;
663
  }
664
665
  /**
666
   * create a fallback for array
667
   *
668
   * 1. use the current array, if it's a array
669
   * 2. call "getArray()" on object, if there is a "Arrayy"-object
670
   * 3. fallback to empty array, if there is nothing
671
   * 4. call "createFromObject()" on object, if there is a "ArrayAccess"-object
672
   * 5. call "__toArray()" on object, if the method exists
673
   * 6. cast a string or object with "__toString()" into an array
674
   * 7. throw a "InvalidArgumentException"-Exception
675
   *
676
   * @param $array
677
   *
678
   * @return array
679
   *
680
   * @throws \InvalidArgumentException
681
   */
682 723
  protected function fallbackForArray(&$array)
683
  {
684 723
    if (is_array($array)) {
685 720
      return $array;
686
    }
687
688 9
    if ($array instanceof self) {
689
      return $array->getArray();
690
    }
691
692 9
    if (!$array) {
693 6
      return array();
694
    }
695
696 8
    if ($array instanceof ArrayAccess) {
697
      /** @noinspection ReferenceMismatchInspection */
698
      return self::createFromObject($array)->getArray();
699
    }
700
701 8
    if (is_object($array) && method_exists($array, '__toArray')) {
702
      return (array)$array->__toArray();
703
    }
704
705
    /** @noinspection ReferenceMismatchInspection */
706
    if (
707 8
        is_string($array)
708
        ||
709 2
        (is_object($array) && method_exists($array, '__toString'))
710 8
    ) {
711 6
      return (array)$array;
712
    }
713
714 2
    throw new \InvalidArgumentException(
715
        'Passed value should be a array'
716 2
    );
717
  }
718
719
  /**
720
   * Find all items in an array that pass the truth test.
721
   *
722
   * @param \Closure|null $closure
723
   *
724
   * @return Arrayy (Immutable)
725
   */
726 9
  public function filter($closure = null)
727
  {
728 9
    if (!$closure) {
729 1
      return $this->clean();
730
    }
731
732 9
    $array = array_filter($this->array, $closure);
733
734 9
    return static::create($array);
735
  }
736
737
  /**
738
   * Filters an array of objects (or a numeric array of associative arrays) based on the value of a particular property
739
   * within that.
740
   *
741
   * @param        $property
742
   * @param        $value
743
   * @param string $comparisonOp
744
   *                            'eq' (equals),<br />
745
   *                            'gt' (greater),<br />
746
   *                            'gte' || 'ge' (greater or equals),<br />
747
   *                            'lt' (less),<br />
748
   *                            'lte' || 'le' (less or equals),<br />
749
   *                            'ne' (not equals),<br />
750
   *                            'contains',<br />
751
   *                            'notContains',<br />
752
   *                            'newer' (via strtotime),<br />
753
   *                            'older' (via strtotime),<br />
754
   *
755
   * @return Arrayy (Immutable)
756
   */
757 1
  public function filterBy($property, $value, $comparisonOp = null)
758
  {
759 1
    if (!$comparisonOp) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $comparisonOp of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
760 1
      $comparisonOp = is_array($value) ? 'contains' : 'eq';
761 1
    }
762
763
    $ops = array(
764
        'eq'          => function ($item, $prop, $value) {
765 1
          return $item[$prop] === $value;
766 1
        },
767
        'gt'          => function ($item, $prop, $value) {
768
          return $item[$prop] > $value;
769 1
        },
770
        'ge'          => function ($item, $prop, $value) {
771
          return $item[$prop] >= $value;
772 1
        },
773
        'gte'         => function ($item, $prop, $value) {
774
          return $item[$prop] >= $value;
775 1
        },
776
        'lt'          => function ($item, $prop, $value) {
777 1
          return $item[$prop] < $value;
778 1
        },
779
        'le'          => function ($item, $prop, $value) {
780
          return $item[$prop] <= $value;
781 1
        },
782
        'lte'         => function ($item, $prop, $value) {
783
          return $item[$prop] <= $value;
784 1
        },
785
        'ne'          => function ($item, $prop, $value) {
786
          return $item[$prop] !== $value;
787 1
        },
788
        'contains'    => function ($item, $prop, $value) {
789 1
          return in_array($item[$prop], (array)$value, true);
790 1
        },
791
        'notContains' => function ($item, $prop, $value) {
792
          return !in_array($item[$prop], (array)$value, true);
793 1
        },
794
        'newer'       => function ($item, $prop, $value) {
795
          return strtotime($item[$prop]) > strtotime($value);
796 1
        },
797
        'older'       => function ($item, $prop, $value) {
798
          return strtotime($item[$prop]) < strtotime($value);
799 1
        },
800 1
    );
801
802 1
    $result = array_values(
803 1
        array_filter(
804 1
            (array)$this->array,
805
            function ($item) use (
806 1
                $property,
807 1
                $value,
808 1
                $ops,
809 1
                $comparisonOp
810
            ) {
811 1
              $item = (array)$item;
812 1
              $itemArrayy = new Arrayy($item);
813 1
              $item[$property] = $itemArrayy->get($property, array());
814
815 1
              return $ops[$comparisonOp]($item, $property, $value);
816
            }
817 1
        )
818 1
    );
819
820 1
    return static::create($result);
821
  }
822
823
  /**
824
   * Find the first item in an array that passes the truth test,
825
   *  otherwise return false
826
   *
827
   * @param \Closure $closure
828
   *
829
   * @return mixed|false false if we did not find the value
830
   */
831 8
  public function find(\Closure $closure)
832
  {
833 8
    foreach ($this->array as $key => $value) {
834 6
      if ($closure($value, $key)) {
835 5
        return $value;
836
      }
837 5
    }
838
839 3
    return false;
840
  }
841
842
  /**
843
   * find by ...
844
   *
845
   * @param        $property
846
   * @param        $value
847
   * @param string $comparisonOp
848
   *
849
   * @return Arrayy (Immutable)
850
   */
851
  public function findBy($property, $value, $comparisonOp = 'eq')
852
  {
853
    return $this->filterBy($property, $value, $comparisonOp);
854
  }
855
856
  /**
857
   * Get the first value from the current array.
858
   *
859
   * @return mixed Return null if there wasn't a element.
860
   */
861 13
  public function first()
862
  {
863 13
    $result = array_shift($this->array);
864
865 13
    if (null === $result) {
866 3
      return null;
867
    } else {
868 10
      return $result;
869
    }
870
  }
871
872
  /**
873
   * Get the first value(s) from the current array.
874
   *
875
   * @param int|null $number how many values you will take?
876
   *
877
   * @return Arrayy (Immutable)
878
   */
879 28
  public function firstsImmutable($number = null)
880
  {
881 28
    if ($number === null) {
882 7
      $array = (array)array_shift($this->array);
883 7
    } else {
884 21
      $number = (int)$number;
885 21
      $array = array_splice($this->array, 0, $number, true);
886
    }
887
888 28
    return static::create($array);
889
  }
890
891
  /**
892
   * Get the first value(s) from the current array.
893
   *
894
   * @param int|null $number how many values you will take?
895
   *
896
   * @return self (Mutable)
897
   */
898 26
  public function firstsMutable($number = null)
899
  {
900 26
    if ($number === null) {
901 11
      $this->array = (array)array_shift($this->array);
902 11
    } else {
903 15
      $number = (int)$number;
904 15
      $this->array = array_splice($this->array, 0, $number, true);
905
    }
906
907 26
    return $this;
908
  }
909
910
  /**
911
   * Exchanges all keys with their associated values in an array.
912
   *
913
   * @return Arrayy (Immutable)
914
   */
915 1
  public function flip()
916
  {
917 1
    $result = array_flip($this->array);
918
919 1
    return static::create($result);
920
  }
921
922
  /**
923
   * Get a value from an array (optional using dot-notation).
924
   *
925
   * @param string $key     The key to look for.
926
   * @param mixed  $default Default value to fallback to.
927
   * @param array  $array   The array to get from, if it's set to "null" we use the current array from the class.
928
   *
929
   * @return mixed
930
   */
931 34
  public function get($key, $default = null, $array = null)
932
  {
933 34
    if (is_array($array) === true) {
934 3
      $usedArray = $array;
935 3
    } else {
936 32
      $usedArray = $this->array;
937
    }
938
939 34
    if (null === $key) {
940 1
      return $usedArray;
941
    }
942
943 34
    if (isset($usedArray[$key])) {
944 23
      return $usedArray[$key];
945
    }
946
947
    // Crawl through array, get key according to object or not
948 19
    foreach (explode('.', $key) as $segment) {
949 19
      if (!isset($usedArray[$segment])) {
950 17
        return $default instanceof Closure ? $default() : $default;
951
      }
952
953 2
      $usedArray = $usedArray[$segment];
954 2
    }
955
956 2
    return $usedArray;
957
  }
958
959
  /**
960
   * Get the current array from the "Arrayy"-object.
961
   *
962
   * @return array
963
   */
964 476
  public function getArray()
965
  {
966 476
    return $this->array;
967
  }
968
969
  /**
970
   * Returns the values from a single column of the input array, identified by
971
   * the $columnKey, can be used to extract data-columns from multi-arrays.
972
   *
973
   * Info: Optionally, you may provide an $indexKey to index the values in the returned
974
   * array by the values from the $indexKey column in the input array.
975
   *
976
   * @param mixed $columnKey
977
   * @param mixed $indexKey
978
   *
979
   * @return Arrayy (Immutable)
980
   */
981 1
  public function getColumn($columnKey = null, $indexKey = null)
982
  {
983 1
    $result = array_column($this->array, $columnKey, $indexKey);
984
985 1
    return static::create($result);
986
  }
987
988
  /**
989
   * Get correct PHP constant for direction.
990
   *
991
   * @param int|string $direction
992
   *
993
   * @return int
994
   */
995 38
  protected function getDirection($direction)
996
  {
997 38
    if (is_string($direction)) {
998 10
      $direction = strtolower($direction);
999
1000 10
      if ($direction === 'desc') {
1001 2
        $direction = SORT_DESC;
1002 2
      } else {
1003 8
        $direction = SORT_ASC;
1004
      }
1005 10
    }
1006
1007
    if (
1008
        $direction !== SORT_DESC
1009 38
        &&
1010
        $direction !== SORT_ASC
1011 38
    ) {
1012
      $direction = SORT_ASC;
1013
    }
1014
1015 38
    return $direction;
1016
  }
1017
1018
  /**
1019
   * alias: for "Arrayy->keys()"
1020
   *
1021
   * @see Arrayy::keys()
1022
   *
1023
   * @return Arrayy (Immutable)
1024
   */
1025
  public function getKeys()
1026
  {
1027
    return $this->keys();
1028
  }
1029
1030
  /**
1031
   * alias: for "Arrayy->randomImmutable()"
1032
   *
1033
   * @see Arrayy::randomImmutable()
1034
   *
1035
   * @return Arrayy (Immutable)
1036
   */
1037 3
  public function getRandom()
1038
  {
1039 3
    return $this->randomImmutable();
1040
  }
1041
1042
  /**
1043
   * alias: for "Arrayy->randomKey()"
1044
   *
1045
   * @see Arrayy::randomKey()
1046
   *
1047
   * @return mixed get a key/index or null if there wasn't a key/index
1048
   */
1049 3
  public function getRandomKey()
1050
  {
1051 3
    return $this->randomKey();
1052
  }
1053
1054
  /**
1055
   * alias: for "Arrayy->randomKeys()"
1056
   *
1057
   * @see Arrayy::randomKeys()
1058
   *
1059
   * @param int $number
1060
   *
1061
   * @return Arrayy (Immutable)
1062
   */
1063 9
  public function getRandomKeys($number)
1064
  {
1065 9
    return $this->randomKeys($number);
1066
  }
1067
1068
  /**
1069
   * alias: for "Arrayy->randomValue()"
1070
   *
1071
   * @see Arrayy::randomValue()
1072
   *
1073
   * @return mixed get a random value or null if there wasn't a value
1074
   */
1075 3
  public function getRandomValue()
1076
  {
1077 3
    return $this->randomValue();
1078
  }
1079
1080
  /**
1081
   * alias: for "Arrayy->randomValues()"
1082
   *
1083
   * @see Arrayy::randomValues()
1084
   *
1085
   * @param int $number
1086
   *
1087
   * @return Arrayy (Immutable)
1088
   */
1089 6
  public function getRandomValues($number)
1090
  {
1091 6
    return $this->randomValues($number);
1092
  }
1093
1094
  /**
1095
   * Group values from a array according to the results of a closure.
1096
   *
1097
   * @param string $grouper a callable function name
1098
   * @param bool   $saveKeys
1099
   *
1100
   * @return Arrayy (Immutable)
1101
   */
1102 3
  public function group($grouper, $saveKeys = false)
1103
  {
1104 3
    $array = (array)$this->array;
1105 3
    $result = array();
1106
1107
    // Iterate over values, group by property/results from closure
1108 3
    foreach ($array as $key => $value) {
1109 3
      $groupKey = is_callable($grouper) ? $grouper($value, $key) : $this->get($grouper, null, $value);
1110 3
      $newValue = $this->get($groupKey, null, $result);
1111
1112
      // Add to results
1113 3
      if ($groupKey !== null) {
1114 2
        if ($saveKeys) {
1115 1
          $result[$groupKey] = $newValue;
1116 1
          $result[$groupKey][$key] = $value;
1117 1
        } else {
1118 1
          $result[$groupKey] = $newValue;
1119 1
          $result[$groupKey][] = $value;
1120
        }
1121 2
      }
1122
1123 3
    }
1124
1125 3
    return static::create($result);
1126
  }
1127
1128
  /**
1129
   * Check if an array has a given key.
1130
   *
1131
   * @param mixed $key
1132
   *
1133
   * @return bool
1134
   */
1135 19
  public function has($key)
1136
  {
1137
    // Generate unique string to use as marker.
1138 19
    $unFound = (string)uniqid('arrayy', true);
1139
1140 19
    return $this->get($key, $unFound) !== $unFound;
1141
  }
1142
1143
  /**
1144
   * Implodes an array.
1145
   *
1146
   * @param string $with What to implode it with
1147
   *
1148
   * @return string
1149
   */
1150 27
  public function implode($with = '')
1151
  {
1152 27
    return implode($with, $this->array);
1153
  }
1154
1155
  /**
1156
   * Given a list and an iterate-function that returns
1157
   * a key for each element in the list (or a property name),
1158
   * returns an object with an index of each item.
1159
   *
1160
   * Just like groupBy, but for when you know your keys are unique.
1161
   *
1162
   * @param mixed $key
1163
   *
1164
   * @return Arrayy (Immutable)
1165
   */
1166 3
  public function indexBy($key)
1167
  {
1168 3
    $results = array();
1169
1170 3
    foreach ($this->array as $a) {
1171 3
      if (isset($a[$key])) {
1172 2
        $results[$a[$key]] = $a;
1173 2
      }
1174 3
    }
1175
1176 3
    return static::create($results);
1177
  }
1178
1179
  /**
1180
   * alias: for "Arrayy->searchIndex()"
1181
   *
1182
   * @see Arrayy::searchIndex()
1183
   *
1184
   * @param mixed $value Value to search for
1185
   *
1186
   * @return mixed
1187
   */
1188 4
  public function indexOf($value)
1189
  {
1190 4
    return $this->searchIndex($value);
1191
  }
1192
1193
  /**
1194
   * Get everything but the last..$to items.
1195
   *
1196
   * @param int $to
1197
   *
1198
   * @return Arrayy (Immutable)
1199
   */
1200 12
  public function initial($to = 1)
1201
  {
1202 12
    $slice = count($this->array) - $to;
1203
1204 12
    return $this->firstsImmutable($slice);
1205
  }
1206
1207
  /**
1208
   * Internal mechanics of remove method.
1209
   *
1210
   * @param $key
1211
   *
1212
   * @return boolean
1213
   */
1214 18
  protected function internalRemove($key)
1215
  {
1216
    // Explode keys
1217 18
    $keys = explode('.', $key);
1218
1219
    // Crawl though the keys
1220 18
    while (count($keys) > 1) {
1221
      $key = array_shift($keys);
1222
1223
      if (!$this->has($key)) {
1224
        return false;
1225
      }
1226
1227
      $this->array = &$this->array[$key];
1228
    }
1229
1230 18
    $key = array_shift($keys);
1231
1232 18
    unset($this->array[$key]);
1233
1234 18
    return true;
1235
  }
1236
1237
  /**
1238
   * Internal mechanic of set method.
1239
   *
1240
   * @param string $key
1241
   * @param mixed  $value
1242
   *
1243
   * @return bool
1244
   */
1245 17
  protected function internalSet($key, $value)
1246
  {
1247 17
    if (null === $key) {
1248
      return false;
1249
    }
1250
1251
    // init
1252 17
    $array = &$this->array;
1253
1254
    // Explode the keys
1255 17
    $keys = explode('.', $key);
1256
1257
    // Crawl through the keys
1258 17
    while (count($keys) > 1) {
1259 1
      $key = array_shift($keys);
1260
      // If the key doesn't exist at this depth, we will just create an empty array
1261
      // to hold the next value, allowing us to create the arrays to hold final
1262
      // values at the correct depth. Then we'll keep digging into the array.
1263 1
      if (!isset($array[$key]) || !is_array($array[$key])) {
1264
        $array[$key] = array();
1265
      }
1266 1
      $array = &$array[$key];
1267 1
    }
1268
1269 17
    $array[array_shift($keys)] = $value;
1270
1271 17
    return true;
1272
  }
1273
1274
  /**
1275
   * Return an array with all elements found in input array.
1276
   *
1277
   * @param array $search
1278
   *
1279
   * @return Arrayy (Immutable)
1280
   */
1281 2
  public function intersection(array $search)
1282
  {
1283 2
    return static::create(array_values(array_intersect($this->array, $search)));
1284
  }
1285
1286
  /** @noinspection ArrayTypeOfParameterByDefaultValueInspection */
1287
1288
  /**
1289
   * Return a boolean flag which indicates whether the two input arrays have any common elements.
1290
   *
1291
   * @param array $search
1292
   *
1293
   * @return bool
1294
   */
1295 1
  public function intersects(array $search)
1296
  {
1297 1
    return count($this->intersection($search)->array) > 0;
1298
  }
1299
1300
  /**
1301
   * Invoke a function on all of an array's values.
1302
   *
1303
   * @param mixed $callable
1304
   * @param mixed $arguments
1305
   *
1306
   * @return Arrayy (Immutable)
1307
   */
1308 1
  public function invoke($callable, $arguments = array())
1309
  {
1310
    // If one argument given for each iteration, create an array for it.
1311 1
    if (!is_array($arguments)) {
1312 1
      $arguments = StaticArrayy::repeat($arguments, count($this->array))->getArray();
1313 1
    }
1314
1315
    // If the callable has arguments, pass them.
1316 1
    if ($arguments) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $arguments of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1317 1
      $array = array_map($callable, $this->array, $arguments);
1318 1
    } else {
1319 1
      $array = array_map($callable, $this->array);
1320
    }
1321
1322 1
    return static::create($array);
1323
  }
1324
1325
  /**
1326
   * Check whether array is associative or not.
1327
   *
1328
   * @return bool Returns true if associative, false otherwise
1329
   */
1330 15
  public function isAssoc()
1331
  {
1332 15
    if ($this->isEmpty()) {
1333 3
      return false;
1334
    }
1335
1336 13
    foreach ($this->keys()->getArray() as $key) {
1337 13
      if (!is_string($key)) {
1338 11
        return false;
1339
      }
1340 3
    }
1341
1342 3
    return true;
1343
  }
1344
1345
  /**
1346
   * Check whether the array is empty or not.
1347
   *
1348
   * @return bool Returns true if empty, false otherwise
1349
   */
1350 25
  public function isEmpty()
1351
  {
1352 25
    return !$this->array;
1353
  }
1354
1355
  /**
1356
   * Check if the current array is equal to the given "$array" or not.
1357
   *
1358
   * @param array $array
1359
   *
1360
   * @return bool
1361
   */
1362
  public function isEqual(array $array)
1363
  {
1364
    return ($this->array === $array);
1365
  }
1366
1367
  /**
1368
   * Check if the current array is a multi-array.
1369
   *
1370
   * @return bool
1371
   */
1372 14
  public function isMultiArray()
1373
  {
1374 14
    return !(count($this->array) === count($this->array, COUNT_RECURSIVE));
1375
  }
1376
1377
  /**
1378
   * Check whether array is numeric or not.
1379
   *
1380
   * @return bool Returns true if numeric, false otherwise
1381
   */
1382 5
  public function isNumeric()
1383
  {
1384 5
    if ($this->isEmpty()) {
1385 2
      return false;
1386
    }
1387
1388 4
    foreach ($this->keys() as $key) {
1389 4
      if (!is_int($key)) {
1390 2
        return false;
1391
      }
1392 3
    }
1393
1394 2
    return true;
1395
  }
1396
1397
  /**
1398
   * Check if the current array is sequential [0, 1, 2, 3, 4, 5 ...] or not.
1399
   *
1400
   * @return bool
1401
   */
1402 1
  public function isSequential()
1403
  {
1404 1
    return array_keys($this->array) === range(0, count($this->array) - 1);
1405
  }
1406
1407
  /**
1408
   * Get all keys from the current array.
1409
   *
1410
   * @return Arrayy (Immutable)
1411
   */
1412 24
  public function keys()
1413
  {
1414 24
    return static::create(array_keys((array)$this->array));
1415
  }
1416
1417
  /**
1418
   * Get the last value from the current array.
1419
   *
1420
   * @return mixed Return null if there wasn't a element.
1421
   */
1422 4
  public function last()
1423
  {
1424 4
    $result = $this->pop();
1425
1426 4
    if (null === $result) {
1427 1
      return null;
1428
    } else {
1429 3
      return $result;
1430
    }
1431
  }
1432
1433
  /**
1434
   * Get the last value(s) from the current array.
1435
   *
1436
   * @param int|null $number
1437
   *
1438
   * @return Arrayy (Immutable)
1439
   */
1440 12
  public function lastsImmutable($number = null)
1441
  {
1442 12
    if ($number === null) {
1443 8
      $poppedValue = (array)$this->pop();
1444 8
      $arrayy = static::create($poppedValue);
1445 8
    } else {
1446 4
      $number = (int)$number;
1447 4
      $arrayy = $this->rest(-$number);
1448
    }
1449
1450 12
    return $arrayy;
1451
  }
1452
1453
  /**
1454
   * Get the last value(s) from the current array.
1455
   *
1456
   * @param int|null $number
1457
   *
1458
   * @return self (Mutable)
1459
   */
1460 12
  public function lastsMutable($number = null)
1461
  {
1462 12
    if ($number === null) {
1463 8
      $poppedValue = (array)$this->pop();
1464 8
      $this->array = static::create($poppedValue)->array;
1465 8
    } else {
1466 4
      $number = (int)$number;
1467 4
      $this->array = $this->rest(-$number)->array;
1468
    }
1469
1470 12
    return $this;
1471
  }
1472
1473
  /**
1474
   * Count the values from the current array.
1475
   *
1476
   * alias: for "Arrayy->size()"
1477
   *
1478
   * @see Arrayy::size()
1479
   *
1480
   * @return int
1481
   */
1482 10
  public function length()
1483
  {
1484 10
    return $this->size();
1485
  }
1486
1487
  /**
1488
   * Apply the given function to the every element of the array,
1489
   * collecting the results.
1490
   *
1491
   * @param callable $callable
1492
   *
1493
   * @return Arrayy (Immutable) Arrayy object with modified elements
1494
   */
1495 4
  public function map($callable)
1496
  {
1497 4
    $result = array_map($callable, $this->array);
1498
1499 4
    return static::create($result);
1500
  }
1501
1502
  /**
1503
   * Check if all items in current array match a truth test.
1504
   *
1505
   * @param \Closure $closure
1506
   *
1507
   * @return bool
1508
   */
1509 9 View Code Duplication
  public function matches(\Closure $closure)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1510
  {
1511
    // Reduce the array to only booleans
1512 9
    $array = $this->each($closure);
1513
1514
    // Check the results
1515 9
    if (count($array) === 0) {
1516 2
      return true;
1517
    }
1518
1519 7
    $array = array_search(false, $array->toArray(), false);
1520
1521 7
    return is_bool($array);
1522
  }
1523
1524
  /**
1525
   * Check if any item in the current array matches a truth test.
1526
   *
1527
   * @param \Closure $closure
1528
   *
1529
   * @return bool
1530
   */
1531 9 View Code Duplication
  public function matchesAny(\Closure $closure)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1532
  {
1533
    // Reduce the array to only booleans
1534 9
    $array = $this->each($closure);
1535
1536
    // Check the results
1537 9
    if (count($array) === 0) {
1538 2
      return true;
1539
    }
1540
1541 7
    $array = array_search(true, $array->toArray(), false);
1542
1543 7
    return is_int($array);
1544
  }
1545
1546
  /**
1547
   * Get the max value from an array.
1548
   *
1549
   * @return mixed
1550
   */
1551 10
  public function max()
1552
  {
1553 10
    if ($this->count() === 0) {
1554 1
      return false;
1555
    }
1556
1557 9
    return max($this->array);
1558
  }
1559
1560
  /**
1561
   * Merge the new $array into the current array.
1562
   *
1563
   * - keep key,value from the current array, also if the index is in the new $array
1564
   *
1565
   * @param array $array
1566
   * @param bool  $recursive
1567
   *
1568
   * @return Arrayy (Immutable)
1569
   */
1570 25 View Code Duplication
  public function mergeAppendKeepIndex(array $array = array(), $recursive = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1571
  {
1572 25
    if (true === $recursive) {
1573 4
      $result = array_replace_recursive($this->array, $array);
1574 4
    } else {
1575 21
      $result = array_replace($this->array, $array);
1576
    }
1577
1578 25
    return static::create($result);
1579
  }
1580
1581
  /**
1582
   * Merge the new $array into the current array.
1583
   *
1584
   * - replace duplicate assoc-keys from the current array with the key,values from the new $array
1585
   * - create new indexes
1586
   *
1587
   * @param array $array
1588
   * @param bool  $recursive
1589
   *
1590
   * @return Arrayy (Immutable)
1591
   */
1592 16 View Code Duplication
  public function mergeAppendNewIndex(array $array = array(), $recursive = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1593
  {
1594 16
    if (true === $recursive) {
1595 4
      $result = array_merge_recursive($this->array, $array);
1596 4
    } else {
1597 12
      $result = array_merge($this->array, $array);
1598
    }
1599
1600 16
    return static::create($result);
1601
  }
1602
1603
  /**
1604
   * Merge the the current array into the $array.
1605
   *
1606
   * - use key,value from the new $array, also if the index is in the current array
1607
   *
1608
   * @param array $array
1609
   * @param bool  $recursive
1610
   *
1611
   * @return Arrayy (Immutable)
1612
   */
1613 16 View Code Duplication
  public function mergePrependKeepIndex(array $array = array(), $recursive = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1614
  {
1615 16
    if (true === $recursive) {
1616 4
      $result = array_replace_recursive($array, $this->array);
1617 4
    } else {
1618 12
      $result = array_replace($array, $this->array);
1619
    }
1620
1621 16
    return static::create($result);
1622
  }
1623
1624
  /**
1625
   * Merge the current array into the new $array.
1626
   *
1627
   * - replace duplicate assoc-keys from new $array with the key,values from the current array
1628
   * - create new indexes
1629
   *
1630
   * @param array $array
1631
   * @param bool  $recursive
1632
   *
1633
   * @return Arrayy (Immutable)
1634
   */
1635 16 View Code Duplication
  public function mergePrependNewIndex(array $array = array(), $recursive = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1636
  {
1637 16
    if (true === $recursive) {
1638 4
      $result = array_merge_recursive($array, $this->array);
1639 4
    } else {
1640 12
      $result = array_merge($array, $this->array);
1641
    }
1642
1643 16
    return static::create($result);
1644
  }
1645
1646
  /**
1647
   * Get the min value from an array.
1648
   *
1649
   * @return mixed
1650
   */
1651 10
  public function min()
1652
  {
1653 10
    if ($this->count() === 0) {
1654 1
      return false;
1655
    }
1656
1657 9
    return min($this->array);
1658
  }
1659
1660
  /**
1661
   * Get a subset of the items from the given array.
1662
   *
1663
   * @param mixed[] $keys
1664
   *
1665
   * @return Arrayy (Immutable)
1666
   */
1667
  public function only(array $keys)
1668
  {
1669
    $array = $this->array;
1670
1671
    return static::create(array_intersect_key($array, array_flip($keys)));
1672
  }
1673
1674
  /**
1675
   * Pad array to the specified size with a given value.
1676
   *
1677
   * @param int   $size  Size of the result array
1678
   * @param mixed $value Empty value by default
1679
   *
1680
   * @return Arrayy (Immutable) Arrayy object padded to $size with $value
1681
   */
1682 4
  public function pad($size, $value)
1683
  {
1684 4
    $result = array_pad($this->array, $size, $value);
1685
1686 4
    return static::create($result);
1687
  }
1688
1689
  /**
1690
   * Pop a specified value off the end of the current array.
1691
   *
1692
   * @return mixed The popped element from the current array.
1693
   */
1694 16
  public function pop()
1695
  {
1696 16
    return array_pop($this->array);
1697
  }
1698
1699
  /**
1700
   * Prepend a value to the current array.
1701
   *
1702
   * @param mixed $value
1703
   * @param mixed $key
1704
   *
1705
   * @return self (Mutable) Return this Arrayy object, with the prepended value.
1706
   */
1707 8
  public function prepend($value, $key = null)
1708
  {
1709 8
    if ($key === null) {
1710 8
      array_unshift($this->array, $value);
1711 8
    } else {
1712
      /** @noinspection AdditionOperationOnArraysInspection */
1713 1
      $this->array = array($key => $value) + $this->array;
1714
    }
1715
1716 8
    return $this;
1717
  }
1718
1719
  /**
1720
   * Push one or more values onto the end of array at once.
1721
   *
1722
   * @return self (Mutable) Return this Arrayy object, with pushed elements to the end of array.
1723
   */
1724 4 View Code Duplication
  public function push(/* variadic arguments allowed */)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1725
  {
1726 4
    if (func_num_args()) {
1727 4
      $args = array_merge(array(&$this->array), func_get_args());
1728 4
      call_user_func_array('array_push', $args);
1729 4
    }
1730
1731 4
    return $this;
1732
  }
1733
1734
  /**
1735
   * Get a random value from the current array.
1736
   *
1737
   * @param null|int $number how many values you will take?
1738
   *
1739
   * @return Arrayy (Immutable)
1740
   */
1741 17
  public function randomImmutable($number = null)
1742
  {
1743 17
    if ($this->count() === 0) {
1744
      return static::create();
1745
    }
1746
1747 17 View Code Duplication
    if ($number === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1748 14
      $arrayRandValue = (array)$this->array[array_rand($this->array)];
1749
1750 14
      return static::create($arrayRandValue);
1751
    }
1752
1753 5
    $arrayTmp = $this->array;
1754 5
    shuffle($arrayTmp);
1755
1756 5
    return self::create($arrayTmp)->firstsImmutable($number);
1757
  }
1758
1759
  /**
1760
   * Pick a random key/index from the keys of this array.
1761
   *
1762
   *
1763
   * @return mixed get a key/index or null if there wasn't a key/index
1764
   *
1765
   * @throws \RangeException If array is empty
1766
   */
1767 4
  public function randomKey()
1768
  {
1769 4
    $result = $this->randomKeys(1);
1770
1771 4
    if (!isset($result[0])) {
1772
      $result[0] = null;
1773
    }
1774
1775 4
    return $result[0];
1776
  }
1777
1778
  /**
1779
   * Pick a given number of random keys/indexes out of this array.
1780
   *
1781
   * @param int $number The number of keys/indexes (should be <= $this->count())
1782
   *
1783
   * @return Arrayy (Immutable)
1784
   *
1785
   * @throws \RangeException If array is empty
1786
   */
1787 14
  public function randomKeys($number)
1788
  {
1789 14
    $number = (int)$number;
1790 14
    $count = $this->count();
1791
1792 14
    if ($number === 0 || $number > $count) {
1793 3
      throw new \RangeException(
1794 3
          sprintf(
1795 3
              'Number of requested keys (%s) must be equal or lower than number of elements in this array (%s)',
1796 3
              $number,
1797
              $count
1798 3
          )
1799 3
      );
1800
    }
1801
1802 11
    $result = (array)array_rand($this->array, $number);
1803
1804 11
    return static::create($result);
1805
  }
1806
1807
  /**
1808
   * Get a random value from the current array.
1809
   *
1810
   * @param null|int $number how many values you will take?
1811
   *
1812
   * @return Arrayy (Mutable)
1813
   */
1814 16
  public function randomMutable($number = null)
1815
  {
1816 16
    if ($this->count() === 0) {
1817
      return static::create();
1818
    }
1819
1820 16 View Code Duplication
    if ($number === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1821 6
      $arrayRandValue = (array)$this->array[array_rand($this->array)];
1822 6
      $this->array = $arrayRandValue;
1823
1824 6
      return $this;
1825
    }
1826
1827 11
    shuffle($this->array);
1828
1829 11
    return $this->firstsMutable($number);
1830
  }
1831
1832
  /**
1833
   * Pick a random value from the values of this array.
1834
   *
1835
   * @return mixed get a random value or null if there wasn't a value
1836
   */
1837 4
  public function randomValue()
1838
  {
1839 4
    $result = $this->randomImmutable();
1840
1841 4
    if (!isset($result[0])) {
1842
      $result[0] = null;
1843
    }
1844
1845 4
    return $result[0];
1846
  }
1847
1848
  /**
1849
   * Pick a given number of random values out of this array.
1850
   *
1851
   * @param int $number
1852
   *
1853
   * @return Arrayy (Mutable)
1854
   */
1855 7
  public function randomValues($number)
1856
  {
1857 7
    $number = (int)$number;
1858
1859 7
    return $this->randomMutable($number);
1860
  }
1861
1862
  /**
1863
   * Get a random value from an array, with the ability to skew the results.
1864
   *
1865
   * Example: randomWeighted(['foo' => 1, 'bar' => 2]) has a 66% chance of returning bar.
1866
   *
1867
   * @param array    $array
1868
   * @param null|int $number how many values you will take?
1869
   *
1870
   * @return Arrayy (Immutable)
1871
   */
1872 9
  public function randomWeighted(array $array, $number = null)
1873
  {
1874 9
    $options = array();
1875 9
    foreach ($array as $option => $weight) {
1876 9
      if ($this->searchIndex($option) !== false) {
1877 2
        for ($i = 0; $i < $weight; ++$i) {
1878 1
          $options[] = $option;
1879 1
        }
1880 2
      }
1881 9
    }
1882
1883 9
    return $this->mergeAppendKeepIndex($options)->randomImmutable($number);
1884
  }
1885
1886
  /**
1887
   * Reduce the current array via callable e.g. anonymous-function.
1888
   *
1889
   * @param mixed $callable
1890
   * @param array $init
1891
   *
1892
   * @return Arrayy (Immutable)
1893
   */
1894 3
  public function reduce($callable, array $init = array())
1895
  {
1896 3
    $result = array_reduce($this->array, $callable, $init);
1897
1898 3
    if ($result === null) {
1899
      $this->array = array();
1900
    } else {
1901 3
      $this->array = (array)$result;
1902
    }
1903
1904 3
    return static::create($this->array);
1905
  }
1906
1907
  /**
1908
   * Create a numerically re-indexed Arrayy object.
1909
   *
1910
   * @return self (Mutable) Return this Arrayy object, with re-indexed array-elements.
1911
   */
1912 9
  public function reindex()
1913
  {
1914 9
    $this->array = array_values($this->array);
1915
1916 9
    return $this;
1917
  }
1918
1919
  /**
1920
   * Return all items that fail the truth test.
1921
   *
1922
   * @param \Closure $closure
1923
   *
1924
   * @return Arrayy (Immutable)
1925
   */
1926 1 View Code Duplication
  public function reject(\Closure $closure)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1927
  {
1928 1
    $filtered = array();
1929
1930 1
    foreach ($this->array as $key => $value) {
1931 1
      if (!$closure($value, $key)) {
1932 1
        $filtered[$key] = $value;
1933 1
      }
1934 1
    }
1935
1936 1
    return static::create($filtered);
1937
  }
1938
1939
  /**
1940
   * Remove a value from the current array (optional using dot-notation).
1941
   *
1942
   * @param mixed $key
1943
   *
1944
   * @return Arrayy (Immutable)
1945
   */
1946 18
  public function remove($key)
1947
  {
1948
    // Recursive call
1949 18
    if (is_array($key)) {
1950
      foreach ($key as $k) {
1951
        $this->internalRemove($k);
1952
      }
1953
1954
      return static::create($this->array);
1955
    }
1956
1957 18
    $this->internalRemove($key);
1958
1959 18
    return static::create($this->array);
1960
  }
1961
1962
  /**
1963
   * Remove the first value from the current array.
1964
   *
1965
   * @return Arrayy (Immutable)
1966
   */
1967 7
  public function removeFirst()
1968
  {
1969 7
    array_shift($this->array);
1970
1971 7
    return static::create($this->array);
1972
  }
1973
1974
  /**
1975
   * Remove the last value from the current array.
1976
   *
1977
   * @return Arrayy (Immutable)
1978
   */
1979 7
  public function removeLast()
1980
  {
1981 7
    array_pop($this->array);
1982
1983 7
    return static::create($this->array);
1984
  }
1985
1986
  /**
1987
   * Removes a particular value from an array (numeric or associative).
1988
   *
1989
   * @param mixed $value
1990
   *
1991
   * @return Arrayy (Immutable)
1992
   */
1993 7
  public function removeValue($value)
1994
  {
1995 7
    $isNumericArray = true;
1996 7
    foreach ($this->array as $key => $item) {
1997 6
      if ($item === $value) {
1998 6
        if (!is_int($key)) {
1999
          $isNumericArray = false;
2000
        }
2001 6
        unset($this->array[$key]);
2002 6
      }
2003 7
    }
2004
2005 7
    if ($isNumericArray) {
2006 7
      $this->array = array_values($this->array);
2007 7
    }
2008
2009 7
    return static::create($this->array);
2010
  }
2011
2012
  /**
2013
   * Replace a key with a new key/value pair.
2014
   *
2015
   * @param $replace
2016
   * @param $key
2017
   * @param $value
2018
   *
2019
   * @return Arrayy (Immutable)
2020
   */
2021 2
  public function replace($replace, $key, $value)
2022
  {
2023 2
    $this->remove($replace);
2024
2025 2
    return $this->set($key, $value);
2026
  }
2027
2028
  /**
2029
   * Create an array using the current array as values and the other array as keys.
2030
   *
2031
   * @param array $keys Keys array
2032
   *
2033
   * @return Arrayy (Immutable) Arrayy object with keys from the other array.
2034
   */
2035 2
  public function replaceAllKeys(array $keys)
2036
  {
2037 2
    $result = array_combine($keys, $this->array);
2038
2039 2
    return static::create($result);
2040
  }
2041
2042
  /**
2043
   * Create an array using the current array as keys and the other array as values.
2044
   *
2045
   * @param array $array Values array
2046
   *
2047
   * @return Arrayy (Immutable) Arrayy object with values from the other array.
2048
   */
2049 2
  public function replaceAllValues(array $array)
2050
  {
2051 2
    $result = array_combine($this->array, $array);
2052
2053 2
    return static::create($result);
2054
  }
2055
2056
  /**
2057
   * Replace the keys in an array with another set.
2058
   *
2059
   * @param array $keys An array of keys matching the array's size
2060
   *
2061
   * @return Arrayy (Immutable)
2062
   */
2063 1
  public function replaceKeys(array $keys)
2064
  {
2065 1
    $values = array_values($this->array);
2066 1
    $result = array_combine($keys, $values);
2067
2068 1
    return static::create($result);
2069
  }
2070
2071
  /**
2072
   * Replace the first matched value in an array.
2073
   *
2074
   * @param mixed $search
2075
   * @param mixed $replacement
2076
   *
2077
   * @return Arrayy (Immutable)
2078
   */
2079 3
  public function replaceOneValue($search, $replacement = '')
2080
  {
2081 3
    $array = $this->array;
2082 3
    $key = array_search($search, $array, true);
2083
2084 3
    if ($key !== false) {
2085 3
      $array[$key] = $replacement;
2086 3
    }
2087
2088 3
    return static::create($array);
2089
  }
2090
2091
  /**
2092
   * Replace values in the current array.
2093
   *
2094
   * @param string $search      The string to replace.
2095
   * @param string $replacement What to replace it with.
2096
   *
2097
   * @return Arrayy (Immutable)
2098
   */
2099 1
  public function replaceValues($search, $replacement = '')
2100
  {
2101 1
    $array = $this->each(
2102
        function ($value) use ($search, $replacement) {
2103 1
          return UTF8::str_replace($search, $replacement, $value);
2104
        }
2105 1
    );
2106
2107 1
    return $array;
2108
  }
2109
2110
  /**
2111
   * Get the last elements from index $from until the end of this array.
2112
   *
2113
   * @param int $from
2114
   *
2115
   * @return Arrayy (Immutable)
2116
   */
2117 15
  public function rest($from = 1)
2118
  {
2119 15
    $result = array_splice($this->array, $from);
2120
2121 15
    return static::create($result);
2122
  }
2123
2124
  /**
2125
   * Return the array in the reverse order.
2126
   *
2127
   * @return self (Mutable) Return this Arrayy object.
2128
   */
2129 7
  public function reverse()
2130
  {
2131 7
    $this->array = array_reverse($this->array);
2132
2133 7
    return $this;
2134
  }
2135
2136
  /**
2137
   * Search for the first index of the current array via $value.
2138
   *
2139
   * @param mixed $value
2140
   *
2141
   * @return mixed
2142
   */
2143 20
  public function searchIndex($value)
2144
  {
2145 20
    return array_search($value, $this->array, true);
2146
  }
2147
2148
  /**
2149
   * Search for the value of the current array via $index.
2150
   *
2151
   * @param mixed $index
2152
   *
2153
   * @return Arrayy (Immutable) will return a empty Arrayy if the value wasn't found
2154
   */
2155 7
  public function searchValue($index)
2156
  {
2157
    // init
2158 7
    $return = array();
2159
2160 7
    if (null !== $index) {
2161 7
      $keyExists = isset($this->array[$index]);
2162
2163 7
      if ($keyExists !== false) {
2164 5
        $return = array($this->array[$index]);
2165 5
      }
2166 7
    }
2167
2168 7
    return static::create($return);
2169
  }
2170
2171
  /**
2172
   * Set a value for the current array (optional using dot-notation).
2173
   *
2174
   * @param string $key   The key to set
2175
   * @param mixed  $value Its value
2176
   *
2177
   * @return Arrayy (Immutable)
2178
   */
2179 17
  public function set($key, $value)
2180
  {
2181 17
    $this->internalSet($key, $value);
2182
2183 17
    return static::create($this->array);
2184
  }
2185
2186
  /**
2187
   * Get a value from a array and set it if it was not.
2188
   *
2189
   * WARNING: this method only set the value, if the $key is not already set
2190
   *
2191
   * @param string $key      The key
2192
   * @param mixed  $fallback The default value to set if it isn't
2193
   *
2194
   * @return mixed (Mutable)
2195
   */
2196 10
  public function setAndGet($key, $fallback = null)
2197
  {
2198
    // If the key doesn't exist, set it
2199 10
    if (!$this->has($key)) {
2200 5
      $this->array = $this->set($key, $fallback)->getArray();
2201 5
    }
2202
2203 10
    return $this->get($key);
2204
  }
2205
2206
  /**
2207
   * Shifts a specified value off the beginning of array.
2208
   *
2209
   * @return mixed A shifted element from the current array.
2210
   */
2211 4
  public function shift()
2212
  {
2213 4
    return array_shift($this->array);
2214
  }
2215
2216
  /**
2217
   * Shuffle the current array.
2218
   *
2219
   * @return Arrayy (Immutable)
2220
   */
2221 1
  public function shuffle()
2222
  {
2223 1
    $array = $this->array;
2224
2225 1
    shuffle($array);
2226
2227 1
    return static::create($array);
2228
  }
2229
2230
  /**
2231
   * Get the size of an array.
2232
   *
2233
   * @return int
2234
   */
2235 110
  public function size()
2236
  {
2237 110
    return count($this->array);
2238
  }
2239
2240
  /**
2241
   * Extract a slice of the array.
2242
   *
2243
   * @param int      $offset       Slice begin index
2244
   * @param int|null $length       Length of the slice
2245
   * @param bool     $preserveKeys Whether array keys are preserved or no
2246
   *
2247
   * @return static A slice of the original array with length $length
2248
   */
2249 4
  public function slice($offset, $length = null, $preserveKeys = false)
2250
  {
2251 4
    $result = array_slice($this->array, $offset, $length, $preserveKeys);
2252
2253 4
    return static::create($result);
2254
  }
2255
2256
  /**
2257
   * Sort the current array and optional you can keep the keys.
2258
   *
2259
   * @param integer $direction use SORT_ASC or SORT_DESC
2260
   * @param integer $strategy
2261
   * @param bool    $keepKeys
2262
   *
2263
   * @return self (Mutable) Return this Arrayy object.
2264
   */
2265 19
  public function sort($direction = SORT_ASC, $strategy = SORT_REGULAR, $keepKeys = false)
2266
  {
2267 19
    $this->sorting($this->array, $direction, $strategy, $keepKeys);
2268
2269 19
    return $this;
2270
  }
2271
2272
  /**
2273
   * Sort the current array by key.
2274
   *
2275
   * @link http://php.net/manual/en/function.ksort.php
2276
   * @link http://php.net/manual/en/function.krsort.php
2277
   *
2278
   * @param int|string $direction use SORT_ASC or SORT_DESC
2279
   * @param int        $strategy  use e.g.: SORT_REGULAR or SORT_NATURAL
2280
   *
2281
   * @return self (Mutable) Return this Arrayy object.
2282
   */
2283 18
  public function sortKeys($direction = SORT_ASC, $strategy = SORT_REGULAR)
2284
  {
2285 18
    $this->sorterKeys($this->array, $direction, $strategy);
2286
2287 18
    return $this;
2288
  }
2289
2290
  /**
2291
   * Sort the current array by value.
2292
   *
2293
   * @param int $direction use SORT_ASC or SORT_DESC
2294
   * @param int $strategy  use e.g.: SORT_REGULAR or SORT_NATURAL
2295
   *
2296
   * @return Arrayy (Immutable)
2297
   */
2298 1
  public function sortValueKeepIndex($direction = SORT_ASC, $strategy = SORT_REGULAR)
2299
  {
2300 1
    return $this->sort($direction, $strategy, true);
2301
  }
2302
2303
  /**
2304
   * Sort the current array by value.
2305
   *
2306
   * @param int $direction use SORT_ASC or SORT_DESC
2307
   * @param int $strategy  use e.g.: SORT_REGULAR or SORT_NATURAL
2308
   *
2309
   * @return Arrayy (Immutable)
2310
   */
2311 1
  public function sortValueNewIndex($direction = SORT_ASC, $strategy = SORT_REGULAR)
2312
  {
2313 1
    return $this->sort($direction, $strategy, false);
2314
  }
2315
2316
  /**
2317
   * Sort a array by value, by a closure or by a property.
2318
   *
2319
   * - If the sorter is null, the array is sorted naturally.
2320
   * - Associative (string) keys will be maintained, but numeric keys will be re-indexed.
2321
   *
2322
   * @param null       $sorter
2323
   * @param string|int $direction
2324
   * @param int        $strategy
2325
   *
2326
   * @return Arrayy (Immutable)
2327
   */
2328 1
  public function sorter($sorter = null, $direction = SORT_ASC, $strategy = SORT_REGULAR)
2329
  {
2330 1
    $array = (array)$this->array;
2331 1
    $direction = $this->getDirection($direction);
2332
2333
    // Transform all values into their results.
2334 1
    if ($sorter) {
2335 1
      $arrayy = new self($array);
2336
2337 1
      $that = $this;
2338 1
      $results = $arrayy->each(
2339
          function ($value) use ($sorter, $that) {
2340 1
            return is_callable($sorter) ? $sorter($value) : $that->get($sorter, null, $value);
2341
          }
2342 1
      );
2343
2344 1
      $results = $results->getArray();
2345 1
    } else {
2346 1
      $results = $array;
2347
    }
2348
2349
    // Sort by the results and replace by original values
2350 1
    array_multisort($results, $direction, $strategy, $array);
2351
2352 1
    return static::create($array);
2353
  }
2354
2355
  /**
2356
   * sorting keys
2357
   *
2358
   * @param array $elements
2359
   * @param int   $direction
2360
   * @param int   $strategy
2361
   */
2362 18
  protected function sorterKeys(array &$elements, $direction = SORT_ASC, $strategy = SORT_REGULAR)
2363
  {
2364 18
    $direction = $this->getDirection($direction);
2365
2366
    switch ($direction) {
2367 18
      case 'desc':
2368 18
      case SORT_DESC:
2369 6
        krsort($elements, $strategy);
2370 6
        break;
2371 13
      case 'asc':
2372 13
      case SORT_ASC:
2373 13
      default:
2374 13
        ksort($elements, $strategy);
2375 13
    }
2376 18
  }
2377
2378
  /**
2379
   * @param array      &$elements
2380
   * @param int|string $direction
2381
   * @param int        $strategy
2382
   * @param bool       $keepKeys
2383
   */
2384 19
  protected function sorting(array &$elements, $direction = SORT_ASC, $strategy = SORT_REGULAR, $keepKeys = false)
2385
  {
2386 19
    $direction = $this->getDirection($direction);
2387
2388 19
    if (!$strategy) {
2389 19
      $strategy = SORT_REGULAR;
2390 19
    }
2391
2392
    switch ($direction) {
2393 19
      case 'desc':
2394 19
      case SORT_DESC:
2395 9
        if ($keepKeys) {
2396 5
          arsort($elements, $strategy);
2397 5
        } else {
2398 4
          rsort($elements, $strategy);
2399
        }
2400 9
        break;
2401 10
      case 'asc':
2402 10
      case SORT_ASC:
2403 10
      default:
2404 10
        if ($keepKeys) {
2405 4
          asort($elements, $strategy);
2406 4
        } else {
2407 6
          sort($elements, $strategy);
2408
        }
2409 10
    }
2410 19
  }
2411
2412
  /**
2413
   * Split an array in the given amount of pieces.
2414
   *
2415
   * @param int  $numberOfPieces
2416
   * @param bool $keepKeys
2417
   *
2418
   * @return Arrayy (Immutable)
2419
   */
2420 1
  public function split($numberOfPieces = 2, $keepKeys = false)
2421
  {
2422 1
    if (count($this->array) === 0) {
2423 1
      $result = array();
2424 1
    } else {
2425 1
      $numberOfPieces = (int)$numberOfPieces;
2426 1
      $splitSize = ceil(count($this->array) / $numberOfPieces);
2427 1
      $result = array_chunk($this->array, $splitSize, $keepKeys);
2428
    }
2429
2430 1
    return static::create($result);
2431
  }
2432
2433
  /**
2434
   * Stripe all empty items.
2435
   *
2436
   * @return Arrayy (Immutable)
2437
   */
2438 1
  public function stripEmpty()
2439
  {
2440 1
    return $this->filter(
2441
        function ($item) {
2442 1
          if (null === $item) {
2443 1
            return false;
2444
          }
2445
2446 1
          return (bool)trim($item);
2447
        }
2448 1
    );
2449
  }
2450
2451
  /**
2452
   * Swap two values between positions by key.
2453
   *
2454
   * @param string|int $swapA an key in the array
2455
   * @param string|int $swapB an key in the array
2456
   *
2457
   * @return Arrayy (Immutable)
2458
   */
2459 1
  public function swap($swapA, $swapB)
2460
  {
2461 1
    $array = $this->array;
2462
2463 1
    list($array[$swapA], $array[$swapB]) = array($array[$swapB], $array[$swapA]);
2464
2465 1
    return static::create($array);
2466
  }
2467
2468
  /**
2469
   * alias: for "Arrayy->getArray()"
2470
   *
2471
   * @see Arrayy::getArray()
2472
   */
2473 153
  public function toArray()
2474
  {
2475 153
    return $this->getArray();
2476
  }
2477
2478
  /**
2479
   * Convert the current array to JSON.
2480
   *
2481
   * @param null $options e.g. JSON_PRETTY_PRINT
2482
   *
2483
   * @return string
2484
   */
2485 5
  public function toJson($options = null)
2486
  {
2487 5
    return UTF8::json_encode($this->array, $options);
2488
  }
2489
2490
  /**
2491
   * Implodes array to a string with specified separator.
2492
   *
2493
   * @param string $separator The element's separator
2494
   *
2495
   * @return string The string representation of array, separated by ","
2496
   */
2497 19
  public function toString($separator = ',')
2498
  {
2499 19
    return $this->implode($separator);
2500
  }
2501
2502
  /**
2503
   * Return a duplicate free copy of the current array.
2504
   *
2505
   * @return Arrayy (Mutable)
2506
   */
2507 8
  public function unique()
2508
  {
2509 8
    $this->array = array_reduce(
0 ignored issues
show
Documentation Bug introduced by
It seems like array_reduce($this->arra...esultArray; }, array()) of type * is incompatible with the declared type array of property $array.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
2510 8
        $this->array,
2511 8
        function ($resultArray, $value) {
2512 7
          if (in_array($value, $resultArray, true) === false) {
2513 7
            $resultArray[] = $value;
2514 7
          }
2515
2516 7
          return $resultArray;
2517 8
        },
2518 8
        array()
2519 8
    );
2520
2521 8
    if ($this->array === null) {
2522
      $this->array = array();
2523
    } else {
2524 8
      $this->array = (array)$this->array;
2525
    }
2526
2527 8
    return $this;
2528
  }
2529
2530
  /**
2531
   * Prepends one or more values to the beginning of array at once.
2532
   *
2533
   * @return self (Mutable) Return this Arrayy object, with prepended elements to the beginning of array.
2534
   */
2535 4 View Code Duplication
  public function unshift(/* variadic arguments allowed */)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2536
  {
2537 4
    if (func_num_args()) {
2538 4
      $args = array_merge(array(&$this->array), func_get_args());
2539 4
      call_user_func_array('array_unshift', $args);
2540 4
    }
2541
2542 4
    return $this;
2543
  }
2544
2545
  /**
2546
   * Get all values from a array.
2547
   *
2548
   * @return Arrayy (Immutable)
2549
   */
2550 2
  public function values()
2551
  {
2552 2
    return static::create(array_values((array)$this->array));
2553
  }
2554
2555
  /**
2556
   * Apply the given function to every element in the array, discarding the results.
2557
   *
2558
   * @param callable $callable
2559
   * @param bool     $recursive Whether array will be walked recursively or no
2560
   *
2561
   * @return self (Mutable) Return this Arrayy object, with modified elements
2562
   */
2563 9
  public function walk($callable, $recursive = false)
2564
  {
2565 9
    if (true === $recursive) {
2566 4
      array_walk_recursive($this->array, $callable);
2567 4
    } else {
2568 5
      array_walk($this->array, $callable);
2569
    }
2570
2571 9
    return $this;
2572
  }
2573
2574
2575
}
2576