Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 23
ContextAwarePluginAssignmentTrait
0.00% covered (danger)
0.00%
0 / 1
33.33% covered (danger)
33.33%
1 / 3
110
0.00% covered (danger)
0.00%
0 / 23
 t
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
0 / 0
 contextHandler
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 addContextAssignmentElement
0.00% covered (danger)
0.00%
0 / 1
72
0.00% covered (danger)
0.00%
0 / 22
<?php
/**
 * @file
 * Contains \Drupal\Core\Plugin\ContextAwarePluginAssignmentTrait.
 */
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(), array $options = array());
  /**
   * Wraps the context handler.
   *
   * @return \Drupal\Core\Plugin\Context\ContextHandlerInterface
   */
  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,
        ];
      }
      if (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;
  }
}