Completed
Push — master ( f7ceef...6986d0 )
by Alejandro
16s
created

pick()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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