Completed
Push — master ( 3023e6...36eaa2 )
by Oscar
06:20
created

Env::stripQuotes()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 11
rs 8.8571
cc 5
eloc 6
nc 2
nop 1
1
<?php
2
3
class Env
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
4
{
5
    const CONVERT_BOOL = 1;
6
    const CONVERT_NULL = 2;
7
    const CONVERT_INT = 4;
8
    const STRIP_QUOTES = 8;
9
10
    public static $options = 15;   //All flags enabled
11
    public static $default = null; //Default value if not exists
12
13
    /**
14
     * Include the global env() function.
15
     */
16
    public static function init()
17
    {
18
        include_once dirname(__FILE__).'/env_function.php';
19
    }
20
21
    /**
22
     * Returns an environment variable.
23
     * 
24
     * @param string   $name
25
     */
26
    public static function get($name)
27
    {
28
        $value = getenv($name);
29
30
        if ($value === false) {
31
            return self::$default;
32
        }
33
34
        return self::convert($value);
35
    }
36
37
    /**
38
     * Converts the type of values like "true", "false", "null" or "123".
39
     *
40
     * @param string   $value
41
     * @param int|null $options
42
     *
43
     * @return mixed
44
     */
45
    public static function convert($value, $options = null)
46
    {
47
        if ($options === null) {
48
            $options = self::$options;
49
        }
50
51
        switch (strtolower($value)) {
52
            case 'true':
53
                return ($options & self::CONVERT_BOOL) ? true : $value;
54
55
            case 'false':
56
                return ($options & self::CONVERT_BOOL) ? false : $value;
57
58
            case 'null':
59
                return ($options & self::CONVERT_NULL) ? null : $value;
60
        }
61
62
        if (($options & self::CONVERT_INT) && ctype_digit($value)) {
63
            return (int) $value;
64
        }
65
66
        if ($options & self::STRIP_QUOTES) {
67
            return self::stripQuotes($value);
68
        }
69
70
        return $value;
71
    }
72
73
    /**
74
     * Strip quotes
75
     *
76
     * @param string $value
77
     *
78
     * @return string
79
     */
80
    private static function stripQuotes($value)
81
    {
82
        if (
83
            ($value[0] === '"' && substr($value, -1) === '"')
84
         || ($value[0] === "'" && substr($value, -1) === "'")
85
        ) {
86
            return substr($value, 1, -1);
87
        }
88
89
        return $value;
90
    }
91
}
92