Version 1
[yaffs-website] / web / core / modules / options / src / Plugin / Field / FieldType / ListItemBase.php
1 <?php
2
3 namespace Drupal\options\Plugin\Field\FieldType;
4
5 use Drupal\Core\Field\AllowedTagsXssTrait;
6 use Drupal\Core\Field\FieldDefinitionInterface;
7 use Drupal\Core\Field\FieldItemBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\Form\OptGroup;
10 use Drupal\Core\Session\AccountInterface;
11 use Drupal\Core\TypedData\OptionsProviderInterface;
12
13 /**
14  * Plugin base class inherited by the options field types.
15  */
16 abstract class ListItemBase extends FieldItemBase implements OptionsProviderInterface {
17
18   use AllowedTagsXssTrait;
19
20   /**
21    * {@inheritdoc}
22    */
23   public static function defaultStorageSettings() {
24     return [
25       'allowed_values' => [],
26       'allowed_values_function' => '',
27     ] + parent::defaultStorageSettings();
28   }
29
30   /**
31    * {@inheritdoc}
32    */
33   public function getPossibleValues(AccountInterface $account = NULL) {
34     // Flatten options firstly, because Possible Options may contain group
35     // arrays.
36     $flatten_options = OptGroup::flattenOptions($this->getPossibleOptions($account));
37     return array_keys($flatten_options);
38   }
39
40   /**
41    * {@inheritdoc}
42    */
43   public function getPossibleOptions(AccountInterface $account = NULL) {
44     return $this->getSettableOptions($account);
45   }
46
47   /**
48    * {@inheritdoc}
49    */
50   public function getSettableValues(AccountInterface $account = NULL) {
51     // Flatten options firstly, because Settable Options may contain group
52     // arrays.
53     $flatten_options = OptGroup::flattenOptions($this->getSettableOptions($account));
54     return array_keys($flatten_options);
55   }
56
57   /**
58    * {@inheritdoc}
59    */
60   public function getSettableOptions(AccountInterface $account = NULL) {
61     $allowed_options = options_allowed_values($this->getFieldDefinition()->getFieldStorageDefinition(), $this->getEntity());
62     return $allowed_options;
63   }
64
65   /**
66    * {@inheritdoc}
67    */
68   public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
69     $allowed_options = options_allowed_values($field_definition->getFieldStorageDefinition());
70     $values['value'] = array_rand($allowed_options);
71     return $values;
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   public function isEmpty() {
78     return empty($this->value) && (string) $this->value !== '0';
79   }
80
81   /**
82    * {@inheritdoc}
83    */
84   public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
85     $allowed_values = $this->getSetting('allowed_values');
86     $allowed_values_function = $this->getSetting('allowed_values_function');
87
88     $element['allowed_values'] = [
89       '#type' => 'textarea',
90       '#title' => t('Allowed values list'),
91       '#default_value' => $this->allowedValuesString($allowed_values),
92       '#rows' => 10,
93       '#access' => empty($allowed_values_function),
94       '#element_validate' => [[get_class($this), 'validateAllowedValues']],
95       '#field_has_data' => $has_data,
96       '#field_name' => $this->getFieldDefinition()->getName(),
97       '#entity_type' => $this->getEntity()->getEntityTypeId(),
98       '#allowed_values' => $allowed_values,
99     ];
100
101     $element['allowed_values']['#description'] = $this->allowedValuesDescription();
102
103     $element['allowed_values_function'] = [
104       '#type' => 'item',
105       '#title' => t('Allowed values list'),
106       '#markup' => t('The value of this field is being determined by the %function function and may not be changed.', ['%function' => $allowed_values_function]),
107       '#access' => !empty($allowed_values_function),
108       '#value' => $allowed_values_function,
109     ];
110
111     return $element;
112   }
113
114   /**
115    * Provides the field type specific allowed values form element #description.
116    *
117    * @return string
118    *   The field type allowed values form specific description.
119    */
120   abstract protected function allowedValuesDescription();
121
122   /**
123    * #element_validate callback for options field allowed values.
124    *
125    * @param $element
126    *   An associative array containing the properties and children of the
127    *   generic form element.
128    * @param $form_state
129    *   The current state of the form for the form this element belongs to.
130    *
131    * @see \Drupal\Core\Render\Element\FormElement::processPattern()
132    */
133   public static function validateAllowedValues($element, FormStateInterface $form_state) {
134     $values = static::extractAllowedValues($element['#value'], $element['#field_has_data']);
135
136     if (!is_array($values)) {
137       $form_state->setError($element, t('Allowed values list: invalid input.'));
138     }
139     else {
140       // Check that keys are valid for the field type.
141       foreach ($values as $key => $value) {
142         if ($error = static::validateAllowedValue($key)) {
143           $form_state->setError($element, $error);
144           break;
145         }
146       }
147
148       // Prevent removing values currently in use.
149       if ($element['#field_has_data']) {
150         $lost_keys = array_keys(array_diff_key($element['#allowed_values'], $values));
151         if (_options_values_in_use($element['#entity_type'], $element['#field_name'], $lost_keys)) {
152           $form_state->setError($element, t('Allowed values list: some values are being removed while currently in use.'));
153         }
154       }
155
156       $form_state->setValueForElement($element, $values);
157     }
158   }
159
160   /**
161    * Extracts the allowed values array from the allowed_values element.
162    *
163    * @param string $string
164    *   The raw string to extract values from.
165    * @param bool $has_data
166    *   The current field already has data inserted or not.
167    *
168    * @return array|null
169    *   The array of extracted key/value pairs, or NULL if the string is invalid.
170    *
171    * @see \Drupal\options\Plugin\Field\FieldType\ListItemBase::allowedValuesString()
172    */
173   protected static function extractAllowedValues($string, $has_data) {
174     $values = [];
175
176     $list = explode("\n", $string);
177     $list = array_map('trim', $list);
178     $list = array_filter($list, 'strlen');
179
180     $generated_keys = $explicit_keys = FALSE;
181     foreach ($list as $position => $text) {
182       // Check for an explicit key.
183       $matches = [];
184       if (preg_match('/(.*)\|(.*)/', $text, $matches)) {
185         // Trim key and value to avoid unwanted spaces issues.
186         $key = trim($matches[1]);
187         $value = trim($matches[2]);
188         $explicit_keys = TRUE;
189       }
190       // Otherwise see if we can use the value as the key.
191       elseif (!static::validateAllowedValue($text)) {
192         $key = $value = $text;
193         $explicit_keys = TRUE;
194       }
195       // Otherwise see if we can generate a key from the position.
196       elseif (!$has_data) {
197         $key = (string) $position;
198         $value = $text;
199         $generated_keys = TRUE;
200       }
201       else {
202         return;
203       }
204
205       $values[$key] = $value;
206     }
207
208     // We generate keys only if the list contains no explicit key at all.
209     if ($explicit_keys && $generated_keys) {
210       return;
211     }
212
213     return $values;
214   }
215
216   /**
217    * Checks whether a candidate allowed value is valid.
218    *
219    * @param string $option
220    *   The option value entered by the user.
221    *
222    * @return string
223    *   The error message if the specified value is invalid, NULL otherwise.
224    */
225   protected static function validateAllowedValue($option) { }
226
227   /**
228    * Generates a string representation of an array of 'allowed values'.
229    *
230    * This string format is suitable for edition in a textarea.
231    *
232    * @param array $values
233    *   An array of values, where array keys are values and array values are
234    *   labels.
235    *
236    * @return string
237    *   The string representation of the $values array:
238    *    - Values are separated by a carriage return.
239    *    - Each value is in the format "value|label" or "value".
240    */
241   protected function allowedValuesString($values) {
242     $lines = [];
243     foreach ($values as $key => $value) {
244       $lines[] = "$key|$value";
245     }
246     return implode("\n", $lines);
247   }
248
249   /**
250    * {@inheritdoc}
251    */
252   public static function storageSettingsToConfigData(array $settings) {
253     if (isset($settings['allowed_values'])) {
254       $settings['allowed_values'] = static::structureAllowedValues($settings['allowed_values']);
255     }
256     return $settings;
257   }
258
259   /**
260    * {@inheritdoc}
261    */
262   public static function storageSettingsFromConfigData(array $settings) {
263     if (isset($settings['allowed_values'])) {
264       $settings['allowed_values'] = static::simplifyAllowedValues($settings['allowed_values']);
265     }
266     return $settings;
267   }
268
269   /**
270    * Simplifies allowed values to a key-value array from the structured array.
271    *
272    * @param array $structured_values
273    *   Array of items with a 'value' and 'label' key each for the allowed
274    *   values.
275    *
276    * @return array
277    *   Allowed values were the array key is the 'value' value, the value is
278    *   the 'label' value.
279    *
280    * @see \Drupal\options\Plugin\Field\FieldType\ListItemBase::structureAllowedValues()
281    */
282   protected static function simplifyAllowedValues(array $structured_values) {
283     $values = [];
284     foreach ($structured_values as $item) {
285       if (is_array($item['label'])) {
286         // Nested elements are embedded in the label.
287         $item['label'] = static::simplifyAllowedValues($item['label']);
288       }
289       $values[$item['value']] = $item['label'];
290     }
291     return $values;
292   }
293
294   /**
295    * Creates a structured array of allowed values from a key-value array.
296    *
297    * @param array $values
298    *   Allowed values were the array key is the 'value' value, the value is
299    *   the 'label' value.
300    *
301    * @return array
302    *   Array of items with a 'value' and 'label' key each for the allowed
303    *   values.
304    *
305    * @see \Drupal\options\Plugin\Field\FieldType\ListItemBase::simplifyAllowedValues()
306    */
307   protected static function structureAllowedValues(array $values) {
308     $structured_values = [];
309     foreach ($values as $value => $label) {
310       if (is_array($label)) {
311         $label = static::structureAllowedValues($label);
312       }
313       $structured_values[] = [
314         'value' => static::castAllowedValue($value),
315         'label' => $label,
316       ];
317     }
318     return $structured_values;
319   }
320
321   /**
322    * Converts a value to the correct type.
323    *
324    * @param mixed $value
325    *   The value to cast.
326    *
327    * @return mixed
328    *   The casted value.
329    */
330   protected static function castAllowedValue($value) {
331     return $value;
332   }
333
334 }