PHP code example of nitier / caster

1. Go to this page and download the library: Download nitier/caster 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/ */

    

nitier / caster example snippets


use Nitier\Caster\Caster;

$payload = [
    'id' => '42',
    'price' => '19.95',
    'active' => 'yes',
    'created_at' => '2024-05-10 12:00:00',
];

$id = Caster::positiveInt($payload['id']);                 // 42
$price = Caster::float($payload['price']);                 // 19.95
$isActive = Caster::bool($payload['active']);              // true
$createdAt = Caster::dateTimeImmutable($payload['created_at']);

$slug = Caster::nonEmptyTrimmedString($payload['slug']);   // trims and rejects empty results
$alias = Caster::nullableString($payload['alias'] ?? null); // ?string
$flag = Caster::bool('Yes');                               // true
$maybeFlag = Caster::tryBool('unknown');                   // null

$publishedAt = Caster::dateTimeImmutable('2024-01-01T10:00:00+00:00');
$maybeExpires = Caster::nullableDateTimeImmutable(
    $payload['expires_at'] ?? null,
    'expires_at',
    DATE_ATOM
);

enum Status: string { case Draft = 'draft'; case Published = 'published'; }

$status = Caster::enum(Status::class, 'draft');        // Status::Draft
$maybeStatus = Caster::tryEnum(Status::class, 'oops'); // null

$maybeAge = Caster::tryInt($payload['age'] ?? null);        // ?int
$maybeActive = Caster::tryBool($payload['active'] ?? null); // ?bool
$maybeDate = Caster::tryDateTimeImmutable($payload['published_at'] ?? null);

$payload = [
    'id' => '100',
    'name' => 'Alice',
    'meta' => ['role' => 'admin'],
    'tags' => ['php', 'caster'],
];

$id = Caster::fromArray($payload, 'id', [Caster::class, 'positiveInt']);
$name = Caster::fromArrayNullable($payload, 'name', [Caster::class, 'nonEmptyTrimmedString']);
$meta = Caster::

$ids = Caster::listOf(['1', '2', '3'], static fn ($value) => Caster::int($value));
$attributes = Caster::arrayOf(
    ['a' => 'true', 'b' => 'false'],
    static fn ($value) => Caster::bool($value)
);

// Nullable variants return null for missing/empty input
$maybeTags = Caster::nullableListOf($payload['tags'] ?? null, static fn ($v) => Caster::string($v));

$data = Caster::json($payload['data']);            // array<string,mixed>
$maybeData = Caster::tryJson($payload['data']);    // ?array<string,mixed>

$name = Caster::er::ns'] ?? null,
    'options',
    static fn ($value) => Caster::string($value)
);