Passed
Pull Request — twig (#780)
by Arnaud
07:49 queued 05:16
created

Asset::save()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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