Passed
Push — fingerprint ( 35d32d...db2713 )
by Arnaud
14:02 queued 10:58
created

Asset::getIntegrity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Assets;
12
13
use Cecil\Builder;
14
use Cecil\Config;
15
use Cecil\Exception\Exception;
16
use Cecil\Util;
17
use MatthiasMullie\Minify;
18
use ScssPhp\ScssPhp\Compiler;
19
20
class Asset implements \ArrayAccess
21
{
22
    const ASSETS_OUTPUT_DIR = '/';
23
24
    /** @var Builder */
25
    protected $builder;
26
    /** @var Config */
27
    protected $config;
28
    /** @var array */
29
    protected $data = [];
30
    /** @var bool */
31
    protected $fingerprinted = false;
32
    /** @var bool */
33
    protected $compiled = false;
34
    /** @var bool */
35
    protected $minified = false;
36
37
    /**
38
     * Creates an Asset from file.
39
     *
40
     * $options[
41
     *     'fingerprint' => true,
42
     *     'minify'      => true,
43
     *     'attributes'  => ['title' => 'Titre'],
44
     * ];
45
     *
46
     * @param Builder    $builder
47
     * @param string     $path
48
     * @param array|null $options
49
     */
50
    public function __construct(Builder $builder, string $path, array $options = null)
51
    {
52
        $this->builder = $builder;
53
        $this->config = $builder->getConfig();
54
        $path = '/'.ltrim($path, '/');
55
56
        if (false === $filePath = $this->findFile($path)) {
57
            throw new Exception(sprintf('Asset file "%s" doesn\'t exist.', $path));
58
        }
59
60
        $pathinfo = pathinfo($path);
61
62
        // handles options
63
        $fingerprint = (bool) $this->config->get('assets.fingerprint.auto');
64
        $minify = (bool) $this->config->get('assets.minify.auto');
65
        $attributes = null;
66
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);
67
68
        // set data
69
        $this->data['file'] = $filePath;
70
        $this->data['path'] = Util::joinPath(self::ASSETS_OUTPUT_DIR, $path);
71
        $this->data['ext'] = $pathinfo['extension'];
72
        $this->data['type'] = explode('/', mime_content_type($filePath))[0];
73
        $this->data['source'] = file_get_contents($filePath);
74
        $this->data['content'] = $this->data['source'];
75
        $this->data['attributes'] = $attributes;
76
77
        // fingerprinting
78
        if ($fingerprint) {
79
            $this->fingerprint();
80
        }
81
        // compiling
82
        if ((bool) $this->config->get('assets.compile.auto')) {
83
            $this->compile();
84
        }
85
        // minifying
86
        if ($minify) {
87
            $this->minify();
88
        }
89
    }
90
91
    /**
92
     * Returns Asset path.
93
     *
94
     * @return string
95
     */
96
    public function __toString(): string
97
    {
98
        return $this->data['path'];
99
    }
100
101
    /**
102
     * Fingerprints a file.
103
     *
104
     * @return self
105
     */
106
    public function fingerprint(): self
107
    {
108
        if ($this->fingerprinted) {
109
            return $this;
110
        }
111
112
        $fingerprint = hash('md5', $this->data['source']);
113
        $this->data['path'] = preg_replace(
114
            '/\.'.$this->data['ext'].'$/m',
115
            ".$fingerprint.".$this->data['ext'],
116
            $this->data['path']
117
        );
118
119
        $this->fingerprinted = true;
120
121
        return $this;
122
    }
123
124
    /**
125
     * Compiles a SCSS.
126
     *
127
     * @return self
128
     */
129
    public function compile(): self
130
    {
131
        if ($this->compiled) {
132
            return $this;
133
        }
134
135
        if ($this->data['ext'] != 'scss') {
136
            return $this;
137
        }
138
139
        $cache = new Cache($this->builder, 'assets');
140
        $cacheKey = $cache->createKeyFromAsset($this);
141
        if (!$cache->has($cacheKey)) {
142
            $scssPhp = new Compiler();
143
            $scssDir = $this->config->get('assets.compile.import') ?? [];
144
            $themes = $this->config->getTheme() ?? [];
145
            foreach ($scssDir as $dir) {
146
                $scssPhp->addImportPath(Util::joinPath($this->config->getStaticPath(), $dir));
147
                $scssPhp->addImportPath(Util::joinPath(dirname($this->data['file']), $dir));
148
                foreach ($themes as $theme) {
149
                    $scssPhp->addImportPath(Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir")));
150
                }
151
            }
152
            $scssPhp->setVariables($this->config->get('assets.compile.variables') ?? []);
153
            $scssPhp->setFormatter('ScssPhp\ScssPhp\Formatter\\'.ucfirst($this->config->get('assets.compile.style')));
154
            $this->data['path'] = preg_replace('/scss/m', 'css', $this->data['path']);
155
            $this->data['ext'] = 'css';
156
            $this->data['content'] = $scssPhp->compile($this->data['content']);
157
            $this->compiled = true;
158
            $cache->set($cacheKey, $this->data);
159
        }
160
        $this->data = $cache->get($cacheKey);
161
162
        return $this;
163
    }
164
165
    /**
166
     * Minifying a CSS or a JS.
167
     *
168
     * @return self
169
     */
170
    public function minify(): self
171
    {
172
        if ($this->minified) {
173
            return $this;
174
        }
175
176
        if ($this->data['ext'] == 'scss') {
177
            $this->compile();
178
        }
179
180
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
181
            return $this;
182
        }
183
184
        $cache = new Cache($this->builder, 'assets');
185
        $cacheKey = $cache->createKeyFromAsset($this);
186
        if (!$cache->has($cacheKey)) {
187
            switch ($this->data['ext']) {
188
                case 'css':
189
                    $minifier = new Minify\CSS($this->data['content']);
190
                    break;
191
                case 'js':
192
                    $minifier = new Minify\JS($this->data['content']);
193
                    break;
194
                default:
195
                    throw new Exception(sprintf('Not able to minify "%s"', $this->data['path']));
196
            }
197
            $this->data['path'] = preg_replace(
198
                '/\.'.$this->data['ext'].'$/m',
199
                '.min.'.$this->data['ext'],
200
                $this->data['path']
201
            );
202
            $this->data['content'] = $minifier->minify();
203
            $this->minified = true;
204
            $cache->set($cacheKey, $this->data);
205
        }
206
        $this->data = $cache->get($cacheKey);
207
208
        return $this;
209
    }
210
211
    /**
212
     * Implements \ArrayAccess.
213
     */
214
    public function offsetSet($offset, $value)
215
    {
216
        if (!is_null($offset)) {
217
            $this->data[$offset] = $value;
218
        }
219
    }
220
221
    /**
222
     * Implements \ArrayAccess.
223
     */
224
    public function offsetExists($offset)
225
    {
226
        return isset($this->data[$offset]);
227
    }
228
229
    /**
230
     * Implements \ArrayAccess.
231
     */
232
    public function offsetUnset($offset)
233
    {
234
        unset($this->data[$offset]);
235
    }
236
237
    /**
238
     * Implements \ArrayAccess.
239
     */
240
    public function offsetGet($offset)
241
    {
242
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
243
    }
244
245
    /**
246
     * Hashing content of an asset with the specified algo, sha384 by default.
247
     * Used for SRI (Subresource Integrity).
248
     *
249
     * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
250
     *
251
     * @return string
252
     */
253
    public function getIntegrity(string $algo = 'sha384'): string
254
    {
255
        return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true)));
256
    }
257
258
    /**
259
     * Saves file.
260
     * Note: a file from `static/` with the same name will be overridden.
261
     *
262
     * @throws Exception
263
     *
264
     * @return void
265
     */
266
    public function save(): void
267
    {
268
        $file = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
269
        if (!$this->builder->getBuildOptions()['dry-run']) {
270
            try {
271
                Util::getFS()->dumpFile($file, $this->data['content']);
272
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
273
                throw new Exception(\sprintf('Can\'t save asset "%s"', $this->data['path']));
274
            }
275
        }
276
    }
277
278
    /**
279
     * Try to find a static file (in site or theme(s)) if exists or returns false.
280
     *
281
     * @param string $path
282
     *
283
     * @return string|false
284
     */
285
    private function findFile(string $path)
286
    {
287
        $filePath = Util::joinFile($this->config->getStaticPath(), $path);
288
        if (Util::getFS()->exists($filePath)) {
289
            return $filePath;
290
        }
291
292
        // checks in each theme
293
        foreach ($this->config->getTheme() as $theme) {
294
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
295
            if (Util::getFS()->exists($filePath)) {
296
                return $filePath;
297
            }
298
        }
299
300
        return false;
301
    }
302
}
303