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