ContextAwarePluginAssignmentTrait.php 2.2 KB

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