Skip to content

Commit a20a2c5

Browse files
committed
Autodelete twig cache after update
1 parent 33c6c3e commit a20a2c5

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

src/Template.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
namespace RobiNN\Pca;
1010

1111
use Exception;
12+
use RuntimeException;
1213
use Twig\Environment;
1314
use Twig\Error\LoaderError;
1415
use Twig\Extension\DebugExtension;
@@ -27,6 +28,39 @@ class Template {
2728
*/
2829
private array $paths = [];
2930

31+
public function __construct() {
32+
$app_version = Admin::VERSION;
33+
$cache_dir = Config::get('twigcache', __DIR__.'/../tmp/twig');
34+
$version_file = $cache_dir.'/app_version.txt';
35+
36+
$saved_version = file_exists($version_file) ? file_get_contents($version_file) : '';
37+
38+
if ($app_version !== $saved_version) {
39+
$this->clearTwigCache($cache_dir);
40+
41+
if (!mkdir($cache_dir, 0777, true) && !is_dir($cache_dir)) {
42+
throw new RuntimeException(sprintf('Directory "%s" was not created', $cache_dir));
43+
}
44+
45+
file_put_contents($version_file, $app_version);
46+
}
47+
}
48+
49+
private function clearTwigCache(string $target_dir): void {
50+
if (!is_dir($target_dir)) {
51+
return;
52+
}
53+
54+
$directory_files = array_diff(scandir($target_dir), ['.', '..']);
55+
56+
foreach ($directory_files as $file_item) {
57+
$file_path = $target_dir.DIRECTORY_SEPARATOR.$file_item;
58+
is_dir($file_path) ? $this->clearTwigCache($file_path) : unlink($file_path);
59+
}
60+
61+
rmdir($target_dir);
62+
}
63+
3064
/**
3165
* Add global Twig variable.
3266
*/

0 commit comments

Comments
 (0)