Skip to content
nutgramPublic

About

A turbocharged json object hydrator for your DTOs

Topics

Resources

Stars

11 stars

Watchers

2 watching

Forks

Repository files navigation

Strongly typed hydrator for PHP 8.0+


Fork of the original project https://github.com/sunrise-php/hydrator.

Installation

composer require nutgram/hydrator

How to use?

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

Allowed property types

Required

If a property has no a default value, then the property is required.

public string $value;

Optional

If a property has a default value, then the property is optional.

public string $value = 'foo';

Null

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;

Boolean

Accepts the following values: true, false, 1, 0, "1", "0", "yes", "no", "on" and "no".

public bool $value;
['value' => true];
['value' => 'yes'];

Integer

Accepts only integers (also as a string).

public int $value;
['value' => 42];
['value' => '42'];

Number<int|float>

Accepts only numbers (also as a string).

public float $value;
['value' => 42.0];
['value' => '42.0'];

String

Accepts only strings.

public string $value;
['value' => 'foo'];

Array<array-key, mixed>

Accepts only arrays.

public array $value;
['value' => [1, 2, 'foo']];

Array<array-key, class>

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
    ],
],

Object

Accepts only objects.

public object $value;
['value' => new stdClass];

DateTime/DateTimeImmutable

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

DateInterval

Accepts only valid date-interval strings based on ISO 8601.

public DateInterval $value;
['value' => 'P1Y']

Enum

Accepts only values that exist in an enum.

enum SomeEnum: int {
    case foo = 0;
    case bar = 1;
}
public SomeEnum $value;
['value' => 0]
['value' => '1']

Association

Accepts a valid structure for an association

final class SomeDto {
    public string $value;
}
public SomeDto $value;
[
    'value' => [
        'value' => 'foo',
    ],
]

Property alias

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 = [];
}

Union types

A union-typed property needs a resolver attribute that picks which of its types to hydrate.

Enum or scalar

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'

Custom resolver

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.

Examples

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

Test run

composer test

About

A turbocharged json object hydrator for your DTOs

Topics

Resources

Stars

11 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages