Arrays::repeat()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace __\Traits;
4
5
use __;
6
7
trait Arrays
8
{
9
    /**
10
     * Append item to array
11
     *
12
     * @usage __::append([1, 2, 3], 4);
13
     *        >> [1, 2, 3, 4]
14
     *
15
     * @param array $array original array
16
     * @param mixed $value new item or value to append
17
     *
18
     * @return array
19
     */
20 1
    public static function append(array $array = [], $value = null): array
21
    {
22 1
        $array[] = $value;
23
24 1
        return $array;
25
    }
26
27
    /**
28
     * Creates  an  array  with  all  falsey  values removed. The values false, null, 0, "", undefined, and NaN are all
29
     * falsey.
30
     *
31
     * @usage __::compact([0, 1, false, 2, '', 3]);
32
     *        >> [1, 2, 3]
33
     *
34
     * @param array $array array to compact
35
     *
36
     * @return array
37
     */
38 3
    public static function compact(array $array = []): array
39
    {
40 3
        $result = [];
41
42 3
        foreach ($array as $value) {
43 3
            if ($value) {
44 3
                $result[] = $value;
45
            }
46
        }
47
48 3
        return $result;
49
    }
50
51
52
    /**
53
     * base flatten
54
     *
55
     * @param array $array
56
     * @param bool  $shallow
57
     * @param bool  $strict
58
     * @param int   $startIndex
59
     *
60
     * @return array
61
     */
62 1
    public static function baseFlatten(
63
        array $array,
64
        bool $shallow = false,
65
        bool $strict = true,
66
        int $startIndex = 0
0 ignored issues
show
Unused Code introduced by
The parameter $startIndex is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

66
        /** @scrutinizer ignore-unused */ int $startIndex = 0

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
67
    ): array {
68 1
        $idx = 0;
69 1
        $output = [];
70
71 1
        foreach ($array as $index => $value) {
72 1
            if (is_array($value)) {
73 1
                if (!$shallow) {
74 1
                    $value = static::baseFlatten($value, $shallow, $strict);
75
                }
76 1
                $j = 0;
77 1
                $len = count($value);
78 1
                while ($j < $len) {
79 1
                    $output[$idx++] = $value[$j++];
80
                }
81
            } else {
82 1
                if (!$strict) {
83 1
                    $output[$idx++] = $value;
84
                }
85
            }
86
        }
87
88 1
        return $output;
89
    }
90
91
    /**
92
     * Flattens a multidimensional array. If you pass shallow, the array will only be flattened a single level.
93
     *
94
     * @usage __::flatten([1, 2, [3, [4]]], [flatten]);
95
     *        >> [1, 2, 3, 4]
96
     *
97
     * @param array $array
98
     * @param bool  $shallow
99
     *
100
     * @return array
101
     */
102 1
    public static function flatten(array $array, bool $shallow = false): array
103
    {
104 1
        return static::baseFlatten($array, $shallow, false);
105
    }
106
107
    /**
108
     *  Patches array by xpath.
109
     *
110
     * @usage __::patch(
111
     *               ['addr' => ['country' => 'US', 'zip' => 12345]],
112
     *               ['/addr/country' => 'CA','/addr/zip' => 54321]
113
     *           );
114
     **       >> ['addr' => ['country' => 'CA', 'zip' => 54321]]
115
     *
116
     * @param array  $array   The array to patch
117
     * @param array  $patches List of new xpath-value pairs
118
     * @param string $parent
119
     *
120
     * @return array Returns patched array
121
     */
122 1
    public static function patch(array $array, array $patches, string $parent = ''): array
123
    {
124 1
        foreach ($array as $key => $value) {
125 1
            $z = $parent . '/' . $key;
126
127 1
            if (isset($patches[$z])) {
128 1
                $array[$key] = $patches[$z];
129 1
                unset($patches[$z]);
130
131 1
                if (!count($patches)) {
132 1
                    break;
133
                }
134
            }
135
136 1
            if (is_array($value)) {
137 1
                $array[$key] = static::patch($value, $patches, $z);
138
            }
139
        }
140
141 1
        return $array;
142
    }
143
144
    /**
145
     * Prepend item or value to an array
146
     *
147
     * @usage __::prepend([1, 2, 3], 4);
148
     *        >> [4, 1, 2, 3]
149
     *
150
     * @param array $array
151
     * @param mixed $value
152
     *
153
     * @return array
154
     */
155 2
    public static function prepend(array $array = [], $value = null): array
156
    {
157 2
        array_unshift($array, $value);
158
159 2
        return $array;
160
    }
161
162
    /**
163
     * Generate range of values based on start , end and step
164
     *
165
     * @usage __::range(1, 10, 2);
166
     **       >> [1, 3, 5, 7, 9]
167
     *
168
     * @param int|null $start range start
169
     * @param int|null $stop  range end
170
     * @param int      $step  range step value
171
     *
172
     * @return array range of values
173
     */
174 1
    public static function range($start = null, $stop = null, int $step = 1): array
175
    {
176 1
        if ($stop == null && $start != null) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $stop of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison === instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing $start of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison !== instead.
Loading history...
177 1
            $stop = $start;
178 1
            $start = 1;
179
        }
180
181 1
        return range($start, $stop, $step);
182
    }
183
184
    /**
185
     * Generate array of repeated values
186
     *
187
     * @usage __::repeat('foo', 3);
188
     **       >> ['foo', 'foo', 'foo']
189
     *
190
     * @param string $object The object to repeat.
191
     * @param int    $times  ow many times has to be repeated.
192
     *
193
     * @return array Returns a new array of filled values.
194
     *
195
     */
196 1
    public static function repeat($object = '', int $times = null): array
197
    {
198 1
        $times = abs($times);
199 1
        if ($times == null) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $times of type double|integer against null; this is ambiguous if the integer can be zero. Consider using a strict comparison === instead.
Loading history...
200 1
            return [];
201
        }
202
203 1
        return array_fill(0, $times, $object);
0 ignored issues
show
Bug introduced by
It seems like $times can also be of type double; however, parameter $num of array_fill() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

203
        return array_fill(0, /** @scrutinizer ignore-type */ $times, $object);
Loading history...
204
    }
205
206
    /**
207
     * Creates an array of elements split into groups the length of size. If array can't be split evenly, the final
208
     * chunk will be the remaining elements.
209
     *
210
     * @usage __::chunk([1, 2, 3, 4, 5], 3);
211
     *        >> [[1, 2, 3], [4, 5]]
212
     *
213
     * @param array $array          original array
214
     * @param int   $size           the chunk size
215
     * @param bool  $preserveKeys   When set to TRUE keys will be preserved. Default is FALSE which will reindex the
216
     *                              chunk numerically
217
     *
218
     * @return array
219
     */
220 1
    public static function chunk(array $array, int $size = 1, bool $preserveKeys = false): array
221
    {
222 1
        return array_chunk($array, $size, $preserveKeys);
223
    }
224
225
    /**
226
     * Creates a slice of array with n elements dropped from the beginning.
227
     *
228
     * @usage __::drop([0, 1, 3], 2);
229
     *        >> [3]
230
     *
231
     * @param array $input  The array to query.
232
     * @param int   $number The number of elements to drop.
233
     *
234
     * @return array
235
     */
236 1
    public static function drop(array $input, int $number = 1): array
237
    {
238 1
        return array_slice($input, $number);
239
    }
240
241
    /**
242
     * Shuffle an array ensuring no item remains in the same position.
243
     *
244
     * @usage __::randomize([1, 2, 3]);
245
     *        >> [2, 3, 1]
246
     *
247
     * @param array $array original array
248
     *
249
     * @return array
250
     */
251 1
    public static function randomize(array $array): array
252
    {
253 1
        for ($i = 0, $c = count($array); $i < $c - 1; $i++) {
254 1
            $j = rand($i + 1, $c - 1);
255 1
            list($array[$i], $array[$j]) = [$array[$j], $array[$i]];
256
        }
257
258 1
        return $array;
259
    }
260
261
    /**
262
     * Search for the index of a value in an array.
263
     *
264
     * @usage __::search(['a', 'b', 'c'], 'b')
265
     *        >> 1
266
     *
267
     * @param array  $array
268
     * @param string $value
269
     *
270
     * @return mixed
271
     */
272 1
    public static function search(array $array, string $value)
273
    {
274 1
        return array_search($value, $array, true);
275
    }
276
277
    /**
278
     * Check if an item is in an array.
279
     *
280
     * @usage __::contains(['a', 'b', 'c'], 'b')
281
     *        >> true
282
     *
283
     * @param array  $array
284
     * @param string $value
285
     *
286
     * @return bool
287
     */
288 1
    public static function contains(array $array, string $value): bool
289
    {
290 1
        return in_array($value, $array, true);
291
    }
292
293
    /**
294
     * Returns the average value of an array.
295
     *
296
     * @usage __::average([1, 2, 3])
297
     *        >> 2
298
     *
299
     * @param array $array    The source array
300
     * @param int   $decimals The number of decimals to return
301
     *
302
     * @return float The average value
303
     */
304 1
    public static function average(array $array, int $decimals = 0): float
305
    {
306 1
        return round((array_sum($array) / count($array)), $decimals);
307
    }
308
309
    /**
310
     * Get the size of an array.
311
     *
312
     * @usage __::size([1, 2, 3])
313
     *        >> 3
314
     *
315
     * @param array $array
316
     *
317
     * @return int
318
     */
319 1
    public static function size(array $array)
320
    {
321 1
        return count($array);
322
    }
323
324
    /**
325
     * Clean all falsy values from an array.
326
     *
327
     * @usage __::clean([true, false, 0, 1, 'string', ''])
328
     *        >> [true, 1, 'string']
329
     *
330
     * @param array $array
331
     *
332
     * @return mixed
333
     */
334 1
    public static function clean(array $array)
335
    {
336
        return __::filter($array, function ($value) {
337 1
            return (bool)$value;
338 1
        });
339
    }
340
341
    /**
342
     * Get a random string from an array.
343
     *
344
     * @usage __::random([1, 2, 3])
345
     *        >> Returns 1, 2 or 3
346
     *
347
     * @param array   $array
348
     * @param integer $take
349
     *
350
     * @return mixed
351
     */
352 1
    public static function random(array $array, $take = null)
353
    {
354 1
        if (!$take) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $take of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. 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 integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
355 1
            return $array[array_rand($array)];
356
        }
357
        shuffle($array);
358
359
        return __::first($array, $take);
360
    }
361
362
363
    /**
364
     * Return an array with all elements found in both input arrays.
365
     *
366
     * @usage __::intersection(["green", "red", "blue"], ["green", "yellow", "red"])
367
     *        >> ["green", "red"]
368
     *
369
     * @param array $a
370
     * @param array $b
371
     *
372
     * @return array
373
     */
374 2
    public static function intersection(array $a, array $b): array
375
    {
376 2
        $a = (array)$a;
377 2
        $b = (array)$b;
378
379 2
        return array_values(array_intersect($a, $b));
380
    }
381
382
    /**
383
     * Return a boolean flag which indicates whether the two input arrays have any common elements.
384
     *
385
     * @usage __::intersects(["green", "red", "blue"], ["green", "yellow", "red"])
386
     *        >> true
387
     *
388
     * @param array $a
389
     * @param array $b
390
     *
391
     * @return bool
392
     */
393 1
    public static function intersects(array $a, array $b): bool
394
    {
395 1
        $a = (array)$a;
396 1
        $b = (array)$b;
397
398 1
        return count(self::intersection($a, $b)) > 0;
399
    }
400
401
    /**
402
     * Exclude the last X elements from an array
403
     *
404
     * @usage __::initial([1, 2, 3], 1);
405
     *        >> [1, 2]
406
     *
407
     * @param array $array
408
     * @param int   $to
409
     *
410
     * @return mixed
411
     */
412 1
    public static function initial(array $array, int $to = 1)
413
    {
414 1
        $slice = count($array) - $to;
415
416 1
        return __::first($array, $slice);
417
    }
418
419
    /**
420
     * Exclude the first X elements from an array
421
     *
422
     * @usage __::rest([1, 2, 3], 2);
423
     *        >> [3]
424
     *
425
     * @param array $array
426
     * @param int   $from
427
     *
428
     * @return array
429
     */
430 1
    public static function rest(array $array, int $from = 1): array
431
    {
432 1
        return array_splice($array, $from);
433
    }
434
435
    /**
436
     * Sort an array by key.
437
     *
438
     * @usage __::sortKeys(['z' => 0, 'b' => 1, 'r' => 2])
439
     *        >> ['b' => 1, 'r' => 2, 'z' => 0]
440
     *
441
     * @param array  $array
442
     * @param string $direction
443
     *
444
     * @return mixed
445
     */
446 1
    public static function sortKeys(array $array, string $direction = 'ASC')
447
    {
448 1
        $direction = (strtolower($direction) === 'desc') ? SORT_DESC : SORT_ASC;
449 1
        if ($direction === SORT_ASC) {
450 1
            ksort($array);
451
        } else {
452
            krsort($array);
453
        }
454
455 1
        return $array;
456
    }
457
458
    /**
459
     * Remove unwanted values from array
460
     *
461
     * @param array        $array
462
     * @param array|string $remove
463
     * @param bool         $preserveKeys , set true if you want to preserve the keys. by default false
464
     *
465
     * @usage _::without([1,5=>3,2 => 4,5],2)
466
     *
467
     * @return array
468
     */
469 2
    public static function without(array $array, $remove, $preserveKeys = false): array
470
    {
471 2
        $remove = !is_array($remove) ? [$remove] : $remove;
472 2
        $result = [];
473 2
        foreach ($array as $key => $value) {
474 2
            if (in_array($value, $remove)) {
475 2
                continue;
476
            }
477
478 2
            if ($preserveKeys) {
479 1
                $result[$key] = $value;
480
            } else {
481 1
                $result[] = $value;
482
            }
483
        }
484
485 2
        return $result;
486
    }
487
}
488