17 use Assetic\Asset\AssetCache;
18 use Assetic\Asset\AssetCollection;
19 use Assetic\Asset\FileAsset;
20 use Assetic\Asset\StringAsset;
21 use Assetic\AssetWriter;
22 use Assetic\Cache\FilesystemCache;
23 use Assetic\Filter\CssRewriteFilter;
24 use Minifier\MinFilter;
26 if (!class_exists(
'Assetic\Asset\AssetCollection')) {
28 'smarty_block_assetic requires '.
29 'Assetic. If you are using composer, add kriswallsmith/assetic '.
30 'as dependency to your project');
60 function smarty_block_assetic($params, $content, Smarty_Internal_Template $template, &$repeat) {
62 if (isset($content)) {
63 if ($params[
'debug'] ==
true) {
71 $urls = StringUtil::getUrls($content);
72 foreach ($urls as $url) {
73 $parts = pathinfo($url);
74 $extension = strtolower($parts[
'extension']);
75 $min = preg_match(
'/\.min$/', $parts[
'filename']);
76 if (!isset($resources[$extension])) {
77 $resources[$extension] = [
'min' => [],
'src' => []];
79 $resources[$extension][$min ?
'min' :
'src'][] = $url;
83 $config = ObjectFactory::getInstance(
'configuration');
84 $basePath = dirname(FileUtil::realpath($_SERVER[
'SCRIPT_FILENAME'])).
'/';
85 $cacheRootAbs = $config->getDirectoryValue(
'cacheDir',
'FrontendCache');
86 $cacheRootRel = URIUtil::makeRelative($cacheRootAbs, $basePath);
87 $hmacKey = $config->getValue(
'secret',
'application');
90 foreach ($resources as $type => $files) {
91 $filesystem =
new FilesystemCache($cacheRootAbs);
92 $writer =
new AssetWriter($cacheRootAbs);
95 $hash = hash_init(
'sha1', HASH_HMAC, $hmacKey);
96 foreach (array_merge($files[
'min'], $files[
'src']) as $file) {
97 $content = file_exists($file) ? file_get_contents($file) :
'';
98 hash_update($hash, $content);
100 $hash = substr(hash_final($hash), 0, 7);
102 $cacheFile = (isset($params[
'name']) ? $params[
'name'] :
'').
'-'.$hash.
'.min.'.$type;
103 $cachePathRel = $cacheRootRel.$cacheFile;
107 if ($type ==
'css') {
108 $filters[] =
new CssRewriteFilter();
110 $minFilters = array_merge($filters, [
new MinFilter($type)]);
115 foreach ($files[
'min'] as $file) {
116 $asset =
new FileAsset($file, $filters,
'', $file);
117 $asset->setTargetPath($cachePathRel);
118 $minAssets[] =
new StringAsset($asset->dump());
120 foreach ($files[
'src'] as $file) {
121 $asset =
new FileAsset($file, $minFilters,
'', $file);
122 $asset->setTargetPath($cachePathRel);
123 $minAssets[] =
new StringAsset($asset->dump());
127 $minCollection =
new AssetCollection($minAssets);
128 $cache =
new AssetCache($minCollection, $filesystem);
129 $cache->setTargetPath($cacheFile);
130 $writer->writeAsset($cache);
135 $tag =
'<script src="'.$cachePathRel.
'"></script>';
138 $tag =
'<link rel="stylesheet" href="'.$cachePathRel.
'">';