File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -270,3 +270,52 @@ final class Book
270
270
```
271
271
272
272
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
+ ```
You can’t perform that action at this time.
0 commit comments