allow to import existing person from normalizer

This commit is contained in:
Julien Fastré 2021-05-21 20:24:24 +02:00
parent 080a54231f
commit 73aeca0916

View File

@ -45,15 +45,18 @@ class PersonNormalizer implements
{ {
private ChillEntityRenderExtension $render; private ChillEntityRenderExtension $render;
private PersonRepository $repository;
use NormalizerAwareTrait; use NormalizerAwareTrait;
use ObjectToPopulateTrait; use ObjectToPopulateTrait;
use DenormalizerAwareTrait; use DenormalizerAwareTrait;
public function __construct(ChillEntityRenderExtension $render) public function __construct(ChillEntityRenderExtension $render, PersonRepository $repository)
{ {
$this->render = $render; $this->render = $render;
$this->repository = $repository;
} }
public function normalize($person, string $format = null, array $context = array()) public function normalize($person, string $format = null, array $context = array())
@ -96,6 +99,18 @@ class PersonNormalizer implements
{ {
$person = $this->extractObjectToPopulate($type, $context); $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) { if (null === $person) {
$person = new Person(); $person = new Person();
} }
@ -113,7 +128,6 @@ class PersonNormalizer implements
] as $item => $class) { ] as $item => $class) {
if (\array_key_exists($item, $data)) { if (\array_key_exists($item, $data)) {
$object = $this->denormalizer->denormalize($data[$item], $class, $format, $context); $object = $this->denormalizer->denormalize($data[$item], $class, $format, $context);
dump($item, $data, $object, $class);
if ($object instanceof $class) { if ($object instanceof $class) {
$person->{'set'.\ucfirst($item)}($object); $person->{'set'.\ucfirst($item)}($object);
} }