schemantic / schemantic
Smart PHP structures
5.1.4
2026-03-18 12:51 UTC
Requires
- php: ^8.1
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.2
- squizlabs/php_codesniffer: ^3.11
README
Recursively parsing PHP structures. Pure PHP 8.1+, no dependencies
Installation
composer require schemantic/schemantic
Simple example
Schemas:
use Schemantic\Attribute\ArrayOf; use Schemantic\Attribute\Validate; use Schemantic\Attribute\Alias; use Schemantic\Schema; class Tag extends Schema { public function __construct( #[Validate\GreaterThan(0)] public readonly int $id, #[Validate\NotEmpty] #[Alias('name')] public readonly stirng $title, #[Validate\Validator(ValidateHelper::class, 'validateColor')] public readonly ?string $color, ) { } } class Product extends Schema { public function __construct( #[Validate\GreaterThan(0)] public readonly int $id, public readonly string $name, #[Timestamp] public readonly \DateTimeImmutable $createdAt, #[Timestamp] public readonly ?\DateTimeImmutable $deletedAt = null, #[Validate\GreaterThan(0)] public readonly ?float $price = null, #[ArrayOf(Tag::class)] #[Validate\Length(max: 3)] public readonly array $tags = [], ) { } }
Data to read:
{
"id": 123456789,
"name": "test-product",
"createdAt": 1771852144,
"price": 12.3,
"tags": [
{
"id": 1,
"name": "tag1",
"color": "#ffd900"
},
{
"id": 2,
"name": "tag2",
"color": null
}
]
}
Usage:
$raw = '{...}'; // the JSON from above // easily switch between different formats $responseData = Product::fromJSON($raw)->toArray(byAlias: true, dump: true, skipNulls: true);
$data = '[{...}, {...}]'; // array of JSONs from above // read JSON as Product[], and exclude rows that do not pass validation $rows = Product::fromJSONMultiple($data, validate: 'exclude');
$model = new \App\Models\Product(); // Laravel model / Doctrine Entity // Update any object fields with an direct assignment and calling setters (::setName(), setPublic()). Virtual setters included $schema = ...; $schema->updateObject($model);
$model = ...; // Laravel model / Doctrine Entity // Read any object fields with direct access and calling getters (::getName(), ::getPublic()). Virtual getter included $schema = Product::fromObject($model);
$schema = ...; // Pass __construct params & set other properties after construction if needed $model = Product::buildObject(\App\Models\Product::class);
Features:
- Recursive sub-structures parsing (and arrays of sub-structures)
- Custom field validation, parsing and dumping via attributes
- Pre-defined fields validations
- Fields aliases
- ORM integration
- JSON parsing
- Enum dump & parsing
Supported types:
- built-in PHP types
- DateTimeInterface
- UnitEnum and BackedEnum
- Sub-schemas
- Arrays of types above
- Nullable types
- Union types