Completed
Push — master ( fd6d08...45a04a )
by Alec
02:53
created

boolToStr()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

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