component_library-1.0.x-dev/modules/gcomponent_library/src/Theming/PreprocessComponentLibraryComponent.php

modules/gcomponent_library/src/Theming/PreprocessComponentLibraryComponent.php
<?php

declare(strict_types=1);

namespace Drupal\gcomponent_library\Theming;

use Drupal\component_library\Entity\ComponentLibraryPattern;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\gcomponent_library\BaseFields;
use Drupal\gcomponent_library\Entity\LibraryCollection;
use Drupal\group\Context\GroupRouteContext;
use Drupal\group\Entity\GroupInterface;

/**
 * Service to preprocess component library components.
 */
final class PreprocessComponentLibraryComponent {

  private GroupRouteContext $groupContextProvider;

  public function __construct(GroupRouteContext $group_context) {
    $this->groupContextProvider = $group_context;
  }

  public function preprocess(array &$variables, array $info): void {
    $contexts = $this->groupContextProvider->getRuntimeContexts(['group']);
    $group = $contexts['group']->getContextValue();
    if ($group === NULL) {
      $group = $variables['context']->getProperty('entity');
      if (!$group instanceof GroupInterface) {
        return;
      }
    }

    $component_id = $info['component_id'];

    if (!\array_key_exists($component_id, LibraryCollection::getSupportedStyles())) {
      return;
    }

    $collection = $group->get(BaseFields::COLLECTION_FIELD)->entity;
    if ($collection === NULL) {
      return;
    }
    \assert($collection instanceof LibraryCollection);

    $variant = $collection->getStyle($component_id) ?? $variables['variant'];
    if (!$group->get(BaseFields::OVERRIDE_FIELD)->isEmpty()) {
      $variant = $group->get(BaseFields::OVERRIDE_FIELD)->first()->getValue()[$component_id] ?? $variant;
    }

    $pattern_entity = ComponentLibraryPattern::load($component_id);
    if ($pattern_entity === NULL) {
      return;
    }
    $component_variant = $pattern_entity->getVariant($variant);
    if ($component_variant === NULL) {
      return;
    }
    $context = [];
    foreach ($pattern_entity->getFields() as $name => $preview_value) {
      $context[$name] = $preview_value;
      if (\array_key_exists($name, $variables)) {
        $context[$name] = $variables[$name];
      }
    }
    $variables['content'] = [
      '#type' => 'inline_template',
      '#template' => $component_variant->get('template'),
      '#context' => $context,
    ];

    $cache_metadata = new CacheableMetadata();
    $cache_metadata->addCacheableDependency($group);
    $cache_metadata->addCacheableDependency($collection);
    $cache_metadata->addCacheableDependency($component_variant);
    $cache_metadata->addCacheableDependency($component_variant->getPatternEntity());
    $cache_metadata->applyTo($variables);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc