a1a1ebdb9ebb12c02e3789471d6de1becb1c79ac
[yaffs-website] / web / core / lib / Drupal / Core / Field / FieldItemList.php
1 <?php
2
3 namespace Drupal\Core\Field;
4
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Entity\FieldableEntityInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Language\LanguageInterface;
9 use Drupal\Core\Session\AccountInterface;
10 use Drupal\Core\TypedData\Plugin\DataType\ItemList;
11
12 /**
13  * Represents an entity field; that is, a list of field item objects.
14  *
15  * An entity field is a list of field items, each containing a set of
16  * properties. Note that even single-valued entity fields are represented as
17  * list of field items, however for easy access to the contained item the entity
18  * field delegates __get() and __set() calls directly to the first item.
19  */
20 class FieldItemList extends ItemList implements FieldItemListInterface {
21
22   /**
23    * Numerically indexed array of field items.
24    *
25    * @var \Drupal\Core\Field\FieldItemInterface[]
26    */
27   protected $list = [];
28
29   /**
30    * The langcode of the field values held in the object.
31    *
32    * @var string
33    */
34   protected $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
35
36   /**
37    * {@inheritdoc}
38    */
39   protected function createItem($offset = 0, $value = NULL) {
40     return \Drupal::service('plugin.manager.field.field_type')->createFieldItem($this, $offset, $value);
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   public function getEntity() {
47     // The "parent" is the TypedData object for the entity, we need to unwrap
48     // the actual entity.
49     return $this->getParent()->getValue();
50   }
51
52   /**
53    * {@inheritdoc}
54    */
55   public function setLangcode($langcode) {
56     $this->langcode = $langcode;
57   }
58
59   /**
60    * {@inheritdoc}
61    */
62   public function getLangcode() {
63     return $this->langcode;
64   }
65
66   /**
67    * {@inheritdoc}
68    */
69   public function getFieldDefinition() {
70     return $this->definition;
71   }
72
73   /**
74    * {@inheritdoc}
75    */
76   public function getSettings() {
77     return $this->definition->getSettings();
78   }
79
80   /**
81    * {@inheritdoc}
82    */
83   public function getSetting($setting_name) {
84     return $this->definition->getSetting($setting_name);
85   }
86
87   /**
88    * {@inheritdoc}
89    */
90   public function filterEmptyItems() {
91     $this->filter(function ($item) {
92       return !$item->isEmpty();
93     });
94     return $this;
95   }
96
97   /**
98    * {@inheritdoc}
99    * @todo Revisit the need when all entity types are converted to NG entities.
100    */
101   public function getValue($include_computed = FALSE) {
102     $values = [];
103     foreach ($this->list as $delta => $item) {
104       $values[$delta] = $item->getValue($include_computed);
105     }
106     return $values;
107   }
108
109   /**
110    * {@inheritdoc}
111    */
112   public function setValue($values, $notify = TRUE) {
113     // Support passing in only the value of the first item, either as a literal
114     // (value of the first property) or as an array of properties.
115     if (isset($values) && (!is_array($values) || (!empty($values) && !is_numeric(current(array_keys($values)))))) {
116       $values = [0 => $values];
117     }
118     parent::setValue($values, $notify);
119   }
120
121   /**
122    * {@inheritdoc}
123    */
124   public function __get($property_name) {
125     // For empty fields, $entity->field->property is NULL.
126     if ($item = $this->first()) {
127       return $item->__get($property_name);
128     }
129   }
130
131   /**
132    * {@inheritdoc}
133    */
134   public function __set($property_name, $value) {
135     // For empty fields, $entity->field->property = $value automatically
136     // creates the item before assigning the value.
137     $item = $this->first() ?: $this->appendItem();
138     $item->__set($property_name, $value);
139   }
140
141   /**
142    * {@inheritdoc}
143    */
144   public function __isset($property_name) {
145     if ($item = $this->first()) {
146       return $item->__isset($property_name);
147     }
148     return FALSE;
149   }
150
151   /**
152    * {@inheritdoc}
153    */
154   public function __unset($property_name) {
155     if ($item = $this->first()) {
156       $item->__unset($property_name);
157     }
158   }
159
160   /**
161    * {@inheritdoc}
162    */
163   public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
164     $access_control_handler = \Drupal::entityManager()->getAccessControlHandler($this->getEntity()->getEntityTypeId());
165     return $access_control_handler->fieldAccess($operation, $this->getFieldDefinition(), $account, $this, $return_as_object);
166   }
167
168   /**
169    * {@inheritdoc}
170    */
171   public function defaultAccess($operation = 'view', AccountInterface $account = NULL) {
172     // Grant access per default.
173     return AccessResult::allowed();
174   }
175
176   /**
177    * {@inheritdoc}
178    */
179   public function applyDefaultValue($notify = TRUE) {
180     if ($value = $this->getFieldDefinition()->getDefaultValue($this->getEntity())) {
181       $this->setValue($value, $notify);
182     }
183     else {
184       // Create one field item and give it a chance to apply its defaults.
185       // Remove it if this ended up doing nothing.
186       // @todo Having to create an item in case it wants to set a value is
187       // absurd. Remove that in https://www.drupal.org/node/2356623.
188       $item = $this->first() ?: $this->appendItem();
189       $item->applyDefaultValue(FALSE);
190       $this->filterEmptyItems();
191     }
192     return $this;
193   }
194
195   /**
196    * {@inheritdoc}
197    */
198   public function preSave() {
199     // Filter out empty items.
200     $this->filterEmptyItems();
201
202     $this->delegateMethod('preSave');
203   }
204
205   /**
206    * {@inheritdoc}
207    */
208   public function postSave($update) {
209     $result = $this->delegateMethod('postSave', $update);
210     return (bool) array_filter($result);
211   }
212
213   /**
214    * {@inheritdoc}
215    */
216   public function delete() {
217     $this->delegateMethod('delete');
218   }
219
220   /**
221    * {@inheritdoc}
222    */
223   public function deleteRevision() {
224     $this->delegateMethod('deleteRevision');
225   }
226
227   /**
228    * Calls a method on each FieldItem.
229    *
230    * Any argument passed will be forwarded to the invoked method.
231    *
232    * @param string $method
233    *   The name of the method to be invoked.
234    *
235    * @return array
236    *   An array of results keyed by delta.
237    */
238   protected function delegateMethod($method) {
239     $result = [];
240     $args = array_slice(func_get_args(), 1);
241     foreach ($this->list as $delta => $item) {
242       // call_user_func_array() is way slower than a direct call so we avoid
243       // using it if have no parameters.
244       $result[$delta] = $args ? call_user_func_array([$item, $method], $args) : $item->{$method}();
245     }
246     return $result;
247   }
248
249   /**
250    * {@inheritdoc}
251    */
252   public function view($display_options = []) {
253     $view_builder = \Drupal::entityManager()->getViewBuilder($this->getEntity()->getEntityTypeId());
254     return $view_builder->viewField($this, $display_options);
255   }
256
257   /**
258    * {@inheritdoc}
259    */
260   public function generateSampleItems($count = 1) {
261     $field_definition = $this->getFieldDefinition();
262     $field_type_class = \Drupal::service('plugin.manager.field.field_type')->getPluginClass($field_definition->getType());
263     for ($delta = 0; $delta < $count; $delta++) {
264       $values[$delta] = $field_type_class::generateSampleValue($field_definition);
265     }
266     $this->setValue($values);
267   }
268
269   /**
270    * {@inheritdoc}
271    */
272   public function getConstraints() {
273     $constraints = parent::getConstraints();
274     // Check that the number of values doesn't exceed the field cardinality. For
275     // form submitted values, this can only happen with 'multiple value'
276     // widgets.
277     $cardinality = $this->getFieldDefinition()->getFieldStorageDefinition()->getCardinality();
278     if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
279       $constraints[] = $this->getTypedDataManager()
280         ->getValidationConstraintManager()
281         ->create('Count', [
282           'max' => $cardinality,
283           'maxMessage' => t('%name: this field cannot hold more than @count values.', ['%name' => $this->getFieldDefinition()->getLabel(), '@count' => $cardinality]),
284         ]);
285     }
286
287     return $constraints;
288   }
289
290   /**
291    * {@inheritdoc}
292    */
293   public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
294     if (empty($this->getFieldDefinition()->getDefaultValueCallback())) {
295       if ($widget = $this->defaultValueWidget($form_state)) {
296         // Place the input in a separate place in the submitted values tree.
297         $element = ['#parents' => ['default_value_input']];
298         $element += $widget->form($this, $element, $form_state);
299
300         return $element;
301       }
302       else {
303         return ['#markup' => $this->t('No widget available for: %type.', ['%type' => $this->getFieldDefinition()->getType()])];
304       }
305     }
306   }
307
308   /**
309    * {@inheritdoc}
310    */
311   public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state) {
312     // Extract the submitted value, and validate it.
313     if ($widget = $this->defaultValueWidget($form_state)) {
314       $widget->extractFormValues($this, $element, $form_state);
315       // Force a non-required field definition.
316       // @see self::defaultValueWidget().
317       $this->getFieldDefinition()->setRequired(FALSE);
318       $violations = $this->validate();
319
320       // Assign reported errors to the correct form element.
321       if (count($violations)) {
322         $widget->flagErrors($this, $violations, $element, $form_state);
323       }
324     }
325   }
326
327   /**
328    * {@inheritdoc}
329    */
330   public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {
331     // Extract the submitted value, and return it as an array.
332     if ($widget = $this->defaultValueWidget($form_state)) {
333       $widget->extractFormValues($this, $element, $form_state);
334       return $this->getValue();
335     }
336   }
337
338   /**
339    * {@inheritdoc}
340    */
341   public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
342     return $default_value;
343   }
344
345   /**
346    * Returns the widget object used in default value form.
347    *
348    * @param \Drupal\Core\Form\FormStateInterface $form_state
349    *   The form state of the (entire) configuration form.
350    *
351    * @return \Drupal\Core\Field\WidgetInterface|null
352    *   A Widget object or NULL if no widget is available.
353    */
354   protected function defaultValueWidget(FormStateInterface $form_state) {
355     if (!$form_state->has('default_value_widget')) {
356       $entity = $this->getEntity();
357
358       // Force a non-required widget.
359       $definition = $this->getFieldDefinition();
360       $definition->setRequired(FALSE);
361       $definition->setDescription('');
362
363       // Use the widget currently configured for the 'default' form mode, or
364       // fallback to the default widget for the field type.
365       $entity_form_display = entity_get_form_display($entity->getEntityTypeId(), $entity->bundle(), 'default');
366       $widget = $entity_form_display->getRenderer($this->getFieldDefinition()->getName());
367       if (!$widget) {
368         $widget = \Drupal::service('plugin.manager.field.widget')->getInstance(['field_definition' => $this->getFieldDefinition()]);
369       }
370
371       $form_state->set('default_value_widget', $widget);
372     }
373
374     return $form_state->get('default_value_widget');
375   }
376
377   /**
378    * {@inheritdoc}
379    */
380   public function equals(FieldItemListInterface $list_to_compare) {
381     $columns = $this->getFieldDefinition()->getFieldStorageDefinition()->getColumns();
382     $count1 = count($this);
383     $count2 = count($list_to_compare);
384     if ($count1 === 0 && $count2 === 0) {
385       // Both are empty we can safely assume that it did not change.
386       return TRUE;
387     }
388     if ($count1 !== $count2) {
389       // One of them is empty but not the other one so the value changed.
390       return FALSE;
391     }
392     $value1 = $this->getValue();
393     $value2 = $list_to_compare->getValue();
394     if ($value1 === $value2) {
395       return TRUE;
396     }
397     // If the values are not equal ensure a consistent order of field item
398     // properties and remove properties which will not be saved.
399     $callback = function (&$value) use ($columns) {
400       if (is_array($value)) {
401         $value = array_intersect_key($value, $columns);
402         ksort($value);
403       }
404     };
405     array_walk($value1, $callback);
406     array_walk($value2, $callback);
407
408     return $value1 == $value2;
409   }
410
411 }