Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
12 / 12 |
|
100.00% |
7 / 7 |
CRAP | |
100.00% |
1 / 1 |
Config | |
100.00% |
12 / 12 |
|
100.00% |
7 / 7 |
9 | |
100.00% |
1 / 1 |
getArray | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getString | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getInt | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getBool | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getFloat | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getNullableString | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
validated | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 |
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 Could possibly be merged by allowing null returns if default is null? Preferably with generics so the type is matched by IDE support. */ |
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 | } |