Last active
September 26, 2022 08:46
-
-
Save yceruto/041116e266c064484edcd8343045f4fc to your computer and use it in GitHub Desktop.
Twig filesystem cache warmer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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