-
-
Notifications
You must be signed in to change notification settings - Fork 926
Description
API Platform version(s) affected: 2.6.5, and any other API platform version using Symfony 4.2 (since the introduction of the skip_null_values
flag)
Description
The HAL format normalizer does things a little differently from the rest of the normalizers, especially when it comes to normalizing relations. In ItemNormalizer#populateRelation, an empty()
check determines whether to leave out a relation. This also affects optional ToOne relations which can have a null value. In the rest of the framework, the skip_null_values
flag in the context determines what to do with such null relations. In HAL, this flag is not respected.
I'd be glad to provide a PR to fix this if requested.
How to reproduce
Create two entities like the following:
/**
* @ORM\Entity
*/
#[ApiResource(normalizationContext: ['skip_null_values' => false])]
class Dummy {
public ?RelatedDummy $relatedDummy = null;
}
/**
* @ORM\Entity
*/
#[ApiResource]
class RelatedDummy {
}
Activate support for HAL in the config:
api_platform:
formats:
jsonhal: [ 'application/hal+json' ]
jsonld: [ 'application/ld+json' ]
Create a Dummy
instance in the database without any RelatedDummy
, and fetch it using the format Accept: application/hal+json
.
Expected result:
{
"_links": {
"self": { "href": "/some/iri" },
"relatedDummy": null
}
}
Actual result:
{
"_links": {
"self": { "href": "/some/iri" }
}
}
Possible Solution
Use a check like the following:
if (empty($attributeValue)) {
$skipNullValues = $context[self::SKIP_NULL_VALUES] ?? $this->defaultContext[self::SKIP_NULL_VALUES] ?? false;
if (null !== $attributeValue || $skipNullValues) {
continue;
}
}