Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / lib / Drupal / Core / Plugin / ContextAwarePluginAssignmentTrait.php
1 <?php
2
3 namespace Drupal\Core\Plugin;
4
5 /**
6  * Handles context assignments for context-aware plugins.
7  */
8 trait ContextAwarePluginAssignmentTrait {
9
10   /**
11    * Ensures the t() method is available.
12    *
13    * @see \Drupal\Core\StringTranslation\StringTranslationTrait
14    */
15   abstract protected function t($string, array $args = [], array $options = []);
16
17   /**
18    * Wraps the context handler.
19    *
20    * @return \Drupal\Core\Plugin\Context\ContextHandlerInterface
21    */
22   protected function contextHandler() {
23     return \Drupal::service('context.handler');
24   }
25
26   /**
27    * Builds a form element for assigning a context to a given slot.
28    *
29    * @param \Drupal\Core\Plugin\ContextAwarePluginInterface $plugin
30    *   The context-aware plugin.
31    * @param \Drupal\Component\Plugin\Context\ContextInterface[] $contexts
32    *   An array of contexts.
33    *
34    * @return array
35    *   A form element for assigning context.
36    */
37   protected function addContextAssignmentElement(ContextAwarePluginInterface $plugin, array $contexts) {
38     $element = [];
39     foreach ($plugin->getContextDefinitions() as $context_slot => $definition) {
40       $valid_contexts = $this->contextHandler()->getMatchingContexts($contexts, $definition);
41       $options = [];
42       foreach ($valid_contexts as $context_id => $context) {
43         $element['#tree'] = TRUE;
44         $options[$context_id] = $context->getContextDefinition()->getLabel();
45         $element[$context_slot] = [
46           '#type' => 'value',
47           '#value' => $context_id,
48         ];
49       }
50
51       if (count($options) > 1 || !$definition->isRequired()) {
52         $assignments = $plugin->getContextMapping();
53         $element[$context_slot] = [
54           '#title' => $definition->getLabel() ?: $this->t('Select a @context value:', ['@context' => $context_slot]),
55           '#type' => 'select',
56           '#options' => $options,
57           '#required' => $definition->isRequired(),
58           '#default_value' => !empty($assignments[$context_slot]) ? $assignments[$context_slot] : '',
59           '#description' => $definition->getDescription(),
60         ];
61         if (!$definition->isRequired()) {
62           $element[$context_slot]['#empty_value'] = '';
63         }
64       }
65     }
66     return $element;
67   }
68
69 }