Completed
Pull Request — master (#246)
by Alejandro
05:59
created

json_decode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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