Search by

msstc4php / vo-base-spiral

maxim.shamaev@gmail.com

Spiral Framework filters, route arguments and validation for msstc4php/vo-base value objects.

Package info

github.com/msstc4php/vo-base-spiral

pkg:composer/msstc4php/vo-base-spiral

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

v1.0.0 2026-11-27 06:58 UTC

This package is auto-updated.

Last update: 2026-11-28 15:05:14 UTC


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 a Port); 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.
  • null or a missing key leaves the property at its default — give a nullable property = null. '' makes a nullable property null and is invalid for a non-nullable one. An instance of the class is kept as it is.
  • BoundedString is always refused ("A bounded string cannot be read from request input."): its payload would let the client choose the bounds. Type the property string and validate the length instead, or use NonEmptyString. It is a field error here, reported with the other fields; the interceptor and vo:valid treat a BoundedString argument or rule as a programmer error (LogicException), since no request could ever satisfy it.
  • Backed enums (CountryCode, ...) stay with Spiral's own EnumCaster, 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's from() 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 a LogicException naming the argument — a programmer error, found on the first request.
  • null (an absent optional segment, /users[/<email>]) stays null, so ?EmailAddress $email = null works; '' is null for 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]],
        ]);
    }
}
  • null and '' pass: emptiness is required'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 BoundedString or a class the mapper cannot read is a LogicException, 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, with CHECKER_ALIAS = 'vo'; it loads FiltersBootloader, binds ValueObjectMapper as a singleton (rebindable by a bootloader listed after it), registers the filter caster and, when ValidatorBootloader is 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 method valid(mixed $value, string $class) and its MESSAGES and ALLOW_EMPTY_VALUES constants.
  • Names users write: the checker alias vo and the rule ['vo:valid', X::class]; the container id ValueObjectMapper::class, which the caster, the interceptor and the checker are built with.

  • Messages: the vo:valid translation 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\TargetCallException with code NOT_FOUND (404) for an invalid route argument;
    • LogicException for configuration errors: a caster property not typed with a single class, a route argument typed with a composite or a trusted-source-only class, a vo:valid rule 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 JsonException of 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:valid validates 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 a msstc4php/* package within its major (those follow the same promise). The spiral/validator floor (1.8) is enforced by a conflict entry, 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