An open API service indexing awesome lists of open source software.

https://github.com/netmexmedia/hydratorbundle

Hydration classes for your Symfony project.
https://github.com/netmexmedia/hydratorbundle

bundle hydration hydrator php symfony symfony-bundle

Last synced: 2 months ago
JSON representation

Hydration classes for your Symfony project.

Awesome Lists containing this project

README

          

# Netmex HydratorBundle

## About
The Netmex HydratorBundle is a Symfony bundle designed to simplify the process of hydrating data transfer objects (DTOs) from arrays or JSON inputs with built-in support for data transformation and validation using Symfony constraints.

It enables you to:
* Define mappers that transform and validate input data.
* Easily create reusable transformers to convert raw data (e.g., capitalization, formatting).
* Handle validation errors gracefully.
* Integrate seamlessly into Symfony controllers for clean and maintainable code.

## Installation

```bash
composer require netmex/hydrator-bundle
```

## Usage

Create a mapper class that implements
```Netmex\HydratorBundle\Contracts\MapperDefinitionInterface```.

##### Example Hydrator
```php
add('key', CapitalizationTransformer::class, [
NotBlank::class => null,
Length::class => ['min' => 6, 'max' => 7],
]);
}

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

### Create a Transformer

```php
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);
}
}
```

## Recommended Directory Layout
```text
src/
├── Hydrator/
│ └── Hydrator.php
├── Transformer/
│ └── CapitalizationTransformer.php
└── Controller/
└── ExampleController.php
```

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

## More about Constraints
See [Symfony Validation Constraints](https://symfony.com/doc/current/validation.html#constraints) for available options.