msstc4php / vo-base-spiral
Spiral Framework filters, route arguments and validation for msstc4php/vo-base value objects.
Requires
- php: >=8.4
- msstc4php/vo-base: ^1.4
- spiral/framework: ^3.18
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.76
- nyholm/psr7: ^1.8
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: >=11.0
- rector/rector: ^2.1
- roave/security-advisories: dev-latest
- spiral/validator: ^1.8
Suggests
- msstc4php/vo-base-cycle: Stores value objects in Cycle ORM entities
- spiral/validator: Enables the vo:valid checker
Provides
None
Conflicts
- spiral/validator: <1.8
Replaces
None
README
Spiral Framework 3.x integration for msstc4php/vo-base: request input becomes value
objects the way Spiral already does it, and invalid input is a field error or a 404 — never a 500.
| Need | What this package gives |
|---|---|
Filter properties typed EmailAddress, Port, GeoCoordinates, ... |
a filter caster: filled from input, invalid → 422 with the field |
Route parameters into typed action arguments (/users/<email> → EmailAddress $email) |
an interceptor: invalid → 404 |
| Validation rules on raw input | the spiral/validator rule ['vo:valid', EmailAddress::class] |
| Storage in Cycle ORM entities | not here: msstc4php/vo-base-cycle |
Every conversion goes through the core's ValueObjectMapper::fromUntrustedPayload(), the same path the Symfony bundle
and the other bridges use. Client-facing messages name the value object's label ("email address"), never a PHP class.
Install
Neither this package nor the core is on Packagist yet, so register both GitHub repositories:
{
"repositories": [
{ "type": "vcs", "url": "https://github.com/msstc4php/vo-base" },
{ "type": "vcs", "url": "https://github.com/msstc4php/vo-base-spiral" }
],
"require": {
"msstc4php/vo-base-spiral": "^1.0"
}
}
Requires PHP >= 8.4, msstc4php/vo-base ^1.4 and spiral/framework ^3.18. spiral/validator ^1.8 is optional (the
vo:valid rule).
Spiral has no package auto-discovery: add the bootloader to your kernel:
use MSSTC4PHP\ValueObject\Spiral\Bootloader\ValueObjectBootloader; final class Kernel extends \Spiral\Framework\Kernel { protected function defineBootloaders(): array { return [ // ... the framework bootloaders, AttributesBootloader among them (filters need it) \Spiral\Validator\Bootloader\ValidatorBootloader::class, ValueObjectBootloader::class, // ... your application bootloaders ]; } }
ValueObjectBootloader loads FiltersBootloader, binds ValueObjectMapper as a singleton, registers the filter
caster and — when ValidatorBootloader is loaded, in this list or in defineAppBootloaders() — the vo checker.
Custom codecs
A composite of your own needs a PayloadCodec (see the core). Rebind the mapper in a bootloader listed after
ValueObjectBootloader; Spiral runs every bootloader's bindings before any boot(), so the caster, the interceptor
and the checker all get yours:
final class AppBootloader extends Bootloader { public function defineSingletons(): array { return [ ValueObjectMapper::class => static fn (): ValueObjectMapper => new ValueObjectMapper([new MoneyCodec()]), // a package's whole set through its ProvidesCodecs class, e.g. vo-documents' composite names: // new ValueObjectMapper(\MSSTC4PHP\ValueObject\Documents\Codecs::all()) ]; } }
Filters
Type the property with the value object; nothing else to configure:
use MSSTC4PHP\ValueObject\Geo\GeoCoordinates; use MSSTC4PHP\ValueObject\Identity\EmailAddress; use MSSTC4PHP\ValueObject\Network\Port; use Spiral\Filters\Attribute\Input\Post; use Spiral\Filters\Model\Filter; final class SignupFilter extends Filter { #[Post] public EmailAddress $email; #[Post] public ?Port $port = null; #[Post] public ?GeoCoordinates $location = null; } final class SignupController { public function signup(SignupFilter $filter): array { return ['email' => (string) $filter->email]; } }
With Spiral's ValidationHandlerMiddleware in the pipeline, {"email": "nope", "port": "70000"} answers:
422 {"errors": {"email": "The value is not a valid email address.", "port": "The value is not a valid port."}}
- Scalar-backed value objects read a string or number (
"8080"for aPort); an array where a string is expected is a field error. - A composite reads an array (a JSON body) or JSON text (a form field:
location={"lat":52.52,"lng":13.405}). A form-encoded array (location[lat]=52.52) carries strings and is refused by the core's codec. nullor a missing key leaves the property at its default — give a nullable property= null.''makes a nullable propertynulland is invalid for a non-nullable one. An instance of the class is kept as it is.BoundedStringis always refused ("A bounded string cannot be read from request input."): its payload would let the client choose the bounds. Type the propertystringand validate the length instead, or useNonEmptyString. It is a field error here, reported with the other fields; the interceptor andvo:validtreat aBoundedStringargument or rule as a programmer error (LogicException), since no request could ever satisfy it.- Backed enums (
CountryCode, ...) stay with Spiral's ownEnumCaster, which registers first and cannot be reordered without replacing Spiral's caster registry. Its error text is Spiral's: "Unable to set enum value." followed by PHP'sfrom()message, which names the enum class. Put#[CastingErrorMessage('Not a valid country.')]on an enum property whose errors reach clients. #[CastingErrorMessage('...')]on a property replaces the message, as for any Spiral caster.
Route arguments
Register ValueObjectArgumentsInterceptor, and a route parameter becomes the value object the action argument is
typed with:
final class UserController { public function show(EmailAddress $email): array { /* ... */ } } $router->setRoute('user', new Route('/users/<email>', new Action(UserController::class, 'show')));
/users/jane@example.com calls show(EmailAddress::from('jane@example.com')); /users/nope is a 404.
List it before any interceptor that reads the arguments: after it they are value objects, no longer strings.
Globally, through the domain core of your application:
use MSSTC4PHP\ValueObject\Spiral\Interceptor\ValueObjectArgumentsInterceptor; use Spiral\Bootloader\DomainBootloader; use Spiral\Core\CoreInterface; final class AppBootloader extends DomainBootloader { protected const SINGLETONS = [CoreInterface::class => [self::class, 'domainCore']]; protected const INTERCEPTORS = [ ValueObjectArgumentsInterceptor::class, // ... your other interceptors ]; }
Or for one route, with its own pipeline:
use Spiral\Interceptors\Handler\AutowireHandler; use Spiral\Interceptors\PipelineBuilder; $pipeline = new PipelineBuilder() ->withInterceptors($container->get(ValueObjectArgumentsInterceptor::class)) ->build(new AutowireHandler($container)); $action = new Action(UserController::class, 'show')->withHandler($pipeline); $router->setRoute('user', new Route('/users/<email>', $action)); // or with the routing configurator: $routes->add('user', '/users/<email>')->action(...)->core($pipeline);
- Arguments bind by name, exactly as Spiral binds route parameters. Scalar-backed value objects and backed enums
(
/countries/<country>→CountryCode $country; an unknown case is a 404): a route parameter is one string. An argument typed with a composite (GeoCoordinates) or a trusted-source-only class (BoundedString) is aLogicExceptionnaming the argument — a programmer error, found on the first request. null(an absent optional segment,/users[/<email>]) staysnull, so?EmailAddress $email = nullworks;''isnullfor a nullable argument and a 404 otherwise. An argument that already is an instance passes through.- Union types (
EmailAddress|string $id) and builtins are left to Spiral. Without the interceptor Spiral answers 400 for a string in a value-object or backed-enum argument.
Validation rule
With spiral/validator, vo:valid validates raw input against a value object without building it:
use Spiral\Filters\Model\FilterDefinitionInterface; use Spiral\Filters\Model\HasFilterDefinition; use Spiral\Validator\FilterDefinition; final class ContactFilter extends Filter implements HasFilterDefinition { #[Post] public string $email = ''; public function filterDefinition(): FilterDefinitionInterface { return new FilterDefinition([ 'email' => ['required', ['vo:valid', EmailAddress::class]], ]); } }
nulland''pass: emptiness isrequired's job. A valid payload or an instance passes; anything else is "The value is not a valid email address." (or the rule's own'error' => '...').- Composites accept an array or JSON text, as the caster does.
- A rule for
BoundedStringor a class the mapper cannot read is aLogicException, even when the field is absent.
Storage
Persisting value objects in Cycle ORM entities is msstc4php/vo-base-cycle's job; Spiral's container injects
the same bound ValueObjectMapper into its typecast handler.
Backward compatibility
1.x follows semantic versioning; a breaking change needs 2.0. Covered by 1.x:
-
Code API: these classes, their constructors with these parameter names (named arguments), the methods of the Spiral interfaces and base classes they implement (including
ValueObjectBootloader::boot()as Spiral calls it; its parameters are injected by Spiral and are not covered):Bootloader\ValueObjectBootloader, withCHECKER_ALIAS = 'vo'; it loadsFiltersBootloader, bindsValueObjectMapperas a singleton (rebindable by a bootloader listed after it), registers the filter caster and, whenValidatorBootloaderis loaded, the checker;Interceptor\ValueObjectArgumentsInterceptor(ValueObjectMapper $mapper), registered by the application;Filter\ValueObjectCaster(ValueObjectMapper $mapper), public so that an application may register it in a caster registry of its own;Validation\ValueObjectChecker(ValueObjectMapper $mapper), its methodvalid(mixed $value, string $class)and itsMESSAGESandALLOW_EMPTY_VALUESconstants.
-
Names users write: the checker alias
voand the rule['vo:valid', X::class]; the container idValueObjectMapper::class, which the caster, the interceptor and the checker are built with. -
Messages: the
vo:validtranslation key[[The value is not a valid {type}.]]and its{type}placeholder. Changing that default text needs 2.0, or a new key with the old one kept. -
Input forms: a scalar-backed value object reads a string or number, a composite an array or JSON text, a backed enum its code. These are vo-base's payload forms, the same the Symfony bundle and the other bridges read.
-
Exceptions:
Spiral\Filters\Exception\SetterException, the property's field error (422), for invalid filter input and for a trusted-source-only property (BoundedString);Spiral\Interceptors\Exception\TargetCallExceptionwith codeNOT_FOUND(404) for an invalid route argument;LogicExceptionfor configuration errors: a caster property not typed with a single class, a route argument typed with a composite or a trusted-source-only class, avo:validrule for a class request input cannot build, and a validator config delivered before the checker could be registered.
The previous exception of a field error for invalid input or of a 404 is vo-base's own exception (or the
JsonExceptionof malformed composite JSON), passed through unchanged; the field error of a trusted-source-only property has no previous exception. -
Enums: filter properties typed with a backed enum stay with Spiral's
EnumCaster, whose error text is Spiral's and names the enum class (#[CastingErrorMessage]replaces it, see Filters); the interceptor binds backed enums itself (an unknown case is a 404);vo:validvalidates them. -
Versions: a minor may add support for a new Spiral or PHP major; dropping a supported Spiral or PHP version needs a major, and so does raising the floor of any third-party dependency (Spiral,
spiral/validator, PHP). A minor may raise the floor of amsstc4php/*package within its major (those follow the same promise). Thespiral/validatorfloor (1.8) is enforced by aconflictentry, since the package is optional.
A minor never refuses a value an earlier 1.x accepted: the caster, the interceptor and the checker add no validation of their own, the value objects (vo-base and the domain packages) decide, and they follow the same rule.
Not covered: exception message wording (the package's messages name classes, type labels, fields, arguments or methods,
never the value), except the translation key above; anything marked @internal (Internal\TypeLabel).
Development
COMPOSER=composer-local.json composer update --ignore-platform-req=php # against ../vo-base
make check # php -l, PHPStan level max, cs-fixer, composer validate/audit, Rector, deptrac
make test # PHPUnit: unit suite plus a booted Spiral kernel with a real HTTP stack
make infection