You are here

class CacheMetadataExtractor in Twig Tweak 3.1.x

Same name and namespace in other branches
  1. 3.x src/CacheMetadataExtractor.php \Drupal\twig_tweak\CacheMetadataExtractor

Cache metadata extractor service.

Hierarchy

Expanded class hierarchy of CacheMetadataExtractor

1 string reference to 'CacheMetadataExtractor'
twig_tweak.services.yml in ./twig_tweak.services.yml
twig_tweak.services.yml
1 service uses CacheMetadataExtractor
twig_tweak.cache_metadata_extractor in ./twig_tweak.services.yml
Drupal\twig_tweak\CacheMetadataExtractor

File

src/CacheMetadataExtractor.php, line 12

Namespace

Drupal\twig_tweak
View source
class CacheMetadataExtractor {

  /**
   * Extracts cache metadata from object or render array.
   *
   * @param \Drupal\Core\Cache\CacheableDependencyInterface|array $input
   *   The cacheable object or render array.
   *
   * @return array
   *   A render array with extracted cache metadata.
   */
  public function extractCacheMetadata($input) : array {
    if ($input instanceof CacheableDependencyInterface) {
      $cache_metadata = CacheableMetadata::createFromObject($input);
    }
    elseif (is_array($input)) {
      $cache_metadata = self::extractFromArray($input);
    }
    else {
      $message = sprintf('The input should be either instance of %s or array. %s was given.', CacheableDependencyInterface::class, \get_debug_type($input));
      throw new \InvalidArgumentException($message);
    }
    $build = [];
    $cache_metadata
      ->applyTo($build);
    return $build;
  }

  /**
   * Extracts cache metadata from renders array.
   */
  private static function extractFromArray(array $build) : CacheableMetadata {
    $cache_metadata = CacheableMetadata::createFromRenderArray($build);
    $keys = Element::children($build);
    foreach (array_intersect_key($build, array_flip($keys)) as $item) {
      $cache_metadata
        ->addCacheableDependency(self::extractFromArray($item));
    }
    return $cache_metadata;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheMetadataExtractor::extractCacheMetadata public function Extracts cache metadata from object or render array.
CacheMetadataExtractor::extractFromArray private static function Extracts cache metadata from renders array.