Skip to content

Commit dea182d

Browse files
authored
Merge pull request #795 from hypervel/feature/typed-enum-config
Add typed enum configuration getters
2 parents 170fd33 + 8a41311 commit dea182d

29 files changed

Lines changed: 312 additions & 50 deletions

‎src/config/src/Repository.php‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Hypervel\Config;
66

77
use ArrayAccess;
8+
use BackedEnum;
89
use Closure;
910
use Hypervel\Contracts\Config\Repository as ConfigContract;
1011
use Hypervel\Support\Arr;
@@ -13,6 +14,9 @@
1314
use Hypervel\Support\Traits\Macroable;
1415
use InvalidArgumentException;
1516
use stdClass;
17+
use UnitEnum;
18+
19+
use function Hypervel\Support\enum_try_from;
1620

1721
class Repository implements ArrayAccess, ConfigContract
1822
{
@@ -286,6 +290,67 @@ public function nullableArray(string $key, mixed $default = null): ?array
286290
return $value;
287291
}
288292

293+
/**
294+
* Get the specified enum configuration value.
295+
*
296+
* @template TEnum of UnitEnum
297+
* @param class-string<TEnum> $enumClass
298+
* @param null|(Closure():(null|TEnum))|TEnum $default
299+
* @return TEnum
300+
* @throws InvalidArgumentException
301+
*/
302+
public function enum(string $key, string $enumClass, mixed $default = null): UnitEnum
303+
{
304+
return $this->resolveEnum($key, $enumClass, $this->get($key, $default));
305+
}
306+
307+
/**
308+
* Get the specified nullable enum configuration value.
309+
*
310+
* Without a default the key must be present, even if its value is null.
311+
*
312+
* @template TEnum of UnitEnum
313+
* @param class-string<TEnum> $enumClass
314+
* @param null|(Closure():(null|TEnum))|TEnum $default
315+
* @return null|TEnum
316+
* @throws InvalidArgumentException
317+
*/
318+
public function nullableEnum(string $key, string $enumClass, mixed $default = null): ?UnitEnum
319+
{
320+
$value = func_num_args() === 2 ? $this->getRequired($key) : $this->get($key, $default);
321+
322+
return $value === null ? null : $this->resolveEnum($key, $enumClass, $value);
323+
}
324+
325+
/**
326+
* Resolve an enum case or its exact backing value.
327+
*
328+
* @template TEnum of UnitEnum
329+
* @param class-string<TEnum> $enumClass
330+
* @return TEnum
331+
*/
332+
private function resolveEnum(string $key, string $enumClass, mixed $value): UnitEnum
333+
{
334+
if ($value instanceof $enumClass) {
335+
return $value;
336+
}
337+
338+
if ((is_string($value) || is_int($value)) && is_subclass_of($enumClass, BackedEnum::class)) {
339+
$case = enum_try_from($enumClass, $value);
340+
341+
if ($case !== null && $case->value === $value) {
342+
return $case;
343+
}
344+
}
345+
346+
throw new InvalidArgumentException(sprintf(
347+
'Configuration value for key [%s] must be a case or backing value of [%s], %s given.',
348+
$key,
349+
$enumClass,
350+
is_string($value) || is_int($value) ? var_export($value, true) : get_debug_type($value),
351+
));
352+
}
353+
289354
/**
290355
* Get the specified configuration value as a Collection.
291356
*

‎src/contracts/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Documentation: https://hypervel.org/docs/contracts
77

88
## Differences From Laravel
99

10-
The `Config\Repository` contract requires `string()`, `integer()`, `float()`, `boolean()`, `array()`, `collection()`, `nullableString()`, `nullableInteger()`, `nullableFloat()`, `nullableBoolean()` and `nullableArray()`. Code that type-hints the contract can use these getters directly. Extending `Hypervel\Config\Repository` supplies them.
10+
The `Config\Repository` contract requires `string()`, `integer()`, `float()`, `boolean()`, `array()`, `collection()`, `enum()`, `nullableString()`, `nullableInteger()`, `nullableFloat()`, `nullableBoolean()`, `nullableArray()` and `nullableEnum()`. Code that type-hints the contract can use these getters directly. Extending `Hypervel\Config\Repository` supplies them.
1111

1212
The `Container` contract also requires `isScoped()`, `isScopedInstance()`, `resolvedShared()`, `forgetInstance()`, `makeTransient()`, `build()`, `buildWith()`, `resolveContextualParameters()`, and `rebinding()`. Custom implementations must provide these methods; extending `Hypervel\Container\Container` supplies them. Lifetime inspection lets consumers cache only the instances the container shares for the worker, instead of caching scoped or fresh services across requests.
1313

‎src/contracts/src/Config/Repository.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Hypervel\Support\Attributes\BootOrTestsOnly;
99
use Hypervel\Support\Collection;
1010
use InvalidArgumentException;
11+
use UnitEnum;
1112

1213
interface Repository
1314
{
@@ -113,6 +114,30 @@ public function array(string $key, mixed $default = null): array;
113114
*/
114115
public function nullableArray(string $key, mixed $default = null): ?array;
115116

117+
/**
118+
* Get the specified enum configuration value.
119+
*
120+
* @template TEnum of UnitEnum
121+
* @param class-string<TEnum> $enumClass
122+
* @param null|(Closure():(null|TEnum))|TEnum $default
123+
* @return TEnum
124+
* @throws InvalidArgumentException
125+
*/
126+
public function enum(string $key, string $enumClass, mixed $default = null): UnitEnum;
127+
128+
/**
129+
* Get the specified nullable enum configuration value.
130+
*
131+
* Without a default the key must be present, even if its value is null.
132+
*
133+
* @template TEnum of UnitEnum
134+
* @param class-string<TEnum> $enumClass
135+
* @param null|(Closure():(null|TEnum))|TEnum $default
136+
* @return null|TEnum
137+
* @throws InvalidArgumentException
138+
*/
139+
public function nullableEnum(string $key, string $enumClass, mixed $default = null): ?UnitEnum;
140+
116141
/**
117142
* Get the specified configuration value as a Collection.
118143
*

‎src/data/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ Documentation: https://hypervel.org/docs/data-objects
66

77
`Resource` authorizes and validates request input under the default `OnlyRequests` strategy, as `Data` and `Dto` do, so request input is validated whichever base class receives it; Spatie's `Resource` never validates. When a named factory accepts a request, Hypervel authorizes the request but does not validate it first, so a factory that returns the finished object is responsible for validation.
88

9+
The shipped `data.validation_strategy` setting holds a `ValidationStrategy` case. Read it with the enum configuration getter. Published configurations may still use its string backing value.
10+
911
Data uses the Validator's syntax for rule sets. Convert Spatie declarations such as `['required|string']` to `['required', 'string']`, and place a regex containing `|` in its own array element. A nested rule array such as `[['in', 'a|b', null]]` is one rule with parameters. See [validation attributes](https://hypervel.org/docs/data-objects#validation-attributes).
1012

1113
With multiple payloads, Hypervel validates the combined input once rather than a request payload on its own, so the rules check the values the object will receive. Later payloads take precedence, and a later explicit `null` replaces an earlier value where Spatie keeps the earlier value, so a later payload can clear a value. An `Optional` value never replaces an earlier value.

‎src/data/config/data.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@
7575
* method. By default, only when a request is passed the data is being validated. This
7676
* behavior can be changed to always validate or to completely disable validation.
7777
*/
78-
'validation_strategy' => ValidationStrategy::OnlyRequests->value,
78+
'validation_strategy' => ValidationStrategy::OnlyRequests,
7979

8080
/*
8181
* A data object can map the names of its properties when transforming (output) or when

‎src/data/src/Support/DataConfig.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ public function __construct(Repository $config)
115115
// @phpstan-ignore hypervel.untypedConfigRead (Date formats may be a string or a non-empty list of strings.)
116116
$this->dateFormats = self::normalizeDateFormats($config->get('data.date_format'));
117117
$this->dateTimezone = $config->nullableString('data.date_timezone');
118-
$this->validationStrategy = ValidationStrategy::from($config->string('data.validation_strategy'));
118+
$this->validationStrategy = $config->enum('data.validation_strategy', ValidationStrategy::class);
119119
$this->inputNameMapper = self::nameMapper($config, 'data.name_mapping_strategy.input');
120120
$this->outputNameMapper = self::nameMapper($config, 'data.name_mapping_strategy.output');
121121
$this->casts = self::extensionMap($config->array('data.casts'), Cast::class, 'data.casts');

‎src/docs/configuration.md‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ php artisan config:show database --json
5656
php artisan config:show app.debug --json
5757
```
5858

59+
Enum settings are displayed as `Class::Case`. In JSON, a backed enum uses its backing value and a unit enum uses its case name.
60+
5961
<a name="environment-configuration"></a>
6062
## Environment Configuration
6163

@@ -350,9 +352,22 @@ function settings(Repository $config): array
350352
}
351353
```
352354

353-
The available methods are `string`, `integer`, `float`, `boolean`, `array`, and `collection`. When no default is supplied, a missing key or wrong type causes Hypervel to throw an `InvalidArgumentException` that names the full configuration key.
355+
The available methods are `string`, `integer`, `float`, `boolean`, `array`, `collection`, and `enum`. When no default is supplied, a missing key or wrong type causes Hypervel to throw an `InvalidArgumentException` that names the full configuration key.
356+
357+
Use `enum` with the enum class to retrieve a case. A backed enum accepts either the case itself or its exact string or integer value. For example, a setting can take its value from an environment variable:
358+
359+
```php
360+
// config/billing.php
361+
'currency' => env('BILLING_CURRENCY', 'USD'),
362+
```
363+
364+
```php
365+
$currency = Config::enum('billing.currency', Currency::class);
366+
```
367+
368+
When supplying a default to the getter, pass a case of the requested enum, such as `Config::enum('billing.currency', Currency::class, Currency::Usd)`. For integer-backed enums, the backing value must be an integer. For enums without backing values, store the case itself in your configuration file.
354369

355-
When a setting accepts null, use `nullableString`, `nullableInteger`, `nullableFloat`, `nullableBoolean`, or `nullableArray`. The key must exist unless you supply a default. For example, the shipped session configuration defines a cookie domain, which may be null. An application may also define an optional audit log channel:
370+
When a setting accepts null, use `nullableString`, `nullableInteger`, `nullableFloat`, `nullableBoolean`, `nullableArray`, or `nullableEnum`. The key must exist unless you supply a default. For example, the shipped session configuration defines a cookie domain, which may be null. An application may also define an optional audit log channel:
356371

357372
```php
358373
$domain = config()->nullableString('session.domain');

‎src/docs/data-objects.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1080,7 +1080,7 @@ Validation runs before construction, not when you call `new` or change a public
10801080
```php
10811081
use Hypervel\Data\Support\Creation\ValidationStrategy;
10821082

1083-
'validation_strategy' => ValidationStrategy::Always->value,
1083+
'validation_strategy' => ValidationStrategy::Always,
10841084
```
10851085

10861086
<a name="inferred-rules"></a>

‎src/foundation/src/Console/ConfigShowCommand.php‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@
44

55
namespace Hypervel\Foundation\Console;
66

7+
use BackedEnum;
78
use Hypervel\Config\Repository;
89
use Hypervel\Console\Command;
910
use Hypervel\Support\Arr;
11+
use JsonSerializable;
1012
use Symfony\Component\Console\Attribute\AsCommand;
1113
use Symfony\Component\Console\Output\OutputInterface;
14+
use UnitEnum;
1215

1316
#[AsCommand(name: 'config:show')]
1417
class ConfigShowCommand extends Command
@@ -47,7 +50,7 @@ public function handle(): int
4750
if ($this->option('json')) {
4851
$this->output->writeln(
4952
// @phpstan-ignore hypervel.untypedConfigRead (The command displays an arbitrary user-selected configuration value.)
50-
json_encode($this->config->get($config), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR),
53+
json_encode($this->jsonValue($this->config->get($config)), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR),
5154
OutputInterface::OUTPUT_RAW,
5255
);
5356

@@ -61,6 +64,20 @@ public function handle(): int
6164
return self::SUCCESS;
6265
}
6366

67+
/**
68+
* Represent unit enum settings by their case names in JSON output.
69+
*/
70+
protected function jsonValue(mixed $value): mixed
71+
{
72+
if (is_array($value)) {
73+
return array_map($this->jsonValue(...), $value);
74+
}
75+
76+
return $value instanceof UnitEnum && ! $value instanceof BackedEnum && ! $value instanceof JsonSerializable
77+
? $value->name
78+
: $value;
79+
}
80+
6481
/**
6582
* Render the configuration values.
6683
*/
@@ -122,6 +139,7 @@ protected function formatValue(mixed $value): string
122139
is_null($value) => '<fg=#ef8414;options=bold>null</>',
123140
is_numeric($value) => "<fg=#ef8414;options=bold>{$value}</>",
124141
is_array($value) => '[]',
142+
$value instanceof UnitEnum => $value::class . '::' . $value->name,
125143
is_object($value) => get_class($value),
126144
is_string($value) => $value,
127145
default => print_r($value, true),

‎src/passport/src/Console/InstallCommand.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class InstallCommand extends Command
3030
*/
3131
public function handle(): void
3232
{
33-
$keyStore = KeyStore::from(config()->string('passport.key_store'));
33+
$keyStore = config()->enum('passport.key_store', KeyStore::class);
3434

3535
if ($keyStore === KeyStore::Files) {
3636
$this->createKeys();

0 commit comments

Comments
 (0)