From 73aeca0916a28901e3750c1601d66301ce05da9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Fastr=C3=A9?= Date: Fri, 21 May 2021 20:24:24 +0200 Subject: [PATCH] allow to import existing person from normalizer --- .../Serializer/Normalizer/PersonNormalizer.php | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Bundle/ChillPersonBundle/Serializer/Normalizer/PersonNormalizer.php b/src/Bundle/ChillPersonBundle/Serializer/Normalizer/PersonNormalizer.php index c4b6a7118..98edcec14 100644 --- a/src/Bundle/ChillPersonBundle/Serializer/Normalizer/PersonNormalizer.php +++ b/src/Bundle/ChillPersonBundle/Serializer/Normalizer/PersonNormalizer.php @@ -45,15 +45,18 @@ class PersonNormalizer implements { private ChillEntityRenderExtension $render; + private PersonRepository $repository; + use NormalizerAwareTrait; use ObjectToPopulateTrait; use DenormalizerAwareTrait; - public function __construct(ChillEntityRenderExtension $render) + public function __construct(ChillEntityRenderExtension $render, PersonRepository $repository) { $this->render = $render; + $this->repository = $repository; } public function normalize($person, string $format = null, array $context = array()) @@ -96,6 +99,18 @@ class PersonNormalizer implements { $person = $this->extractObjectToPopulate($type, $context); + if (\array_key_exists('id', $data)) { + $person = $this->repository->find($data['id']); + + if (null === $person) { + throw new UnexpectedValueException("The person with id \"{$data['id']}\" does ". + "not exists"); + } + // currently, not allowed to update a person through api + // if instantiated with id + return $person; + } + if (null === $person) { $person = new Person(); } @@ -113,7 +128,6 @@ class PersonNormalizer implements ] as $item => $class) { if (\array_key_exists($item, $data)) { $object = $this->denormalizer->denormalize($data[$item], $class, $format, $context); - dump($item, $data, $object, $class); if ($object instanceof $class) { $person->{'set'.\ucfirst($item)}($object); }