]> git.agnieray.net Git - galette.git/blob - bin/twig-cache
Merge branch 'hotfix/1.0.3'
[galette.git] / bin / twig-cache
1 #!/bin/php
2 <?php
3
4 use Twig\Cache\CacheInterface;
5 use Twig\Cache\FilesystemCache;
6 use Twig\Environment;
7 use Twig\Loader\FilesystemLoader;
8 use Twig\TwigFunction;
9
10 if ( !class_exists('\Twig\Loader\FilesystemLoader')) {
11 require_once __DIR__ . '/../galette/vendor/autoload.php';
12 }
13
14 function rmdir_recursive($path){
15 if(!empty($path) && is_dir($path) ){
16 $dir = new RecursiveDirectoryIterator(
17 $path,
18 RecursiveDirectoryIterator::SKIP_DOTS
19 );
20 $files = new RecursiveIteratorIterator(
21 $dir,
22 RecursiveIteratorIterator::CHILD_FIRST
23 );
24
25 foreach ($files as $fpath) {
26 ($fpath->isDir() && !$fpath->isLink()) ? rmdir($fpath->getPathname()) : unlink($fpath->getPathname());
27 }
28
29 rmdir($path);
30 return true;
31 }
32 return false;
33 }
34
35 /**
36 * Return a custom Twig cache handler.
37 * This handler is useful to be able to preserve filenames of compiled files.
38 *
39 * @param string $directory
40 *
41 * @return CacheInterface
42 */
43 function getTwigCacheHandler(string $directory): CacheInterface
44 {
45 return new class($directory) extends FilesystemCache {
46
47 private string $directory;
48
49 public function __construct(string $directory, int $options = 0)
50 {
51 $this->directory = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
52 parent::__construct($directory, $options);
53 }
54
55 public function generateKey(string $name, string $className): string
56 {
57 return $this->directory . $name;
58 }
59 };
60 }
61
62 $directory = sprintf('%s/../galette/templates/default', __DIR__);
63 $cache_dir = sprintf('%s/../tempcache', __DIR__);
64 $cache = getTwigCacheHandler($cache_dir);
65 if (file_exists($cache_dir)) {
66 rmdir_recursive($cache_dir);
67 }
68 mkdir($cache_dir);
69
70 $iterator = new RecursiveIteratorIterator(
71 new RecursiveDirectoryIterator($directory),
72 RecursiveIteratorIterator::LEAVES_ONLY
73 );
74
75 $loader = new FilesystemLoader($directory);
76 $twig = new Environment(
77 $loader,
78 [
79 'cache' => $cache,
80 'auto_reload' => true,
81 ]
82 );
83
84 $twig_functions = [
85 '__',
86 '_T',
87 '_Tn',
88 '_Tx',
89 '_Tnx',
90 'url_for',
91 'memberName',
92 'callstatic',
93 'is_current_url',
94 'get_class',
95 'base_path',
96 'file_exists'
97 ];
98
99 foreach ($twig_functions as $function) {
100 $twig->addFunction(new TwigFunction($function, $function));
101 }
102
103 /** @var SplFileInfo $file */
104 foreach ($iterator as $file) {
105 if ($file->isFile()) {
106 $twig->load(str_replace($directory . '/', '', $file));
107 }
108 }