PHP code example of netmex / hydrator-bundle

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

    

netmex / hydrator-bundle example snippets




namespace App\Hydrator;

use App\Entity\MyClass;
use Netmex\HydratorBundle\Contracts\BuilderInterface;
use Netmex\HydratorBundle\Contracts\MapperDefinitionInterface;
use Netmex\HydratorBundle\Options\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
use App\Transformer\CapitalizationTransformer;

class Hydrator implements MapperDefinitionInterface
{
    public function process(BuilderInterface $builder): void
    {
        $builder
            ->add('key', CapitalizationTransformer::class, [
                NotBlank::class => null,
                Length::class => ['min' => 6, 'max' => 7],
            ]);
    }

    public function options(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'model' => MyClass::class,
        ]);
    }
}



namespace App\Transformer;

use Netmex\HydratorBundle\Contracts\TransformerInterface;

class CapitalizationTransformer implements TransformerInterface
{
    public function transform(string $data): string
    {
        return strtoupper($data);
    }
}



namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use App\Hydrator\Hydrator;
use Netmex\HydratorBundle\Contracts\MapperInterface;
use Netmex\HydratorBundle\Exception\ValidationFailedException;

class ExampleController
{
    #[Route('/example', name: 'app_example')]
    public function index(Request $request, MapperInterface $hydrator): Response
    {
        $jsonContent = $request->getContent();
        $data = json_decode($jsonContent, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return new JsonResponse(['error' => 'Invalid JSON'], 400);
        }

        try {
            $result = $hydrator->build(Hydrator::class, $data);
        } catch (ValidationFailedException $e) {
            return new JsonResponse(['errors' => (string) $e->getViolations()], 400);
        }

        return new JsonResponse($result);
    }
}

try {
    $data = $hydrator->build(Hydrator::class, $requestData);
} catch (ValidationFailedException $e) {
    return new JsonResponse(['errors' => (string) $e->getViolations()], 400);
}
text
src/
├── Hydrator/
│   └── Hydrator.php
├── Transformer/
│   └── CapitalizationTransformer.php
└── Controller/
    └── ExampleController.php