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

functions.php ➔ json_decode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 3
dl 0
loc 9
rs 9.9666
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 getenv;
8
use function in_array;
9
use function json_last_error;
10
use function json_last_error_msg;
11
use function strtolower;
12
use function trim;
13
14
/**
15
 * Gets the value of an environment variable. Supports boolean, empty and null.
16
 * This is basically Laravel's env helper
17
 *
18
 * @param string $key
19
 * @param mixed $default
20
 * @return mixed
21
 * @link https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L369
22
 */
23
function env($key, $default = null)
24
{
25
    $value = getenv($key);
26
    if ($value === false) {
27
        return $default;
28
    }
29
30
    switch (strtolower($value)) {
31
        case 'true':
32
        case '(true)':
33
            return true;
34
        case 'false':
35
        case '(false)':
36
            return false;
37
        case 'empty':
38
        case '(empty)':
39
            return '';
40
        case 'null':
41
        case '(null)':
42
            return null;
43
    }
44
45
    return trim($value);
46
}
47
48
function contains($needle, array $haystack): bool
49
{
50
    return in_array($needle, $haystack, true);
51
}
52
53
function json_decode(string $json, int $depth = 512, int $options = 0): array
54
{
55
    $data = \json_decode($json, true, $depth, $options);
56
    if (JSON_ERROR_NONE !== json_last_error()) {
57
        throw new Exception\InvalidArgumentException('Error decoding JSON: ' . json_last_error_msg());
58
    }
59
60
    return $data;
61
}
62