Component   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 70
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A hashByContent() 0 16 1
A hash() 0 12 4
A init() 0 6 1
1
<?php
2
namespace Intersvyaz\AssetManager;
3
4
use Yii;
5
use yii\caching\Cache;
6
use yii\caching\CacheInterface;
7
use yii\di\Instance;
8
9
/**
10
 * Расширенный AssetManager, позволяющий рассчитывать хэш публикации ассетов по содержимому директории.
11
 * Необходимо для того, чтобы на всех нодах проекта ассеты находилить в одинаковых директориях.
12
 */
13
class Component extends \yii\web\AssetManager
14
{
15
    /**
16
     * Включение расчета хэша ассетов по содержимому директории.
17
     * @var bool
18
     */
19
    public $hashByContent = false;
20
21
    /**
22
     * Класс, реализующий возможность вычисления хэша по ФС.
23
     * @var FileSystemHashInterface
24
     */
25
    public $fileSystemHash = '\Intersvyaz\AssetManager\FileSystemHash';
26
27
    /**
28
     * Имя компонента, используемого для кеширования.
29
     * @var CacheInterface|array|string
30
     */
31
    public $cacheComponent = 'cache';
32
33
    /**
34
     * @inheritdoc
35
     */
36
    public function init()
37
    {
38
        parent::init();
39
        $this->fileSystemHash = Instance::ensure(
40
            $this->fileSystemHash,
41
            'Intersvyaz\AssetManager\FileSystemHashInterface'
42
        );
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    protected function hash($path)
49
    {
50
        if (!$this->hashByContent) {
51
            return parent::hash($path);
52
        }
53
54
        if (is_callable($this->hashCallback)) {
55
            return call_user_func($this->hashCallback, $path);
56
        }
57
58
        $path = (is_file($path) ? dirname($path) : $path);
59
        return $this->hashByContent($path);
60
    }
61
62
    /**
63
     * Расчет хэша ассетов по содержимому директории.
64
     * @param string $path
65
     * @return string
66
     */
67
    protected function hashByContent($path)
68
    {
69
        $filemtime = @filemtime($path);
70
        $key = md5(__CLASS__ . $path . $filemtime);
71
72
        /** @var Cache $cacheComponent */
73
        $cacheComponent = Yii::$app->{$this->cacheComponent};
74
75
        $hash = (string)$cacheComponent->getOrSet($key, function () use ($path) {
76
            return $this->fileSystemHash->hashPath($path);
77
        });
78
79
        return sprintf('%x', crc32(
80
                $this->fileSystemHash->hashPathName($path) . '|' .
81
                $hash . Yii::getVersion() . '|' .
82
                $this->linkAssets
83
            )
84
        );
85
    }
86
}
87