PHP code example of rasuvaeff / schema

1. Go to this page and download the library: Download rasuvaeff/schema library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rasuvaeff / schema example snippets


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
]);

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

use Rasuvaeff\PropertyTesting\Random;

$random = new Random(42);
$value = $user->arbitrary()->generate($random)->value;  // always parses

#[Property(runs: 300)]
public function queuePayloadIsHandled(SchemaInterface $payload): void
{
    $value = Gen::draw($payload->arbitrary());
    // ...
}

$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

$wire = $user->toWire($parsed);   // ['role' => Role::Admin, ...] → ['role' => 'admin', ...]

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

$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']

Schema::string()->regexUnchecked(
    '^a+\z',
    Gen::map(Gen::intBetween(1, 8), static fn (int $n): string => str_repeat('a', $n)),
);

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(),
);