14
14
use Psr \Container \ContainerInterface ;
15
15
use Symfony \Component \HttpKernel \CacheWarmer \CacheWarmerInterface ;
16
16
use Symfony \Contracts \Service \ServiceSubscriberInterface ;
17
+ use Twig \Cache \CacheInterface ;
17
18
use Twig \Environment ;
18
19
use Twig \Error \Error ;
19
20
@@ -34,26 +35,41 @@ class TemplateCacheWarmer implements CacheWarmerInterface, ServiceSubscriberInte
34
35
public function __construct (
35
36
private ContainerInterface $ container ,
36
37
private iterable $ iterator ,
38
+ private ?CacheInterface $ cache = null ,
37
39
) {
38
40
}
39
41
40
42
public function warmUp (string $ cacheDir , ?string $ buildDir = null ): array
41
43
{
44
+ if (!$ buildDir ) {
45
+ return [];
46
+ }
47
+
42
48
$ this ->twig ??= $ this ->container ->get ('twig ' );
43
49
44
- foreach ($ this ->iterator as $ template ) {
45
- try {
46
- $ this ->twig ->load ($ template );
47
- } catch (Error ) {
48
- /*
49
- * Problem during compilation, give up for this template (e.g. syntax errors).
50
- * Failing silently here allows to ignore templates that rely on functions that aren't available in
51
- * the current environment. For example, the WebProfilerBundle shouldn't be available in the prod
52
- * environment, but some templates that are never used in prod might rely on functions the bundle provides.
53
- * As we can't detect which templates are "really" important, we try to load all of them and ignore
54
- * errors. Error checks may be performed by calling the lint:twig command.
55
- */
50
+ $ originalCache = $ this ->twig ->getCache ();
51
+ if (null !== $ this ->cache ) {
52
+ // Swap the cache for the warmup as the Twig Environment has the ChainCache injected
53
+ $ this ->twig ->setCache ($ this ->cache );
54
+ }
55
+
56
+ try {
57
+ foreach ($ this ->iterator as $ template ) {
58
+ try {
59
+ $ this ->twig ->load ($ template );
60
+ } catch (Error ) {
61
+ /*
62
+ * Problem during compilation, give up for this template (e.g. syntax errors).
63
+ * Failing silently here allows to ignore templates that rely on functions that aren't available in
64
+ * the current environment. For example, the WebProfilerBundle shouldn't be available in the prod
65
+ * environment, but some templates that are never used in prod might rely on functions the bundle provides.
66
+ * As we can't detect which templates are "really" important, we try to load all of them and ignore
67
+ * errors. Error checks may be performed by calling the lint:twig command.
68
+ */
69
+ }
56
70
}
71
+ } finally {
72
+ $ this ->twig ->setCache ($ originalCache );
57
73
}
58
74
59
75
return [];
0 commit comments