Retriever::prepareValue()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 17
rs 9.6111
1
<?php
2
3
/*
4
 * This file is part of the PHP-ENV package.
5
 *
6
 * (c) Jitendra Adhikari <[email protected]>
7
 *     <https://github.com/adhocore>
8
 *
9
 * Licensed under MIT license.
10
 */
11
12
namespace Ahc\Env;
13
14
/**
15
 * Environment variable retriever for PHP.
16
 *
17
 * @author   Jitendra Adhikari <[email protected]>
18
 * @license  MIT
19
 *
20
 * @link     https://github.com/adhocore/env
21
 */
22
class Retriever
23
{
24
    /**
25
     * Get the env variable by its key/name.
26
     *
27
     * @param string    $key
28
     * @param mixed     $default
29
     * @param int|null  $filter  PHP's filter constants. See http://php.net/filter_var
30
     * @param int|array $options Additional options to filter.
31
     *
32
     * @return mixed
33
     */
34
    public static function getEnv($key, $default = null, $filter = null, $options = null)
35
    {
36
        if (false !== $env = \getenv($key)) {
37
            return static::prepareValue($env, $filter, $options);
38
        }
39
40
        if (isset($_ENV[$key])) {
41
            return static::prepareValue($_ENV[$key], $filter, $options);
42
        }
43
44
        if (isset($_SERVER[$key])) {
45
            return static::prepareValue($_SERVER[$key], $filter, $options);
46
        }
47
48
        // Default is not passed through filter!
49
        return $default;
50
    }
51
52
    protected static function prepareValue($env, $filter, $options)
53
    {
54
        static $special = [
55
            'true' => true, 'false' => false, 'null' => null,
56
            'TRUE' => true, 'FALSE' => false, 'NULL' => null,
57
        ];
58
59
        // strlen($env) < 6.
60
        if (!isset($env[5]) && \array_key_exists($env, $special)) {
61
            return $special[$env];
62
        }
63
64
        if ($filter === null || !\function_exists('filter_var')) {
65
            return $env;
66
        }
67
68
        return \filter_var($env, $filter, $options);
69
    }
70
}
71