Skip to content

Commit

Permalink
Try implementing a normalizer for integerdata
Browse files Browse the repository at this point in the history
  • Loading branch information
joecorall committed Oct 28, 2024
1 parent 01f5257 commit f46dee4
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
5 changes: 5 additions & 0 deletions jsonld.services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

50 changes: 50 additions & 0 deletions src/Normalizer/IntegerDataNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace Drupal\jsonld\Normalizer;

use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\TypedData\Type\IntegerInterface;
use Drupal\serialization\Normalizer\NormalizerBase;
use Drupal\serialization\Normalizer\SerializedColumnNormalizerTrait;

/**
* Converts integer data objects to their casted values.
*/
class IntegerDataNormalizer extends NormalizerBase {

use SerializedColumnNormalizerTrait;

/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
// Add cacheability if applicable.
$this->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,
];
}

}

0 comments on commit f46dee4

Please sign in to comment.