Passed
Pull Request — master (#11)
by Zeeshan
01:34
created

Arrays::compact()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
crap 3
1
<?php
2
3
namespace __\Traits;
4
5
use Closure;
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 $start of type null|integer 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 $stop of type null|integer 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 null   $times  ow many times has to be repeated.
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $times is correct as it would always require null to be passed?
Loading history...
192
     *
193
     * @return array Returns a new array of filled values.
194
     *
195
     */
196 1
    public static function repeat(string $object = '', $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 integer|double 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