You are here

public function SectionComponentRenderArray::setComponentContexts in Core Context 8

Sets context values on a section component at render time.

Parameters

\Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent $event: The event object.

File

src/EventSubscriber/SectionComponentRenderArray.php, line 66

Class

SectionComponentRenderArray
Reacts to a render array being generated for a layout section component.

Namespace

Drupal\core_context\EventSubscriber

Code

public function setComponentContexts(SectionComponentBuildRenderArrayEvent $event) {
  $plugin = $event
    ->getPlugin();

  // If the plugin cannot accept contexts, there's no point in continuing.
  if (!$plugin instanceof ContextAwarePluginInterface) {
    return;
  }

  // @todo Remove when https://www.drupal.org/project/drupal/issues/3018782 is
  // done.
  // @see \Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay::buildSections()
  $contexts = $event
    ->getContexts();
  if (isset($contexts['layout_builder.entity']) && empty($contexts['entity'])) {
    $contexts['entity'] =& $contexts['layout_builder.entity'];
  }

  // The event is unaware of the section storage, so we need to use the
  // available contexts to find the correct section storage.
  $section_storage = $this->sectionStorageManager
    ->findByContext($contexts, $event
    ->getCacheableMetadata());

  // If the section storage is overriding another one, the contexts provided
  // by the override should be overlaid on top of the ones provided by the
  // underlying default.
  $contexts = $this
    ->getContextsFromSectionStorage($section_storage);
  while ($section_storage instanceof OverridesSectionStorageInterface) {
    $section_storage = $section_storage
      ->getDefaultSectionStorage();
    $contexts += $this
      ->getContextsFromSectionStorage($section_storage);
  }

  // Filter out any contexts which the plugin does not recognize.
  $contexts = array_intersect_key($contexts, $plugin
    ->getContextDefinitions());
  foreach ($contexts as $name => $context) {
    $plugin
      ->setContextValue($name, $context
      ->getContextValue());
  }
}