SerializedColumnNormalizerTrait.php in Drupal 9
File
core/modules/serialization/src/Normalizer/SerializedColumnNormalizerTrait.php
View source
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Core\Field\FieldItemInterface;
trait SerializedColumnNormalizerTrait {
protected function checkForSerializedStrings($data, $class, FieldItemInterface $field_item) {
if (!is_array($data)) {
$data = [
$field_item
->getDataDefinition()
->getMainPropertyName() => $data,
];
}
if ($this
->dataHasStringForSerializeColumn($field_item, $data)) {
$field_name = $field_item
->getParent() ? $field_item
->getParent()
->getName() : $field_item
->getName();
throw new \LogicException(sprintf('The generic FieldItemNormalizer cannot denormalize string values for "%s" properties of the "%s" field (field item class: %s).', implode('", "', $this
->getSerializedPropertyNames($field_item)), $field_name, $class));
}
}
protected function dataHasStringForSerializeColumn(FieldItemInterface $field_item, array $data) {
foreach ($this
->getSerializedPropertyNames($field_item) as $property_name) {
if (isset($data[$property_name]) && is_string($data[$property_name])) {
return TRUE;
}
}
return FALSE;
}
protected function getSerializedPropertyNames(FieldItemInterface $field_item) {
$field_storage_definition = $field_item
->getFieldDefinition()
->getFieldStorageDefinition();
if ($custom_property_names = $this
->getCustomSerializedPropertyNames($field_item)) {
return $custom_property_names;
}
$field_storage_schema = $field_item
->schema($field_storage_definition);
if (!isset($field_storage_schema['columns'])) {
return [];
}
$serialized_columns = array_filter($field_storage_schema['columns'], function ($column_schema) {
return isset($column_schema['serialize']) && $column_schema['serialize'] === TRUE;
});
return array_keys($serialized_columns);
}
protected function getCustomSerializedPropertyNames(FieldItemInterface $field_item) {
if ($field_item instanceof PluginInspectionInterface) {
$definition = $field_item
->getPluginDefinition();
$serialized_fields = $field_item
->getEntity()
->getEntityType()
->get('serialized_field_property_names');
$field_name = $field_item
->getFieldDefinition()
->getName();
if (is_array($serialized_fields) && isset($serialized_fields[$field_name]) && is_array($serialized_fields[$field_name])) {
return $serialized_fields[$field_name];
}
if (isset($definition['serialized_property_names']) && is_array($definition['serialized_property_names'])) {
return $definition['serialized_property_names'];
}
}
return [];
}
}