component_library-1.0.x-dev/src/VariationTemplateLoader.php
src/VariationTemplateLoader.php
<?php
declare(strict_types=1);
namespace Drupal\component_library;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Twig\Error\LoaderError;
use Twig\Loader\LoaderInterface;
use Twig\Source;
/**
* Loads templates from the component variation storage.
*/
final class VariationTemplateLoader implements LoaderInterface {
/**
* The entity_type.manager service.
*/
private EntityTypeManagerInterface $entityTypeManager;
/**
* The instantiated Cache backend.
*/
private CacheBackendInterface $configCache;
/**
* Constructs a new template loader instance.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, CacheBackendInterface $config_cache) {
$this->entityTypeManager = $entity_type_manager;
$this->configCache = $config_cache;
}
/**
* {@inheritdoc}
*/
public function exists($name): bool {
if (\str_starts_with($name, '@component_variation/')) {
$variation_id = \explode('/', $name, 2)[1];
$variation = $this->entityTypeManager
->getStorage('component_library_variant')
->load($variation_id);
return (bool) $variation;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function getSourceContext($name): Source {
$variation_id = \explode('/', $name)[1];
$variation = $this->entityTypeManager->getStorage('component_library_variant')->load($variation_id);
if (!$variation) {
throw new LoaderError(\sprintf('Could not load variation "%s".', $variation_id));
}
return new Source($variation->get('template'), $name);
}
/**
* {@inheritdoc}
*/
public function getCacheKey($name): string {
return $name;
}
/**
* {@inheritdoc}
*/
public function isFresh($name, $time): bool {
// Variation entity does not have "changed" property. So we check freshness
// using config cache.
$variation_id = \explode('/', $name, 2)[1];
$cache = $this->configCache->get('component_library.variant.' . $variation_id);
return $cache && ($time > $cache->created);
}
}
