Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/config/src/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Hypervel\Config;

use ArrayAccess;
use BackedEnum;
use Closure;
use Hypervel\Contracts\Config\Repository as ConfigContract;
use Hypervel\Support\Arr;
Expand All @@ -13,6 +14,9 @@
use Hypervel\Support\Traits\Macroable;
use InvalidArgumentException;
use stdClass;
use UnitEnum;

use function Hypervel\Support\enum_try_from;

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

/**
* Get the specified enum configuration value.
*
* @template TEnum of UnitEnum
* @param class-string<TEnum> $enumClass
* @param null|(Closure():(null|TEnum))|TEnum $default
* @return TEnum
* @throws InvalidArgumentException
*/
public function enum(string $key, string $enumClass, mixed $default = null): UnitEnum
{
return $this->resolveEnum($key, $enumClass, $this->get($key, $default));
}

/**
* Get the specified nullable enum configuration value.
*
* Without a default the key must be present, even if its value is null.
*
* @template TEnum of UnitEnum
* @param class-string<TEnum> $enumClass
* @param null|(Closure():(null|TEnum))|TEnum $default
* @return null|TEnum
* @throws InvalidArgumentException
*/
public function nullableEnum(string $key, string $enumClass, mixed $default = null): ?UnitEnum
{
$value = func_num_args() === 2 ? $this->getRequired($key) : $this->get($key, $default);

return $value === null ? null : $this->resolveEnum($key, $enumClass, $value);
}

/**
* Resolve an enum case or its exact backing value.
*
* @template TEnum of UnitEnum
* @param class-string<TEnum> $enumClass
* @return TEnum
*/
private function resolveEnum(string $key, string $enumClass, mixed $value): UnitEnum
{
if ($value instanceof $enumClass) {
return $value;
}

if ((is_string($value) || is_int($value)) && is_subclass_of($enumClass, BackedEnum::class)) {
$case = enum_try_from($enumClass, $value);

if ($case !== null && $case->value === $value) {
return $case;
}
}

throw new InvalidArgumentException(sprintf(
'Configuration value for key [%s] must be a case or backing value of [%s], %s given.',
$key,
$enumClass,
is_string($value) || is_int($value) ? var_export($value, true) : get_debug_type($value),
));
}

/**
* Get the specified configuration value as a Collection.
*
Expand Down
2 changes: 1 addition & 1 deletion src/contracts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Documentation: https://hypervel.org/docs/contracts

## Differences From Laravel

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.
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.

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.

Expand Down
25 changes: 25 additions & 0 deletions src/contracts/src/Config/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Hypervel\Support\Attributes\BootOrTestsOnly;
use Hypervel\Support\Collection;
use InvalidArgumentException;
use UnitEnum;

interface Repository
{
Expand Down Expand Up @@ -113,6 +114,30 @@ public function array(string $key, mixed $default = null): array;
*/
public function nullableArray(string $key, mixed $default = null): ?array;

/**
* Get the specified enum configuration value.
*
* @template TEnum of UnitEnum
* @param class-string<TEnum> $enumClass
* @param null|(Closure():(null|TEnum))|TEnum $default
* @return TEnum
* @throws InvalidArgumentException
*/
public function enum(string $key, string $enumClass, mixed $default = null): UnitEnum;

/**
* Get the specified nullable enum configuration value.
*
* Without a default the key must be present, even if its value is null.
*
* @template TEnum of UnitEnum
* @param class-string<TEnum> $enumClass
* @param null|(Closure():(null|TEnum))|TEnum $default
* @return null|TEnum
* @throws InvalidArgumentException
*/
public function nullableEnum(string $key, string $enumClass, mixed $default = null): ?UnitEnum;

/**
* Get the specified configuration value as a Collection.
*
Expand Down
2 changes: 2 additions & 0 deletions src/data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Documentation: https://hypervel.org/docs/data-objects

`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.

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.

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).

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.
Expand Down
2 changes: 1 addition & 1 deletion src/data/config/data.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
* method. By default, only when a request is passed the data is being validated. This
* behavior can be changed to always validate or to completely disable validation.
*/
'validation_strategy' => ValidationStrategy::OnlyRequests->value,
'validation_strategy' => ValidationStrategy::OnlyRequests,

/*
* A data object can map the names of its properties when transforming (output) or when
Expand Down
2 changes: 1 addition & 1 deletion src/data/src/Support/DataConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public function __construct(Repository $config)
// @phpstan-ignore hypervel.untypedConfigRead (Date formats may be a string or a non-empty list of strings.)
$this->dateFormats = self::normalizeDateFormats($config->get('data.date_format'));
$this->dateTimezone = $config->nullableString('data.date_timezone');
$this->validationStrategy = ValidationStrategy::from($config->string('data.validation_strategy'));
$this->validationStrategy = $config->enum('data.validation_strategy', ValidationStrategy::class);
$this->inputNameMapper = self::nameMapper($config, 'data.name_mapping_strategy.input');
$this->outputNameMapper = self::nameMapper($config, 'data.name_mapping_strategy.output');
$this->casts = self::extensionMap($config->array('data.casts'), Cast::class, 'data.casts');
Expand Down
19 changes: 17 additions & 2 deletions src/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ php artisan config:show database --json
php artisan config:show app.debug --json
```

Enum settings are displayed as `Class::Case`. In JSON, a backed enum uses its backing value and a unit enum uses its case name.

<a name="environment-configuration"></a>
## Environment Configuration

Expand Down Expand Up @@ -350,9 +352,22 @@ function settings(Repository $config): array
}
```

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.
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.

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:

```php
// config/billing.php
'currency' => env('BILLING_CURRENCY', 'USD'),
```

```php
$currency = Config::enum('billing.currency', Currency::class);
```

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.

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:
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:

```php
$domain = config()->nullableString('session.domain');
Expand Down
2 changes: 1 addition & 1 deletion src/docs/data-objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -1080,7 +1080,7 @@ Validation runs before construction, not when you call `new` or change a public
```php
use Hypervel\Data\Support\Creation\ValidationStrategy;

'validation_strategy' => ValidationStrategy::Always->value,
'validation_strategy' => ValidationStrategy::Always,
```

<a name="inferred-rules"></a>
Expand Down
20 changes: 19 additions & 1 deletion src/foundation/src/Console/ConfigShowCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@

namespace Hypervel\Foundation\Console;

use BackedEnum;
use Hypervel\Config\Repository;
use Hypervel\Console\Command;
use Hypervel\Support\Arr;
use JsonSerializable;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Output\OutputInterface;
use UnitEnum;

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

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

/**
* Represent unit enum settings by their case names in JSON output.
*/
protected function jsonValue(mixed $value): mixed
{
if (is_array($value)) {
return array_map($this->jsonValue(...), $value);
}

return $value instanceof UnitEnum && ! $value instanceof BackedEnum && ! $value instanceof JsonSerializable
? $value->name
: $value;
}

/**
* Render the configuration values.
*/
Expand Down Expand Up @@ -122,6 +139,7 @@ protected function formatValue(mixed $value): string
is_null($value) => '<fg=#ef8414;options=bold>null</>',
is_numeric($value) => "<fg=#ef8414;options=bold>{$value}</>",
is_array($value) => '[]',
$value instanceof UnitEnum => $value::class . '::' . $value->name,
is_object($value) => get_class($value),
is_string($value) => $value,
default => print_r($value, true),
Expand Down
2 changes: 1 addition & 1 deletion src/passport/src/Console/InstallCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class InstallCommand extends Command
*/
public function handle(): void
{
$keyStore = KeyStore::from(config()->string('passport.key_store'));
$keyStore = config()->enum('passport.key_store', KeyStore::class);

if ($keyStore === KeyStore::Files) {
$this->createKeys();
Expand Down
2 changes: 1 addition & 1 deletion src/passport/src/Console/KeysCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class KeysCommand extends Command
*/
public function handle(): int
{
if (KeyStore::from(config()->string('passport.key_store')) === KeyStore::Database) {
if (config()->enum('passport.key_store', KeyStore::class) === KeyStore::Database) {
if (app(SigningKeyRepository::class)->create((int) $this->option('length')) === null) {
$this->components->error('Signing keys already exist. Use passport:keys:rotate to rotate them.');

Expand Down
2 changes: 1 addition & 1 deletion src/passport/src/Console/KeysRevokeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class KeysRevokeCommand extends Command
*/
public function handle(SigningKeyRepository $keys, Repository $config): int
{
if (KeyStore::from($config->string('passport.key_store')) !== KeyStore::Database) {
if ($config->enum('passport.key_store', KeyStore::class) !== KeyStore::Database) {
$this->components->error('This command requires the database key store. Rotate file keys manually using passport.verification_keys.');

return Command::FAILURE;
Expand Down
2 changes: 1 addition & 1 deletion src/passport/src/Console/KeysRotateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class KeysRotateCommand extends Command
*/
public function handle(SigningKeyRepository $keys, Repository $config): int
{
if (KeyStore::from($config->string('passport.key_store')) !== KeyStore::Database) {
if ($config->enum('passport.key_store', KeyStore::class) !== KeyStore::Database) {
$this->components->error('This command requires the database key store. Rotate file keys manually using passport.verification_keys.');

return Command::FAILURE;
Expand Down
4 changes: 2 additions & 2 deletions src/passport/src/PassportServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ protected function scheduleMaintenance(): void
->cron($config->string('passport.pruning.schedule'))->onOneServer()->withoutOverlapping()->runInBackground();
}

if (KeyStore::from($config->string('passport.key_store')) === KeyStore::Database
if ($config->enum('passport.key_store', KeyStore::class) === KeyStore::Database
&& $config->boolean('passport.key_rotation.enabled')) {
$schedule->command('passport:keys:rotate', ['--due'])
->cron($config->string('passport.key_rotation.schedule'))->onOneServer()->withoutOverlapping()->runInBackground();
Expand Down Expand Up @@ -326,7 +326,7 @@ protected function validateConfiguration(): void
Passport::refreshToken(), Passport::refreshTokenFamily(), Passport::pushedAuthorizationRequest(),
];

if (KeyStore::from($config->string('passport.key_store')) === KeyStore::Database) {
if ($config->enum('passport.key_store', KeyStore::class) === KeyStore::Database) {
$models[] = Passport::signingKey();
$refreshInterval = $config->integer('passport.key_refresh_interval');

Expand Down
2 changes: 1 addition & 1 deletion src/passport/src/ServerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ public function entry(): ServerEntry
*/
protected function defaultEntry(): ServerEntry
{
if (KeyStore::from($this->config->string('passport.key_store')) === KeyStore::Files) {
if ($this->config->enum('passport.key_store', KeyStore::class) === KeyStore::Files) {
return $this->defaultEntry ??= $this->makeEntry(new ServerSettings(
$this->fileKeys(),
issuer: ($issuer = $this->config->nullableString('passport.issuer')) === '' ? null : $issuer,
Expand Down
Loading