Skip to content

Repository files navigation

Struct

Build StatusCode Climate

Declarative structure builder for PHP 7.

Usage

Create some model:

<?phpdeclare(strict_types=1);
namespaceMyNamespace;
useAcelot\Struct\Struct;
useAcelot\Struct\Schema;
useAcelot\Struct\Schema\Prop;
usefunctionAcelot\AutoMapper\from;
useRespect\Validation\Rules\{
AllOf, StringType, Alnum, NoWhitespace, Length, Instance
};
/** * @property-read string $login * @property-read string $password * @property-read string $name * @property-read \DateTimeInterface $birthday */class CreateUserModel extends Struct
{
publicstaticfunctiongetSchema() : Schema
{
returnnewSchema(
Prop::create('login')
->withValidator(newAllOf(
newStringType(),
newAlnum(),
newNoWhitespace(),
newLength(0, 64)
)), Prop::create('password')
->withValidator(newAllOf(
newStringType(),
newLength(0, 256)
)),
Prop::create('name')
->withValidator(newAllOf(
newStringType(),
newLength(0, 256)
))
->withMapper(from('name')->trim()->default('John Doe'), 'json')
->notRequired(),
Prop::create('birthday')
->withValidator(newInstance(\DateTimeInterface::class))
->withMapper(from('birthday')->convert(function ($value) {
returnnew \DateTimeImmutable($value);
}), 'json')
->notRequired()
);
}
}

Use model:

<?phpdeclare(strict_types=1);
namespaceMyNamespace;
$json = <<<JSON{ "login": "superhacker", "password": "correcthorsebatterystaple", "birthday": "1988-08-08"}JSON;
$model = CreateUserModel::mapFrom(json_decode($json), 'json');
echo$model->login; // "superhacker"echo$model->password; // "correcthorsebatterystaple"echo$model->name; // "John Doe"var_export($model->birthday);
// DateTime::__set_state(array(// 'date' => '1988-08-08 00:00:00.000000',// 'timezone_type' => 3,// 'timezone' => 'UTC',// ))

About

Declarative structure builder for PHP 7

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages