You are here

protected function BooleanItemNormalizer::constructValue in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/serialization/tests/modules/test_fieldtype_boolean_emoji_normalizer/src/Normalizer/BooleanItemNormalizer.php \Drupal\test_fieldtype_boolean_emoji_normalizer\Normalizer\BooleanItemNormalizer::constructValue()

Build the field item value using the incoming data.

Most normalizers that extend this class can simply use this method to construct the denormalized value without having to override denormalize() and reimplementing its validation logic or its call to set the field value.

It's recommended to not override this and instead provide a (de)normalizer at the DataType level.

Parameters

mixed $data: The incoming data for this field item.

array $context: The context passed into the Normalizer.

Return value

mixed The value to use in Entity::setValue().

Overrides FieldableEntityNormalizerTrait::constructValue

File

core/modules/serialization/tests/modules/test_fieldtype_boolean_emoji_normalizer/src/Normalizer/BooleanItemNormalizer.php, line 31

Class

BooleanItemNormalizer
Normalizes boolean fields weirdly: renders them as ๐Ÿ‘ (TRUE) or ๐Ÿ‘Ž (FALSE).

Namespace

Drupal\test_fieldtype_boolean_emoji_normalizer\Normalizer

Code

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;
}