diff --git a/jsonld.services.yml b/jsonld.services.yml index 50ad197..efd9842 100644 --- a/jsonld.services.yml +++ b/jsonld.services.yml @@ -40,3 +40,8 @@ services: jsonld.normalizer_utils: class: Drupal\jsonld\Utils\JsonldNormalizerUtils arguments: ['@config.factory', '@language_manager', '@router.route_provider'] + jsonld.normalizer.integer_data: + class: Drupal\jsonld\Normalizer\IntegerDataNormalizer + tags: + - { name: normalizer, priority: 5 } + diff --git a/src/Normalizer/IntegerDataNormalizer.php b/src/Normalizer/IntegerDataNormalizer.php new file mode 100644 index 0000000..41dc8c9 --- /dev/null +++ b/src/Normalizer/IntegerDataNormalizer.php @@ -0,0 +1,50 @@ +addCacheableDependency($context, $object); + + $parent = $object->getParent(); + if ($parent instanceof FieldItemInterface && $object->getValue()) { + $serialized_property_names = $this->getCustomSerializedPropertyNames($parent); + if (in_array($object->getName(), $serialized_property_names, TRUE)) { + return unserialize($object->getValue()); + } + } + + // Typed data casts NULL objects to their empty variants, so for example + // the empty string ('') for string type data, or 0 for integer typed data. + // In a better world with typed data implementing algebraic data types, + // getCastedValue would return NULL, but as typed data is not aware of real + // optional values on the primitive level, we implement our own optional + // value normalization here. + return $object->getValue() === NULL ? NULL : $object->getCastedValue(); + } + + /** + * {@inheritdoc} + */ + public function getSupportedTypes(?string $format): array { + return [ + IntegerInterface::class => TRUE, + ]; + } + +}