PHP code example of sunrise / hydrator

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

    

sunrise / hydrator example snippets


enum Status: int
{
    case ENABLED = 1;
    case DISABLED = 0;
}

final class CategoryDto
{
    public function __construct(
        public readonly string $name,
    ) {
    }
}

final class TagDto
{
    public function __construct(
        public readonly string $name,
    ) {
    }
}

final class TagDtoCollection implements ArrayAccess
{
    public function __construct(TagDto ...$tags)
    {
    }
}

final class PublicationDto
{
    public function __construct(
        public readonly string $name,
        public readonly CategoryDto $category,
        public readonly TagDtoCollection $tags,
        public readonly Status $status = Status::DISABLED,
        #[\Sunrise\Hydrator\Annotation\Format(DateTimeInterface::RFC3339)]
        public readonly DateTimeImmutable $createdAt = new DateTimeImmutable('now'),
    ) {
    }
}

$data = [
    'name' => 'Some product',
    'category' => [
        'name' => 'Some category',
    ],
    'tags' => [
        [
            'name' => 'foo',
        ],
        [
            'name' => 'bar',
        ],
    ],
    'status' => 0,
];

$product = (new \Sunrise\Hydrator\Hydrator)->hydrate(PublicationDto::class, $data);

$json = <<<JSON
{
    "name": "Some product",
    "category": {
        "name": "Some category"
    },
    "tags": [
        {
            "name": "foo"
        },
        {
            "name": "bar"
        }
    ],
    "status": 0
}
JSON;

$product = (new \Sunrise\Hydrator\Hydrator)->hydrateWithJson(PublicationDto::class, $json);

public readonly string $value;

public readonly string $value = 'foo';

public readonly ?string $value;

public readonly bool $value;

public readonly int $value;

public readonly float $value;

public readonly string $value;

public readonly array $value;

#[\Sunrise\Hydrator\Annotation\Subtype(SomeDto::class)]
public readonly array $value;

#[\Sunrise\Hydrator\Annotation\Subtype(SomeDto::class, limit: 100)]
public readonly array $value;

final class TagDto
{
}

final class TagDtoCollection implements \ArrayAccess
{
}

final class CreateProductDto
{
    public function __construct(
        #[\Sunrise\Hydrator\Annotation\Subtype(TagDto::class, limit: 10)]
        public readonly TagDtoCollection $tags,
    ) {
    }
}

final class TagDtoCollection implements \ArrayAccess
{
    public function __construct(public TagDto ...$tags)
    {
    }
}

final class CreateProductDto
{
    public function __construct(
        public readonly TagDtoCollection $tags,
    ) {
    }
}

#[\Sunrise\Hydrator\Annotation\Subtype(\DateTimeImmutable::class, limit: 100)]
#[\Sunrise\Hydrator\Annotation\Format('Y-m-d H:i:s')]
public readonly array $value;

use Sunrise\Hydrator\Type;

$data = [...];

$collection = $hydrator->castValue($data, Type::fromName(SomeDtoCollection::class));

#[\Sunrise\Hydrator\Annotation\Format('Y-m-d H:i:s')]
public readonly DateTimeImmutable $value;

#[\Sunrise\Hydrator\Annotation\Format('U')]
public readonly DateTimeImmutable $value;

use Sunrise\Hydrator\Dictionary\ContextKey;
use Sunrise\Hydrator\Hydrator;

$hydrator = new Hydrator([
    ContextKey::TIMESTAMP_FORMAT => 'Y-m-d H:i:s',
]);

public readonly DateTimeZone $value;

use Sunrise\Hydrator\Dictionary\ContextKey;
use Sunrise\Hydrator\Hydrator;

$hydrator = new Hydrator([
    ContextKey::TIMEZONE => 'Europe/Kyiv',
]);

public readonly \Ramsey\Uuid\UuidInterface $value;

public readonly \Symfony\Component\Uid\UuidV4 $value;

public readonly SomeEnum $value;

public readonly SomeEnum $value;

public readonly SomeDto $value;

use Sunrise\Hydrator\Exception\InvalidValueException;
use Sunrise\Hydrator\Type;
use Sunrise\Hydrator\TypeConverterInterface;
use Psr\Message\UriInterface;
use Sunrise\Http\Message\Uri;

final class UriTypeConverter implements TypeConverterInterface
{
    public function castValue($value, Type $type, array $path): Generator
    {
        if ($type->getName() <> UriInterface::class) {
            return;
        }

        if (!\is_string($value)) {
            throw InvalidValueException::mustBeString($path);
        }

        try {
            yield new Uri($value);
        } catch (\InvalidArgumentException $e) {
            throw new InvalidValueException(
                'This value is not a valid URI.',
                'c66741c6-e3c0-4522-a8e3-97528d7712a3',
                $path,
            );
        }
    }

    public function getWeight(): int
    {
        return 0;
    }
}

$hydrator->addTypeConverter(new UriTypeConverter());

#[\Sunrise\Hydrator\Annotation\Ignore]
public string $value;

#[\Sunrise\Hydrator\Annotation\Alias('error-codes')]
public array $errorCodes = [];

try {
    $hydrator->hydrate(...);
} catch (\Sunrise\Hydrator\Exception\InvalidDataException $e) {
    // It's runtime error
} catch (\Sunrise\Hydrator\Exception\InvalidObjectException $e) {
    // It's logic error
}

try {
    $hydrator->hydrate(...);
} catch (\Sunrise\Hydrator\Exception\InvalidDataException $e) {
    $violations = $e->getViolations();
}

try {
    $hydrator->hydrate(...);
} catch (\Sunrise\Hydrator\Exception\InvalidDataException $e) {
    $errors = $e->getExceptions();
    foreach ($errors as $error) {
        echo $error->getMessage(), PHP_EOL;
        echo $error->getPropertyPath(), PHP_EOL;
        echo $error->getErrorCode(), PHP_EOL;
    }
}

$localizedMessages = [
    // using the error code dictionary...
    \Sunrise\Hydrator\Dictionary\ErrorCode::INVALID_TIMESTAMP => 'Это значение не является валидной временной меткой; ожидаемый формат: {{ expected_format }}.',

    // or using the error message dictionary...
    \Sunrise\Hydrator\Dictionary\ErrorMessage::INVALID_TIMESTAMP => 'Это значение не является валидной временной меткой; ожидаемый формат: {{ expected_format }}.',
];

try {
    $hydrator->hydrate(...);
} catch (\Sunrise\Hydrator\Exception\InvalidDataException $e) {
    foreach ($e->getExceptions() as $error) {
        // original message...
        $message = $error->getMessage();

        // using the error code dictionary...
        if (isset($localizedMessages[$error->getErrorCode()])) {
            // localized message
            $message = \strtr($localizedMessages[$error->getErrorCode()], $error->getMessagePlaceholders()), PHP_EOL;
        }

        // or using the error message dictionary...
        if (isset($localizedMessages[$error->getMessageTemplate()])) {
            // localized message
            $message = \strtr($localizedMessages[$error->getMessageTemplate()], $error->getMessagePlaceholders()), PHP_EOL;
        }
    }
}

$hydrator->useDefaultAnnotationReader();

$hydrator->setAnnotationReader(...);
bash
composer