BooleanItemNormalizer.php
Same filename in other branches
- 9 core/modules/serialization/tests/modules/test_fieldtype_boolean_emoji_normalizer/src/Normalizer/BooleanItemNormalizer.php
- 8.9.x core/modules/serialization/tests/modules/test_fieldtype_boolean_emoji_normalizer/src/Normalizer/BooleanItemNormalizer.php
- 10 core/modules/serialization/tests/modules/test_fieldtype_boolean_emoji_normalizer/src/Normalizer/BooleanItemNormalizer.php
Namespace
Drupal\test_fieldtype_boolean_emoji_normalizer\NormalizerFile
-
core/
modules/ serialization/ tests/ modules/ test_fieldtype_boolean_emoji_normalizer/ src/ Normalizer/ BooleanItemNormalizer.php
View source
<?php
namespace Drupal\test_fieldtype_boolean_emoji_normalizer\Normalizer;
use Drupal\Core\Field\Plugin\Field\FieldType\BooleanItem;
use Drupal\serialization\Normalizer\FieldItemNormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Normalizes boolean fields weirdly: renders them as 👍 (TRUE) or 👎 (FALSE).
*/
class BooleanItemNormalizer extends FieldItemNormalizer implements DenormalizerInterface {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []) : array|string|int|float|bool|\ArrayObject|null {
$data = parent::normalize($object, $format, $context);
$data['value'] = $data['value'] ? '👍' : '👎';
return $data;
}
/**
* {@inheritdoc}
*/
protected function constructValue($data, $context) {
// Just like \Drupal\serialization\Normalizer\FieldItemNormalizer's logic
// for denormalization, which uses TypedDataInterface::setValue(), allow the
// keying by main property name ("value") to be implied.
if (!is_array($data)) {
$data = [
'value' => $data,
];
}
if (!in_array($data['value'], [
'👍',
'👎',
], TRUE)) {
throw new \UnexpectedValueException('Only 👍 and 👎 are acceptable values.');
}
$data['value'] = $data['value'] === '👍';
return $data;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format) : array {
return [
BooleanItem::class => TRUE,
];
}
}
Classes
Title | Deprecated | Summary |
---|---|---|
BooleanItemNormalizer | Normalizes boolean fields weirdly: renders them as 👍 (TRUE) or 👎 (FALSE). |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.