improvements-2.x-dev/src/Cache/EntityFieldCacheContext.php

src/Cache/EntityFieldCacheContext.php
<?php

namespace Drupal\improvements\Cache;

use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CalculatedCacheContextInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Calculated cache context ID: 'entity_field:%field_name', e.g.'entity_field:field_category' (to vary by field_category value).
 */
class EntityFieldCacheContext implements CalculatedCacheContextInterface {

  protected RouteMatchInterface $routeMatch;

  /**
   * Class constructor.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel(): MarkupInterface {
    return t('Entity field value');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext($field_name = NULL): string {
    if ($route_parameters = $this->routeMatch->getParameters()->all()) {
      foreach ($route_parameters as $route_parameter) {
        if ($route_parameter instanceof FieldableEntityInterface && $route_parameter->hasField($field_name)) {
          $field_items = $route_parameter->get($field_name);
          if (!$field_items->isEmpty()) {
            $main_property_name = $field_items->first()->mainPropertyName();
            return (string)$field_items->{$main_property_name};
          }
        }
      }
    }

    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($field_name = NULL): CacheableMetadata {
    return new CacheableMetadata();
  }

}

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

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