Completed
Push — master ( 278b7a...941193 )
by Lars
02:17
created

Arrayy::toJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Arrayy;
4
5
use ArrayAccess;
6
use voku\helper\UTF8;
7
8
/**
9
 * Methods to manage arrays.
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
class Arrayy extends ArrayyAbstract implements \Countable, \IteratorAggregate, \ArrayAccess
15
{
16
  /**
17
   * Initializes
18
   *
19
   * @param array $array
20
   */
21 403
  public function __construct($array = array())
22
  {
23 403
    if (!$array) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $array 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...
24 81
      $array = array();
25 81
    }
26
27
    if (
28 403
        is_string($array)
29
        ||
30 403
        (is_object($array) && method_exists($array, '__toString'))
31 403
    ) {
32 1
      $array = (array)$array;
33 1
    }
34
35 403
    if (!is_array($array)) {
36 2
      throw new \InvalidArgumentException(
37
          'Passed value must be a array'
38 2
      );
39
    }
40
41 401
    $this->array = $array;
42 401
  }
43
44
  /**
45
   * magic to string
46
   *
47
   * @return string
48
   */
49 14
  public function __toString()
50
  {
51 14
    return $this->implode(',');
52
  }
53
54
  /**
55
   * Get a data by key
56
   *
57
   * @param $key
58
   *
59
   * @return mixed
60
   */
61
  public function &__get($key)
62
  {
63
    return $this->array[$key];
64
  }
65
66
  /**
67
   * Assigns a value to the specified data
68
   *
69
   * @param $key
70
   * @param $value
71
   */
72
  public function __set($key, $value)
73
  {
74
    $this->array[$key] = $value;
75
  }
76
77
  /**
78
   * Whether or not an data exists by key
79
   *
80
   * @param $key
81
   *
82
   * @return bool
83
   */
84
  public function __isset($key)
85
  {
86
    return isset($this->array[$key]);
87
  }
88
89
  /**
90
   * Unsets an data by key
91
   *
92
   * @param mixed $key
93
   */
94
  public function __unset($key)
95
  {
96
    unset($this->array[$key]);
97
  }
98
99
  /**
100
   * Assigns a value to the specified offset
101
   *
102
   *
103
   * @param mixed $offset
104
   * @param mixed $value
105
   */
106 2
  public function offsetSet($offset, $value)
107
  {
108 2
    if (null === $offset) {
109
      $this->array[] = $value;
110
    } else {
111 2
      $this->array[$offset] = $value;
112
    }
113 2
  }
114
115
  /**
116
   * Whether or not an offset exists
117
   *
118
   * @param mixed $offset
119
   *
120
   * @return bool
121
   */
122 9
  public function offsetExists($offset)
123
  {
124 9
    return isset($this->array[$offset]);
125
  }
126
127
  /**
128
   * Unsets an offset
129
   *
130
   * @param mixed $offset
131
   */
132 1
  public function offsetUnset($offset)
133
  {
134 1
    if ($this->offsetExists($offset)) {
135 1
      unset($this->array[$offset]);
136 1
    }
137 1
  }
138
139
  /**
140
   * Returns the value at specified offset
141
   *
142
   * @param mixed $offset
143
   *
144
   * @return null
145
   */
146 8
  public function offsetGet($offset)
147
  {
148 8
    return $this->offsetExists($offset) ? $this->array[$offset] : null;
149
  }
150
151
  /**
152
   * Returns a new ArrayIterator, thus implementing the IteratorAggregate
153
   * interface.
154
   *
155
   * @return \ArrayIterator An iterator for the values in the array
156
   */
157 2
  public function getIterator()
158
  {
159 2
    return new \ArrayIterator($this->array);
160
  }
161
162
  /**
163
   * call object as function
164
   *
165
   * @param mixed $key
166
   *
167
   * @return mixed
168
   */
169
  public function __invoke($key = null)
170
  {
171
    if ($key !== null) {
172
      if (isset($this->array[$key])) {
173
        return $this->array[$key];
174
      } else {
175
        return false;
176
      }
177
    }
178
179
    return (array)$this->array;
180
  }
181
182
  /**
183
   * get the current array from the "Arrayy"-object
184
   *
185
   * @return array
186
   */
187 231
  public function getArray()
188
  {
189 231
    return $this->array;
190
  }
191
192
  /**
193
   * Creates a Arrayy object
194
   *
195
   * @param array $array
196
   *
197
   * @return Arrayy
198
   */
199 306
  public static function create($array = array())
200
  {
201 306
    return new static($array);
202
  }
203
204
  /**
205
   * Create a new Arrayy object via string.
206
   *
207
   * @param string      $str       The input string.
208
   * @param string|null $delimiter The boundary string.
209
   * @param string|null $regEx     Use the $delimiter or the $regEx, so if $pattern is null, $delimiter will be used.
210
   *
211
   * @return Arrayy
212
   */
213 2
  public static function createFromString($str, $delimiter, $regEx = null)
214
  {
215 2
    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...
216 1
      preg_match_all($regEx, $str, $array);
217
218 1
      if (count($array) > 0) {
219 1
        $array = $array[0];
220 1
      }
221
222 1
    } else {
223 1
      $array = explode($delimiter, $str);
224
    }
225
226
    // trim all string in the array
227 2
    array_walk(
228 2
        $array,
229
        function (&$val) {
230 2
          if (is_string($val)) {
231 2
            $val = trim($val);
232 2
          }
233 2
        }
234 2
    );
235
236 2
    return self::create($array);
237
  }
238
239
  /**
240
   * create a new Arrayy object via JSON,
241
   *
242
   * @param string $json
243
   *
244
   * @return Arrayy
245
   */
246 1
  public static function createFromJson($json)
247
  {
248 1
    $array = UTF8::json_decode($json, true);
249
250 1
    return self::create($array);
251
  }
252
253
  ////////////////////////////////////////////////////////////////////
254
  ///////////////////////////// ANALYZE //////////////////////////////
255
  ////////////////////////////////////////////////////////////////////
256
257
  /**
258
   * Search for the value of the current array via $index.
259
   *
260
   * @param mixed $index
261
   *
262
   * @return Arrayy will return a empty Arrayy if the value wasn't found
263
   */
264 7
  public function searchValue($index)
265
  {
266
    // init
267 7
    $return = array();
268
269 7
    if (null !== $index) {
270 7
      $keyExists = isset($this->array[$index]);
271
272 7
      if ($keyExists !== false) {
273 5
        $return = array($this->array[$index]);
274 5
      }
275 7
    }
276
277 7
    return static::create((array)$return);
278
  }
279
280
  /**
281
   * Search for the first index of the current array via $value.
282
   *
283
   * @param mixed $value
284
   *
285
   * @return Arrayy will return a empty Arrayy if the index wasn't found
286
   */
287 16
  public function searchIndex($value)
288
  {
289 16
    $key = array_search($value, $this->array, true);
290
291 16
    if ($key === false) {
292 9
      $return = array();
293 9
    } else {
294 7
      $return = array($key);
295
    }
296
297 16
    return static::create((array)$return);
298
  }
299
300
  /**
301
   * Check if all items in current array match a truth test.
302
   *
303
   * @param \Closure $closure
304
   *
305
   * @return bool
306
   */
307 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...
308
  {
309
    // Reduce the array to only booleans
310 9
    $array = $this->each($closure);
311
312
    // Check the results
313 9
    if (count($array) === 0) {
314 2
      return true;
315
    }
316 7
    $array = array_search(false, $array, false);
317
318 7
    return is_bool($array);
319
  }
320
321
  /**
322
   * Check if any item in the current array matches a truth test.
323
   *
324
   * @param \Closure $closure
325
   *
326
   * @return bool
327
   */
328 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...
329
  {
330
    // Reduce the array to only booleans
331 9
    $array = $this->each($closure);
332
333
    // Check the results
334 9
    if (count($array) === 0) {
335 2
      return true;
336
    }
337 7
    $array = array_search(true, $array, false);
338
339 7
    return is_int($array);
340
  }
341
342
  /**
343
   * Check if we have named keys in the current array.
344
   *
345
   * @return bool
346
   */
347 12
  public function isAssoc()
348
  {
349 12
    if (count($this->array) === 0) {
350 1
      return false;
351
    }
352
353 11
    return (bool)count(array_filter(array_keys($this->array), 'is_string'));
354
  }
355
356
  /**
357
   * Check if the current array is a multi-array.
358
   *
359
   * @return bool
360
   */
361 13
  public function isMultiArray()
362
  {
363 13
    return !(count($this->array) === count($this->array, COUNT_RECURSIVE));
364
  }
365
366
  /**
367
   * Check if an item is in the current array.
368
   *
369
   * @param mixed $value
370
   *
371
   * @return bool
372
   */
373 9
  public function contains($value)
374
  {
375 9
    return in_array($value, $this->array, true);
376
  }
377
378
  /**
379
   * Returns the average value of the current array.
380
   *
381
   * @param int $decimals The number of decimals to return
382
   *
383
   * @return int|double The average value
384
   */
385 10
  public function average($decimals = null)
386
  {
387 10
    $count = $this->count();
388
389 10
    if (!$count) {
390 2
      return 0;
391
    }
392
393 8
    if (!is_int($decimals)) {
394 3
      $decimals = null;
395 3
    }
396
397 8
    return round(array_sum($this->array) / $count, $decimals);
398
  }
399
400
  /**
401
   * Count the values from the current array.
402
   *
403
   * INFO: only a alias for "$arrayy->size()"
404
   *
405
   * @return int
406
   */
407 10
  public function length()
408
  {
409 10
    return $this->size();
410
  }
411
412
  /**
413
   * Count the values from the current array.
414
   *
415
   * INFO: only a alias for "$arrayy->size()"
416
   *
417
   * @return int
418
   */
419 59
  public function count()
420
  {
421 59
    return $this->size();
422
  }
423
424
  /**
425
   * Get the size of an array.
426
   *
427
   * @return int
428
   */
429 59
  public function size()
430
  {
431 59
    return count($this->array);
432
  }
433
434
  /**
435
   * Get the max value from an array.
436
   *
437
   * @return mixed
438
   */
439 10
  public function max()
440
  {
441 10
    if ($this->count() === 0) {
442 1
      return false;
443
    }
444
445 9
    return max($this->array);
446
  }
447
448
  /**
449
   * Get the min value from an array.
450
   *
451
   * @return mixed
452
   */
453 10
  public function min()
454
  {
455 10
    if ($this->count() === 0) {
456 1
      return false;
457
    }
458
459 9
    return min($this->array);
460
  }
461
462
  ////////////////////////////////////////////////////////////////////
463
  //////////////////////////// FETCH FROM ////////////////////////////
464
  ////////////////////////////////////////////////////////////////////
465
466
  /**
467
   * Find the first item in an array that passes the truth test,
468
   *  otherwise return false
469
   *
470
   * @param \Closure $closure
471
   *
472
   * @return mixed|false false if we couldn't find the value
473
   */
474 7
  public function find(\Closure $closure)
475
  {
476 7
    foreach ($this->array as $key => $value) {
477 5
      if ($closure($value, $key)) {
478 4
        return $value;
479
      }
480 4
    }
481
482 3
    return false;
483
  }
484
485
  /**
486
   * Clean all falsy values from an array.
487
   *
488
   * @return Arrayy
489
   */
490 8
  public function clean()
491
  {
492 8
    return $this->filter(
493
        function ($value) {
494 7
          return (bool)$value;
495
        }
496 8
    );
497
  }
498
499
  /**
500
   * Get a random string from an array.
501
   *
502
   * @param null|int $take how many values you will take?
503
   *
504
   * @return Arrayy
505
   */
506 18
  public function random($take = null)
507
  {
508 18
    if ($this->count() === 0) {
509
      return self::create(array());
510
    }
511
512 18
    if ($take === null) {
513 12
      return static::create((array)$this->array[array_rand($this->array)]);
514
    }
515
516 8
    shuffle($this->array);
517
518 8
    return $this->first($take);
519
  }
520
521
  /**
522
   * Get a random value from an array, with the ability to skew the results.
523
   *
524
   * Example: randomWeighted(['foo' => 1, 'bar' => 2]) has a 66% chance of returning bar.
525
   *
526
   * @param array    $array
527
   * @param null|int $take how many values you will take?
528
   *
529
   * @return Arrayy
530
   */
531 9
  public function randomWeighted(array $array, $take = null)
532
  {
533 9
    $options = array();
534 9
    foreach ($array as $option => $weight) {
535 9
      if ($this->searchIndex($option)->count() > 0) {
536 2
        for ($i = 0; $i < $weight; ++$i) {
537 1
          $options[] = $option;
538 1
        }
539 2
      }
540 9
    }
541
542 9
    return $this->mergeAppendKeepIndex($options)->random($take);
543
  }
544
545
  /**
546
   * Return an array with all elements found in input array.
547
   *
548
   * @param array $search
549
   *
550
   * @return Arrayy
551
   */
552 2
  public function intersection(array $search)
553
  {
554 2
    return static::create(array_values(array_intersect($this->array, $search)));
555
  }
556
557
  /**
558
   * Return a boolean flag which indicates whether the two input arrays have any common elements.
559
   *
560
   * @param array $search
561
   *
562
   * @return bool
563
   */
564 1
  public function intersects(array $search)
565
  {
566 1
    return count($this->intersection($search)->array) > 0;
567
  }
568
569
  ////////////////////////////////////////////////////////////////////
570
  ///////////////////////////// SLICERS //////////////////////////////
571
  ////////////////////////////////////////////////////////////////////
572
573
  /**
574
   * Get the first value(s) from the current array.
575
   *
576
   * @param int|null $take how many values you will take?
577
   *
578
   * @return Arrayy
579
   */
580 33
  public function first($take = null)
581
  {
582 33
    if ($take === null) {
583 8
      $array = array_shift($this->array);
584 8
    } else {
585 25
      $array = array_splice($this->array, 0, $take, true);
586
    }
587
588 33
    return static::create((array)$array);
589
  }
590
591
  /**
592
   * Get the last value(s) from the current array.
593
   *
594
   * @param int|null $take
595
   *
596
   * @return Arrayy
597
   */
598 11
  public function last($take = null)
599
  {
600 11
    if ($take === null) {
601 7
      $array = static::create((array)array_pop($this->array));
602 7
    } else {
603 4
      $array = $this->rest(-$take);
604
    }
605
606 11
    return $array;
607
  }
608
609
  /**
610
   * Get everything but the last..$to items.
611
   *
612
   * @param int $to
613
   *
614
   * @return Arrayy
615
   */
616 12
  public function initial($to = 1)
617
  {
618 12
    $slice = count($this->array) - $to;
619
620 12
    return $this->first($slice);
621
  }
622
623
  /**
624
   * Get the last elements from index $from until the end of this array.
625
   *
626
   * @param int $from
627
   *
628
   * @return Arrayy
629
   */
630 16
  public function rest($from = 1)
631
  {
632 16
    return static::create(array_splice($this->array, $from));
633
  }
634
635
  ////////////////////////////////////////////////////////////////////
636
  ///////////////////////////// ACT UPON /////////////////////////////
637
  ////////////////////////////////////////////////////////////////////
638
639
  /**
640
   * Iterate over an array and execute a callback for each loop.
641
   *
642
   * @param \Closure $closure
643
   *
644
   * @return Arrayy
645
   */
646 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...
647
  {
648 2
    $array = $this->array;
649
650 2
    foreach ($array as $key => $value) {
651 2
      $closure($value, $key);
652 2
    }
653
654 2
    return static::create($array);
655
  }
656
657
  ////////////////////////////////////////////////////////////////////
658
  ////////////////////////////// ALTER ///////////////////////////////
659
  ////////////////////////////////////////////////////////////////////
660
661
  /**
662
   * Merge the new $array into the current array.
663
   *
664
   * - replace duplicate assoc-keys from the current array with the key,values from the new $array
665
   * - create new indexes
666
   *
667
   * @param array $array
668
   *
669
   * @return Arrayy
670
   */
671 8
  public function mergeAppendNewIndex(array $array = array())
672
  {
673 8
    return static::create(array_merge($this->array, $array));
674
  }
675
676
  /**
677
   * Merge the current array into the new $array.
678
   *
679
   * - replace duplicate assoc-keys from new $array with the key,values from the current array
680
   * - create new indexes
681
   *
682
   * @param array $array
683
   *
684
   * @return Arrayy
685
   */
686 8
  public function mergePrependNewIndex(array $array = array())
687
  {
688 8
    return static::create(array_merge($array, $this->array));
689
  }
690
691
  /**
692
   * Merge the new $array into the current array.
693
   *
694
   * - keep key,value from the current array, also if the index is in the new $array
695
   *
696
   * @param array $array
697
   *
698
   * @return Arrayy
699
   */
700 17
  public function mergeAppendKeepIndex(array $array = array())
701
  {
702 17
    return static::create(array_replace($this->array, $array));
703
  }
704
705
  /**
706
   * Merge the the current array into the $array.
707
   *
708
   * - use key,value from the new $array, also if the index is in the current array
709
   *
710
   * @param array $array
711
   *
712
   * @return Arrayy
713
   */
714 8
  public function mergePrependKeepIndex(array $array = array())
715
  {
716 8
    return static::create(array_replace($array, $this->array));
717
  }
718
719
  /**
720
   * Return values that are only in the current array.
721
   *
722
   * @param array $array
723
   *
724
   * @return Arrayy
725
   */
726 8
  public function diff(array $array = array())
727
  {
728 8
    return static::create(array_diff($this->array, $array));
729
  }
730
731
  /**
732
   * Return values that are only in the new $array.
733
   *
734
   * @param array $array
735
   *
736
   * @return Arrayy
737
   */
738 8
  public function diffReverse(array $array = array())
739
  {
740 8
    return static::create(array_diff($array, $this->array));
741
  }
742
743
  /**
744
   * Replace the first matched value in an array.
745
   *
746
   * @param mixed $search
747
   * @param mixed $replacement
748
   *
749
   * @return Arrayy
750
   */
751 3
  public function replaceOneValue($search, $replacement = '')
752
  {
753 3
    $array = $this->array;
754 3
    $key = array_search($search, $array, true);
755
756 3
    if ($key !== false) {
757 3
      $array[$key] = $replacement;
758 3
    }
759
760 3
    return static::create($array);
761
  }
762
763
  /**
764
   * Replace values in the current array.
765
   *
766
   * @param string $search      The string to replace.
767
   * @param string $replacement What to replace it with.
768
   *
769
   * @return Arrayy
770
   */
771 1
  public function replaceValues($search, $replacement = '')
772
  {
773 1
    $array = $this->each(
774
        function ($value) use ($search, $replacement) {
775 1
          return UTF8::str_replace($search, $replacement, $value);
776
        }
777 1
    );
778
779 1
    return static::create((array)$array);
780
  }
781
782
  /**
783
   * Replace the keys in an array with another set.
784
   *
785
   * @param array $keys An array of keys matching the array's size
786
   *
787
   * @return Arrayy
788
   */
789 1
  public function replaceKeys(array $keys)
790
  {
791 1
    $values = array_values($this->array);
792
793 1
    return static::create(array_combine($keys, $values));
794
  }
795
796
  /**
797
   * Iterate over the current array and modify the array's value.
798
   *
799
   * @param \Closure $closure
800
   *
801
   * @return array
802
   */
803 22
  public function each(\Closure $closure)
804
  {
805 22
    $array = $this->array;
806
807 22
    foreach ($array as $key => &$value) {
808 18
      $value = $closure($value, $key);
809 22
    }
810
811 22
    return $array;
812
  }
813
814
  /**
815
   * Shuffle the current array.
816
   *
817
   * @return Arrayy
818
   */
819 1
  public function shuffle()
820
  {
821 1
    $array = $this->array;
822
823 1
    shuffle($array);
824
825 1
    return static::create($array);
826
  }
827
828
829
  /**
830
   * Split an array in the given amount of pieces.
831
   *
832
   * @param int  $numberOfPieces
833
   * @param bool $preserveKeys
834
   *
835
   * @return array
836
   */
837 1
  public function split($numberOfPieces = 2, $preserveKeys = false)
838
  {
839 1
    if (count($this->array) === 0) {
840 1
      return self::create(array());
841
    }
842
843 1
    $splitSize = ceil(count($this->array) / $numberOfPieces);
844
845 1
    return self::create(array_chunk($this->array, $splitSize, $preserveKeys));
846
  }
847
848
  /**
849
   * Sort the current array by key.
850
   *
851
   * @param string $direction
852
   *
853
   * @return Arrayy
854
   */
855 9
  public function sortKeys($direction = 'ASC')
856
  {
857 9
    $array = $this->array;
858 9
    $direction = strtolower($direction);
859
860 9
    if ($direction === 'desc') {
861 1
      $directionType = SORT_DESC;
862 1
    } else {
863 8
      $directionType = SORT_ASC;
864
    }
865
866 9
    if ($directionType === SORT_ASC) {
867 8
      ksort($array);
868 8
    } else {
869 1
      krsort($array);
870
    }
871
872 9
    return static::create($array);
873
  }
874
875
  /**
876
   * Implodes an array.
877
   *
878
   * @param string $with What to implode it with
879
   *
880
   * @return string
881
   */
882 22
  public function implode($with = '')
883
  {
884 22
    return implode($with, $this->array);
885
  }
886
887
  /**
888
   * Returns the values from a single column of the input array, identified by
889
   * the $columnKey, can be used to extract data-columns from multi-arrays.
890
   *
891
   * Info: Optionally, you may provide an $indexKey to index the values in the returned
892
   * array by the values from the $indexKey column in the input array.
893
   *
894
   * @param mixed $columnKey
895
   * @param mixed $indexKey
896
   *
897
   * @return Arrayy
898
   */
899 1
  public function getColumn($columnKey = null, $indexKey = null)
900
  {
901 1
    return self::create(array_column($this->array, $columnKey, $indexKey));
0 ignored issues
show
Bug introduced by
It seems like array_column($this->array, $columnKey, $indexKey) targeting array_column() can also be of type false or null; however, Arrayy\Arrayy::create() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
902
  }
903
904
  /**
905
   * Find all items in an array that pass the truth test.
906
   *
907
   * @param \Closure|null $closure
908
   *
909
   * @return Arrayy
910
   */
911 8
  public function filter($closure = null)
912
  {
913 8
    if (!$closure) {
914 1
      return $this->clean();
915
    }
916
917 8
    $array = array_filter($this->array, $closure);
918
919 8
    return static::create($array);
920
  }
921
922
  /**
923
   * Invoke a function on all of an array's values.
924
   *
925
   * @param mixed $callable
926
   * @param array $arguments
927
   *
928
   * @return Arrayy
929
   */
930 2
  public function invoke($callable, $arguments = array())
931
  {
932
    // If one argument given for each iteration, create an array for it.
933 1
    if (!is_array($arguments)) {
934 1
      $arguments = StaticArrayy::repeat($arguments, count($this->array))->getArray();
935 1
    }
936
937
    // If the callable has arguments, pass them.
938 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...
939 1
      $array = array_map($callable, $this->array, $arguments);
940 2
    } else {
941 1
      $array = array_map($callable, $this->array);
942
    }
943
944 1
    return static::create($array);
945
  }
946
947
  /**
948
   * Return all items that fail the truth test.
949
   *
950
   * @param \Closure $closure
951
   *
952
   * @return Arrayy
953
   */
954 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...
955
  {
956 1
    $filtered = array();
957
958 1
    foreach ($this->array as $key => $value) {
959 1
      if (!$closure($value, $key)) {
960 1
        $filtered[$key] = $value;
961 1
      }
962 1
    }
963
964 1
    return static::create($filtered);
965
  }
966
967
  /**
968
   * Remove the first value from the current array.
969
   *
970
   * @return Arrayy
971
   */
972 8
  public function removeFirst()
973
  {
974 8
    array_shift($this->array);
975
976 8
    return static::create($this->array);
977
  }
978
979
  /**
980
   * Remove the last value from the current array.
981
   *
982
   * @return Arrayy
983
   */
984 7
  public function removeLast()
985
  {
986 7
    array_pop($this->array);
987
988 7
    return static::create($this->array);
989
  }
990
991
  /**
992
   * Removes a particular value from an array (numeric or associative).
993
   *
994
   * @param mixed $value
995
   *
996
   * @return Arrayy
997
   */
998 7
  public function removeValue($value)
999
  {
1000 7
    $isNumericArray = true;
1001 7
    foreach ($this->array as $key => $item) {
1002 6
      if ($item === $value) {
1003 6
        if (!is_int($key)) {
1004
          $isNumericArray = false;
1005
        }
1006 6
        unset($this->array[$key]);
1007 6
      }
1008 7
    }
1009
1010 7
    if ($isNumericArray) {
1011 7
      $this->array = array_values($this->array);
1012 7
    }
1013
1014 7
    return static::create($this->array);
1015
  }
1016
1017
  /**
1018
   * Prepend a value to an array.
1019
   *
1020
   * @param mixed $value
1021
   *
1022
   * @return Arrayy
1023
   */
1024 7
  public function prepend($value)
1025
  {
1026 7
    array_unshift($this->array, $value);
1027
1028 7
    return static::create($this->array);
1029
  }
1030
1031
  /**
1032
   * Append a value to an array.
1033
   *
1034
   * @param mixed $value
1035
   *
1036
   * @return Arrayy
1037
   */
1038 8
  public function append($value)
1039
  {
1040 8
    $this->array[] = $value;
1041
1042 8
    return static::create($this->array);
1043
  }
1044
1045
  /**
1046
   * Return the array in the reverse order.
1047
   *
1048
   * @return Arrayy
1049
   */
1050 7
  public function reverse()
1051
  {
1052 7
    $this->array = array_reverse($this->array);
1053
1054 7
    return static::create($this->array);
1055
  }
1056
1057
  /**
1058
   * Exchanges all keys with their associated values in an array.
1059
   *
1060
   * @return Arrayy
1061
   */
1062 1
  public function flip()
1063
  {
1064 1
    $this->array = array_flip($this->array);
1065
1066 1
    return static::create($this->array);
1067
  }
1068
1069
  /**
1070
   * Reduce the current array via callable e.g. anonymous-function.
1071
   *
1072
   * @param mixed $predicate
1073
   * @param array $init
1074
   *
1075
   * @return Arrayy
1076
   */
1077 2
  public function reduce($predicate, array $init = array())
1078
  {
1079 2
    $this->array = array_reduce($this->array, $predicate, $init);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_reduce($this->array, $predicate, $init) 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...
1080
1081 2
    return static::create($this->array);
1082
  }
1083
1084
  /**
1085
   * Return a duplicate free copy of the current array.
1086
   *
1087
   * @return Arrayy
1088
   */
1089 7
  public function unique()
1090
  {
1091 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...
1092 7
        $this->array,
1093 7
        function ($resultArray, $value) {
1094 6
          if (in_array($value, $resultArray, true) === false) {
1095 6
            $resultArray[] = $value;
1096 6
          }
1097
1098 6
          return $resultArray;
1099 7
        },
1100 7
        array()
1101 7
    );
1102
1103 7
    return static::create($this->array);
1104
  }
1105
1106
  /**
1107
   * Convert the current array to JSON.
1108
   *
1109
   * @param null $options e.g. JSON_PRETTY_PRINT
1110
   *
1111
   * @return string
1112
   */
1113 1
  public function toJson($options = null)
1114
  {
1115 1
    return UTF8::json_encode($this->array, $options);
1116
  }
1117
}
1118