|
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
|
|
|
* @internal This facade is not (yet) meant to be used by the end user. |
|
14
|
|
|
* @experimental This facade is experimental and may change in the future. |
|
15
|
|
|
* |
|
16
|
|
|
* @todo If class is kept internal, the facade alias should be removed from config. |
|
17
|
|
|
* |
|
18
|
|
|
* @see \Illuminate\Config\Repository |
|
19
|
|
|
* @see \Illuminate\Support\Facades\Config |
|
20
|
|
|
* @see \Hyde\Framework\Testing\Feature\TypedConfigFacadeTest |
|
21
|
|
|
*/ |
|
22
|
|
|
class Config extends \Illuminate\Support\Facades\Config |
|
23
|
|
|
{ |
|
24
|
|
|
/** @var false {@todo Consider setting to true} */ |
|
25
|
|
|
protected const STRICT_DEFAULT = false; |
|
26
|
|
|
|
|
27
|
|
|
public static function getArray(string $key, array $default = null, bool $strict = self::STRICT_DEFAULT): array |
|
28
|
|
|
{ |
|
29
|
|
|
return (array) self::validated(static::get($key, $default), 'array', $key, $strict); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public static function getString(string $key, string $default = null, bool $strict = self::STRICT_DEFAULT): string |
|
33
|
|
|
{ |
|
34
|
|
|
return (string) self::validated(static::get($key, $default), 'string', $key, $strict); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public static function getInt(string $key, int $default = null, bool $strict = self::STRICT_DEFAULT): int |
|
38
|
|
|
{ |
|
39
|
|
|
return (int) self::validated(static::get($key, $default), 'int', $key, $strict); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public static function getBool(string $key, bool $default = null, bool $strict = self::STRICT_DEFAULT): bool |
|
43
|
|
|
{ |
|
44
|
|
|
return (bool) self::validated(static::get($key, $default), 'bool', $key, $strict); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public static function getFloat(string $key, float $default = null, bool $strict = self::STRICT_DEFAULT): float |
|
48
|
|
|
{ |
|
49
|
|
|
return (float) self::validated(static::get($key, $default), 'float', $key, $strict); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
protected static function validated(mixed $value, string $type, string $key, bool $strict): mixed |
|
53
|
|
|
{ |
|
54
|
|
|
if ($strict && ! ("is_$type")($value)) { |
|
55
|
|
|
throw new TypeError(sprintf('%s(): Config value %s must be of type %s, %s given', __METHOD__, $key, $type, gettype($value))); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $value; |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|