MetatagFieldItem.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace Drupal\metatag\Plugin\Field\FieldType;
  3. use Drupal\Core\Field\FieldItemBase;
  4. use Drupal\Core\Field\FieldStorageDefinitionInterface;
  5. use Drupal\Core\TypedData\DataDefinition;
  6. /**
  7. * Plugin implementation of the 'metatag' field type.
  8. *
  9. * @FieldType(
  10. * id = "metatag",
  11. * label = @Translation("Meta tags"),
  12. * description = @Translation("This field stores code meta tags."),
  13. * default_widget = "metatag_firehose",
  14. * default_formatter = "metatag_empty_formatter",
  15. * serialized_property_names = {
  16. * "value"
  17. * }
  18. * )
  19. */
  20. class MetatagFieldItem extends FieldItemBase {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public static function schema(FieldStorageDefinitionInterface $field_definition) {
  25. return [
  26. 'columns' => [
  27. 'value' => [
  28. 'type' => 'text',
  29. 'size' => 'big',
  30. 'not null' => FALSE,
  31. ],
  32. ],
  33. ];
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
  39. $properties['value'] = DataDefinition::create('metatag')
  40. ->setLabel(t('Metatag'))
  41. ->setRequired(TRUE);
  42. return $properties;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function isEmpty() {
  48. $value = $this->get('value')->getValue();
  49. return $value === NULL || $value === '' || $value === serialize([]);
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function preSave() {
  55. parent::preSave();
  56. // Merge field defaults on top of global ones.
  57. $default_tags = metatag_get_default_tags();
  58. // Get the value about to be saved.
  59. $current_value = $this->value;
  60. // Only unserialize if still serialized string.
  61. if (is_string($current_value)) {
  62. $current_tags = unserialize($current_value);
  63. }
  64. else {
  65. $current_tags = $current_value;
  66. }
  67. // Only include values that differ from the default.
  68. // @todo When site defaults are added, account for those.
  69. $tags_to_save = [];
  70. foreach ($current_tags as $tag_id => $tag_value) {
  71. if (!isset($default_tags[$tag_id]) || ($tag_value != $default_tags[$tag_id])) {
  72. $tags_to_save[$tag_id] = $tag_value;
  73. }
  74. }
  75. // Update the value to only save overridden tags.
  76. $this->value = serialize($tags_to_save);
  77. }
  78. }