Completed
Push — master ( 4c5280...5cdc1d )
by Alec
08:43
created

value()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 5
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace AlecRabbit;
4
5
use const AlecRabbit\Helpers\Strings\Constants\STR_EMPTY;
6
use const AlecRabbit\Helpers\Strings\Constants\STR_FALSE;
7
use const AlecRabbit\Helpers\Strings\Constants\STR_NULL;
8
use const AlecRabbit\Helpers\Strings\Constants\STR_TRUE;
9
10
const STR_DOUBLE = 'double';
11
const STR_FLOAT = 'float';
12
13
define(__NAMESPACE__ . '\STR_DOUBLE_LENGTH', strlen(STR_DOUBLE));
14
15
/**
16
 * Gets the value of an environment variable.
17
 *
18
 * @param  string $key
19
 * @param  mixed $default
20
 * @return mixed
21
 */
22
function env($key, $default = null)
23
{
24 42
    if (false === $value = \getenv($key)) {
25 18
        $value = value($default);
26
    }
27
28 42
    $value = \ltrim(\rtrim($value, ')"'), '("');
29
30 42
    switch (strtolower($value)) {
31 42
        case STR_TRUE:
32 4
            $value = true;
33 4
            break;
34 38
        case STR_FALSE:
35 4
            $value = false;
36 4
            break;
37 34
        case STR_EMPTY:
38 30
        case STR_NULL:
39 8
            $value = '';
40 8
            break;
41
    }
42
43 42
    return $value;
44
}
45
46
/**
47
 * Return the default value of the given value.
48
 *
49
 * @param  mixed $value
50
 * @return mixed
51
 */
52
function value($value)
53
{
54
    return
55 18
        $value instanceof \Closure ?
56 18
            $value() : $value;
57
}
58
59
/**
60
 * Returns the type of a variable.
61
 *
62
 * @param mixed $var
63
 * @return string
64
 */
65
function typeOf($var): string
66
{
67 12
    $type = \is_object($var) ? \get_class($var) : \gettype($var);
68 12
    if (strlen($type) === STR_DOUBLE_LENGTH) {
69 2
        $type = str_replace(STR_DOUBLE, STR_FLOAT, $type);
70
    }
71 12
    return $type;
72
}
73
74
75
//function caller(int $depth = 2): string
76
//{
77
//    $caller = (new \Exception())->getTrace()[$depth];
78
//    $r = $caller['function'] . '()';
79
//    if (isset($caller['class'])) {
80
//        $r .= ' in ' . $caller['class'];
81
//    }
82
//    if (isset($caller['object'])) {
83
//        $r .= ' (' . get_class($caller['object']) . ')';
84
//    }
85
//    unset($e);
86
//    return $r;
87
//}
88