|
1
|
|
|
<?php |
|
2
|
|
|
namespace Intersvyaz\AssetManager; |
|
3
|
|
|
|
|
4
|
|
|
use RecursiveDirectoryIterator; |
|
5
|
|
|
use RecursiveIteratorIterator; |
|
6
|
|
|
use SplFileInfo; |
|
7
|
|
|
use Yii; |
|
8
|
|
|
use yii\caching\Cache; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Расширенный AssetManager, позволяющий рассчитывать хэш публикации ассетов по содержимому директории. |
|
12
|
|
|
* Необходимо для того, чтобы на всех нодах проекта ассеты находилить в одинаковых директориях. |
|
13
|
|
|
*/ |
|
14
|
|
|
class Component extends \yii\web\AssetManager |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Включение расчета хэша ассетов по содержимому директории. |
|
18
|
|
|
* @var bool |
|
19
|
|
|
*/ |
|
20
|
|
|
public $hashByContent = false; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Имя компонента, используемого для кеширования. |
|
24
|
|
|
* @var string |
|
25
|
|
|
*/ |
|
26
|
|
|
public $cacheComponent = 'cache'; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @inheritdoc |
|
30
|
|
|
*/ |
|
31
|
|
|
public function hash($path) |
|
32
|
|
|
{ |
|
33
|
|
|
if (!$this->hashByContent) { |
|
34
|
|
|
return parent::hash($path); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
if (is_callable($this->hashCallback)) { |
|
38
|
|
|
return call_user_func($this->hashCallback, $path); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
$path = (is_file($path) ? dirname($path) : $path); |
|
42
|
|
|
return $this->hashByContent($path); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Расчет хэша ассетов по содержимому директории. |
|
47
|
|
|
* @param string $path |
|
48
|
|
|
* @return string |
|
49
|
|
|
*/ |
|
50
|
|
|
private function hashByContent($path) |
|
51
|
|
|
{ |
|
52
|
|
|
$filemtime = @filemtime($path); |
|
53
|
|
|
$key = md5(__CLASS__ . $path . $filemtime); |
|
54
|
|
|
|
|
55
|
|
|
/** @var Cache $cacheComponent */ |
|
56
|
|
|
$cacheComponent = Yii::$app->{$this->cacheComponent}; |
|
57
|
|
|
$hash = $cacheComponent->getOrSet($key, function () use ($path, $filemtime) { |
|
|
|
|
|
|
58
|
|
|
$files = []; |
|
59
|
|
|
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); |
|
60
|
|
|
|
|
61
|
|
|
/** @var SplFileInfo $file */ |
|
62
|
|
|
foreach ($it as $file) { |
|
63
|
|
|
if ($file->isFile()) { |
|
64
|
|
|
$files[] = md5_file($file); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return md5($path . implode($files, '|')); |
|
|
|
|
|
|
69
|
|
|
}, 1); |
|
70
|
|
|
|
|
71
|
|
|
return sprintf('%x', crc32($hash . Yii::getVersion() . '|' . $this->linkAssets)); |
|
|
|
|
|
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|
This check looks for imports that have been defined, but are not used in the scope.