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