Completed
Pull Request — master (#10)
by Lars
03:38
created

Arrayy::sorting()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 8

Importance

Changes 4
Bugs 1 Features 2
Metric Value
c 4
b 1
f 2
dl 0
loc 27
ccs 21
cts 21
cp 1
rs 5.3846
cc 8
eloc 19
nc 20
nop 4
crap 8
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 701
  public function __construct($array = array())
29
  {
30 701
    $array = $this->fallbackForArray($array);
31
32 699
    $this->array = $array;
0 ignored issues
show
Documentation Bug introduced by
It seems like $array can also be of type object<Arrayy\Arrayy>. However, the property $array is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
33 699
  }
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 15
  public function __toString()
96
  {
97 15
    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
   * @param mixed $value
114
   *
115
   * @return self (Mutable) Return this Arrayy object, with the appended values.
116
   */
117 1
  public function add($value)
118
  {
119 1
    return $this->append($value);
120
  }
121
122
  /**
123
   * Append a value to the current array.
124
   *
125
   * @param mixed $value
126
   *
127
   * @return self (Mutable) Return this Arrayy object, with the appended values.
128
   */
129 9
  public function append($value)
130
  {
131 9
    $this->array[] = $value;
132
133 9
    return $this;
134
  }
135
136
  /**
137
   * Count the values from the current array.
138
   *
139
   * INFO: only a alias for "$arrayy->size()"
140
   *
141
   * @return int
142
   */
143 110
  public function count()
144
  {
145 110
    return $this->size();
146
  }
147
148
  /**
149
   * Returns a new ArrayIterator, thus implementing the IteratorAggregate interface.
150
   *
151
   * @return \ArrayIterator An iterator for the values in the array.
152
   */
153 16
  public function getIterator()
154
  {
155 16
    return new \ArrayIterator($this->array);
156
  }
157
158
  /**
159
   * Whether or not an offset exists.
160
   *
161
   * @param mixed $offset
162
   *
163
   * @return bool
164
   */
165 31
  public function offsetExists($offset)
166
  {
167 31
    return isset($this->array[$offset]);
168
  }
169
170
  /**
171
   * Returns the value at specified offset.
172
   *
173
   * @param mixed $offset
174
   *
175
   * @return mixed return null if the offset did not exists
176
   */
177 22
  public function offsetGet($offset)
178
  {
179 22
    return $this->offsetExists($offset) ? $this->array[$offset] : null;
180
  }
181
182
  /**
183
   * Assigns a value to the specified offset.
184
   *
185
   * @param mixed $offset
186
   * @param mixed $value
187
   */
188 13
  public function offsetSet($offset, $value)
189
  {
190 13
    if (null === $offset) {
191 4
      $this->array[] = $value;
192 4
    } else {
193 9
      $this->array[$offset] = $value;
194
    }
195 13
  }
196
197
  /**
198
   * Unset an offset.
199
   *
200
   * @param mixed $offset
201
   */
202 5
  public function offsetUnset($offset)
203
  {
204 5
    if ($this->offsetExists($offset)) {
205 3
      unset($this->array[$offset]);
206 3
    }
207 5
  }
208
209
  /**
210
   * Serialize the current array.
211
   *
212
   * @return string
213
   */
214 2
  public function serialize()
215
  {
216 2
    return serialize($this->array);
217
  }
218
219
  /**
220
   * Unserialize an string and return this object.
221
   *
222
   * @param string $string
223
   *
224
   * @return self (Mutable)
225
   */
226 1
  public function unserialize($string)
227
  {
228 1
    $this->array = unserialize($string);
229
230 1
    return $this;
231
  }
232
233
  /**
234
   * Iterate over the current array and execute a callback for each loop.
235
   *
236
   * @param \Closure $closure
237
   *
238
   * @return Arrayy (Immutable)
239
   */
240 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...
241
  {
242 2
    $array = $this->array;
243
244 2
    foreach ($array as $key => $value) {
245 2
      $closure($value, $key);
246 2
    }
247
248 2
    return static::create($array);
249
  }
250
251
  /**
252
   * Returns the average value of the current array.
253
   *
254
   * @param int $decimals The number of decimals to return
255
   *
256
   * @return int|double The average value
257
   */
258 10
  public function average($decimals = null)
259
  {
260 10
    $count = $this->count();
261
262 10
    if (!$count) {
263 2
      return 0;
264
    }
265
266 8
    if (!is_int($decimals)) {
267 3
      $decimals = null;
268 3
    }
269
270 8
    return round(array_sum($this->array) / $count, $decimals);
271
  }
272
273
  /**
274
   * Create a chunked version of the current array.
275
   *
276
   * @param int  $size         Size of each chunk
277
   * @param bool $preserveKeys Whether array keys are preserved or no
278
   *
279
   * @return Arrayy (Immutable) A new array of chunks from the original array.
280
   */
281 4
  public function chunk($size, $preserveKeys = false)
282
  {
283 4
    $result = array_chunk($this->array, $size, $preserveKeys);
284
285 4
    return static::create($result);
286
  }
287
288
  /**
289
   * Clean all falsy values from the current array.
290
   *
291
   * @return Arrayy (Immutable)
292
   */
293 8
  public function clean()
294
  {
295 8
    return $this->filter(
296
        function ($value) {
297 7
          return (bool)$value;
298
        }
299 8
    );
300
  }
301
302
  /**
303
   * WARNING!!! -> Clear the current array.
304
   *
305
   * @return self (Mutable) Return this Arrayy object, with an empty array.
306
   */
307 4
  public function clear()
308
  {
309 4
    $this->array = array();
310
311 4
    return $this;
312
  }
313
314
  /**
315
   * Check if an item is in the current array.
316
   *
317
   * @param mixed $value
318
   *
319
   * @return bool
320
   */
321 13
  public function contains($value)
322
  {
323 13
    return in_array($value, $this->array, true);
324
  }
325
326
  /**
327
   * Check if the given key/index exists in the array.
328
   *
329
   * @param mixed $key Key/index to search for
330
   *
331
   * @return bool Returns true if the given key/index exists in the array, false otherwise
332
   */
333 4
  public function containsKey($key)
334
  {
335 4
    return array_key_exists($key, $this->array);
336
  }
337
338
  /** @noinspection ArrayTypeOfParameterByDefaultValueInspection */
339
  /**
340
   * Creates an Arrayy object.
341
   *
342
   * @param array $array
343
   *
344
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
345
   */
346 441
  public static function create($array = array())
347
  {
348 441
    return new static($array);
349
  }
350
351
  /** @noinspection ArrayTypeOfParameterByDefaultValueInspection */
352
  /**
353
   * WARNING: Creates an Arrayy object by reference.
354
   *
355
   * @param array $array
356
   *
357
   * @return self (Mutable) Return this Arrayy object.
358
   */
359
  public function createByReference(&$array = array())
360
  {
361
    $array = $this->fallbackForArray($array);
362
363
    $this->array = &$array;
364
365
    return $this;
366
  }
367
368
  /**
369
   * Create an new Arrayy object via JSON.
370
   *
371
   * @param string $json
372
   *
373
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
374
   */
375 5
  public static function createFromJson($json)
376
  {
377 5
    $array = UTF8::json_decode($json, true);
378
379 5
    return static::create($array);
380
  }
381
382
  /**
383
   * Create an new instance filled with values from an object that have implemented ArrayAccess.
384
   *
385
   * @param ArrayAccess $object Object that implements ArrayAccess
386
   *
387
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
388
   */
389 4
  public static function createFromObject(ArrayAccess $object)
390
  {
391 4
    $array = new static();
392 4
    foreach ($object as $key => $value) {
393
      /** @noinspection OffsetOperationsInspection */
394 3
      $array[$key] = $value;
395 4
    }
396
397 4
    return $array;
398
  }
399
400
  /**
401
   * Create an new instance containing a range of elements.
402
   *
403
   * @param mixed $low  First value of the sequence
404
   * @param mixed $high The sequence is ended upon reaching the end value
405
   * @param int   $step Used as the increment between elements in the sequence
406
   *
407
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
408
   */
409 1
  public static function createWithRange($low, $high, $step = 1)
410
  {
411 1
    return static::create(range($low, $high, $step));
412
  }
413
414
  /**
415
   * Create an new Arrayy object via string.
416
   *
417
   * @param string      $str       The input string.
418
   * @param string|null $delimiter The boundary string.
419
   * @param string|null $regEx     Use the $delimiter or the $regEx, so if $pattern is null, $delimiter will be used.
420
   *
421
   * @return Arrayy (Immutable) Returns an new instance of the Arrayy object.
422
   */
423 8
  public static function createFromString($str, $delimiter, $regEx = null)
424
  {
425 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...
426 1
      preg_match_all($regEx, $str, $array);
427
428 1
      if (count($array) > 0) {
429 1
        $array = $array[0];
430 1
      }
431
432 1
    } else {
433 7
      $array = explode($delimiter, $str);
434
    }
435
436
    // trim all string in the array
437 8
    array_walk(
438 8
        $array,
439
        function (&$val) {
440
          /** @noinspection ReferenceMismatchInspection */
441 8
          if (is_string($val)) {
442 8
            $val = trim($val);
443 8
          }
444 8
        }
445 8
    );
446
447 8
    return static::create($array);
448
  }
449
450
  /**
451
   * Custom sort by index via "uksort".
452
   *
453
   * @link http://php.net/manual/en/function.uksort.php
454
   *
455
   * @param callable $function
456
   *
457
   * @return self (Mutable) Return this Arrayy object.
458
   */
459 5
  public function customSortKeys($function)
460
  {
461 5
    uksort($this->array, $function);
462
463 5
    return $this;
464
  }
465
466
  /**
467
   * Custom sort by value via "usort".
468
   *
469
   * @link http://php.net/manual/en/function.usort.php
470
   *
471
   * @param callable $function
472
   *
473
   * @return self (Mutable) Return this Arrayy object.
474
   */
475 4
  public function customSortValues($function)
476
  {
477 4
    usort($this->array, $function);
478
479 4
    return $this;
480
  }
481
482
  /**
483
   * Return values that are only in the current array.
484
   *
485
   * @param array $array
486
   *
487
   * @return Arrayy (Immutable)
488
   */
489 12
  public function diff(array $array = array())
490
  {
491 12
    $result = array_diff($this->array, $array);
492
493 12
    return static::create($result);
494
  }
495
496
  /**
497
   * Return values that are only in the new $array.
498
   *
499
   * @param array $array
500
   *
501
   * @return Arrayy (Immutable)
502
   */
503 8
  public function diffReverse(array $array = array())
504
  {
505 8
    $result = array_diff($array, $this->array);
506
507 8
    return static::create($result);
508
  }
509
510
  /**
511
   * Return values that are only in the current multi-dimensional array.
512
   *
513
   * @param array      $array
514
   * @param null|array $helperVariableForRecursion (only for internal usage)
515
   *
516
   * @return Arrayy (Immutable)
517
   */
518 1
  public function diffRecursive(array $array = array(), $helperVariableForRecursion = null)
519
  {
520 1
    $result = array();
521
522 1
    if ($helperVariableForRecursion !== null && is_array($helperVariableForRecursion) === true) {
523 1
      $arrayForTheLoop = $helperVariableForRecursion;
524 1
    } else {
525 1
      $arrayForTheLoop = $this->array;
526
    }
527
528 1
    foreach ($arrayForTheLoop as $key => $value) {
529 1
      if (array_key_exists($key, $array)) {
530 1
        if (is_array($value)) {
531 1
          $recursiveDiff = $this->diffRecursive($array[$key], $value);
532 1
          if (count($recursiveDiff)) {
533 1
            $result[$key] = $recursiveDiff;
534 1
          }
535 1
        } else {
536 1
          if ($value != $array[$key]) {
537 1
            $result[$key] = $value;
538 1
          }
539
        }
540 1
      } else {
541 1
        $result[$key] = $value;
542
      }
543 1
    }
544
545 1
    return static::create($result);
546
  }
547
548
  /**
549
   * Iterate over the current array and modify the array's value.
550
   *
551
   * @param \Closure $closure
552
   *
553
   * @return Arrayy (Immutable)
554
   */
555 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...
556
  {
557 22
    $array = $this->array;
558
559 22
    foreach ($array as $key => &$value) {
560 18
      $value = $closure($value, $key);
561 22
    }
562
563 22
    return static::create($array);
564
  }
565
566
  /**
567
   * Check if a value is in the current array using a closure.
568
   *
569
   * @param \Closure $closure
570
   *
571
   * @return bool Returns true if the given value is found, false otherwise
572
   */
573 4
  public function exists(\Closure $closure)
574
  {
575 4
    $isExists = false;
576 4
    foreach ($this->array as $key => $value) {
577 3
      if ($closure($value, $key)) {
578 1
        $isExists = true;
579 1
        break;
580
      }
581 4
    }
582
583 4
    return $isExists;
584
  }
585
586
  /**
587
   * create a fallback for array
588
   *
589
   * 1. use the current array, if it's a array
590
   * 2. call "getArray()" on object, if there is a "Arrayy"-object
591
   * 3. fallback to empty array, if there is nothing
592
   * 4. call "createFromObject()" on object, if there is a "ArrayAccess"-object
593
   * 5. call "__toArray()" on object, if the method exists
594
   * 6. cast a string or object with "__toString()" into an array
595
   * 7. throw a "InvalidArgumentException"-Exception
596
   *
597
   * @param $array
598
   *
599
   * @return array
600
   *
601
   * @throws \InvalidArgumentException
602
   */
603 701
  protected function fallbackForArray(&$array)
604
  {
605 701
    if (is_array($array)) {
606 698
      return $array;
607
    }
608
609 6
    if ($array instanceof self) {
610
      return $array->getArray();
611
    }
612
613 6
    if (!$array) {
614 3
      return array();
615
    }
616
    
617 5
    if ($array instanceof ArrayAccess) {
618
      /** @noinspection ReferenceMismatchInspection */
619
      return self::createFromObject($array);
620
    }
621
622 5
    if (is_object($array) && method_exists($array, '__toArray')) {
623
      return (array)$array->__toArray();
624
    }
625
626
    /** @noinspection ReferenceMismatchInspection */
627
    if (
628 5
        is_string($array)
629
        ||
630 2
        (is_object($array) && method_exists($array, '__toString'))
631 5
    ) {
632 3
      return (array)$array;
633
    }
634
635 2
    throw new \InvalidArgumentException(
636
        'Passed value should be a array'
637 2
    );
638
  }
639
640
  /**
641
   * Find all items in an array that pass the truth test.
642
   *
643
   * @param \Closure|null $closure
644
   *
645
   * @return Arrayy (Immutable)
646
   */
647 8
  public function filter($closure = null)
648
  {
649 8
    if (!$closure) {
650 1
      return $this->clean();
651
    }
652
653 8
    $array = array_filter($this->array, $closure);
654
655 8
    return static::create($array);
656
  }
657
658
  /**
659
   * Filters an array of objects (or a numeric array of associative arrays) based on the value of a particular property
660
   * within that.
661
   *
662
   * @param        $property
663
   * @param        $value
664
   * @param string $comparisonOp
665
   *                            'eq' (equals),<br />
666
   *                            'gt' (greater),<br />
667
   *                            'gte' || 'ge' (greater or equals),<br />
668
   *                            'lt' (less),<br />
669
   *                            'lte' || 'le' (less or equals),<br />
670
   *                            'ne' (not equals),<br />
671
   *                            'contains',<br />
672
   *                            'notContains',<br />
673
   *                            'newer' (via strtotime),<br />
674
   *                            'older' (via strtotime),<br />
675
   *
676
   * @return Arrayy (Immutable)
677
   */
678 1
  public function filterBy($property, $value, $comparisonOp = null)
679
  {
680 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...
681 1
      $comparisonOp = is_array($value) ? 'contains' : 'eq';
682 1
    }
683
684
    $ops = array(
685
        'eq'          => function ($item, $prop, $value) {
686 1
          return $item[$prop] === $value;
687 1
        },
688
        'gt'          => function ($item, $prop, $value) {
689
          return $item[$prop] > $value;
690 1
        },
691
        'ge'         => function ($item, $prop, $value) {
692
          return $item[$prop] >= $value;
693 1
        },
694
        'gte'         => function ($item, $prop, $value) {
695
          return $item[$prop] >= $value;
696 1
        },
697
        'lt'          => function ($item, $prop, $value) {
698 1
          return $item[$prop] < $value;
699 1
        },
700
        'le'         => function ($item, $prop, $value) {
701
          return $item[$prop] <= $value;
702 1
        },
703
        'lte'         => function ($item, $prop, $value) {
704
          return $item[$prop] <= $value;
705 1
        },
706
        'ne'          => function ($item, $prop, $value) {
707
          return $item[$prop] !== $value;
708 1
        },
709
        'contains'    => function ($item, $prop, $value) {
710 1
          return in_array($item[$prop], (array)$value, true);
711 1
        },
712
        'notContains' => function ($item, $prop, $value) {
713
          return !in_array($item[$prop], (array)$value, true);
714 1
        },
715
        'newer'       => function ($item, $prop, $value) {
716
          return strtotime($item[$prop]) > strtotime($value);
717 1
        },
718
        'older'       => function ($item, $prop, $value) {
719
          return strtotime($item[$prop]) < strtotime($value);
720 1
        },
721 1
    );
722
723 1
    $result = array_values(
724 1
        array_filter(
725 1
            (array)$this->array,
726
            function ($item) use (
727 1
                $property,
728 1
                $value,
729 1
                $ops,
730 1
                $comparisonOp
731
            ) {
732 1
              $item = (array)$item;
733 1
              $itemArrayy = new Arrayy($item);
734 1
              $item[$property] = $itemArrayy->get($property, array());
735
736 1
              return $ops[$comparisonOp]($item, $property, $value);
737
            }
738 1
        )
739 1
    );
740
741 1
    return static::create($result);
742
  }
743
744
  /**
745
   * Find the first item in an array that passes the truth test,
746
   *  otherwise return false
747
   *
748
   * @param \Closure $closure
749
   *
750
   * @return mixed|false false if we did not find the value
751
   */
752 8
  public function find(\Closure $closure)
753
  {
754 8
    foreach ($this->array as $key => $value) {
755 6
      if ($closure($value, $key)) {
756 5
        return $value;
757
      }
758 5
    }
759
760 3
    return false;
761
  }
762
763
  /**
764
   * find by ...
765
   *
766
   * @param        $property
767
   * @param        $value
768
   * @param string $comparisonOp
769
   *
770
   * @return Arrayy (Immutable)
771
   */
772
  public function findBy($property, $value, $comparisonOp = 'eq')
773
  {
774
    return $this->filterBy($property, $value, $comparisonOp);
775
  }
776
777
  /**
778
   * Get the first value from the current array.
779
   *
780
   * @return mixed Return null if there wasn't a element.
781
   */
782 13
  public function first()
783
  {
784 13
    $result = array_shift($this->array);
785
786 13
    if (null === $result) {
787 3
      return null;
788
    } else {
789 10
      return $result;
790
    }
791
  }
792
793
  /**
794
   * Get the first value(s) from the current array.
795
   *
796
   * @param int|null $number how many values you will take?
797
   *
798
   * @return self (Mutable)
799
   */
800 26
  public function firstsMutable($number = null)
801
  {
802 26
    if ($number === null) {
803 11
      $this->array = (array)array_shift($this->array);
804 11
    } else {
805 15
      $number = (int)$number;
806 15
      $this->array = array_splice($this->array, 0, $number, true);
807
    }
808
809 26
    return $this;
810
  }
811
812
  /**
813
   * Get the first value(s) from the current array.
814
   *
815
   * @param int|null $number how many values you will take?
816
   *
817
   * @return Arrayy (Immutable)
818
   */
819 28
  public function firstsImmutable($number = null)
820
  {
821 28
    if ($number === null) {
822 7
      $array = (array)array_shift($this->array);
823 7
    } else {
824 21
      $number = (int)$number;
825 21
      $array = array_splice($this->array, 0, $number, true);
826
    }
827
828 28
    return static::create($array);
829
  }
830
831
  /**
832
   * Exchanges all keys with their associated values in an array.
833
   *
834
   * @return Arrayy (Immutable)
835
   */
836 1
  public function flip()
837
  {
838 1
    $result = array_flip($this->array);
839
840 1
    return static::create($result);
841
  }
842
843
  /**
844
   * Get a value from an array (optional using dot-notation).
845
   *
846
   * @param string $key     The key to look for.
847
   * @param mixed  $default Default value to fallback to.
848
   * @param array  $array   The array to get from, if it's set to "null" we use the current array from the class.
849
   *
850
   * @return mixed
851
   */
852 34
  public function get($key, $default = null, $array = null)
853
  {
854 34
    if (is_array($array) === true) {
855 3
      $usedArray = $array;
856 3
    } else {
857 32
      $usedArray = $this->array;
858
    }
859
860 34
    if (null === $key) {
861 1
      return $usedArray;
862
    }
863
864 34
    if (isset($usedArray[$key])) {
865 23
      return $usedArray[$key];
866
    }
867
868
    // Crawl through array, get key according to object or not
869 19
    foreach (explode('.', $key) as $segment) {
870 19
      if (!isset($usedArray[$segment])) {
871 17
        return $default instanceof Closure ? $default() : $default;
872
      }
873
874 2
      $usedArray = $usedArray[$segment];
875 2
    }
876
877 2
    return $usedArray;
878
  }
879
880
  /**
881
   * Get the current array from the "Arrayy"-object.
882
   *
883
   * @return array
884
   */
885 475
  public function getArray()
886
  {
887 475
    return $this->array;
888
  }
889
890
  /**
891
   * Returns the values from a single column of the input array, identified by
892
   * the $columnKey, can be used to extract data-columns from multi-arrays.
893
   *
894
   * Info: Optionally, you may provide an $indexKey to index the values in the returned
895
   * array by the values from the $indexKey column in the input array.
896
   *
897
   * @param mixed $columnKey
898
   * @param mixed $indexKey
899
   *
900
   * @return Arrayy (Immutable)
901
   */
902 1
  public function getColumn($columnKey = null, $indexKey = null)
903
  {
904 1
    $result = array_column($this->array, $columnKey, $indexKey);
905
906 1
    return static::create($result);
907
  }
908
909
  /**
910
   * Get correct PHP constant for direction.
911
   *
912
   * @param int|string $direction
913
   *
914
   * @return int
915
   */
916 38
  protected function getDirection($direction)
917
  {
918 38
    if (is_string($direction)) {
919 10
      $direction = strtolower($direction);
920
921 10
      if ($direction === 'desc') {
922 2
        $direction = SORT_DESC;
923 2
      } else {
924 8
        $direction = SORT_ASC;
925
      }
926 10
    }
927
928
    if (
929
        $direction !== SORT_DESC
930 38
        &&
931
        $direction !== SORT_ASC
932 38
    ) {
933
      $direction = SORT_ASC;
934
    }
935
936 38
    return $direction;
937
  }
938
939
  /**
940
   * alias: for "Arrayy->keys()"
941
   *
942
   * @return Arrayy (Immutable)
943
   */
944
  public function getKeys()
945
  {
946
    return $this->keys();
947
  }
948
949
  /**
950
   * alias: for "Arrayy->random()"
951
   *
952
   * @return Arrayy (Immutable)
953
   */
954 3
  public function getRandom()
955
  {
956 3
    return $this->randomImmutable();
957
  }
958
959
  /**
960
   * alias: for "Arrayy->randomKey()"
961
   *
962
   * @return mixed get a key/index or null if there wasn't a key/index
963
   */
964 3
  public function getRandomKey()
965
  {
966 3
    return $this->randomKey();
967
  }
968
969
  /**
970
   * alias: for "Arrayy->randomKeys()"
971
   *
972
   * @param int $number
973
   *
974
   * @return Arrayy (Immutable)
975
   */
976 9
  public function getRandomKeys($number)
977
  {
978 9
    return $this->randomKeys($number);
979
  }
980
981
  /**
982
   * alias: for "Arrayy->randomValue()"
983
   *
984
   * @return mixed get a random value or null if there wasn't a value
985
   */
986 3
  public function getRandomValue()
987
  {
988 3
    return $this->randomValue();
989
  }
990
991
  /**
992
   * alias: for "Arrayy->randomValues()"
993
   *
994
   * @param int $number
995
   *
996
   * @return Arrayy (Immutable)
997
   */
998 6
  public function getRandomValues($number)
999
  {
1000 6
    return $this->randomValues($number);
1001
  }
1002
1003
  /**
1004
   * Group values from a array according to the results of a closure.
1005
   *
1006
   * @param string $grouper a callable function name
1007
   * @param bool   $saveKeys
1008
   *
1009
   * @return Arrayy (Immutable)
1010
   */
1011 3
  public function group($grouper, $saveKeys = false)
1012
  {
1013 3
    $array = (array)$this->array;
1014 3
    $result = array();
1015
1016
    // Iterate over values, group by property/results from closure
1017 3
    foreach ($array as $key => $value) {
1018 3
      $groupKey = is_callable($grouper) ? $grouper($value, $key) : $this->get($grouper, null, $value);
1019 3
      $newValue = $this->get($groupKey, null, $result);
1020
1021
      // Add to results
1022 3
      if ($groupKey !== null) {
1023 2
        if ($saveKeys) {
1024 1
          $result[$groupKey] = $newValue;
1025 1
          $result[$groupKey][$key] = $value;
1026 1
        } else {
1027 1
          $result[$groupKey] = $newValue;
1028 1
          $result[$groupKey][] = $value;
1029
        }
1030 2
      }
1031
1032 3
    }
1033
1034 3
    return static::create($result);
1035
  }
1036
1037
  /**
1038
   * Check if an array has a given key.
1039
   *
1040
   * @param mixed $key
1041
   *
1042
   * @return bool
1043
   */
1044 19
  public function has($key)
1045
  {
1046
    // Generate unique string to use as marker.
1047 19
    $unFound = (string)uniqid('arrayy', true);
1048
1049 19
    return $this->get($key, $unFound) !== $unFound;
1050
  }
1051
1052
  /**
1053
   * Implodes an array.
1054
   *
1055
   * @param string $with What to implode it with
1056
   *
1057
   * @return string
1058
   */
1059 23
  public function implode($with = '')
1060
  {
1061 23
    return implode($with, $this->array);
1062
  }
1063
1064
  /**
1065
   * Given a list and an iterate-function that returns
1066
   * a key for each element in the list (or a property name),
1067
   * returns an object with an index of each item.
1068
   *
1069
   * Just like groupBy, but for when you know your keys are unique.
1070
   *
1071
   * @param mixed $key
1072
   *
1073
   * @return Arrayy (Immutable)
1074
   */
1075 3
  public function indexBy($key)
1076
  {
1077 3
    $results = array();
1078
1079 3
    foreach ($this->array as $a) {
1080 3
      if (isset($a[$key])) {
1081 2
        $results[$a[$key]] = $a;
1082 2
      }
1083 3
    }
1084
1085 3
    return static::create($results);
1086
  }
1087
1088
  /**
1089
   * alias: for "Arrayy->searchIndex()"
1090
   *
1091
   * @param mixed $value Value to search for
1092
   *
1093
   * @return mixed
1094
   */
1095 4
  public function indexOf($value)
1096
  {
1097 4
    return $this->searchIndex($value);
1098
  }
1099
1100
  /**
1101
   * Get everything but the last..$to items.
1102
   *
1103
   * @param int $to
1104
   *
1105
   * @return Arrayy (Immutable)
1106
   */
1107 12
  public function initial($to = 1)
1108
  {
1109 12
    $slice = count($this->array) - $to;
1110
1111 12
    return $this->firstsImmutable($slice);
1112
  }
1113
1114
  /**
1115
   * Internal mechanics of remove method.
1116
   *
1117
   * @param $key
1118
   *
1119
   * @return boolean
1120
   */
1121 18
  protected function internalRemove($key)
1122
  {
1123
    // Explode keys
1124 18
    $keys = explode('.', $key);
1125
1126
    // Crawl though the keys
1127 18
    while (count($keys) > 1) {
1128
      $key = array_shift($keys);
1129
1130
      if (!$this->has($key)) {
1131
        return false;
1132
      }
1133
1134
      $this->array = &$this->array[$key];
1135
    }
1136
1137 18
    $key = array_shift($keys);
1138
1139 18
    unset($this->array[$key]);
1140
1141 18
    return true;
1142
  }
1143
1144
  /**
1145
   * Internal mechanic of set method.
1146
   *
1147
   * @param string $key
1148
   * @param mixed $value
1149
   *
1150
   * @return bool
1151
   */
1152 17
  protected function internalSet($key, $value)
1153
  {
1154 17
    if (null === $key) {
1155
      return false;
1156
    }
1157
1158
    // init
1159 17
    $array = &$this->array;
1160
1161
    // Explode the keys
1162 17
    $keys = explode('.', $key);
1163
1164
    // Crawl through the keys
1165 17
    while (count($keys) > 1) {
1166 1
      $key = array_shift($keys);
1167
      // If the key doesn't exist at this depth, we will just create an empty array
1168
      // to hold the next value, allowing us to create the arrays to hold final
1169
      // values at the correct depth. Then we'll keep digging into the array.
1170 1
      if (! isset($array[$key]) || ! is_array($array[$key])) {
1171
        $array[$key] = array();
1172
      }
1173 1
      $array = &$array[$key];
1174 1
    }
1175
1176 17
    $array[array_shift($keys)] = $value;
1177
1178 17
    return true;
1179
  }
1180
1181
  /**
1182
   * Return an array with all elements found in input array.
1183
   *
1184
   * @param array $search
1185
   *
1186
   * @return Arrayy (Immutable)
1187
   */
1188 2
  public function intersection(array $search)
1189
  {
1190 2
    $result = array_values(array_intersect($this->array, $search));
1191
1192 2
    return static::create($result);
1193
  }
1194
1195
  /**
1196
   * Return a boolean flag which indicates whether the two input arrays have any common elements.
1197
   *
1198
   * @param array $search
1199
   *
1200
   * @return bool
1201
   */
1202 1
  public function intersects(array $search)
1203
  {
1204 1
    return count($this->intersection($search)->array) > 0;
1205
  }
1206
1207
  /** @noinspection ArrayTypeOfParameterByDefaultValueInspection */
1208
  /**
1209
   * Invoke a function on all of an array's values.
1210
   *
1211
   * @param mixed $callable
1212
   * @param mixed $arguments
1213
   *
1214
   * @return Arrayy (Immutable)
1215
   */
1216 1
  public function invoke($callable, $arguments = array())
1217
  {
1218
    // If one argument given for each iteration, create an array for it.
1219 1
    if (!is_array($arguments)) {
1220 1
      $arguments = StaticArrayy::repeat($arguments, count($this->array))->getArray();
1221 1
    }
1222
1223
    // If the callable has arguments, pass them.
1224 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...
1225 1
      $array = array_map($callable, $this->array, $arguments);
1226 1
    } else {
1227 1
      $array = array_map($callable, $this->array);
1228
    }
1229
1230 1
    return static::create($array);
1231
  }
1232
1233
  /**
1234
   * Check whether array is associative or not.
1235
   *
1236
   * @return bool Returns true if associative, false otherwise
1237
   */
1238 15
  public function isAssoc()
1239
  {
1240 15
    if ($this->isEmpty()) {
1241 3
      return false;
1242
    }
1243
1244 13
    foreach ($this->keys()->getArray() as $key) {
1245 13
      if (!is_string($key)) {
1246 11
        return false;
1247
      }
1248 3
    }
1249
1250 3
    return true;
1251
  }
1252
1253
  /**
1254
   * Check whether the array is empty or not.
1255
   *
1256
   * @return bool Returns true if empty, false otherwise
1257
   */
1258 23
  public function isEmpty()
1259
  {
1260 23
    return !$this->array;
1261
  }
1262
1263
  /**
1264
   * Check if the current array is a multi-array.
1265
   *
1266
   * @return bool
1267
   */
1268 14
  public function isMultiArray()
1269
  {
1270 14
    return !(count($this->array) === count($this->array, COUNT_RECURSIVE));
1271
  }
1272
1273
  /**
1274
   * Check whether array is numeric or not.
1275
   *
1276
   * @return bool Returns true if numeric, false otherwise
1277
   */
1278 4
  public function isNumeric()
1279
  {
1280 4
    if ($this->isEmpty()) {
1281 1
      return false;
1282
    }
1283
1284 3
    foreach ($this->keys() as $key) {
1285 3
      if (!is_int($key)) {
1286 2
        return false;
1287
      }
1288 2
    }
1289
1290 1
    return true;
1291
  }
1292
1293
  /**
1294
   * Get all keys from the current array.
1295
   *
1296
   * @return Arrayy (Immutable)
1297
   */
1298 21
  public function keys()
1299
  {
1300 21
    $array = array_keys((array)$this->array);
1301
1302 21
    return static::create($array);
1303
  }
1304
1305
  /**
1306
   * Get the last value from the current array.
1307
   *
1308
   * @return mixed Return null if there wasn't a element.
1309
   */
1310 4
  public function last()
1311
  {
1312 4
    $result = $this->pop();
1313
1314 4
    if (null === $result) {
1315 1
      return null;
1316
    } else {
1317 3
      return $result;
1318
    }
1319
  }
1320
1321
  /**
1322
   * Get the last value(s) from the current array.
1323
   *
1324
   * @param int|null $number
1325
   *
1326
   * @return Arrayy (Immutable)
1327
   */
1328 12
  public function lastsImmutable($number = null)
1329
  {
1330 12
    if ($number === null) {
1331 8
      $poppedValue = (array)$this->pop();
1332 8
      $arrayy = static::create($poppedValue);
1333 8
    } else {
1334 4
      $number = (int)$number;
1335 4
      $arrayy = $this->rest(-$number);
1336
    }
1337
1338 12
    return $arrayy;
1339
  }
1340
1341
  /**
1342
   * Get the last value(s) from the current array.
1343
   *
1344
   * @param int|null $number
1345
   *
1346
   * @return self (Mutable)
1347
   */
1348 12
  public function lastsMutable($number = null)
1349
  {
1350 12
    if ($number === null) {
1351 8
      $poppedValue = (array)$this->pop();
1352 8
      $this->array = static::create($poppedValue)->array;
1353 8
    } else {
1354 4
      $number = (int)$number;
1355 4
      $this->array = $this->rest(-$number)->array;
1356
    }
1357
1358 12
    return $this;
1359
  }
1360
1361
  /**
1362
   * Count the values from the current array.
1363
   *
1364
   * INFO: only a alias for "$arrayy->size()"
1365
   *
1366
   * @return int
1367
   */
1368 10
  public function length()
1369
  {
1370 10
    return $this->size();
1371
  }
1372
1373
  /**
1374
   * Apply the given function to the every element of the array,
1375
   * collecting the results.
1376
   *
1377
   * @param callable $callable
1378
   *
1379
   * @return Arrayy (Immutable) Arrayy object with modified elements
1380
   */
1381 4
  public function map($callable)
1382
  {
1383 4
    $result = array_map($callable, $this->array);
1384
1385 4
    return static::create($result);
1386
  }
1387
1388
  /**
1389
   * Check if all items in current array match a truth test.
1390
   *
1391
   * @param \Closure $closure
1392
   *
1393
   * @return bool
1394
   */
1395 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...
1396
  {
1397
    // Reduce the array to only booleans
1398 9
    $array = $this->each($closure);
1399
1400
    // Check the results
1401 9
    if (count($array) === 0) {
1402 2
      return true;
1403
    }
1404
1405 7
    $array = array_search(false, $array->toArray(), false);
1406
1407 7
    return is_bool($array);
1408
  }
1409
1410
  /**
1411
   * Check if any item in the current array matches a truth test.
1412
   *
1413
   * @param \Closure $closure
1414
   *
1415
   * @return bool
1416
   */
1417 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...
1418
  {
1419
    // Reduce the array to only booleans
1420 9
    $array = $this->each($closure);
1421
1422
    // Check the results
1423 9
    if (count($array) === 0) {
1424 2
      return true;
1425
    }
1426
1427 7
    $array = array_search(true, $array->toArray(), false);
1428
1429 7
    return is_int($array);
1430
  }
1431
1432
  /**
1433
   * Get the max value from an array.
1434
   *
1435
   * @return mixed
1436
   */
1437 10
  public function max()
1438
  {
1439 10
    if ($this->count() === 0) {
1440 1
      return false;
1441
    }
1442
1443 9
    return max($this->array);
1444
  }
1445
1446
  /**
1447
   * Merge the new $array into the current array.
1448
   *
1449
   * - keep key,value from the current array, also if the index is in the new $array
1450
   *
1451
   * @param array $array
1452
   * @param bool  $recursive
1453
   *
1454
   * @return Arrayy (Immutable)
1455
   */
1456 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...
1457
  {
1458 25
    if (true === $recursive) {
1459 4
      $result = array_replace_recursive($this->array, $array);
1460 4
    } else {
1461 21
      $result = array_replace($this->array, $array);
1462
    }
1463
1464 25
    return static::create($result);
1465
  }
1466
1467
  /**
1468
   * Merge the new $array into the current array.
1469
   *
1470
   * - replace duplicate assoc-keys from the current array with the key,values from the new $array
1471
   * - create new indexes
1472
   *
1473
   * @param array $array
1474
   * @param bool  $recursive
1475
   *
1476
   * @return Arrayy (Immutable)
1477
   */
1478 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...
1479
  {
1480 16
    if (true === $recursive) {
1481 4
      $result = array_merge_recursive($this->array, $array);
1482 4
    } else {
1483 12
      $result = array_merge($this->array, $array);
1484
    }
1485
1486 16
    return static::create($result);
1487
  }
1488
1489
  /**
1490
   * Merge the the current array into the $array.
1491
   *
1492
   * - use key,value from the new $array, also if the index is in the current array
1493
   *
1494
   * @param array $array
1495
   * @param bool  $recursive
1496
   *
1497
   * @return Arrayy (Immutable)
1498
   */
1499 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...
1500
  {
1501 16
    if (true === $recursive) {
1502 4
      $result = array_replace_recursive($array, $this->array);
1503 4
    } else {
1504 12
      $result = array_replace($array, $this->array);
1505
    }
1506
1507 16
    return static::create($result);
1508
  }
1509
1510
  /**
1511
   * Merge the current array into the new $array.
1512
   *
1513
   * - replace duplicate assoc-keys from new $array with the key,values from the current array
1514
   * - create new indexes
1515
   *
1516
   * @param array $array
1517
   * @param bool  $recursive
1518
   *
1519
   * @return Arrayy (Immutable)
1520
   */
1521 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...
1522
  {
1523 16
    if (true === $recursive) {
1524 4
      $result = array_merge_recursive($array, $this->array);
1525 4
    } else {
1526 12
      $result = array_merge($array, $this->array);
1527
    }
1528
1529 16
    return static::create($result);
1530
  }
1531
1532
  /**
1533
   * Get the min value from an array.
1534
   *
1535
   * @return mixed
1536
   */
1537 10
  public function min()
1538
  {
1539 10
    if ($this->count() === 0) {
1540 1
      return false;
1541
    }
1542
1543 9
    return min($this->array);
1544
  }
1545
1546
  /**
1547
   * Pad array to the specified size with a given value.
1548
   *
1549
   * @param int   $size  Size of the result array
1550
   * @param mixed $value Empty value by default
1551
   *
1552
   * @return Arrayy (Immutable) Arrayy object padded to $size with $value
1553
   */
1554 4
  public function pad($size, $value)
1555
  {
1556 4
    $result = array_pad($this->array, $size, $value);
1557
1558 4
    return static::create($result);
1559
  }
1560
1561
  /**
1562
   * Pop a specified value off the end of the current array.
1563
   *
1564
   * @return mixed The popped element from the current array.
1565
   */
1566 16
  public function pop()
1567
  {
1568 16
    return array_pop($this->array);
1569
  }
1570
1571
  /**
1572
   * Prepend a value to the current array.
1573
   *
1574
   * @param mixed $value
1575
   *
1576
   * @return self (Mutable) Return this Arrayy object, with the prepended value.
1577
   */
1578 7
  public function prepend($value)
1579
  {
1580 7
    array_unshift($this->array, $value);
1581
1582 7
    return $this;
1583
  }
1584
1585
  /**
1586
   * Push one or more values onto the end of array at once.
1587
   *
1588
   * @return self (Mutable) Return this Arrayy object, with pushed elements to the end of array.
1589
   */
1590 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...
1591
  {
1592 4
    if (func_num_args()) {
1593 4
      $args = array_merge(array(&$this->array), func_get_args());
1594 4
      call_user_func_array('array_push', $args);
1595 4
    }
1596
1597 4
    return $this;
1598
  }
1599
1600
  /**
1601
   * Get a random value from the current array.
1602
   *
1603
   * @param null|int $number how many values you will take?
1604
   *
1605
   * @return Arrayy (Mutable)
1606
   */
1607 16
  public function randomMutable($number = null)
1608
  {
1609 16
    if ($this->count() === 0) {
1610
      return static::create();
1611
    }
1612
1613 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...
1614 6
      $arrayRandValue = (array)$this->array[array_rand($this->array)];
1615 6
      $this->array = $arrayRandValue;
1616
1617 6
      return $this;
1618
    }
1619
1620 11
    shuffle($this->array);
1621
1622 11
    return $this->firstsMutable($number);
1623
  }
1624
1625
  /**
1626
   * Get a random value from the current array.
1627
   *
1628
   * @param null|int $number how many values you will take?
1629
   *
1630
   * @return Arrayy (Immutable)
1631
   */
1632 17
  public function randomImmutable($number = null)
1633
  {
1634 17
    if ($this->count() === 0) {
1635
      return static::create();
1636
    }
1637
1638 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...
1639 14
      $arrayRandValue = (array)$this->array[array_rand($this->array)];
1640
1641 14
      return static::create($arrayRandValue);
1642
    }
1643
1644 5
    $arrayTmp = $this->array;
1645 5
    shuffle($arrayTmp);
1646
1647 5
    return self::create($arrayTmp)->firstsImmutable($number);
1648
  }
1649
1650
  /**
1651
   * Pick a random key/index from the keys of this array.
1652
   *
1653
   *
1654
   * @return mixed get a key/index or null if there wasn't a key/index
1655
   *
1656
   * @throws \RangeException If array is empty
1657
   */
1658 4
  public function randomKey()
1659
  {
1660 4
    $result = $this->randomKeys(1);
1661
1662 4
    if (!isset($result[0])) {
1663
      $result[0] = null;
1664
    }
1665
1666 4
    return $result[0];
1667
  }
1668
1669
  /**
1670
   * Pick a given number of random keys/indexes out of this array.
1671
   *
1672
   * @param int $number The number of keys/indexes (should be <= $this->count())
1673
   *
1674
   * @return Arrayy (Immutable)
1675
   *
1676
   * @throws \RangeException If array is empty
1677
   */
1678 14
  public function randomKeys($number)
1679
  {
1680 14
    $number = (int)$number;
1681 14
    $count = $this->count();
1682
1683 14
    if ($number === 0 || $number > $count) {
1684 3
      throw new \RangeException(
1685 3
          sprintf(
1686 3
              'Number of requested keys (%s) must be equal or lower than number of elements in this array (%s)',
1687 3
              $number,
1688
              $count
1689 3
          )
1690 3
      );
1691
    }
1692
1693 11
    $result = (array)array_rand($this->array, $number);
1694
1695 11
    return static::create($result);
1696
  }
1697
1698
  /**
1699
   * Pick a random value from the values of this array.
1700
   *
1701
   * @return mixed get a random value or null if there wasn't a value
1702
   */
1703 4
  public function randomValue()
1704
  {
1705 4
    $result = $this->randomImmutable();
1706
1707 4
    if (!isset($result[0])) {
1708
      $result[0] = null;
1709
    }
1710
1711 4
    return $result[0];
1712
  }
1713
1714
  /**
1715
   * Pick a given number of random values out of this array.
1716
   *
1717
   * @param int $number
1718
   *
1719
   * @return Arrayy (Mutable)
1720
   */
1721 7
  public function randomValues($number)
1722
  {
1723 7
    $number = (int)$number;
1724
1725 7
    return $this->randomMutable($number);
1726
  }
1727
1728
  /**
1729
   * Get a random value from an array, with the ability to skew the results.
1730
   *
1731
   * Example: randomWeighted(['foo' => 1, 'bar' => 2]) has a 66% chance of returning bar.
1732
   *
1733
   * @param array    $array
1734
   * @param null|int $number how many values you will take?
1735
   *
1736
   * @return Arrayy (Immutable)
1737
   */
1738 9
  public function randomWeighted(array $array, $number = null)
1739
  {
1740 9
    $options = array();
1741 9
    foreach ($array as $option => $weight) {
1742 9
      if ($this->searchIndex($option) !== false) {
1743 2
        for ($i = 0; $i < $weight; ++$i) {
1744 1
          $options[] = $option;
1745 1
        }
1746 2
      }
1747 9
    }
1748
1749 9
    return $this->mergeAppendKeepIndex($options)->randomImmutable($number);
1750
  }
1751
1752
  /**
1753
   * Reduce the current array via callable e.g. anonymous-function.
1754
   *
1755
   * @param mixed $callable
1756
   * @param array $init
1757
   *
1758
   * @return Arrayy (Immutable)
1759
   */
1760 3
  public function reduce($callable, array $init = array())
1761
  {
1762 3
    $result = array_reduce($this->array, $callable, $init);
1763
1764 3
    if ($result === null) {
1765
      $this->array = array();
1766
    } else {
1767 3
      $this->array = (array)$result;
1768
    }
1769
1770 3
    return static::create($this->array);
1771
  }
1772
1773
  /**
1774
   * Create a numerically re-indexed Arrayy object.
1775
   *
1776
   * @return self (Mutable) Return this Arrayy object, with re-indexed array-elements.
1777
   */
1778 9
  public function reindex()
1779
  {
1780 9
    $this->array = array_values($this->array);
1781
1782 9
    return $this;
1783
  }
1784
1785
  /**
1786
   * Return all items that fail the truth test.
1787
   *
1788
   * @param \Closure $closure
1789
   *
1790
   * @return Arrayy (Immutable)
1791
   */
1792 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...
1793
  {
1794 1
    $filtered = array();
1795
1796 1
    foreach ($this->array as $key => $value) {
1797 1
      if (!$closure($value, $key)) {
1798 1
        $filtered[$key] = $value;
1799 1
      }
1800 1
    }
1801
1802 1
    return static::create($filtered);
1803
  }
1804
1805
  /**
1806
   * Remove a value from the current array (optional using dot-notation).
1807
   *
1808
   * @param mixed $key
1809
   *
1810
   * @return Arrayy (Immutable)
1811
   */
1812 18
  public function remove($key)
1813
  {
1814
    // Recursive call
1815 18
    if (is_array($key)) {
1816
      foreach ($key as $k) {
1817
        $this->internalRemove($k);
1818
      }
1819
1820
      return static::create($this->array);
1821
    }
1822
1823 18
    $this->internalRemove($key);
1824
1825 18
    return static::create($this->array);
1826
  }
1827
1828
  /**
1829
   * Remove the first value from the current array.
1830
   *
1831
   * @return Arrayy (Immutable)
1832
   */
1833 7
  public function removeFirst()
1834
  {
1835 7
    array_shift($this->array);
1836
1837 7
    return static::create($this->array);
1838
  }
1839
1840
  /**
1841
   * Remove the last value from the current array.
1842
   *
1843
   * @return Arrayy (Immutable)
1844
   */
1845 7
  public function removeLast()
1846
  {
1847 7
    array_pop($this->array);
1848
1849 7
    return static::create($this->array);
1850
  }
1851
1852
  /**
1853
   * Removes a particular value from an array (numeric or associative).
1854
   *
1855
   * @param mixed $value
1856
   *
1857
   * @return Arrayy (Immutable)
1858
   */
1859 7
  public function removeValue($value)
1860
  {
1861 7
    $isNumericArray = true;
1862 7
    foreach ($this->array as $key => $item) {
1863 6
      if ($item === $value) {
1864 6
        if (!is_int($key)) {
1865
          $isNumericArray = false;
1866
        }
1867 6
        unset($this->array[$key]);
1868 6
      }
1869 7
    }
1870
1871 7
    if ($isNumericArray) {
1872 7
      $this->array = array_values($this->array);
1873 7
    }
1874
1875 7
    return static::create($this->array);
1876
  }
1877
1878
  /**
1879
   * Replace a key with a new key/value pair.
1880
   *
1881
   * @param $replace
1882
   * @param $key
1883
   * @param $value
1884
   *
1885
   * @return Arrayy (Immutable)
1886
   */
1887 2
  public function replace($replace, $key, $value)
1888
  {
1889 2
    $this->remove($replace);
1890
1891 2
    return $this->set($key, $value);
1892
  }
1893
1894
  /**
1895
   * Create an array using the current array as values and the other array as keys.
1896
   *
1897
   * @param array $keys Keys array
1898
   *
1899
   * @return Arrayy (Immutable) Arrayy object with keys from the other array.
1900
   */
1901 2
  public function replaceAllKeys(array $keys)
1902
  {
1903 2
    $result = array_combine($keys, $this->array);
1904
1905 2
    return static::create($result);
1906
  }
1907
1908
  /**
1909
   * Create an array using the current array as keys and the other array as values.
1910
   *
1911
   * @param array $array Values array
1912
   *
1913
   * @return Arrayy (Immutable) Arrayy object with values from the other array.
1914
   */
1915 2
  public function replaceAllValues(array $array)
1916
  {
1917 2
    $result = array_combine($this->array, $array);
1918
1919 2
    return static::create($result);
1920
  }
1921
1922
  /**
1923
   * Replace the keys in an array with another set.
1924
   *
1925
   * @param array $keys An array of keys matching the array's size
1926
   *
1927
   * @return Arrayy (Immutable)
1928
   */
1929 1
  public function replaceKeys(array $keys)
1930
  {
1931 1
    $values = array_values($this->array);
1932 1
    $result = array_combine($keys, $values);
1933
1934 1
    return static::create($result);
1935
  }
1936
1937
  /**
1938
   * Replace the first matched value in an array.
1939
   *
1940
   * @param mixed $search
1941
   * @param mixed $replacement
1942
   *
1943
   * @return Arrayy (Immutable)
1944
   */
1945 3
  public function replaceOneValue($search, $replacement = '')
1946
  {
1947 3
    $array = $this->array;
1948 3
    $key = array_search($search, $array, true);
1949
1950 3
    if ($key !== false) {
1951 3
      $array[$key] = $replacement;
1952 3
    }
1953
1954 3
    return static::create($array);
1955
  }
1956
1957
  /**
1958
   * Replace values in the current array.
1959
   *
1960
   * @param string $search      The string to replace.
1961
   * @param string $replacement What to replace it with.
1962
   *
1963
   * @return Arrayy (Immutable)
1964
   */
1965 1
  public function replaceValues($search, $replacement = '')
1966
  {
1967 1
    $array = $this->each(
1968
        function ($value) use ($search, $replacement) {
1969 1
          return UTF8::str_replace($search, $replacement, $value);
1970
        }
1971 1
    );
1972
1973 1
    return $array;
1974
  }
1975
1976
  /**
1977
   * Get the last elements from index $from until the end of this array.
1978
   *
1979
   * @param int $from
1980
   *
1981
   * @return Arrayy (Immutable)
1982
   */
1983 16
  public function rest($from = 1)
1984
  {
1985 16
    $result = array_splice($this->array, $from);
1986
1987 16
    return static::create($result);
1988
  }
1989
1990
  /**
1991
   * Return the array in the reverse order.
1992
   *
1993
   * @return self (Mutable) Return this Arrayy object.
1994
   */
1995 7
  public function reverse()
1996
  {
1997 7
    $this->array = array_reverse($this->array);
1998
1999 7
    return $this;
2000
  }
2001
2002
  /**
2003
   * Search for the first index of the current array via $value.
2004
   *
2005
   * @param mixed $value
2006
   *
2007
   * @return mixed
2008
   */
2009 20
  public function searchIndex($value)
2010
  {
2011 20
    return array_search($value, $this->array, true);
2012
  }
2013
2014
  /**
2015
   * Search for the value of the current array via $index.
2016
   *
2017
   * @param mixed $index
2018
   *
2019
   * @return Arrayy (Immutable) will return a empty Arrayy if the value wasn't found
2020
   */
2021 7
  public function searchValue($index)
2022
  {
2023
    // init
2024 7
    $return = array();
2025
2026 7
    if (null !== $index) {
2027 7
      $keyExists = isset($this->array[$index]);
2028
2029 7
      if ($keyExists !== false) {
2030 5
        $return = array($this->array[$index]);
2031 5
      }
2032 7
    }
2033
2034 7
    return static::create($return);
2035
  }
2036
2037
  /**
2038
   * Set a value for the current array (optional using dot-notation).
2039
   *
2040
   * @param string $key   The key to set
2041
   * @param mixed  $value Its value
2042
   *
2043
   * @return Arrayy (Immutable)
2044
   */
2045 17
  public function set($key, $value)
2046
  {
2047 17
    $this->internalSet($key, $value);
2048
2049 17
    return static::create($this->array);
2050
  }
2051
2052
  /**
2053
   * Get a value from a array and set it if it was not.
2054
   *
2055
   * WARNING: this method only set the value, if the $key is not already set
2056
   *
2057
   * @param string $key      The key
2058
   * @param mixed  $fallback The default value to set if it isn't
2059
   *
2060
   * @return mixed (Mutable)
2061
   */
2062 10
  public function setAndGet($key, $fallback = null)
2063
  {
2064
    // If the key doesn't exist, set it
2065 10
    if (!$this->has($key)) {
2066 5
      $this->array = $this->set($key, $fallback)->getArray();
2067 5
    }
2068
2069 10
    return $this->get($key);
2070
  }
2071
2072
  /**
2073
   * Shifts a specified value off the beginning of array.
2074
   *
2075
   * @return mixed A shifted element from the current array.
2076
   */
2077 4
  public function shift()
2078
  {
2079 4
    return array_shift($this->array);
2080
  }
2081
2082
  /**
2083
   * Shuffle the current array.
2084
   *
2085
   * @return Arrayy (Immutable)
2086
   */
2087 1
  public function shuffle()
2088
  {
2089 1
    $array = $this->array;
2090
2091 1
    shuffle($array);
2092
2093 1
    return static::create($array);
2094
  }
2095
2096
  /**
2097
   * Get the size of an array.
2098
   *
2099
   * @return int
2100
   */
2101 110
  public function size()
2102
  {
2103 110
    return count($this->array);
2104
  }
2105
2106
  /**
2107
   * Extract a slice of the array.
2108
   *
2109
   * @param int      $offset       Slice begin index
2110
   * @param int|null $length       Length of the slice
2111
   * @param bool     $preserveKeys Whether array keys are preserved or no
2112
   *
2113
   * @return static A slice of the original array with length $length
2114
   */
2115 4
  public function slice($offset, $length = null, $preserveKeys = false)
2116
  {
2117 4
    $result = array_slice($this->array, $offset, $length, $preserveKeys);
2118
2119 4
    return static::create($result);
2120
  }
2121
2122
  /**
2123
   * Sort the current array and optional you can keep the keys.
2124
   *
2125
   * @param integer $direction use SORT_ASC or SORT_DESC
2126
   * @param integer $strategy
2127
   * @param bool       $keepKeys
2128
   *
2129
   * @return self (Mutable) Return this Arrayy object.
2130
   */
2131 19
  public function sort($direction = SORT_ASC, $strategy = SORT_REGULAR, $keepKeys = false)
2132
  {
2133 19
    $this->sorting($this->array, $direction, $strategy, $keepKeys);
2134
2135 19
    return $this;
2136
  }
2137
2138
  /**
2139
   * Sort the current array by key.
2140
   *
2141
   * @link http://php.net/manual/en/function.ksort.php
2142
   * @link http://php.net/manual/en/function.krsort.php
2143
   *
2144
   * @param int|string $direction use SORT_ASC or SORT_DESC
2145
   * @param int        $strategy  use e.g.: SORT_REGULAR or SORT_NATURAL
2146
   *
2147
   * @return self (Mutable) Return this Arrayy object.
2148
   */
2149 18
  public function sortKeys($direction = SORT_ASC, $strategy = SORT_REGULAR)
2150
  {
2151 18
    $this->sorterKeys($this->array, $direction, $strategy);
2152
2153 18
    return $this;
2154
  }
2155
2156
  /**
2157
   * Sort the current array by value.
2158
   *
2159
   * @param int $direction use SORT_ASC or SORT_DESC
2160
   * @param int $strategy  use e.g.: SORT_REGULAR or SORT_NATURAL
2161
   *
2162
   * @return Arrayy (Immutable)
2163
   */
2164 1
  public function sortValueKeepIndex($direction = SORT_ASC, $strategy = SORT_REGULAR)
2165
  {
2166 1
    return $this->sort($direction, $strategy, true);
2167
  }
2168
2169
  /**
2170
   * Sort the current array by value.
2171
   *
2172
   * @param int $direction use SORT_ASC or SORT_DESC
2173
   * @param int $strategy  use e.g.: SORT_REGULAR or SORT_NATURAL
2174
   *
2175
   * @return Arrayy (Immutable)
2176
   */
2177 1
  public function sortValueNewIndex($direction = SORT_ASC, $strategy = SORT_REGULAR)
2178
  {
2179 1
    return $this->sort($direction, $strategy, false);
2180
  }
2181
2182
  /**
2183
   * Sort a array by value, by a closure or by a property.
2184
   *
2185
   * - If the sorter is null, the array is sorted naturally.
2186
   * - Associative (string) keys will be maintained, but numeric keys will be re-indexed.
2187
   *
2188
   * @param null       $sorter
2189
   * @param string|int $direction
2190
   * @param int        $strategy
2191
   *
2192
   * @return Arrayy (Immutable)
2193
   */
2194 1
  public function sorter($sorter = null, $direction = SORT_ASC, $strategy = SORT_REGULAR)
2195
  {
2196 1
    $array = (array)$this->array;
2197 1
    $direction = $this->getDirection($direction);
2198
2199
    // Transform all values into their results.
2200 1
    if ($sorter) {
2201 1
      $arrayy = new self($array);
2202
2203 1
      $that = $this;
2204 1
      $results = $arrayy->each(
2205
          function ($value) use ($sorter, $that) {
2206 1
            return is_callable($sorter) ? $sorter($value) : $that->get($sorter, null, $value);
2207
          }
2208 1
      );
2209
2210 1
      $results = $results->getArray();
2211 1
    } else {
2212 1
      $results = $array;
2213
    }
2214
2215
    // Sort by the results and replace by original values
2216 1
    array_multisort($results, $direction, $strategy, $array);
2217
2218 1
    return static::create($array);
2219
  }
2220
2221
  /**
2222
   * sorting keys
2223
   *
2224
   * @param array $elements
2225
   * @param int   $direction
2226
   * @param int   $strategy
2227
   */
2228 18
  protected function sorterKeys(array &$elements, $direction = SORT_ASC, $strategy = SORT_REGULAR)
2229
  {
2230 18
    $direction = $this->getDirection($direction);
2231
2232
    switch ($direction) {
2233 18
      case 'desc':
2234 18
      case SORT_DESC:
2235 6
        krsort($elements, $strategy);
2236 6
        break;
2237 13
      case 'asc':
2238 13
      case SORT_ASC:
2239 13
      default:
2240 13
        ksort($elements, $strategy);
2241 13
    }
2242 18
  }
2243
2244
  /**
2245
   * @param array      &$elements
2246
   * @param int|string $direction
2247
   * @param int        $strategy
2248
   * @param bool       $keepKeys
2249
   */
2250 19
  protected function sorting(array &$elements, $direction = SORT_ASC, $strategy = SORT_REGULAR, $keepKeys = false)
2251
  {
2252 19
    $direction = $this->getDirection($direction);
2253
2254 19
    if (!$strategy) {
2255 19
      $strategy = SORT_REGULAR;
2256 19
    }
2257
2258
    switch ($direction) {
2259 19
      case 'desc':
2260 19
      case SORT_DESC:
2261 9
        if ($keepKeys) {
2262 5
          arsort($elements, $strategy);
2263 5
        } else {
2264 4
          rsort($elements, $strategy);
2265
        }
2266 9
        break;
2267 10
      case 'asc':
2268 10
      case SORT_ASC:
2269 10
      default:
2270 10
        if ($keepKeys) {
2271 4
          asort($elements, $strategy);
2272 4
        } else {
2273 6
          sort($elements, $strategy);
2274
        }
2275 10
    }
2276 19
  }
2277
2278
  /**
2279
   * Split an array in the given amount of pieces.
2280
   *
2281
   * @param int  $numberOfPieces
2282
   * @param bool $keepKeys
2283
   *
2284
   * @return Arrayy (Immutable)
2285
   */
2286 1
  public function split($numberOfPieces = 2, $keepKeys = false)
2287
  {
2288 1
    if (count($this->array) === 0) {
2289 1
      $result = array();
2290 1
    } else {
2291 1
      $numberOfPieces = (int)$numberOfPieces;
2292 1
      $splitSize = ceil(count($this->array) / $numberOfPieces);
2293 1
      $result = array_chunk($this->array, $splitSize, $keepKeys);
2294
    }
2295
2296 1
    return static::create($result);
2297
  }
2298
2299
  /**
2300
   * alias: for "Arrayy->getArray()"
2301
   */
2302 153
  public function toArray()
2303
  {
2304 153
    return $this->getArray();
2305
  }
2306
2307
  /**
2308
   * Convert the current array to JSON.
2309
   *
2310
   * @param null $options e.g. JSON_PRETTY_PRINT
2311
   *
2312
   * @return string
2313
   */
2314 5
  public function toJson($options = null)
2315
  {
2316 5
    return UTF8::json_encode($this->array, $options);
2317
  }
2318
2319
  /**
2320
   * Implodes array to a string with specified separator.
2321
   *
2322
   * @param string $separator The element's separator
2323
   *
2324
   * @return string The string representation of array, separated by ","
2325
   */
2326 15
  public function toString($separator = ',')
2327
  {
2328 15
    return $this->implode($separator);
2329
  }
2330
2331
  /**
2332
   * Return a duplicate free copy of the current array.
2333
   *
2334
   * @return Arrayy (Mutable)
2335
   */
2336 7
  public function unique()
2337
  {
2338 7
    $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...
2339 7
        $this->array,
2340 7
        function ($resultArray, $value) {
2341 6
          if (in_array($value, $resultArray, true) === false) {
2342 6
            $resultArray[] = $value;
2343 6
          }
2344
2345 6
          return $resultArray;
2346 7
        },
2347 7
        array()
2348 7
    );
2349
2350 7
    if ($this->array === null) {
2351
      $this->array = array();
2352
    } else {
2353 7
      $this->array = (array)$this->array;
2354
    }
2355
2356 7
    return $this;
2357
  }
2358
2359
  /**
2360
   * Prepends one or more values to the beginning of array at once.
2361
   *
2362
   * @return self (Mutable) Return this Arrayy object, with prepended elements to the beginning of array.
2363
   */
2364 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...
2365
  {
2366 4
    if (func_num_args()) {
2367 4
      $args = array_merge(array(&$this->array), func_get_args());
2368 4
      call_user_func_array('array_unshift', $args);
2369 4
    }
2370
2371 4
    return $this;
2372
  }
2373
2374
  /**
2375
   * Get all values from a array.
2376
   *
2377
   * @return Arrayy (Immutable)
2378
   */
2379 1
  public function values()
2380
  {
2381 1
    $array = array_values((array)$this->array);
2382
2383 1
    return static::create($array);
2384
  }
2385
2386
  /**
2387
   * Apply the given function to every element in the array, discarding the results.
2388
   *
2389
   * @param callable $callable
2390
   * @param bool     $recursive Whether array will be walked recursively or no
2391
   *
2392
   * @return self (Mutable) Return this Arrayy object, with modified elements
2393
   */
2394 9
  public function walk($callable, $recursive = false)
2395
  {
2396 9
    if (true === $recursive) {
2397 4
      array_walk_recursive($this->array, $callable);
2398 4
    } else {
2399 5
      array_walk($this->array, $callable);
2400
    }
2401
2402 9
    return $this;
2403
  }
2404
2405
2406
}
2407