summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/Plugin/ContextAwarePluginAssignmentTrait.php
blob: 035c69809a319ce4af1a75d3f24bfc4caae05ab9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

namespace Drupal\Core\Plugin;

/**
 * Handles context assignments for context-aware plugins.
 */
trait ContextAwarePluginAssignmentTrait {

  /**
   * Ensures the t() method is available.
   *
   * @see \Drupal\Core\StringTranslation\StringTranslationTrait
   */
  abstract protected function t($string, array $args = [], array $options = []);

  /**
   * Wraps the context handler.
   *
   * @return \Drupal\Core\Plugin\Context\ContextHandlerInterface
   *   the context handler service.
   */
  protected function contextHandler() {
    return \Drupal::service('context.handler');
  }

  /**
   * Builds a form element for assigning a context to a given slot.
   *
   * @param \Drupal\Core\Plugin\ContextAwarePluginInterface $plugin
   *   The context-aware plugin.
   * @param \Drupal\Component\Plugin\Context\ContextInterface[] $contexts
   *   An array of contexts.
   *
   * @return array
   *   A form element for assigning context.
   */
  protected function addContextAssignmentElement(ContextAwarePluginInterface $plugin, array $contexts) {
    $element = [];
    foreach ($plugin->getContextDefinitions() as $context_slot => $definition) {
      $valid_contexts = $this->contextHandler()->getMatchingContexts($contexts, $definition);
      $options = [];
      foreach ($valid_contexts as $context_id => $context) {
        $element['#tree'] = TRUE;
        $options[$context_id] = $context->getContextDefinition()->getLabel();
        $element[$context_slot] = [
          '#type' => 'value',
          '#value' => $context_id,
        ];
      }

      // Show the context selector only if there is more than 1 option to choose
      // from. Also, show if there is a single option but the plugin does not
      // require a context.
      if (count($options) > 1 || (count($options) == 1 && !$definition->isRequired())) {
        $assignments = $plugin->getContextMapping();
        $element[$context_slot] = [
          '#title' => $definition->getLabel() ?: $this->t('Select a @context value:', ['@context' => $context_slot]),
          '#type' => 'select',
          '#options' => $options,
          '#required' => $definition->isRequired(),
          '#default_value' => !empty($assignments[$context_slot]) ? $assignments[$context_slot] : '',
          '#description' => $definition->getDescription(),
        ];
        if (!$definition->isRequired()) {
          $element[$context_slot]['#empty_value'] = '';
        }
      }
    }
    return $element;
  }

}