Skip to content

Commit 0d32349

Browse files
committed
Add docs about dto validation
1 parent 903c060 commit 0d32349

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

core/dto.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,3 +270,52 @@ final class Book
270270
```
271271

272272
The `Book` `attribute` property will now be an instance of `Attribute` after the (de)normalization phase.
273+
274+
## Validating Data Transfer Objects
275+
276+
Before transforming DTO to your API Resource you may want to ensure that the DTO
277+
has valid data. In this case we can inject the validator to your data transformer
278+
and validate it.
279+
280+
```php
281+
<?php
282+
// src/DataTransformer/BookInputDataTransformer.php
283+
284+
namespace App\DataTransformer;
285+
286+
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
287+
use ApiPlatform\Core\Validator\ValidatorInterface;
288+
use App\Dto\BookInput;
289+
use App\Entity\Book;
290+
291+
final class BookInputDataTransformer implements DataTransformerInterface
292+
{
293+
private $validator;
294+
295+
public function __construct(ValidatorInterface $validator)
296+
{
297+
$this->validator = $validator;
298+
}
299+
300+
/**
301+
* @param BookInput $data
302+
*/
303+
public function transform($data, string $to, array $context = []): Book
304+
{
305+
$this->validator->validate($data);
306+
307+
$book = new Book();
308+
$book->isbn = $data->isbn;
309+
return $book;
310+
}
311+
312+
public function supportsTransformation($data, string $to, array $context = []): bool
313+
{
314+
if ($data instanceof Book) {
315+
return false;
316+
}
317+
318+
return Book::class === $to && null !== ($context['input']['class'] ?? null);
319+
}
320+
}
321+
```

0 commit comments

Comments
 (0)