Completed
Pull Request — master (#224)
by Alejandro
03:14
created

functions.php ➔ contains()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common;
5
6
use const JSON_ERROR_NONE;
7
use function array_key_exists;
8
use function array_shift;
9
use function getenv;
10
use function in_array;
11
use function is_array;
12
use function json_last_error;
13
use function json_last_error_msg;
14
use function strtolower;
15
use function trim;
16
17
/**
18
 * Gets the value of an environment variable. Supports boolean, empty and null.
19
 * This is basically Laravel's env helper
20
 *
21
 * @param string $key
22
 * @param mixed $default
23
 * @return mixed
24
 * @link https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L369
25
 */
26
function env($key, $default = null)
27
{
28
    $value = getenv($key);
29
    if ($value === false) {
30
        return $default;
31
    }
32
33
    switch (strtolower($value)) {
34
        case 'true':
35
        case '(true)':
36
            return true;
37
        case 'false':
38
        case '(false)':
39
            return false;
40
        case 'empty':
41
        case '(empty)':
42
            return '';
43
        case 'null':
44
        case '(null)':
45
            return null;
46
    }
47
48
    return trim($value);
49
}
50
51
function contains($needle, array $haystack): bool
52
{
53
    return in_array($needle, $haystack, true);
54
}
55
56
function json_decode(string $json, int $depth = 512, int $options = 0): array
57
{
58
    $data = \json_decode($json, true, $depth, $options);
59
    if (JSON_ERROR_NONE !== json_last_error()) {
60
        throw new Exception\InvalidArgumentException('Error decoding JSON: ' . json_last_error_msg());
61
    }
62
63
    return $data;
64
}
65
66
function array_path_exists(array $path, array $array): bool
67
{
68
    // As soon as a step is not found, the path does not exist
69
    $step = array_shift($path);
70
    if (! array_key_exists($step, $array)) {
71
        return false;
72
    }
73
74
    // Once the path is empty, we have found all the parts in the path
75
    if (empty($path)) {
76
        return true;
77
    }
78
79
    // If current value is not an array, then we have not found the path
80
    $newArray = $array[$step];
81
    if (! is_array($newArray)) {
82
        return false;
83
    }
84
85
    return array_path_exists($path, $newArray);
86
}
87
88
function array_get_path(array $path, array $array)
89
{
90
    do {
91
        $step = array_shift($path);
92
        if (! is_array($array) || ! array_key_exists($step, $array)) {
93
            return null;
94
        }
95
96
        $array = $array[$step];
97
    } while (! empty($path));
98
99
    return $array;
100
}
101