api-platform / api-platform/core

CR: Use ItemNormalizer/IriConverter without throwing Exceptions on wrong IRIs

Open
#8,014 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
PHP
Stars
2.6k
Forks
980
Avg merge
2d 5h
Merged PRs (30d)
48

Description

I use the ItemNormalizer to (de)normalize object structures from/to arrays where references are represented by their IRIs.
The serialized string is saved in the database and represents a published, fixed, unchangeable state of an API resource. Some references are not part of the publishing (means it isn't embedded) and reference an entity from the conventional database table. So the database cannot care about the referential integrity.
If I try to deserialize to such an object, an [UnexpectedValueException](https://github.com/api-platform/core/blob/4717bd5643d7761707229ed8705ae6824248f7e3/src/Serializer/AbstractItemNormalizer.php#L469) can appear if the reference doesn't exists anymore.

Currently the only one solution would be the following:
```
foreach ($normalizedObject as $key => $value) {
try {
$this->normalizer->denormalize([$key => $value], $className, null, [AbstractNormalizer::OBJECT_TO_POPULATE => $object]);
} catch (UnexpectedValueException $e) {}
}
```
There is some overhead because each field is denormalized for itself. This works great as long the field isn't an array field, where only one item isn't denormalizable anymore.
With some effort I can handle also this situation, but it will be ugly code.
The better solution would be to skip values which cannot be resolved. Currently there is no way to configure a behaviour like this. This would be my change request. :-)
Maybe there could be an context option for this.

Disclaimer: Usually I would use an other API design for this requirement. But it's not mine...

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.