diff --git a/src/config/src/Repository.php b/src/config/src/Repository.php index 8a7361f8fc..ff955b5d72 100644 --- a/src/config/src/Repository.php +++ b/src/config/src/Repository.php @@ -5,6 +5,7 @@ namespace Hypervel\Config; use ArrayAccess; +use BackedEnum; use Closure; use Hypervel\Contracts\Config\Repository as ConfigContract; use Hypervel\Support\Arr; @@ -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 { @@ -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 $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 $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 $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. * diff --git a/src/contracts/README.md b/src/contracts/README.md index ca63ec8b27..4483b4b7cc 100644 --- a/src/contracts/README.md +++ b/src/contracts/README.md @@ -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. diff --git a/src/contracts/src/Config/Repository.php b/src/contracts/src/Config/Repository.php index 34a8ba8523..3e9d06b40b 100644 --- a/src/contracts/src/Config/Repository.php +++ b/src/contracts/src/Config/Repository.php @@ -8,6 +8,7 @@ use Hypervel\Support\Attributes\BootOrTestsOnly; use Hypervel\Support\Collection; use InvalidArgumentException; +use UnitEnum; interface Repository { @@ -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 $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 $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. * diff --git a/src/data/README.md b/src/data/README.md index 5e0c06fc14..db54fa1dc5 100644 --- a/src/data/README.md +++ b/src/data/README.md @@ -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. diff --git a/src/data/config/data.php b/src/data/config/data.php index 2c39234e8b..6f721afea1 100644 --- a/src/data/config/data.php +++ b/src/data/config/data.php @@ -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 diff --git a/src/data/src/Support/DataConfig.php b/src/data/src/Support/DataConfig.php index 05c20b41b1..750c92de44 100644 --- a/src/data/src/Support/DataConfig.php +++ b/src/data/src/Support/DataConfig.php @@ -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'); diff --git a/src/docs/configuration.md b/src/docs/configuration.md index 6400eaca71..44728c640d 100644 --- a/src/docs/configuration.md +++ b/src/docs/configuration.md @@ -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. + ## Environment Configuration @@ -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'); diff --git a/src/docs/data-objects.md b/src/docs/data-objects.md index 36b0511c57..674419abfe 100644 --- a/src/docs/data-objects.md +++ b/src/docs/data-objects.md @@ -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, ``` diff --git a/src/foundation/src/Console/ConfigShowCommand.php b/src/foundation/src/Console/ConfigShowCommand.php index c9004b646b..31332bc61d 100644 --- a/src/foundation/src/Console/ConfigShowCommand.php +++ b/src/foundation/src/Console/ConfigShowCommand.php @@ -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 @@ -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, ); @@ -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. */ @@ -122,6 +139,7 @@ protected function formatValue(mixed $value): string is_null($value) => 'null', is_numeric($value) => "{$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), diff --git a/src/passport/src/Console/InstallCommand.php b/src/passport/src/Console/InstallCommand.php index 12e73f8ac5..183435e0ff 100644 --- a/src/passport/src/Console/InstallCommand.php +++ b/src/passport/src/Console/InstallCommand.php @@ -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(); diff --git a/src/passport/src/Console/KeysCommand.php b/src/passport/src/Console/KeysCommand.php index 353f06df78..69edd81cc8 100644 --- a/src/passport/src/Console/KeysCommand.php +++ b/src/passport/src/Console/KeysCommand.php @@ -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.'); diff --git a/src/passport/src/Console/KeysRevokeCommand.php b/src/passport/src/Console/KeysRevokeCommand.php index d0a8484f3f..88ec6b439b 100644 --- a/src/passport/src/Console/KeysRevokeCommand.php +++ b/src/passport/src/Console/KeysRevokeCommand.php @@ -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; diff --git a/src/passport/src/Console/KeysRotateCommand.php b/src/passport/src/Console/KeysRotateCommand.php index 30469b7c3c..a908909752 100644 --- a/src/passport/src/Console/KeysRotateCommand.php +++ b/src/passport/src/Console/KeysRotateCommand.php @@ -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; diff --git a/src/passport/src/PassportServiceProvider.php b/src/passport/src/PassportServiceProvider.php index ac20afe903..e83ac05fbe 100644 --- a/src/passport/src/PassportServiceProvider.php +++ b/src/passport/src/PassportServiceProvider.php @@ -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(); @@ -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'); diff --git a/src/passport/src/ServerFactory.php b/src/passport/src/ServerFactory.php index f888a871a4..de4429d33f 100644 --- a/src/passport/src/ServerFactory.php +++ b/src/passport/src/ServerFactory.php @@ -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, diff --git a/src/phpstan/src/Internal/ConfigHelper.php b/src/phpstan/src/Internal/ConfigHelper.php index e3f4617a9c..6e869b32f6 100644 --- a/src/phpstan/src/Internal/ConfigHelper.php +++ b/src/phpstan/src/Internal/ConfigHelper.php @@ -25,6 +25,7 @@ use PHPStan\Analyser\DependencyTracker; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredService; +use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\MethodReflection; use PHPStan\TrinaryLogic; use PHPStan\Type\ArrayType; @@ -44,6 +45,7 @@ use PHPStan\Type\TypeTraverser; use PHPStan\Type\UnionType; use PHPStan\Type\VerbosityLevel; +use UnitEnum; use function array_all; use function array_any; @@ -59,8 +61,8 @@ class ConfigHelper * The repository and Config facade methods whose return types come from config values. */ private const array METHODS = [ - 'get', 'string', 'integer', 'float', 'boolean', 'array', 'collection', - 'nullablestring', 'nullableinteger', 'nullablefloat', 'nullableboolean', 'nullablearray', + 'get', 'string', 'integer', 'float', 'boolean', 'array', 'collection', 'enum', + 'nullablestring', 'nullableinteger', 'nullablefloat', 'nullableboolean', 'nullablearray', 'nullableenum', ]; /** @@ -86,7 +88,7 @@ public function getValueType(CallLike $call, Scope $scope): ?Type { $lookup = $this->lookup($call, $scope); - return $lookup === null ? null : $this->valueWithDefault($lookup, $call, $scope, false); + return $lookup === null ? null : $this->valueWithDefault($lookup, $call->getArg('default', 1), $scope, false); } /** @@ -139,10 +141,9 @@ private function lookup(CallLike $call, Scope $scope): ?array * * @param array{TrinaryLogic, Type} $lookup */ - private function valueWithDefault(array $lookup, CallLike $call, Scope $scope, bool $typed): Type + private function valueWithDefault(array $lookup, ?Arg $default, Scope $scope, bool $typed): Type { [$presence, $type] = $lookup; - $default = $call->getArg('default', 1); if ($presence->yes() || ($typed && $default === null)) { return $type; @@ -195,13 +196,15 @@ public function getMethodReturnType(CallLike $call, Scope $scope): ?Type return null; } - $valueType = $this->valueWithDefault($lookup, $call, $scope, $methodName !== 'get'); + $enumType = $this->enumType($methodName, $call, $scope); + $default = $call->getArg('default', $enumType === null ? 1 : 2); + $valueType = $this->valueWithDefault($lookup, $default, $scope, $methodName !== 'get'); if ($methodName === 'get') { return $valueType; } - $type = TypeCombinator::intersect($valueType, $this->getGetterType($methodName)); + $type = $this->typedResult($methodName, $valueType, $enumType); if ($type instanceof NeverType) { return new ErrorType; @@ -231,29 +234,78 @@ public function getTypeError(CallLike $call, Scope $scope, string $methodName): $getter = $this->getterName($methodName); $keyDescription = $scope->getType($key->value)->describe(VerbosityLevel::precise()); - if ($lookup[0]->no() && $call->getArg('default', 1) === null) { + $enumType = $this->enumType($methodName, $call, $scope); + $default = $call->getArg('default', $enumType === null ? 1 : 2); + + if ($lookup[0]->no() && $default === null) { return sprintf('Config key %s is not defined, so %s() throws. Check the key and its configuration.', $keyDescription, $getter); } - $value = $this->valueWithDefault($lookup, $call, $scope, true); + $value = $this->valueWithDefault($lookup, $default, $scope, true); - if ($value instanceof NeverType || ! TypeCombinator::intersect($value, $this->getGetterType($methodName)) instanceof NeverType) { + if ($value instanceof NeverType || ! $this->typedResult($methodName, $value, $enumType) instanceof NeverType) { return null; } return sprintf( 'Config key %s is not %s, so %s() throws. Correct the config value or use the getter that matches its type.', $keyDescription, - $this->getterDescription($methodName), + $this->getterDescription($methodName, $enumType), $getter, ); } + /** + * Resolve the enum getter's type from the requested enum class. + */ + private function enumType(string $methodName, CallLike $call, Scope $scope): ?Type + { + if ($methodName !== 'enum' && $methodName !== 'nullableenum') { + return null; + } + + $enum = new ObjectType(UnitEnum::class); + $argument = $call->getArg('enumClass', 1); + if ($argument !== null) { + $enum = TypeCombinator::intersect($enum, $scope->getType($argument->value)->getClassStringObjectType()); + } + + return $enum; + } + + /** + * Narrow the result to values the getter accepts, including cases returned for backing values. + */ + private function typedResult(string $method, Type $value, ?Type $enum): Type + { + $result = TypeCombinator::intersect($value, $this->getGetterType($method, $enum)); + + if ($enum === null || ($value->isString()->no() && $value->isInteger()->no())) { + return $result; + } + + $classes = $enum->getObjectClassReflections(); + if ($classes === [] || ! array_all($classes, static fn (ClassReflection $class): bool => $class->isEnum())) { + // The backing values of a runtime-selected enum class may be unknown. + return TypeCombinator::union($result, $enum); + } + + $matches = [$result]; + foreach ($enum->getEnumCases() as $case) { + $backing = $case->getBackingValueType(); + if ($backing !== null && ! TypeCombinator::intersect($value, $backing) instanceof NeverType) { + $matches[] = $case; + } + } + + return TypeCombinator::union(...$matches); + } + /** * Recommend a getter when every possible key is present and has one supported type. * * @param DependencyTracker&Scope $scope - * @return null|array{string, string, string} + * @return null|array{string, string, string, string} */ public function recommendedGetter(CallLike $call, Scope $scope): ?array { @@ -281,6 +333,8 @@ public function recommendedGetter(CallLike $call, Scope $scope): ?array } $type = TypeCombinator::removeNull($lookup[1]); + $enumClasses = $type->isEnum()->yes() ? $type->getObjectClassReflections() : []; + $enumType = count($enumClasses) === 1 && $enumClasses[0]->isEnum() ? new ObjectType($enumClasses[0]->getName()) : null; $method = match (true) { $type instanceof NeverType => null, $type->isString()->yes() => 'string', @@ -288,6 +342,7 @@ public function recommendedGetter(CallLike $call, Scope $scope): ?array $type->isFloat()->yes() => 'float', $type->isBoolean()->yes() => 'boolean', $type->isArray()->yes() => 'array', + $enumType !== null => 'enum', default => null, }; @@ -301,14 +356,15 @@ public function recommendedGetter(CallLike $call, Scope $scope): ?array $default = $call->getArg('default', 1); - if ($default !== null && ! TypeCombinator::addNull($this->getGetterType($method))->isSuperTypeOf($this->defaultType($default, $scope))->yes()) { + if ($default !== null && ! TypeCombinator::addNull($this->getGetterType($method, $enumType))->isSuperTypeOf($this->defaultType($default, $scope))->yes()) { return null; } return [ $scope->getType($key->value)->describe(VerbosityLevel::precise()), $this->getterName($method), - $this->getterDescription($method), + $this->getterDescription($method, $enumType), + $enumType === null ? '' : sprintf(' Pass %s::class as the second argument.', $enumType->getClassName()), ]; } @@ -323,13 +379,14 @@ private function getterName(string $method): string /** * Describe the config values a getter accepts. */ - private function getterDescription(string $method): string + private function getterDescription(string $method, ?Type $enum = null): string { if (str_starts_with($method, 'nullable')) { - return $this->getterDescription(substr($method, 8)) . ' or null'; + return $this->getterDescription(substr($method, 8), $enum) . ' or null'; } return match ($method) { + 'enum' => $enum->describe(VerbosityLevel::typeOnly()), 'string' => 'a string', 'integer' => 'an integer', 'float' => 'a float', @@ -438,13 +495,14 @@ public function isConfigMethod(MethodReflection $method): bool /** * Get the type a typed getter requires its value to have. */ - private function getGetterType(string $methodName): Type + private function getGetterType(string $methodName, ?Type $enum = null): Type { if (str_starts_with($methodName, 'nullable')) { - return TypeCombinator::addNull($this->getGetterType(substr($methodName, 8))); + return TypeCombinator::addNull($this->getGetterType(substr($methodName, 8), $enum)); } return match ($methodName) { + 'enum' => $enum, 'string' => new StringType, 'integer' => new IntegerType, 'float' => new FloatType, diff --git a/src/phpstan/src/Rules/NoUntypedConfigReadsRule.php b/src/phpstan/src/Rules/NoUntypedConfigReadsRule.php index cc2203848b..52bf9199a3 100644 --- a/src/phpstan/src/Rules/NoUntypedConfigReadsRule.php +++ b/src/phpstan/src/Rules/NoUntypedConfigReadsRule.php @@ -68,7 +68,7 @@ public function processNode(Node $node, Scope $scope): array $recommendation = $this->configHelper->recommendedGetter($node, $scope); $message = $recommendation === null ? 'Read configuration with the typed getter that matches the values this caller accepts.' - : sprintf('Read config key %s with %s().', $recommendation[0], $recommendation[1]); + : sprintf('Read config key %s with %s().%s', $recommendation[0], $recommendation[1], $recommendation[3]); return [ RuleErrorBuilder::message($message) diff --git a/src/phpstan/src/Rules/TypedConfigGetterRule.php b/src/phpstan/src/Rules/TypedConfigGetterRule.php index e827e73fec..f469f8c385 100644 --- a/src/phpstan/src/Rules/TypedConfigGetterRule.php +++ b/src/phpstan/src/Rules/TypedConfigGetterRule.php @@ -69,7 +69,7 @@ public function processNode(Node $node, Scope $scope): array return []; } - [$key, $getter, $description] = $recommendation; + [$key, $getter, $description, $argumentTip] = $recommendation; return [ RuleErrorBuilder::message(sprintf( @@ -82,7 +82,7 @@ public function processNode(Node $node, Scope $scope): array ->tip(sprintf( 'Use config()->%1$s(), Config::%1$s() or the repository\'s %1$s(). Without a default, the key must exist. If the key may be omitted, pass its documented fallback. If omission means null, use a nullable getter with an explicit null.', $getter, - )) + ) . $argumentTip) ->build(), ]; } diff --git a/src/phpstan/src/Support/ConfigSourceResolver.php b/src/phpstan/src/Support/ConfigSourceResolver.php index 31caaf5fde..b9b1e7ec2a 100644 --- a/src/phpstan/src/Support/ConfigSourceResolver.php +++ b/src/phpstan/src/Support/ConfigSourceResolver.php @@ -123,8 +123,8 @@ class ConfigSourceResolver * The repository methods that only read. */ private const array READ_METHODS = [ - 'all', 'array', 'boolean', 'collection', 'float', 'get', 'getmany', - 'has', 'integer', 'nullablearray', 'nullableboolean', 'nullablefloat', 'nullableinteger', 'nullablestring', + 'all', 'array', 'boolean', 'collection', 'enum', 'float', 'get', 'getmany', + 'has', 'integer', 'nullablearray', 'nullableboolean', 'nullableenum', 'nullablefloat', 'nullableinteger', 'nullablestring', 'offsetexists', 'offsetget', 'string', ]; diff --git a/src/support/src/Facades/Config.php b/src/support/src/Facades/Config.php index ebb190ba2d..07b21f069c 100644 --- a/src/support/src/Facades/Config.php +++ b/src/support/src/Facades/Config.php @@ -9,6 +9,7 @@ * @method static array array(string $key, null|array|\Closure $default = null) * @method static bool boolean(string $key, null|bool|\Closure $default = null) * @method static \Hypervel\Support\Collection collection(string $key, null|array|\Closure $default = null) + * @method static \UnitEnum enum(string $key, string $enumClass, null|\Closure|\UnitEnum $default = null) * @method static float float(string $key, null|\Closure|float $default = null) * @method static void flushMacros() * @method static void flushState() @@ -21,6 +22,7 @@ * @method static void mixin(object $mixin, bool $replace = true) * @method static null|array nullableArray(string $key, null|array|\Closure $default = null) * @method static bool|null nullableBoolean(string $key, null|bool|\Closure $default = null) + * @method static null|\UnitEnum nullableEnum(string $key, string $enumClass, null|\Closure|\UnitEnum $default = null) * @method static float|null nullableFloat(string $key, null|\Closure|float $default = null) * @method static int|null nullableInteger(string $key, null|\Closure|int $default = null) * @method static string|null nullableString(string $key, null|\Closure|string $default = null) diff --git a/tests/Config/RepositoryTest.php b/tests/Config/RepositoryTest.php index 9e4a6c0eb3..64e8e5547c 100644 --- a/tests/Config/RepositoryTest.php +++ b/tests/Config/RepositoryTest.php @@ -7,9 +7,13 @@ use Hypervel\Config\Repository; use Hypervel\Support\Collection; use Hypervel\Support\Facades\Config; +use Hypervel\Tests\Support\Fixtures\TestEnum; +use Hypervel\Tests\Support\Fixtures\TestIntegerBackedEnum; +use Hypervel\Tests\Support\Fixtures\TestStringBackedEnum; use Hypervel\Tests\TestCase; use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; class RepositoryTest extends TestCase { @@ -327,6 +331,42 @@ public function testItGetsAsString(): void ); } + public function testEnumGettersReadCasesAndUseDefaultsOnlyForMissingKeys(): void + { + $repository = new Repository(['unit' => TestEnum::A, 'backed' => TestStringBackedEnum::B, 'disabled' => null]); + Config::swap($repository); + + $this->assertSame(TestEnum::A, $repository->enum('unit', TestEnum::class)); + $this->assertSame(TestStringBackedEnum::B, Config::nullableEnum('backed', TestStringBackedEnum::class)); + $this->assertSame(TestEnum::A, $repository->enum('missing', TestEnum::class, static fn () => TestEnum::A)); + $this->assertNull(Config::nullableEnum('disabled', TestEnum::class, TestEnum::A)); + $this->assertNull(Config::nullableEnum('missing', TestEnum::class, null)); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageIs('Configuration value for key [missing] is not defined.'); + Config::nullableEnum('missing', TestEnum::class); + } + + public function testEnumGettersResolveExactBackingValues(): void + { + $repository = new Repository(['text' => 'B', 'number' => 0]); + + $this->assertSame(TestStringBackedEnum::B, $repository->enum('text', TestStringBackedEnum::class)); + $this->assertSame(TestIntegerBackedEnum::Zero, $repository->nullableEnum('number', TestIntegerBackedEnum::class)); + } + + #[TestWith(['0', TestIntegerBackedEnum::class, "'0'"])] + #[TestWith(['typo', TestStringBackedEnum::class, "'typo'"])] + #[TestWith(['A', TestEnum::class, "'A'"])] + #[TestWith([TestStringBackedEnum::A, TestEnum::class, TestStringBackedEnum::class])] + public function testEnumGetterRejectsInvalidValues(mixed $value, string $enumClass, string $description): void + { + $repository = new Repository(['mode' => $value]); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageIs(sprintf('Configuration value for key [mode] must be a case or backing value of [%s], %s given.', $enumClass, $description)); + $repository->enum('mode', $enumClass); + } + #[DataProvider('nullableGetters')] public function testNullableGetterPreservesValuesAndOnlyEvaluatesDefaultsForMissingKeys(string $getter, mixed $value): void { diff --git a/tests/Data/DataConfigTest.php b/tests/Data/DataConfigTest.php index f16541cdcd..af7614dbfb 100644 --- a/tests/Data/DataConfigTest.php +++ b/tests/Data/DataConfigTest.php @@ -18,7 +18,6 @@ use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; -use ValueError; class DataConfigTest extends TestCase { @@ -111,7 +110,8 @@ public static function invalidScalarConfigurationProvider(): iterable public function testInvalidValidationStrategyFailsFast(): void { - $this->expectException(ValueError::class); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Configuration value for key [data.validation_strategy]'); $this->makeConfig(['validation_strategy' => 'sometimes']); } diff --git a/tests/Foundation/Console/ConfigShowCommandTest.php b/tests/Foundation/Console/ConfigShowCommandTest.php index 4c80a58a97..e68a006ac1 100644 --- a/tests/Foundation/Console/ConfigShowCommandTest.php +++ b/tests/Foundation/Console/ConfigShowCommandTest.php @@ -6,6 +6,8 @@ use Hypervel\Foundation\Console\ConfigShowCommand; use Hypervel\Support\Facades\Artisan; +use Hypervel\Tests\Support\Fixtures\TestEnum; +use Hypervel\Tests\Support\Fixtures\TestIntegerBackedEnum; use JsonException; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; @@ -47,6 +49,7 @@ public function testDisplayConfig(): void 'empty_array' => [], 'assoc_array' => ['foo' => 'bar'], 'class' => new stdClass, + 'mode' => TestEnum::A, ]); $this->artisan(ConfigShowCommand::class, ['config' => 'test']) @@ -60,7 +63,8 @@ public function testDisplayConfig(): void ->expectsOutput(' array ⇁ 0 .... Hypervel\Foundation\Console\ConfigShowCommand ') ->expectsOutput(' empty_array ............................................. [] ') ->expectsOutput(' assoc_array ⇁ foo ...................................... bar ') - ->expectsOutput(' class ............................................. stdClass '); + ->expectsOutput(' class ............................................. stdClass ') + ->expectsOutputToContain(TestEnum::class . '::A'); } public function testDisplayNestedConfigItems(): void @@ -118,6 +122,14 @@ public static function jsonValues(): array ]; } + public function testShowsUnitNamesAndBackingValuesInJson(): void + { + config(['app.modes' => ['nested' => [TestEnum::A, TestIntegerBackedEnum::Zero]]]); + + $this->assertSame(0, Artisan::call('config:show', ['config' => 'app.modes', '--json' => true])); + $this->assertSame(['nested' => ['A', 0]], json_decode(Artisan::output(), true, flags: JSON_THROW_ON_ERROR)); + } + public function testJsonFailsForMissingConfiguration(): void { $this->artisan(ConfigShowCommand::class, ['config' => 'invalid', '--json' => true]) diff --git a/tests/PHPStan/Rules/ConfigTypeRuleTest.php b/tests/PHPStan/Rules/ConfigTypeRuleTest.php index cdb3ccf04f..7cb9d8d42e 100644 --- a/tests/PHPStan/Rules/ConfigTypeRuleTest.php +++ b/tests/PHPStan/Rules/ConfigTypeRuleTest.php @@ -19,13 +19,15 @@ protected function getRule(): Rule public function testRule(): void { $this->analyse([__DIR__ . '/data/config-type-rule.php'], [ - ["Config key 'test.foo' is not an integer, so integer() throws. Correct the config value or use the getter that matches its type.", 14], - ["Config key 'test.foo' is not an array, so array() throws. Correct the config value or use the getter that matches its type.", 16], - ["Config key 'auth.defaults.guard' is not a float, so float() throws. Correct the config value or use the getter that matches its type.", 17], - ["Config key 'test.missing' is not defined, so boolean() throws. Check the key and its configuration.", 31], - ["Config key 'test.foo' is not an integer, so integer() throws. Correct the config value or use the getter that matches its type.", 40], - ["Config key 'test.missing' is not defined, so nullableInteger() throws. Check the key and its configuration.", 57], - ["Config key 'test.foo' is not an integer or null, so nullableInteger() throws. Correct the config value or use the getter that matches its type.", 58], + ["Config key 'test.foo' is not an integer, so integer() throws. Correct the config value or use the getter that matches its type.", 15], + ["Config key 'test.foo' is not an array, so array() throws. Correct the config value or use the getter that matches its type.", 17], + ["Config key 'auth.defaults.guard' is not a float, so float() throws. Correct the config value or use the getter that matches its type.", 18], + ["Config key 'test.missing' is not defined, so boolean() throws. Check the key and its configuration.", 32], + ["Config key 'test.foo' is not an integer, so integer() throws. Correct the config value or use the getter that matches its type.", 41], + ["Config key 'test.missing' is not defined, so nullableInteger() throws. Check the key and its configuration.", 58], + ["Config key 'test.foo' is not an integer or null, so nullableInteger() throws. Correct the config value or use the getter that matches its type.", 59], + ["Config key 'test.missing' is not defined, so enum() throws. Check the key and its configuration.", 60], + ["Config key 'test.foo' is not Hypervel\\Cache\\TagMode or null, so nullableEnum() throws. Correct the config value or use the getter that matches its type.", 61], ]); } diff --git a/tests/PHPStan/Rules/TypedConfigGetterRuleTest.php b/tests/PHPStan/Rules/TypedConfigGetterRuleTest.php index 2813d11627..ba2d77d32d 100644 --- a/tests/PHPStan/Rules/TypedConfigGetterRuleTest.php +++ b/tests/PHPStan/Rules/TypedConfigGetterRuleTest.php @@ -22,10 +22,10 @@ protected function getRule(): Rule public function testApplication(): void { - $error = static fn (string $key, string $description, string $getter, int $line): array => [ + $error = static fn (string $key, string $description, string $getter, int $line, string $argumentTip = ''): array => [ sprintf('Config key %s always holds %s, so read it with %s().', $key, $description, $getter), $line, - sprintf("Use config()->%1\$s(), Config::%1\$s() or the repository's %1\$s(). Without a default, the key must exist. If the key may be omitted, pass its documented fallback. If omission means null, use a nullable getter with an explicit null.", $getter), + sprintf("Use config()->%1\$s(), Config::%1\$s() or the repository's %1\$s(). Without a default, the key must exist. If the key may be omitted, pass its documented fallback. If omission means null, use a nullable getter with an explicit null.", $getter) . $argumentTip, ]; // The analyzer tests boot a Testbench package application. @@ -40,6 +40,7 @@ public function testApplication(): void $error("'typed.hosts'", 'an array', 'array', 19), $error("'typed.label'|'typed.name'", 'a string', 'string', 20), $error("'typed.optional_label'", 'a string or null', 'nullableString', 31), + $error("'typed.mode'", 'Hypervel\Cache\TagMode', 'enum', 34, ' Pass Hypervel\Cache\TagMode::class as the second argument.'), ]); } finally { self::setPackageApplication($packageApplication); diff --git a/tests/PHPStan/Rules/data/config-type-rule.php b/tests/PHPStan/Rules/data/config-type-rule.php index 76eb0243f4..019d4aab04 100644 --- a/tests/PHPStan/Rules/data/config-type-rule.php +++ b/tests/PHPStan/Rules/data/config-type-rule.php @@ -4,6 +4,7 @@ namespace ConfigTypeRule; +use Hypervel\Cache\TagMode; use Hypervel\Config\Repository; use Hypervel\Support\Facades\Config; @@ -56,6 +57,8 @@ public function nullableGetters(bool $secondary): void Config::nullableString($secondary ? 'test.missing' : 'test.foo'); Config::nullableInteger('test.missing'); Config::nullableInteger('test.foo'); + Config::enum('test.missing', TagMode::class); + config()->nullableEnum('test.foo', TagMode::class); } } diff --git a/tests/PHPStan/Rules/data/typed-config-getters.php b/tests/PHPStan/Rules/data/typed-config-getters.php index 489716d895..72ff68ad3a 100644 --- a/tests/PHPStan/Rules/data/typed-config-getters.php +++ b/tests/PHPStan/Rules/data/typed-config-getters.php @@ -31,5 +31,6 @@ public function reads(Repository $config, bool $secondary): void config('typed.optional_label'); config('typed.environment'); config('typed.name', static fn () => []); + config('typed.mode'); } } diff --git a/tests/PHPStan/Type/data/config-repository-method.php b/tests/PHPStan/Type/data/config-repository-method.php index 908fa01ef3..8cfc148c7b 100644 --- a/tests/PHPStan/Type/data/config-repository-method.php +++ b/tests/PHPStan/Type/data/config-repository-method.php @@ -2,14 +2,17 @@ namespace ConfigRepositoryMethod; +use Hypervel\Cache\TagMode; use Hypervel\Config\Repository; use Hypervel\Support\Facades\Config; +use UnitEnum; use function PHPStan\Testing\assertType; // Unlike upstream, an absent key returns its default and a present key ignores it, and only the // application's repository has the application's values: config() or a resolution of it from the // application container. -function test(Repository $config, bool $secondary): void +/** @param class-string $enumClass */ +function test(Repository $config, bool $secondary, string $enumClass): void { assertType('null', config()->get('foo')); assertType('array{guard: \'web\', passwords: \'users\'}', app('config')->get('auth.defaults')); @@ -35,6 +38,17 @@ function test(Repository $config, bool $secondary): void assertType('Hypervel\Support\Collection<0|1|2, 1|2|3>', config()->collection('test.bar')); assertType('*ERROR*', config()->collection('test.foo')); + assertType('Hypervel\Cache\TagMode', Config::enum(...['typed.mode', TagMode::class])); + assertType('Hypervel\Cache\TagMode', config()->enum('test.missing', TagMode::class, fn () => TagMode::Any)); + assertType('UnitEnum', Config::enum('typed.mode_value', $enumClass)); + assertType('Hypervel\Cache\TagMode::Any', Config::enum('typed.mode_value', TagMode::class)); + assertType('Hypervel\Cache\TagMode::All', Config::enum('typed.mode', TagMode::class)); + assertType('Hypervel\Cache\TagMode', Config::enum('logging.channels.undeclared', TagMode::class)); + assertType('Hypervel\Cache\TagMode|null', $config->nullableEnum('unknown', TagMode::class)); + assertType('null', Config::nullableEnum(default: null, enumClass: TagMode::class, key: 'test.missing')); + assertType('*ERROR*', config()->enum('typed.name', TagMode::class)); + assertType('*ERROR*', config()->nullableEnum('test.missing', TagMode::class)); + // A repository received or built elsewhere may hold other values. assertType('mixed', $config->get('test.foo')); assertType('mixed', (new Repository(['test' => ['foo' => 123]]))->get('test.foo')); diff --git a/tests/PHPStan/application/config/typed.php b/tests/PHPStan/application/config/typed.php index dcc672b73c..ed05a010a5 100644 --- a/tests/PHPStan/application/config/typed.php +++ b/tests/PHPStan/application/config/typed.php @@ -2,7 +2,11 @@ declare(strict_types=1); +use Hypervel\Cache\TagMode; + return [ + 'mode' => TagMode::All, + 'mode_value' => 'any', 'name' => 'Hypervel', 'label' => 'Typed', 'port' => 3306,