Fork of the original project https://github.com/sunrise-php/hydrator.
composer require nutgram/hydratoruse SergiX44\Hydrator\Hydrator;
$hydrator = new Hydrator();
// create and hydrate an object with an array
$data = [/* the class props here */];
$object = $hydrator->hydrate(SomeDto::class, $data);
// hydrate an object with an array
$data = [/* the class props here */];
$hydrator->hydrate($object, $data);
// creates and hydrate an object with JSON
$json = '{...}';
$object = $hydrator->hydrateWithJson(SomeDto::class, $json);
// hydrate an object with JSON
$json = '{...}';
$hydrator->hydrateWithJson($object, $json);
// pass JSON decoding flags
$options = JSON_OBJECT_AS_ARRAY|JSON_BIGINT_AS_STRING;
$hydrator->hydrateWithJson($object, $json, $options);If a property has no a default value, then the property is required.
public string $value;If a property has a default value, then the property is optional.
public string $value = 'foo';If a property is nullable, then the property can accept null.
public ?string $value;If the property should be optional, then it must has a default value.
public ?string $value = null;Accepts the following values: true, false, 1, 0, "1", "0", "yes", "no", "on" and "no".
public bool $value;['value' => true];
['value' => 'yes'];Accepts only integers (also as a string).
public int $value;['value' => 42];
['value' => '42'];Accepts only numbers (also as a string).
public float $value;['value' => 42.0];
['value' => '42.0'];Accepts only strings.
public string $value;['value' => 'foo'];Accepts only arrays.
public array $value;['value' => [1, 2, 'foo']];Accept a list of objects.
final class SomeDto {
public readonly string $value;
}use SergiX44\Hydrator\Annotation\ArrayType;
#[ArrayType(SomeDto::class)]
public array $value;[
'value' => [
[
'value' => 'foo',
],
[
'value' => 'bar',
],
],
],By default, every element of the array is hydrated into the given class, so a
scalar element (or null) will raise an error. Set skipScalars: true to leave
scalar and null elements untouched, hydrating only the array/object elements:
#[ArrayType(SomeDto::class, skipScalars: true)]
public array $value;[
'value' => [
['value' => 'foo'], // hydrated into SomeDto
'bar', // kept as-is
42, // kept as-is
null, // kept as-is
],
],Accepts only objects.
public object $value;['value' => new stdClass];Integers (also as a string) will be handled as a timestamp, otherwise accepts only valid date-time strings.
public DateTimeImmutable $value;// 2010-01-01
['value' => 1262304000];
// 2010-01-01
['value' => '1262304000'];
// normal date
['value' => '2010-01-01'];Accepts only valid date-interval strings based on ISO 8601.
public DateInterval $value;['value' => 'P1Y']Accepts only values that exist in an enum.
enum SomeEnum: int {
case foo = 0;
case bar = 1;
}public SomeEnum $value;['value' => 0]
['value' => '1']Accepts a valid structure for an association
final class SomeDto {
public string $value;
}public SomeDto $value;[
'value' => [
'value' => 'foo',
],
]If you need to get a non-normalized key, use aliases.
For example, the Google Recaptcha API returns the following response:
{
"success": false,
"error-codes": []
}To correctly map the response, use the following model:
use SergiX44\Hydrator\Annotation\Alias;
final class RecaptchaVerificationResult {
public bool $success;
#[Alias('error-codes')]
public array $errorCodes = [];
}A union-typed property needs a resolver attribute that picks which of its types to hydrate.
EnumOrScalar hydrates the enum when the value is one of its cases, and otherwise the scalar type that matches the
value. The enum must be the first type of the union.
use SergiX44\Hydrator\Resolver\EnumOrScalar;
#[EnumOrScalar]
public Status|string $status;['status' => 1] // Status::ENABLED
['status' => 'unknown'] // 'unknown'Extend UnionResolver, implement resolve() and mark the class as a property attribute. resolve() receives the
property's value and $data, the whole object the property belongs to. It is called only when $data contains the
property: a missing property is reported as required, or keeps its default value.
use Attribute;
use ReflectionType;
use RuntimeException;
use SergiX44\Hydrator\Annotation\UnionResolver;
#[Attribute(Attribute::TARGET_PROPERTY)]
class TextResolver extends UnionResolver
{
public function resolve(string $propertyName, array $propertyTypes, mixed $value, array $data): ReflectionType
{
$wanted = is_string($value) ? 'string' : FormattedText::class;
foreach ($propertyTypes as $type) {
if ($type->getName() === $wanted) {
return $type;
}
}
throw new RuntimeException("Unable to resolve $propertyName");
}
}#[TextResolver]
public string|FormattedText $text;PHP lists the union's class types before the built-in ones, so match the types by name, not by position.
final class Product {
public string $name;
public Category $category;
#[ArrayType(Tag::class)]
public array $tags;
public Status $status;
}
final class Category {
public string $name;
}
final class Tag {
public string $name;
}
enum Status: int {
case ENABLED = 1;
case DISABLED = 0;
}$product = $hydrator->hydrate(Product::class, [
'name' => 'Stool',
'category' => [
'name' => 'Furniture',
],
'tags' => [
[
'name' => 'Wood',
],
[
'name' => 'Lacquered',
],
],
'status' => 0,
]);composer test