Version 1
[yaffs-website] / web / core / modules / text / src / Plugin / Field / FieldType / TextItemBase.php
1 <?php
2
3 namespace Drupal\text\Plugin\Field\FieldType;
4
5 use Drupal\Component\Utility\Random;
6 use Drupal\Core\Field\FieldDefinitionInterface;
7 use Drupal\Core\Field\FieldItemBase;
8 use Drupal\Core\Field\FieldStorageDefinitionInterface;
9 use Drupal\Core\TypedData\DataDefinition;
10
11 /**
12  * Base class for 'text' configurable field types.
13  */
14 abstract class TextItemBase extends FieldItemBase {
15
16   /**
17    * {@inheritdoc}
18    */
19   public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
20     $properties['value'] = DataDefinition::create('string')
21       ->setLabel(t('Text'))
22       ->setRequired(TRUE);
23
24     $properties['format'] = DataDefinition::create('filter_format')
25       ->setLabel(t('Text format'));
26
27     $properties['processed'] = DataDefinition::create('string')
28       ->setLabel(t('Processed text'))
29       ->setDescription(t('The text with the text format applied.'))
30       ->setComputed(TRUE)
31       ->setClass('\Drupal\text\TextProcessed')
32       ->setSetting('text source', 'value');
33
34     return $properties;
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   public function applyDefaultValue($notify = TRUE) {
41     // @todo: Add in the filter default format here.
42     $this->setValue(['format' => NULL], $notify);
43     return $this;
44   }
45
46   /**
47    * {@inheritdoc}
48    */
49   public function isEmpty() {
50     $value = $this->get('value')->getValue();
51     return $value === NULL || $value === '';
52   }
53
54   /**
55    * {@inheritdoc}
56    */
57   public function onChange($property_name, $notify = TRUE) {
58     // Unset processed properties that are affected by the change.
59     foreach ($this->definition->getPropertyDefinitions() as $property => $definition) {
60       if ($definition->getClass() == '\Drupal\text\TextProcessed') {
61         if ($property_name == 'format' || ($definition->getSetting('text source') == $property_name)) {
62           $this->writePropertyValue($property, NULL);
63         }
64       }
65     }
66     parent::onChange($property_name, $notify);
67   }
68
69   /**
70    * {@inheritdoc}
71    */
72   public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
73     $random = new Random();
74     $settings = $field_definition->getSettings();
75
76     if (empty($settings['max_length'])) {
77       // Textarea handling
78       $value = $random->paragraphs();
79     }
80     else {
81       // Textfield handling.
82       $value = substr($random->sentences(mt_rand(1, $settings['max_length'] / 3), FALSE), 0, $settings['max_length']);
83     }
84
85     $values = [
86       'value' => $value,
87       'summary' => $value,
88       'format' => filter_fallback_format(),
89     ];
90     return $values;
91   }
92
93 }