Completed
Push — master ( a2d719...4531d5 )
by Radu
07:41
created

ArrayHelper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 13
c 1
b 0
f 0
dl 0
loc 42
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isMultidimensional() 0 6 2
A get() 0 5 2
A toUrlQueryString() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebServCo\Framework\Helpers;
6
7
class ArrayHelper
8
{
9
    /**
10
    * Get a value from an array if it exists, otherwise a specified default value.
11
    * For multi dimensional arrays please see ArrayStorage.
12
    *
13
    * @param array<mixed> $array
14
    * @param mixed $key
15
    * @param mixed $defaultValue
16
    * @return mixed
17
    */
18
    public static function get(array $array, $key, $defaultValue = null)
19
    {
20
        return \array_key_exists($key, $array)
21
            ? $array[$key]
22
            : $defaultValue;
23
    }
24
25
    /**
26
    * @param array<mixed> $array
27
    */
28
    public static function isMultidimensional(array $array): bool
29
    {
30
        if (!$array) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $array of type array<mixed,mixed> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
31
            return false;
32
        }
33
        return \is_array($array[\key($array)]);
34
    }
35
36
    /**
37
    * @param array<int|string,int|float|string> $array
38
    */
39
    public static function toUrlQueryString(array $array): ?string
40
    {
41
        if (!$array) {
42
            return null;
43
        }
44
        $queries = [];
45
        foreach ($array as $k => $v) {
46
            $queries[] = \sprintf('%s=%s', $k, $v);
47
        }
48
        return '?' . \implode('&', $queries);
49
    }
50
}
51