|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Application\Bundle\DefaultBundle\Twig; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Class AssetVersionExtension. |
|
7
|
|
|
* |
|
8
|
|
|
* @author Timur Bolotiukh <[email protected]> |
|
9
|
|
|
*/ |
|
10
|
|
|
class AssetVersionExtension extends \Twig_Extension |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var string */ |
|
13
|
|
|
private $webRoot; |
|
14
|
|
|
|
|
15
|
|
|
/** @var string */ |
|
16
|
|
|
private $environment; |
|
17
|
|
|
|
|
18
|
|
|
const REV_MANIFEST_FILE = 'rev-manifest.json'; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* AssetVersionExtension constructor. |
|
22
|
|
|
* |
|
23
|
|
|
* @param string $rootDir |
|
24
|
|
|
* @param string $environment |
|
25
|
|
|
*/ |
|
26
|
|
|
public function __construct($rootDir, $environment) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->webRoot = realpath($rootDir.'/../web'); |
|
29
|
|
|
$this->environment = $environment; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* {@inheritdoc} |
|
34
|
|
|
*/ |
|
35
|
|
|
public function getFilters() |
|
36
|
|
|
{ |
|
37
|
|
|
return array( |
|
38
|
|
|
new \Twig_SimpleFilter('app_asset_version', array($this, 'getAssetVersion')), |
|
39
|
|
|
); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param string $asset |
|
44
|
|
|
* |
|
45
|
|
|
* @return string |
|
46
|
|
|
* |
|
47
|
|
|
* @throws \Exception |
|
48
|
|
|
*/ |
|
49
|
|
|
public function getAssetVersion($asset) |
|
50
|
|
|
{ |
|
51
|
|
|
if ('test' === $this->environment) { |
|
52
|
|
|
return $asset; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$path = pathinfo($this->webRoot.DIRECTORY_SEPARATOR.$asset); |
|
56
|
|
|
$manifestFile = $path['dirname'].DIRECTORY_SEPARATOR.self::REV_MANIFEST_FILE; |
|
57
|
|
|
|
|
58
|
|
|
if (!file_exists($manifestFile)) { |
|
59
|
|
|
throw new \Exception(sprintf('Cannot find manifest file: "%s"', $manifestFile)); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
$manifestPaths = json_decode(file_get_contents($manifestFile), true); |
|
63
|
|
|
|
|
64
|
|
|
if (!isset($manifestPaths[$path['basename']])) { |
|
65
|
|
|
throw new \Exception(sprintf('There is no file "%s" in the version manifest!', $path['basename'])); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return pathinfo($asset)['dirname'].DIRECTORY_SEPARATOR.$manifestPaths[$path['basename']]; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @return string |
|
73
|
|
|
*/ |
|
74
|
|
|
public function getName() |
|
75
|
|
|
{ |
|
76
|
|
|
return 'app_asset_version'; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|