FieldInputValueNormalizerTrait.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace Drupal\Core\Field;
  3. /**
  4. * A trait used to assist in the normalization of raw input field values.
  5. *
  6. * @internal
  7. *
  8. * @see \Drupal\Core\Field\FieldConfigBase
  9. * @see \Drupal\Core\Field\BaseFieldDefinition
  10. */
  11. trait FieldInputValueNormalizerTrait {
  12. /**
  13. * Ensure a field value is transformed into a format keyed by delta.
  14. *
  15. * @param mixed $value
  16. * The raw field value to normalize.
  17. * @param string $main_property_name
  18. * The main field property name.
  19. *
  20. * @return array
  21. * A field value normalized into a format keyed by delta.
  22. */
  23. protected static function normalizeValue(&$value, $main_property_name) {
  24. if (!isset($value) || $value === NULL) {
  25. return [];
  26. }
  27. if (!is_array($value)) {
  28. if ($main_property_name === NULL) {
  29. throw new \InvalidArgumentException('A main property is required when normalizing scalar field values.');
  30. }
  31. return [[$main_property_name => $value]];
  32. }
  33. if (!empty($value) && !is_numeric(array_keys($value)[0])) {
  34. return [0 => $value];
  35. }
  36. return $value;
  37. }
  38. }