Skip to content

Instantly share code, notes, and snippets.

@yceruto
Last active September 26, 2022 08:46
Show Gist options
  • Save yceruto/041116e266c064484edcd8343045f4fc to your computer and use it in GitHub Desktop.
Save yceruto/041116e266c064484edcd8343045f4fc to your computer and use it in GitHub Desktop.
Twig filesystem cache warmer
<?php
use Symfony\Component\Finder\Finder;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
class FilesystemCacheWarmer
{
private $twig;
public function __construct(Environment $twig)
{
$this->twig = $twig;
}
public function warmUp(): void
{
foreach ($this->getIterator() as $template) {
try {
$this->twig->loadTemplate($template);
} catch (\Twig\Error\Error $e) {
// problem during compilation, give up
// might be a syntax error or a non-Twig template
}
}
}
public function getIterator(): \ArrayIterator
{
$loader = $this->twig->getLoader();
if (!$loader instanceof FilesystemLoader) {
throw new \InvalidArgumentException('Expected FilesystemLoader.');
}
$templates = [];
foreach ($loader->getNamespaces() as $namespace) {
foreach ($loader->getPaths($namespace) as $path) {
$templates = array_merge($templates, $this->findTemplatesInDirectory($path, $namespace));
}
}
return new \ArrayIterator(array_unique($templates));
}
private function findTemplatesInDirectory(string $dir, string $namespace): array
{
if (!is_dir($dir)) {
return [];
}
$templates = array();
foreach (Finder::create()->files()->followLinks()->in($dir) as $file) {
$templates[] = (FilesystemLoader::MAIN_NAMESPACE !== $namespace ? '@'.$namespace.'/' : '').str_replace('\\', '/', $file->getRelativePathname());
}
return $templates;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment