PHP code example of makinacorpus / generated-hydrator-bundle

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

    

makinacorpus / generated-hydrator-bundle example snippets




return [
    // ...
    \GeneratedHydrator\Bridge\Symfony\GeneratedHydratorBundle::class => ['all' => true],
];


use App\Domain\Model\SomeEntity;
use GeneratedHydrator\Bridge\Symfony\Hydrator;

function some_function(Hydrator $hydrator)
{
    $object = $hydrator->createAndHydrate(
        SomeEntity::class,
        [
            // Scalar values
            'foo' => 1,
            // ...

            // It also handles nested objects
            'bar' => [
                'baz' => 2,
                // ...
            ],
        ]
    );
}

use App\Domain\Model\SomeEntity;
use GeneratedHydrator\Bridge\Symfony\Hydrator;

function some_function(Hydrator $hydrator)
{
    $object = new SomeEntity();

    $valueArray = $hydrator->extract($object);
}

namespace App\Entity;

interface Identifier
{
    public function __construct(mixed $value);

    public function __toString(): string;
}

class FooId
{
    public function __construct(
        private mixed $value,
    ) {}

    public function __toString(): string
    {
        return (string) $this->id;
    }
}

namespace App\Entity;

class Foo
{
    public function __construct(
        private FooId $id,
    ) {}

    // ...
}

$foo = $hydrator->createAndHydrate(
    \App\Entity\Foo::class,
    [
        'id' => '12345',
    ],
);

namespace App\ValueHydrator;

use App\Entity\Identifier;
use GeneratedHydrator\Bridge\Symfony\Error\CannotHydrateValueError;
use GeneratedHydrator\Bridge\Symfony\ValueHydrator\ValueHydrator;

class IdentifierValueHydrator implements ValueHydrator
{
    /**
     * {@inheritdoc}
     */
    public function supports(string $phpType): bool
    {
        return \is_subclass_of($phpType, Identifier::class);
    }

    /**
     * {@inheritdoc}
     */
    public function hydrate(string $phpType, mixed $value): mixed
    {
        if (\is_subclass_of($phpType, Identifier::class)) {
            return new $phpType($value);
        }
        throw new CannotHydrateValueError();
    }
}