Completed
Pull Request — master (#1)
by Chad
01:57
created

Arrays::changeKeyCase()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 35
rs 8.439
cc 5
eloc 21
nc 16
nop 2
1
<?php
2
/**
3
 * Defines the \DominionEnterprises\Util\Arrays class.
4
 */
5
6
namespace DominionEnterprises\Util;
7
8
/**
9
 * Class of static array utility functions.
10
 */
11
final class Arrays
12
{
13
    /**
14
     * Const for lower cased array keys.
15
     *
16
     * @const integer
17
     */
18
    const CASE_LOWER = 1;
19
20
    /**
21
     * Const for upper cased array keys.
22
     *
23
     * @const integer
24
     */
25
    const CASE_UPPER = 2;
26
27
    /**
28
     * Const for camel caps cased array keys.
29
     *
30
     * @const integer
31
     */
32
    const CASE_CAMEL_CAPS = 4;
33
34
    /**
35
     * Const for underscored cased array keys.
36
     *
37
     * @const integer
38
     */
39
    const CASE_UNDERSCORE = 8;
40
41
    /**
42
     * Simply returns an array value if the key exist or null if it does not.
43
     *
44
     * @param array $array the array to be searched
45
     * @param string|integer $key the key to search for
46
     * @param mixed $default the value to return if the $key is not found in $array
47
     *
48
     * @return mixed array value or given default value
49
     */
50
    public static function get(array $array, $key, $default = null)
51
    {
52
        return array_key_exists($key, $array) ? $array[$key] : $default;
53
    }
54
55
    /**
56
     * Simply returns an array value if the key isset,4 $default if it is not
57
     *
58
     * @param array $array the array to be searched
59
     * @param string|integer $key the key to search for
60
     * @param mixed $default the value to return if the $key is not found in $array or if the value of $key element is
61
     *                       null
62
     *
63
     * @return mixed array value or given default value
64
     */
65
    public static function getIfSet(array $array, $key, $default = null)
66
    {
67
        return isset($array[$key]) ? $array[$key] : $default;
68
    }
69
70
    /**
71
     * Sets destination array values to be the source values if the source key exist in the source array.
72
     *
73
     * @param array $source
74
     * @param array &$dest
75
     * @param array $keyMap mapping of dest keys to source keys. If $keyMap is associative, the keys will be the
76
     *                      destination keys. If numeric the values will be the destination keys
77
     *
78
     * @return void
79
     */
80 View Code Duplication
    public static function copyIfKeysExist(array $source, array &$dest, array $keyMap)
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...
81
    {
82
        foreach ($keyMap as $destKey => $sourceKey) {
83
            if (is_int($destKey)) {
84
                $destKey = $sourceKey;
85
            }
86
87
            if (array_key_exists($sourceKey, $source)) {
88
                $dest[$destKey] = $source[$sourceKey];
89
            }
90
        }
91
    }
92
93
    /**
94
     * Sets destination array values to be the source values if the source key is set in the source array.
95
     *
96
     * @param array $source
97
     * @param array &$dest
98
     * @param array $keyMap mapping of dest keys to source keys. If $keyMap is associative, the keys will be the
99
     *                      destination keys. If numeric the values will be the destination keys
100
     *
101
     * @return void
102
     */
103 View Code Duplication
    public static function copyIfSet(array $source, array &$dest, array $keyMap)
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...
104
    {
105
        foreach ($keyMap as $destKey => $sourceKey) {
106
            if (is_int($destKey)) {
107
                $destKey = $sourceKey;
108
            }
109
110
            if (isset($source[$sourceKey])) {
111
                $dest[$destKey] = $source[$sourceKey];
112
            }
113
        }
114
    }
115
116
    /**
117
     * Returns true and fills $value if $key exists in $array, otherwise fills $value with null and returns false
118
     *
119
     * @param array $array The array to pull from
120
     * @param string|integer $key The key to get
121
     * @param mixed &$value The value to set
122
     *
123
     * @return bool true if $key was found and filled in $value, false if $key was not found and $value was set to null
124
     */
125
    public static function tryGet(array $array, $key, &$value)
126
    {
127
        if ((is_string($key) || is_int($key)) && array_key_exists($key, $array)) {
128
            $value = $array[$key];
129
            return true;
130
        }
131
132
        $value = null;
133
        return false;
134
    }
135
136
    /**
137
     * Projects values of a key into an array.
138
     *
139
     * if $input = [
140
     *     ['key 1' => 'item 1 value 1', 'key 2' => 'item 1 value 2'],
141
     *     ['key 1' => 'item 2 value 1', 'key 2' => 'item 2 value 2'],
142
     *     ['key 1' => 'item 3 value 1'],
143
     * ]
144
     * and $key = 'key 2'
145
     * and $strictKeyCheck = false
146
     *
147
     * then return ['item 1 value 2', 'item 2 value 2']
148
     *
149
     * but if $strictKeyCheck = true then an InvalidArgumentException occurs since 'key 2' wasnt in item 3
150
     *
151
     * @param array $input the array to project from
152
     * @param string|integer $key the key which values we are to project
153
     * @param boolean $strictKeyCheck ensure key is in each $input array or not
154
     *
155
     * @return array the projection
156
     *
157
     * @throws \InvalidArgumentException if $strictKeyCheck was not a bool
158
     * @throws \InvalidArgumentException if a value in $input was not an array
159
     * @throws \InvalidArgumentException if a key was not in one of the $input arrays
160
     */
161
    public static function project(array $input, $key, $strictKeyCheck = true)
162
    {
163
        if ($strictKeyCheck !== false && $strictKeyCheck !== true) {
164
            throw new \InvalidArgumentException('$strictKeyCheck was not a bool');
165
        }
166
167
        $projection = [];
168
169
        foreach ($input as $itemKey => $item) {
170
            if (!is_array($item)) {
171
                throw new \InvalidArgumentException('a value in $input was not an array');
172
            }
173
174
            if (array_key_exists($key, $item)) {
175
                $projection[$itemKey] = $item[$key];
176
            } elseif ($strictKeyCheck) {
177
                throw new \InvalidArgumentException('key was not in one of the $input arrays');
178
            }
179
        }
180
181
        return $projection;
182
    }
183
184
    /**
185
     * Returns a sub set of the given $array based on the given $conditions
186
     *
187
     * @param array[] $array an array of arrays to be checked
188
     * @param array $conditions array of key/value pairs to filter by
189
     *
190
     * @return array the subset
191
     *
192
     * @throws \InvalidArgumentException if a value in $array was not an array
193
     */
194
    public static function where(array $array, array $conditions)
195
    {
196
        $result = [];
197
        foreach ($array as $item) {
198
            if (!is_array($item)) {
199
                throw new \InvalidArgumentException('a value in $array was not an array');
200
            }
201
202
            foreach ($conditions as $key => $value) {
203
                if (!array_key_exists($key, $item) || $item[$key] !== $value) {
204
                    continue 2; // continue to the next item in $array
205
                }
206
            }
207
208
            $result[] = $item;
209
        }
210
211
        return $result;
212
    }
213
214
    /**
215
     * Takes each item and embeds it into the destination array, returning the result.
216
     *
217
     * Each item's key is used as the key in the destination array so that keys are preserved.  Each resulting item in
218
     * the destination will be embedded into a field named by $fieldName.  Any items that don't have an entry in
219
     * destination already will be added, not skipped.
220
     *
221
     * For example, embedInto(['Joe', 'Sue'], 'lastName', [['firstName' => 'Billy'], ['firstName' => 'Bobby']]) will
222
     * return [['firstName' => 'Billy', 'lastName' => 'Joe'], ['firstName' => 'Bobby', 'lastName' => 'Sue']]
223
     *
224
     * @param array $items The items to embed into the result.
225
     * @param string $fieldName The name of the field to embed the items into.  This field must not exist in the
226
     *                          destination items already.
227
     * @param array $destination An optional array of arrays to embed the items into.  If this is not provided then
228
     *                           empty records are assumed and the new record will be created only containing
229
     *                           $fieldName.
230
     * @param bool $overwrite whether to overwrite $fieldName in $destination array
231
     *
232
     * @return array $destination, with all items in $items added using their keys, but underneath a nested $fieldName
233
     *               key.
234
     *
235
     * @throws \InvalidArgumentException if $fieldName was not a string
236
     * @throws \InvalidArgumentException if a value in $destination was not an array
237
     * @throws \Exception if $fieldName key already exists in a $destination array
238
     */
239
    public static function embedInto(array $items, $fieldName, array $destination = [], $overwrite = false)
240
    {
241
        if (!is_string($fieldName)) {
242
            throw new \InvalidArgumentException('$fieldName was not a string');
243
        }
244
245
        if ($overwrite !== false && $overwrite !== true) {
246
            throw new \InvalidArgumentException('$overwrite was not a bool');
247
        }
248
249
        foreach ($items as $key => $item) {
250
            if (array_key_exists($key, $destination)) {
251
                if (!is_array($destination[$key])) {
252
                    throw new \InvalidArgumentException('a value in $destination was not an array');
253
                }
254
255
                if (!$overwrite && array_key_exists($fieldName, $destination[$key])) {
256
                    throw new \Exception('$fieldName key already exists in a $destination array');
257
                }
258
259
                $destination[$key][$fieldName] = $item;
260
            } else {
261
                $destination[$key] = [$fieldName => $item];
262
            }
263
        }
264
265
        return $destination;
266
    }
267
268
    /**
269
     * Fills the given $template array with values from the $source array
270
     *
271
     * @param array $template the array to be filled
272
     * @param array $source the array to fetch values from
273
     *
274
     * @return array Returns a filled version of $template
275
     */
276
    public static function fillIfKeysExist(array $template, array $source)
277
    {
278
        $result = $template;
279
        foreach ($template as $key => $value) {
280
            if (array_key_exists($key, $source)) {
281
                $result[$key] = $source[$key];
282
            }
283
        }
284
285
        return $result;
286
    }
287
288
    /**
289
     * Extracts an associative array from the given multi-dimensional array.
290
     *
291
     * @param array $input The multi-dimensional array.
292
     * @param string|int $keyIndex The index to be used as the key of the resulting single dimensional result array.
293
     * @param string|int $valueIndex The index to be used as the value of the resulting single dimensional result array.
294
     *                               If a sub array does not contain this element null will be used as the value.
295
     * @param string $duplicateBehavior Instruct how to handle duplicate resulting values, 'takeFirst', 'takeLast',
296
     *                                  'throw'
297
     *
298
     * @return array an associative array
299
     *
300
     * @throws \InvalidArgumentException Thrown if $input is not an multi-dimensional array
301
     * @throws \InvalidArgumentException Thrown if $keyIndex is not an int or string
302
     * @throws \InvalidArgumentException Thrown if $valueIndex is not an int or string
303
     * @throws \InvalidArgumentException Thrown if $duplicateBehavior is not 'takeFirst', 'takeLast', 'throw'
304
     * @throws \UnexpectedValueException Thrown if a $keyIndex value is not a string or integer
305
     * @throws \Exception Thrown if $duplicatedBehavior is 'throw' and duplicate entries are found.
306
     */
307
    public static function extract(array $input, $keyIndex, $valueIndex, $duplicateBehavior = 'takeLast')
308
    {
309
        if (!in_array($duplicateBehavior, ['takeFirst', 'takeLast', 'throw'])) {
310
            throw new \InvalidArgumentException("\$duplicateBehavior was not 'takeFirst', 'takeLast', or 'throw'");
311
        }
312
313
        if (!is_string($keyIndex) && !is_int($keyIndex)) {
314
            throw new \InvalidArgumentException('$keyIndex was not a string or integer');
315
        }
316
317
        if (!is_string($valueIndex) && !is_int($valueIndex)) {
318
            throw new \InvalidArgumentException('$valueIndex was not a string or integer');
319
        }
320
321
        $result = [];
322
        foreach ($input as $index => $array) {
323
            if (!is_array($array)) {
324
                throw new \InvalidArgumentException('$arrays was not a multi-dimensional array');
325
            }
326
327
            $key = self::get($array, $keyIndex);
328
            if (!is_string($key) && !is_int($key)) {
329
                throw new \UnexpectedValueException(
330
                    "Value for \$arrays[{$index}][{$keyIndex}] was not a string or integer"
331
                );
332
            }
333
334
            $value = self::get($array, $valueIndex);
335
            if (!array_key_exists($key, $result)) {
336
                $result[$key] = $value;
337
                continue;
338
            }
339
340
            if ($duplicateBehavior === 'throw') {
341
                throw new \Exception("Duplicate entry for '{$key}' found.");
342
            }
343
344
            if ($duplicateBehavior === 'takeLast') {
345
                $result[$key] = $value;
346
            }
347
        }
348
349
        return $result;
350
    }
351
352
    /**
353
     * Returns the first set {@see isset()} value specified by the given array of keys.
354
     *
355
     * @param array $array The array containing the possible values.
356
     * @param array $keys Array of keys to search for. The first set value will be returned.
357
     * @param mixed $default The default value to return if no set value was found in the array.
358
     *
359
     * @return mixed Returns the found set value or the given default value.
360
     */
361
    public static function getFirstSet(array $array, array $keys, $default = null)
362
    {
363
        foreach ($keys as $key) {
364
            if (isset($array[$key])) {
365
                return $array[$key];
366
            }
367
        }
368
369
        return $default;
370
    }
371
372
    /**
373
     * Partitions the given $input array into an array of $partitionCount sub arrays.
374
     *
375
     * This is a slight modification of the function suggested on
376
     * http://php.net/manual/en/function.array-chunk.php#75022. This method does not pad with empty partitions and
377
     * ensures positive partition count.
378
     *
379
     * @param array $input The array to partition.
380
     * @param int $partitionCount The maximum number of partitions to create.
381
     * @param bool $preserveKeys Flag to preserve numeric array indexes. Associative indexes are preserved by default.
382
     *
383
     * @return array A multi-dimensional array containing $partitionCount sub arrays.
384
     *
385
     * @throws \InvalidArgumentException Thrown if $partitionCount is not a positive integer.
386
     * @throws \InvalidArgumentException Thrown if $preserveKeys is not a boolean value.
387
     */
388
    public static function partition(array $input, $partitionCount, $preserveKeys = false)
389
    {
390
        if (!is_int($partitionCount) || $partitionCount < 1) {
391
            throw new \InvalidArgumentException('$partitionCount must be a positive integer');
392
        }
393
394
        if ($preserveKeys !== false && $preserveKeys !== true) {
395
            throw new \InvalidArgumentException('$preserveKeys must be a boolean value');
396
        }
397
398
        $inputLength = count($input);
399
        $partitionLength = floor($inputLength / $partitionCount);
400
        $partitionRemainder = $inputLength % $partitionCount;
401
        $partitions = [];
402
        $sliceOffset = 0;
403
        for ($partitionIndex = 0; $partitionIndex < $partitionCount && $sliceOffset < $inputLength; $partitionIndex++) {
404
            $sliceLength = ($partitionIndex < $partitionRemainder) ? $partitionLength + 1 : $partitionLength;
405
            $partitions[$partitionIndex] = array_slice($input, $sliceOffset, $sliceLength, $preserveKeys);
406
            $sliceOffset += $sliceLength;
407
        }
408
409
        return $partitions;
410
    }
411
412
    /**
413
     * Unsets all elements in the given $array specified by $keys
414
     *
415
     * @param array &$array The array containing the elements to unset.
416
     * @param array $keys Array of keys to unset.
417
     *
418
     * @return void
419
     */
420
    public static function unsetAll(array &$array, array $keys)
421
    {
422
        foreach ($keys as $key) {
423
            unset($array[$key]);
424
        }
425
    }
426
427
    /**
428
     * Convert all empty strings or strings that contain only whitespace to null in the given array
429
     *
430
     * @param array &$array The array containing empty strings
431
     *
432
     * @return void
433
     */
434
    public static function nullifyEmptyStrings(array &$array)
435
    {
436
        foreach ($array as &$value) {
437
            if (is_string($value) && trim($value) === '') {
438
                $value = null;
439
            }
440
        }
441
    }
442
443
    /**
444
     * Traverses the given $array using the key path specified by $delimitedKey and returns the final value.
445
     *
446
     * Example:
447
     * <br />
448
     * <pre>
449
     * use DominionEnterprises\Util\Arrays;
450
     * $array = [
451
     *     'db' => [
452
     *         'host' => 'localhost',
453
     *         'login' => [
454
     *             'username' => 'scott',
455
     *             'password' => 'tiger',
456
     *         ],
457
     *     ],
458
     * ];
459
     * echo Arrays::getNested($array, 'db.login.username');
460
     * </pre>
461
     * <br />
462
     * Output:
463
     * <pre>
464
     * scott
465
     * </pre>
466
     *
467
     * @param array  $array        The array to traverse.
468
     * @param string $delimitedKey A string of keys to traverse into the array.
469
     * @param string $delimiter    A string specifiying how the keys are delimited. The default is '.'.
470
     *
471
     * @return mixed The value at the inner most key or null if a key does not exist.
472
     */
473
    final public static function getNested(array $array, $delimitedKey, $delimiter = '.')
474
    {
475
        $pointer = $array;
476
        foreach (explode($delimiter, $delimitedKey) as $key) {
477
            if (is_array($pointer) && array_key_exists($key, $pointer)) {
478
                $pointer = $pointer[$key];
479
                continue;
480
            }
481
482
            return null;
483
        }
484
485
        return $pointer;
486
    }
487
488
    /**
489
     * Changes the case of all keys in an array. Numbered indices are left as is.
490
     *
491
     * @param array   $input The array to work on.
492
     * @param integer $case  The case to which the keys should be set.
493
     *
494
     * @return array Returns an array with its keys case changed.
495
     */
496
    public static function changeKeyCase(array $input, $case = self::CASE_LOWER)
497
    {
498
        if ($case & self::CASE_UNDERSCORE) {
499
            $copy = [];
500
            array_walk(
501
                $input,
502
                function ($value, $key) use (&$copy) {
503
                    $copy[preg_replace("/([a-z])([A-Z0-9])/", '$1_$2', $key)] = $value;
504
                }
505
            );
506
            $input = $copy;
507
        }
508
509
        if ($case & self::CASE_CAMEL_CAPS) {
510
            $copy = [];
511
            array_walk(
512
                $input,
513
                function ($value, $key) use (&$copy) {
514
                    $key = lcfirst(str_replace(' ', '', ucwords(strtolower(str_replace('_', ' ', $key)))));
515
                    $copy[$key] = $value;
516
                }
517
            );
518
            $input = $copy;
519
        }
520
521
        if ($case & self::CASE_UPPER) {
522
            $input = array_change_key_case($input, \CASE_UPPER);
523
        }
524
525
        if ($case & self::CASE_LOWER) {
526
            $input = array_change_key_case($input, \CASE_LOWER);
527
        }
528
529
        return $input;
530
    }
531
}
532