1
+ <?php
2
+ /**
3
+ * Author: Łukasz Barulski
4
+ * Date: 17.09.15 15:43
5
+ */
6
+
7
+ namespace Docplanner \AssetsBundle \Service ;
8
+
9
+ use Docplanner \AssetsBundle \IO \Asset ;
10
+ use Symfony \Component \HttpKernel \CacheWarmer \CacheWarmer ;
11
+
12
+ class RevisionWarmer extends CacheWarmer
13
+ {
14
+ const CACHE_FILE_NAME = 'assetsRevisions.php ' ;
15
+
16
+ /**
17
+ * @var array
18
+ */
19
+ private $ config ;
20
+ /**
21
+ * @var AssetsRepository
22
+ */
23
+ private $ repository ;
24
+
25
+ /**
26
+ * @param AssetsRepository $repository
27
+ * @param array $config
28
+ */
29
+ public function __construct (AssetsRepository $ repository , array $ config )
30
+ {
31
+ $ this ->repository = $ repository ;
32
+ $ this ->config = $ config ;
33
+ }
34
+
35
+
36
+ /**
37
+ * Checks whether this warmer is optional or not.
38
+ * Optional warmers can be ignored on certain conditions.
39
+ * A warmer should return true if the cache can be
40
+ * generated incrementally and on-demand.
41
+ * @return Boolean true if the warmer is optional, false otherwise
42
+ */
43
+ public function isOptional ()
44
+ {
45
+ return false ;
46
+ }
47
+
48
+ /**
49
+ * Warms up the cache.
50
+ *
51
+ * @param string $cacheDir The cache directory
52
+ */
53
+ public function warmUp ($ cacheDir )
54
+ {
55
+ $ data = $ this ->calculateHashes ();
56
+ $ this ->createPhpFile ($ cacheDir , $ data );
57
+ }
58
+
59
+ /**
60
+ * @return array
61
+ */
62
+ private function calculateHashes ()
63
+ {
64
+ $ data = [];
65
+ foreach (['script ' => $ this ->repository ->getScripts (), 'style ' => $ this ->repository ->getStyles ()] as $ type => $ assetsList )
66
+ {
67
+ /** @var Asset $asset */
68
+ foreach ($ assetsList as $ assetName => $ asset )
69
+ {
70
+ if (null !== $ asset ->getPath ())
71
+ {
72
+ $ data [$ type ][$ assetName ] = crc32 (file_get_contents ($ asset ->getPath ()));
73
+ }
74
+ }
75
+ }
76
+
77
+ return $ data ;
78
+ }
79
+
80
+ /**
81
+ * @param string $cacheDir
82
+ * @param array $data
83
+ */
84
+ private function createPhpFile ($ cacheDir , array $ data )
85
+ {
86
+ $ data = '<?php ' . PHP_EOL . 'return ' . var_export ($ data , true ) . '; ' ;
87
+ $ this ->writeCacheFile ($ cacheDir . '/ ' . self ::CACHE_FILE_NAME , $ data );
88
+ }
89
+ }
0 commit comments