Passed
Push — master ( 4c267c...1bfd55 )
by Pierrick
10:36
created

Env::cast()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 2
dl 0
loc 8
ccs 7
cts 7
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of NACL.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @copyright 2019 Nuglif (2018) Inc.
9
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
10
 * @author    Pierrick Charron <[email protected]>
11
 * @author    Charle Demers <[email protected]>
12
 */
13
14
declare(strict_types=1);
15
16
namespace Nuglif\Nacl\Macros;
17
18
use Nuglif\Nacl\MacroInterface;
19
use Nuglif\Nacl\TypeCaster;
20
21
class Env implements MacroInterface
22
{
23 591
    public function getName(): string
24
    {
25 591
        return 'env';
26
    }
27
28 10
    public function execute(mixed $parameter, array $options = []): mixed
29
    {
30 10
        $options = array_merge([
31 10
            'type' => 'string',
32 10
        ], $options);
33
34 10
        $val = getenv($parameter);
35
36 10
        if (false === $val) {
37 4
            return array_key_exists('default', $options) ? $options['default'] : false;
38
        }
39
40 6
        return $this->cast($val, $options['type']);
41
    }
42
43 6
    private function cast(string $value, string $type): bool|string|int|float
44
    {
45 6
        return match ($type) {
46 6
            'bool', 'boolean' => TypeCaster::toBool($value),
47 6
            'int', 'integer' => (int) TypeCaster::toNum($value),
48 6
            'num', 'numeric' => TypeCaster::toNum($value),
49 6
            'str', 'string' => $value,
50 6
            default => throw new \InvalidArgumentException('Unknown type: ' . $type),
51 6
        };
52
    }
53
}
54