GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#9)
by
unknown
01:29
created

array_functions.php ➔ array_change_key_case()   C

Complexity

Conditions 15
Paths 6

Size

Total Lines 60
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 38
nc 6
nop 2
dl 0
loc 60
rs 6.305
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Spatie;
4
5
const CASE_LOWER = \CASE_LOWER;
6
const CASE_UPPER = \CASE_UPPER;
7
const CASE_SNAKE = 2;
8
const CASE_TITLE = 3;
9
const CASE_CAMEL = 4;
10
const CASE_PASCAL = 5;
11
const CASE_LISP = 6;
12
13
/**
14
 * Get a random value from an array.
15
 *
16
 * @param array $array
17
 * @param int   $numReq The amount of values to return
18
 *
19
 * @return mixed
20
 */
21
function array_rand_value(array $array, $numReq = 1)
22
{
23
    if (!count($array)) {
24
        return;
25
    }
26
27
    $keys = array_rand($array, $numReq);
28
29
    if ($numReq === 1) {
30
        return $array[$keys];
31
    }
32
33
    return array_intersect_key($array, array_flip($keys));
34
}
35
36
/**
37
 * Get a random value from an array, with the ability to skew the results.
38
 * Example: array_rand_weighted(['foo' => 1, 'bar' => 2]) has a 66% chance of returning bar.
39
 *
40
 * @param array $array
41
 *
42
 * @return mixed
43
 */
44
function array_rand_weighted(array $array)
45
{
46
    $options = [];
47
48
    foreach ($array as $option => $weight) {
49
        for ($i = 0; $i < $weight; ++$i) {
50
            $options[] = $option;
51
        }
52
    }
53
54
    return array_rand_value($options);
55
}
56
57
/**
58
 * Determine if all given needles are present in the haystack.
59
 *
60
 * @param array|string $needles
61
 * @param array        $haystack
62
 *
63
 * @return bool
64
 */
65
function values_in_array($needles, array $haystack)
66
{
67
    if (!is_array($needles)) {
68
        $needles = [$needles];
69
    }
70
71
    return count(array_intersect($needles, $haystack)) === count($needles);
72
}
73
74
/**
75
 * Determine if all given needles are present in the haystack as array keys.
76
 *
77
 * @param array|string $needles
78
 * @param array        $haystack
79
 *
80
 * @return bool
81
 */
82
function array_keys_exist($needles, array $haystack)
83
{
84
    if (!is_array($needles)) {
85
        return array_key_exists($needles, $haystack);
86
    }
87
88
    return values_in_array($needles, array_keys($haystack));
89
}
90
91
/**
92
 * Returns an array with two elements.
93
 *
94
 * Iterates over each value in the array passing them to the callback function.
95
 * If the callback function returns true, the current value from array is returned in the first
96
 * element of result array. If not, it is return in the second element of result array.
97
 *
98
 * Array keys are preserved.
99
 *
100
 * @param array    $array
101
 * @param callable $callback
102
 *
103
 * @return array
104
 */
105
function array_split_filter(array $array, callable $callback)
106
{
107
    $passesFilter = array_filter($array, $callback);
108
109
    $negatedCallback = function ($item) use ($callback) { return !$callback($item); };
110
111
    $doesNotPassFilter = array_filter($array, $negatedCallback);
112
113
    return [$passesFilter, $doesNotPassFilter];
114
}
115
116
/**
117
 * Split an array in the given amount of pieces.
118
 *
119
 * @param array $array
120
 * @param int   $numberOfPieces
121
 * @param bool  $preserveKeys
122
 *
123
 * @return array
124
 */
125
function array_split(array $array, $numberOfPieces = 2, $preserveKeys = false)
126
{
127
    if (count($array) === 0) {
128
        return [];
129
    }
130
131
    $splitSize = ceil(count($array) / $numberOfPieces);
132
133
    return array_chunk($array, $splitSize, $preserveKeys);
134
}
135
136
/**
137
 * Returns an array with the unique values from all the given arrays.
138
 *
139
 * @param \array[] $arrays
140
 *
141
 * @return array
142
 */
143
function array_merge_values(array ...$arrays)
144
{
145
    $allValues = array_reduce($arrays, function ($carry, $array) {
146
         return array_merge($carry, $array);
147
    }, []);
148
149
    return array_values(array_unique($allValues));
150
}
151
152
/**
153
 * Flatten an array of arrays. The `$levels` parameter specifies how deep you want to
154
 * recurse in the array. If `$levels` is -1, the function will recurse infinitely.
155
 *
156
 * @param array $array
157
 * @param int   $levels
158
 *
159
 * @return array
160
 */
161
function array_flatten(array $array, $levels = -1)
162
{
163
    if ($levels === 0) {
164
        return $array;
165
    }
166
167
    $flattened = [];
168
169
    if ($levels !== -1) {
170
        --$levels;
171
    }
172
173
    foreach ($array as $element) {
174
        $flattened = array_merge(
175
            $flattened,
176
            is_array($element) ? array_flatten($element, $levels) : [$element]
177
        );
178
    }
179
180
    return $flattened;
181
}
182
183
/**
184
 * Very similar to \array_change_key_case, accepts more cases:
185
 * `CASE_LOWER`, `CASE_UPPER`, `CASE_SNAKE`, `CASE_TITLE`, `CASE_CAMEL`, `CASE_PASCAL`, `CASE_LISP`
186
 * all in the `Spatie` namespace.
187
 *
188
 * @param array $array
189
 * @param int   $case
190
 *
191
 * @return array
192
 */
193
function array_change_key_case(array $array, $case = CASE_LOWER)
194
{
195
    if ($case === CASE_LOWER || $case === CASE_UPPER) {
196
        return \array_change_key_case($array, $case);
197
    }
198
199
    // If case is invalid, no need to perform expensive operation.
200
    if (!is_int($case) || $case < CASE_SNAKE || $case > CASE_LISP) {
201
        return $array;
202
    }
203
204
    static $changeCase;
205
    $changeCase or $changeCase = function ($key, $case) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
206
        if (is_numeric($key)) {
207
            return $key;
208
        }
209
210
        // change "camelCase" to "camel Case", "foo123bar" to "foo 123 bar", "foo!bar" to "foo! bar"
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
211
        $key = preg_replace(
212
            [
213
                '/([^a-zA-Z0-9\s\_\-])([a-zA-Z0-9])/',
214
                '/([a-z])([A-Z])/',
215
                '/([a-zA-Z])([\d])/',
216
                '/([\d])([a-zA-Z])/',
217
            ],
218
            '${1} ${2}',
219
            $key
220
        );
221
222
        $words = preg_split('/_+|-+|\s+/', strtolower($key));
223
224
        switch ($case) {
225
            case CASE_SNAKE:
226
                return implode('_', $words);
227
            case CASE_TITLE:
228
                return ucfirst(implode(' ', $words));
229
            case CASE_CAMEL:
230
            case CASE_PASCAL:
231
                $first = $case === CASE_CAMEL ? array_shift($words) : '';
232
                return preg_replace_callback(
233
                    '/([^a-zA-Z]+)([a-zA-Z]{1})([^a-zA-Z]+)/',
234
                    function (array $matches) {
235
                        return $matches[1] . strtolower($matches[2]) . $matches[3];
236
                    },
237
                    $first . implode('', array_map('ucfirst', $words))
238
                );
239
            case CASE_LISP:
240
                return implode('-', $words);
241
            default:
242
                return $key;
243
        }
244
    };
245
246
    $changed = [];
247
    foreach ($array as $key => $value) {
248
        $changed[$changeCase($key, $case)]  = $value;
249
    }
250
251
    return $changed;
252
}
253