rasuvaeff / schema
Schema-as-code combinators for PHP: one definition drives runtime validation, property-based generation and JSON Schema export
Requires
- php: 8.3 - 8.5
- ext-filter: *
- ext-mbstring: *
- rasuvaeff/property-testing-core: ^1.2
Requires (Dev)
- ergebnis/composer-normalize: ^2.51
- friendsofphp/php-cs-fixer: ^3.95
- infection/infection: ^0.35
- maglnet/composer-require-checker: ^4.17
- opis/json-schema: ^2.6
- rasuvaeff/property-testing-testo: ^1.0
- rasuvaeff/rector-named-literals: ^1.0
- rasuvaeff/understudy-testo: ^1.0
- rector/rector: ^2.4
- roave/backward-compatibility-check: ^8.0
- testo/bridge-infection: ^0.1.6
- testo/testo: ^0.10.25
- vimeo/psalm: ^6.16
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-10-11 09:02:09 UTC
README
Schema-as-code for PHP: one definition, two ports. The same Schema::object([...])
tree validates runtime input and feeds property-based tests a generator over
the exact same value set — so the validator and the tests can never drift apart.
Using an AI coding assistant? llms.txt is a compact API reference designed for LLMs.
Why
Validation rules and test generators are usually written separately, in different
places, by different versions of you. They drift: the queue consumer accepts
status: 'pending', the property test never generates it, and the tests are
blind to what production actually lets through. rasuvaeff/schema kills the
drift by construction: one schema defines the set, parse() checks it,
arbitrary() generates from it — the parity is pinned by the package's own
property suite over random schema trees.
The pattern is proven elsewhere (pydantic + hypothesis in Python,
Zod + fast-check in TypeScript); this is the PHP take, built on
rasuvaeff/property-testing-core.
Requirements
- PHP 8.3 / 8.4 / 8.5
ext-mbstringrasuvaeff/property-testing-core^1.2 (runtime — the generator port is the product, not a test utility)
Installation
composer require rasuvaeff/schema
Usage
Define
use Rasuvaeff\Schema\Schema; $user = Schema::object([ 'email' => Schema::string()->min(3)->max(254), 'age' => Schema::int()->min(18)->max(120), 'role' => Schema::enum(Role::class), // backed enum 'tags' => Schema::arrayOf(Schema::string()->min(1))->maxCount(20), 'bio' => Schema::string()->max(1000)->default(''), // default ≡ optional 'meta' => Schema::mapOf(Schema::json())->optional(), 'score' => Schema::float()->min(0.0)->max(1.0), // finite floats only 'created_at' => Schema::dateTime(), // RFC 3339 in, DateTimeImmutable out ]);
Validate
$result = $user->parse($payload); if (!$result->ok) { foreach ($result->errors as $error) { // '$.tags[2]' / RFC 6901 '/tags/2' — the segments are the source of truth $error->toPath(); $error->toJsonPointer(); $error->message; // kinds and sizes only, never the offending value } } $value = $user->parseOrThrow($payload); // SchemaException carries every error // SchemaException extends InvalidArgumentException — an invalid input, // not a runtime failure. Consumers with an InvalidArgumentException // contract can let it propagate as is.
Object semantics, pinned: an absent optional key is absent from the result
(not null); a defaulted key is always present, carrying the validated,
normalized default (an enum default may be given as its backed value and is
stored as the instance). nullable() is about the value; optional() is
about the key.
Generate
use Rasuvaeff\PropertyTesting\Random; $random = new Random(42); $value = $user->arbitrary()->generate($random)->value; // always parses
In property tests (with rasuvaeff/property-testing-testo) the schema is the
generator:
#[Property(runs: 300)] public function queuePayloadIsHandled(SchemaInterface $payload): void { $value = Gen::draw($payload->arbitrary()); // ... }
Export
$export = $user->toJsonSchema(); // strict (default): a transform // without a declared codec throws $export->schema; // pure draft 2020-12 fragment $export->nonRepresentable; // list<NonRepresentable>: what // was dropped, with paths $export->assertFullyRepresentable(); // throws listing every entry $user->toJsonSchema(lenient: true); // a codec-less transform exports // as {} + an entry instead
Refinements always export as the inner schema — an honest superset, recorded
in nonRepresentable. A transform with a declared codec exports it, and the
package's own law 2 checks the codec against the generator's actual output.
An object's default annotation goes through the wire seam: an enum default
instance is exported as its backed value.
Wire: toWire()
parse/arbitrary live in the PHP domain (an enum stays an instance);
queues, HTTP and JSON storage need the wire form. toWire() is the
projection: an enum instance becomes its backed value, containers convert
recursively, a transform's declared wire callback is applied, everything
else passes through.
$wire = $user->toWire($parsed); // ['role' => Role::Admin, ...] → ['role' => 'admin', ...]
The inverse pair of the generator's domain — arbitrary() produces PHP
values, toWire() hands them to the wire. Found by the first consumer
pilot (keppio): the queue property test needed exactly this projection.
Combinators
Schema::int()->min(0)->transform(static fn (int $v): string => (string) $v); // generation maps into the target space; shrinking stays in the source space Schema::int()->min(1)->nullable(); // instance form == Schema::nullable(...) Schema::string()->refine(static fn (string $v): bool => !str_contains($v, ' '), 'No spaces'); // prefer constraints — a refinement filters the generator and burns budget
Order rule: combinators first, property modifiers last —
->min(1)->transform(...)->optional().
Hydrating into a DTO: into()
$user = Schema::object([ 'name' => Schema::string()->min(1), 'role' => Schema::enum(Role::class), ])->into(UserDto::class); $dto = $user->parseOrThrow($payload); // UserDto, role already a Role case $user->toWire($dto); // ['name' => ..., 'role' => 'admin']
The parsed properties are passed to the constructor as named arguments,
after defaults and strip() are settled. The DTO takes its properties as
public promoted constructor arguments — that is what makes toWire()
lossless. A constructor that throws becomes a parse error carrying the class
names only. The export is the object schema's own. Keep the DTO's own
invariants within the schema: a constructor stricter than the schema breaks
the generator.
Patterns outside the generatable subset: regexUnchecked()
regex() only accepts patterns Gen::stringMatching can generate — \z,
lookaround and backreferences are rejected at construction. regexUnchecked()
is the explicit opt-out: you supply the generator, the schema keeps the
pattern for parsing and export.
Schema::string()->regexUnchecked( '^a+\z', Gen::map(Gen::intBetween(1, 8), static fn (int $n): string => str_repeat('a', $n)), );
The parity law is then yours: everything the generator produces must match.
Build matching values constructively; a Gen::filter() with the pattern as
predicate only works when matches are common. The export records a
regexUnchecked entry in nonRepresentable — nothing vouches that a JSON
Schema (ECMA-262) validator reads the PCRE pattern the same way.
Testing: Testing\RoundTrip
The parity laws, defined once next to the schema instead of being copied
into every consumer's test support. Framework-agnostic: each method checks
one value and throws Testing\RoundTripException on violation, so it plugs
into a property test (feed it $schema->arbitrary()) or a PHPUnit loop.
RoundTrip::assertParses($schema, $value); // generated ⇒ parses RoundTrip::assertWireRoundTrip($schema, $value); // toWire → parse → toWire is lossless RoundTrip::assertConsumerRoundTrip( // your hydrate/wire pair $schema, $payload, static fn (mixed $p): object => Message::fromPayload($p), static fn (object $m): array => $m->toPayload(), );
assertConsumerRoundTrip() checks that hydrate($payload) succeeds, that
the schema's toWire($payload) equals your wire form of the hydrated object,
and that wire → hydrate → wire is lossless. Failure messages carry the stage
and value kinds only, never the values. assertWireRoundTrip() needs an
invertible schema: a transform without a wire inverse, or a union whose
members overlap (first success wins, so the wire form may re-parse through
another member), breaks it by construction — prefer Schema::discriminated().
Security
Error messages never embed input values — kinds and sizes only
(get_debug_type, lengths, counts). Payloads may carry secrets; errors
travel to logs and Sentry. A transform callback that throws contributes
its class name only.
Strings are JSON's domain: string() rejects invalid UTF-8 up-front
(mb_check_encoding), before any length, format or pattern check, so the
code-point length and the pattern engine never disagree about the input. A
PCRE engine failure (e.g. backtrack limit exhausted) is reported as its own
error — Pattern check failed (PCRE engine error: …) — never as a plain
pattern mismatch.
API
The Schema facade is the single entry point; every factory returns a
SchemaType subclass, all of them @api:
| Type | Factory | Notes |
|---|---|---|
Type\StringSchema |
Schema::string() |
code-point min/max, regex, regexUnchecked (own generator), format; rejects invalid UTF-8 |
Type\IntSchema |
Schema::int() |
min/max, positive() (≥1), nonNegative() (≥0), coerce() |
Type\FloatSchema |
Schema::float() |
finite only (NaN/INF rejected); min/max, allowInt(), coerce(); export type: number |
Type\DateTimeSchema |
Schema::dateTime() |
RFC 3339 wire ↔ DateTimeImmutable domain; inclusive min/max |
Type\BoolSchema |
Schema::bool() |
coerce() ("true"/"1" → true) |
Type\LiteralSchema |
Schema::literal($v) |
strict === |
Type\EnumSchema |
Schema::enum(Role::class) |
backed; instance or backed value in, instance out |
Type\JsonValueSchema |
Schema::json() |
the json_decode domain |
Type\ArraySchema |
Schema::arrayOf($el) |
list; minCount/maxCount |
Type\MapSchema |
Schema::mapOf($v) |
string keys; minCount/maxCount |
Type\ObjectSchema |
Schema::object([...]) |
optional/default properties, additionalProperties(), strip() |
Type\UnionSchema |
Schema::union([...]) |
first success wins |
Type\DiscriminatedSchema |
Schema::discriminated('kind', ['a' => $obj, ...]) |
tag selects the branch; disjoint by construction (required literal tag); export oneOf |
Type\TupleSchema |
Schema::tuple([...]) |
fixed-length heterogeneous list; export prefixItems + items: false |
Type\NullableSchema |
Schema::nullable($s) |
value-level null |
Type\LazySchema |
Schema::lazy($fn) |
recursion, memoized |
Combinator\TransformSchema |
->transform($fn) |
target-space generation, source-space shrinking |
Combinator\RefineSchema |
->refine($fn, $msg) |
post-condition; filtered generation |
Type\ObjectProperty |
->optional() / ->default($v) |
property modifiers; default validated on construction |
Combinator\IntoSchema |
Schema::object([...])->into(Dto::class) |
hydrates the parsed properties into a DTO (named arguments); export and wire stay the object's |
Testing helpers: Testing\RoundTrip (assertParses, assertWireRoundTrip,
assertConsumerRoundTrip) and Testing\RoundTripException.
Results: ParseResult / ParseError (segments → $.tags[2] and RFC 6901),
SchemaException, JsonSchemaExport + NonRepresentable /
NonRepresentableException (strict export).
Examples
- examples/queue-payload.php — object schema with enum/default, error paths, generation from the same schema.
Development
No PHP/Composer on the host — Docker:
docker run --rm -v "$PWD":/app -w /app composer:2 composer build
See AGENTS.md for the full command set and invariants.
License
BSD-3-Clause. See LICENSE.md.