Passed
Push — twig ( 9a88d6...936c6d )
by Arnaud
02:51
created

Asset::exists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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
    /** @var Builder */
23
    protected $builder;
24
    /** @var Config */
25
    protected $config;
26
    /** @var bool */
27
    /** @var array */
28
    protected $data = [];
29
    protected $versioned = false;
30
    /** @var bool */
31
    protected $compiled = false;
32
    /** @var bool */
33
    protected $minified = false;
34
35
    /**
36
     * Creates an Asset from file.
37
     *
38
     * $options[
39
     *     'minify'     => true,
40
     *     'version'    => true,
41
     *     'attributes' => ['title' => 'Titre'],
42
     * ];
43
     *
44
     * @param Builder    $builder
45
     * @param string     $path
46
     * @param array|null $options
47
     */
48
    public function __construct(Builder $builder, string $path, array $options = null)
49
    {
50
        $this->builder = $builder;
51
        $this->config = $builder->getConfig();
52
        $path = '/'.ltrim($path, '/');
53
54
        if (false === $filePath = $this->findFile($path)) {
55
            throw new Exception(sprintf('Asset file "%s" doesn\'t exist.', $path));
56
        }
57
58
        $pathinfo = pathinfo($path);
59
60
        // handles options
61
        $minify = (bool) $this->config->get('assets.minify.auto');
62
        $version = (bool) $this->config->get('assets.version.auto');
63
        $attributes = null;
64
        extract(is_array($options) ? $options : [], EXTR_IF_EXISTS);
65
66
        // set data
67
        $this->data['file'] = $filePath;
68
        $this->data['path'] = $path;
69
        $this->data['ext'] = $pathinfo['extension'];
70
        $this->data['type'] = explode('/', mime_content_type($filePath))[0];
71
        $this->data['source'] = file_get_contents($filePath);
72
        $this->data['content'] = $this->data['source'];
73
        $this->data['attributes'] = $attributes;
74
75
        // versionning
76
        if ($version) {
77
            $this->version();
78
        }
79
        // compiling
80
        if ((bool) $this->config->get('assets.sass.auto')) {
81
            $this->compile();
82
        }
83
        // minifying
84
        if ($minify) {
85
            $this->minify();
86
        }
87
    }
88
89
    /**
90
     * Returns Asset path.
91
     *
92
     * @return string
93
     */
94
    public function __toString(): string
95
    {
96
        return $this->data['path'];
97
    }
98
99
    /**
100
     * Versions a file.
101
     *
102
     * @return self
103
     */
104
    public function version(): self
105
    {
106
        if ($this->versioned) {
107
            return $this;
108
        }
109
110
        switch ($this->config->get('assets.version.strategy')) {
111
            case 'static':
112
                $version = $this->config->get('assets.version.value');
113
                break;
114
            case 'buildtime':
115
                $version = $this->builder->time;
116
                break;
117
            case 'today':
118
            default:
119
                $version = date('Ymd');
120
                break;
121
        }
122
123
        if ($this->config->get('assets.version.strategy') == 'static') {
124
            $version = $this->config->get('assets.version.value');
125
        }
126
127
        $this->data['path'] = preg_replace('/'.$this->data['ext'].'$/m', "$version.".$this->data['ext'], $this->data['path']);
128
129
        $this->versioned = true;
130
131
        return $this;
132
    }
133
134
    /**
135
     * Compiles a SCSS.
136
     *
137
     * @return self
138
     */
139
    public function compile(): self
140
    {
141
        if ($this->compiled) {
142
            return $this;
143
        }
144
145
        if ($this->data['ext'] != 'scss') {
146
            return $this;
147
        }
148
149
        $cache = new Cache($this->builder, 'assets');
150
        $cacheKey = $cache->createKeyFromAsset($this);
151
        if (!$cache->has($cacheKey)) {
152
            $scssPhp = new Compiler();
153
            // import
154
            $scssDir = $this->config->get('assets.sass.dir') ?? [];
155
            $themes = $this->config->getTheme() ?? [];
156
            foreach ($scssDir as $dir) {
157
                $scssPhp->addImportPath(Util::joinPath($this->config->getStaticPath(), $dir));
158
                $scssPhp->addImportPath(Util::joinPath(dirname($this->data['file']), $dir));
159
                foreach ($themes as $theme) {
160
                    $scssPhp->addImportPath(Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir")));
161
                }
162
            }
163
            $scssPhp->setVariables($this->config->get('assets.sass.variables') ?? []);
164
            $scssPhp->setFormatter('ScssPhp\ScssPhp\Formatter\\'.ucfirst($this->config->get('assets.sass.style')));
165
            $this->data['path'] = preg_replace('/scss/m', 'css', $this->data['path']);
166
            $this->data['ext'] = 'css';
167
            $this->data['content'] = $scssPhp->compile($this->data['content']);
168
            $this->compiled = true;
169
            $cache->set($cacheKey, $this->data);
170
        }
171
        $this->data = $cache->get($cacheKey);
172
173
        return $this;
174
    }
175
176
    /**
177
     * Minifying a CSS or a JS.
178
     *
179
     * @return self
180
     */
181
    public function minify(): self
182
    {
183
        if ($this->minified) {
184
            return $this;
185
        }
186
187
        if ($this->data['ext'] == 'scss') {
188
            $this->compile();
189
        }
190
191
        if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') {
192
            return $this;
193
        }
194
195
        $cache = new Cache($this->builder, 'assets');
196
        $cacheKey = $cache->createKeyFromAsset($this);
197
        if (!$cache->has($cacheKey)) {
198
            switch ($this->data['ext']) {
199
                case 'css':
200
                    $minifier = new Minify\CSS($this->data['content']);
201
                    break;
202
                case 'js':
203
                    $minifier = new Minify\JS($this->data['content']);
204
                    break;
205
                default:
206
                    throw new Exception(sprintf('Not able to minify "%s"', $this->data['path']));
207
            }
208
            $this->data['content'] = $minifier->minify();
209
            $this->minified = true;
210
            $cache->set($cacheKey, $this->data);
211
        }
212
        $this->data = $cache->get($cacheKey);
213
214
        return $this;
215
    }
216
217
    /**
218
     * Implements \ArrayAccess.
219
     */
220
    public function offsetSet($offset, $value)
221
    {
222
        if (!is_null($offset)) {
223
            $this->data[$offset] = $value;
224
        }
225
    }
226
227
    /**
228
     * Implements \ArrayAccess.
229
     */
230
    public function offsetExists($offset)
231
    {
232
        return isset($this->data[$offset]);
233
    }
234
235
    /**
236
     * Implements \ArrayAccess.
237
     */
238
    public function offsetUnset($offset)
239
    {
240
        unset($this->data[$offset]);
241
    }
242
243
    /**
244
     * Implements \ArrayAccess.
245
     */
246
    public function offsetGet($offset)
247
    {
248
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
249
    }
250
251
    /**
252
     * Saves file.
253
     *
254
     * @return void
255
     */
256
    public function save(): void
257
    {
258
        $file = Util::joinFile($this->config->getOutputPath(), $this->data['path']);
259
        if (!$this->builder->getBuildOptions()['dry-run'] && !is_file($file)) {
260
            Util::getFS()->dumpFile($file, $this->data['content']);
261
        }
262
    }
263
264
    /**
265
     * Try to find a static file (in site or theme(s)) if exists or returns false.
266
     *
267
     * @param string $path
268
     *
269
     * @return string|false
270
     */
271
    private function findFile(string $path)
272
    {
273
        $filePath = Util::joinFile($this->config->getStaticPath(), $path);
274
        if (Util::getFS()->exists($filePath)) {
275
            return $filePath;
276
        }
277
278
        // checks in each theme
279
        foreach ($this->config->getTheme() as $theme) {
280
            $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path);
281
            if (Util::getFS()->exists($filePath)) {
282
                return $filePath;
283
            }
284
        }
285
286
        return false;
287
    }
288
}
289