Config::getNullableString()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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