Passed
Push — master ( fd4a88...7449e0 )
by Caen
04:01 queued 12s
created

Config::getBool()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Facades;
6
7
use TypeError;
8
9
/**
10
 * An extension of the Laravel Config facade with extra
11
 * accessors that ensure the types of the returned values.
12
 *
13
 * @see \Illuminate\Config\Repository
14
 * @see \Illuminate\Support\Facades\Config
15
 * @see \Hyde\Framework\Testing\Feature\TypedConfigFacadeTest
16
 */
17
class Config extends \Illuminate\Support\Facades\Config
18
{
19
    public static function getArray(string $key, array $default = null): array
20
    {
21
        return (array) self::validated(static::get($key, $default), 'array', $key);
22
    }
23
24
    public static function getString(string $key, string $default = null): string
25
    {
26
        return (string) self::validated(static::get($key, $default), 'string', $key);
27
    }
28
29
    public static function getInt(string $key, int $default = null): int
30
    {
31
        return (int) self::validated(static::get($key, $default), 'int', $key);
32
    }
33
34
    public static function getBool(string $key, bool $default = null): bool
35
    {
36
        return (bool) self::validated(static::get($key, $default), 'bool', $key);
37
    }
38
39
    public static function getFloat(string $key, float $default = null): float
40
    {
41
        return (float) self::validated(static::get($key, $default), 'float', $key);
42
    }
43
44
    /** @experimental */
45
    public static function getNullableString(string $key, string $default = null): ?string
46
    {
47
        $value = static::get($key, $default);
48
49
        if ($value === null) {
50
            return null;
51
        }
52
53
        return (string) self::validated($value, 'string', $key);
54
    }
55
56
    protected static function validated(mixed $value, string $type, string $key): mixed
57
    {
58
        if (! ("is_$type")($value)) {
59
            throw new TypeError(sprintf('%s(): Config value %s must be of type %s, %s given', __METHOD__, $key, $type, gettype($value)));
60
        }
61
62
        return $value;
63
    }
64
}
65