Completed
Pull Request — master (#10)
by Zeeshan
01:46
created

Arrays::append()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
namespace __\Traits;
4
5
trait Arrays
6
{
7
    /**
8
     * Append item to array
9
     *
10
     ** __::append([1, 2, 3], 4);
11
     ** // → [1, 2, 3, 4]
12
     *
13
     * @param array $array original array
14
     * @param mixed $value new item or value to append
15
     *
16
     * @return array
17
     *
18
     */
19 1
    public static function append(array $array = [], $value = null): array
20
    {
21 1
        $array[] = $value;
22
23 1
        return $array;
24
    }
25
26
    /**
27
     * Creates  an  array  with  all  falsey  values removed. The values
28
     * false, null, 0, "", undefined, and NaN are all falsey.
29
     *
30
     ** __::compact([0, 1, false, 2, '', 3]);
31
     ** // → [1, 2, 3]
32
     *
33
     * @param array $array array to compact
34
     *
35
     * @return array
36
     *
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
     */
63 1
    public static function baseFlatten(
64
        array $array,
65
        bool $shallow = false,
66
        bool $strict = true,
67
        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

67
        /** @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...
68
    ): array {
69 1
        $idx    = 0;
70 1
        $output = [];
71
72 1
        foreach ($array as $index => $value) {
73 1
            if (is_array($value)) {
74
                if (!$shallow) {
75 1
                    $value = static::baseFlatten($value, $shallow, $strict);
76 1
                }
77
                $j   = 0;
78 1
                $len = count($value);
79 1
                while ($j < $len) {
80 1
                    $output[$idx++] = $value[$j++];
81 1
                }
82
            } else {
83
                if (!$strict) {
84 1
                    $output[$idx++] = $value;
85 1
                }
86
            }
87
        }
88
89
        return $output;
90 1
    }
91
92
    /**
93
     * Flattens a multidimensional array. If you pass shallow, the array will only be flattened a single level.
94
     *
95
     * __::flatten([1, 2, [3, [4]]], [flatten]);
96
     *      >> [1, 2, 3, 4]
97
     *
98
     * @param array $array
99
     * @param bool  $shallow
100
     *
101
     * @return array
102
     *
103
     */
104
    public static function flatten(array $array, bool $shallow = false): array
105 1
    {
106
        return static::baseFlatten($array, $shallow, false);
107 1
    }
108
109
    /**
110
     *  Patches array by xpath.
111
     *
112
     ** __::patch(['addr' => ['country' => 'US', 'zip' => 12345]], ['/addr/country' => 'CA', '/addr/zip' => 54321]);
113
     ** // → ['addr' => ['country' => 'CA', 'zip' => 54321]]
114
     *
115
     * @param array  $array   The array to patch
116
     * @param array  $patches List of new xpath-value pairs
117
     * @param string $parent
118
     *
119
     * @return array Returns patched array
120
     *
121
     */
122
    public static function patch(array $array, array $patches, string $parent = ''): array
123 1
    {
124
        foreach ($array as $key => $value) {
125 1
            $z = $parent . '/' . $key;
126 1
127
            if (isset($patches[$z])) {
128 1
                $array[$key] = $patches[$z];
129 1
                unset($patches[$z]);
130 1
131
                if (!count($patches)) {
132 1
                    break;
133 1
                }
134
            }
135
136
            if (is_array($value)) {
137 1
                $array[$key] = static::patch($value, $patches, $z);
138 1
            }
139
        }
140
141
        return $array;
142 1
    }
143
144
    /**
145
     * Prepend item or value to an array
146
     *
147
     ** __::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
     */
156
    public static function prepend(array $array = [], $value = null): array
157 2
    {
158
        array_unshift($array, $value);
159 2
160
        return $array;
161 2
    }
162
163
    /**
164
     * Generate range of values based on start , end and step
165
     ** __::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
     */
175
    public static function range($start = null, $stop = null, int $step = 1): array
176 1
    {
177
        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...
178 1
            $stop  = $start;
179 1
            $start = 1;
180 1
        }
181
182
        return range($start, $stop, $step);
183 1
    }
184
185
    /**
186
     * Generate array of repeated values
187
     *
188
     ** __::repeat('foo', 3);
189
     ** // >> ['foo', 'foo', 'foo']
190
     *
191
     * @param string $object The object to repeat.
192
     * @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...
193
     *
194
     * @return array Returns a new array of filled values.
195
     *
196
     */
197
    public static function repeat(string $object = '', $times = null): array
198 1
    {
199
        if ($times != null) {
200 1
            return array_fill(0, $times, $object);
201 1
202
        }
203
204
        return [];
205
    }
206
207
208
    /**
209
     * Creates an array of elements split into groups the length of size. If array can't be split evenly, the final
210
     * chunk will be the remaining elements.
211
     *
212
     * __::chunk([1, 2, 3, 4, 5], 3);
213
     * // >> [[1, 2, 3], [4, 5]]
214
     *
215
     * @param array $array          original array
216
     * @param int   $size           the chunk size
217
     * @param bool  $preserveKeys   When set to TRUE keys will be preserved. Default is FALSE which will reindex the
218
     *                              chunk numerically
219
     *
220
     * @return array
221
     *
222
     */
223
    public static function chunk(array $array, int $size = 1, bool $preserveKeys = false): array
224
    {
225
        return array_chunk($array, $size, $preserveKeys);
226
    }
227
228
    /**
229
     * Creates a slice of array with n elements dropped from the beginning.
230
     *
231
     ** __::drop([0, 1, 3], 2);
232
     ** // >> [3]
233
     *
234
     * @param array $input  The array to query.
235
     * @param int   $number The number of elements to drop.
236
     *
237
     * @return array
238
     *
239
     */
240
    public static function drop(array $input, int $number = 1): array
241
    {
242
        return array_slice($input, $number);
243
    }
244
245
    /**
246
     * Shuffle an array ensuring no item remains in the same position.
247
     *
248
     ** __::randomize([1, 2, 3]);
249
     ** // >> [2, 3, 1]
250
     *
251
     * @param array $array original array
252
     *
253
     * @return array
254
     *
255
     */
256
    public static function randomize(array $array): array
257
    {
258
        for ($i = 0, $c = count($array); $i < $c - 1; $i++) {
259
            $j = rand($i + 1, $c - 1);
260
            list($array[$i], $array[$j]) = [$array[$j], $array[$i]];
261
        }
262
263
        return $array;
264
    }
265
}
266