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.
- Host: GitHub
- URL: https://github.com/netmexmedia/hydratorbundle
- Owner: netmexmedia
- Created: 2025-05-30T13:15:42.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-05-30T19:52:27.000Z (about 1 year ago)
- Last Synced: 2025-06-08T13:05:15.600Z (about 1 year ago)
- Topics: bundle, hydration, hydrator, php, symfony, symfony-bundle
- Language: PHP
- Homepage:
- Size: 2.1 MB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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.