Passed
Push — master ( 506152...7c24f3 )
by Alexander
05:14 queued 01:53
created

AssetConverter::setIsOutdatedCallback()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Assets;
6
7
use Psr\Log\LoggerInterface;
8
use Yiisoft\Aliases\Aliases;
9
use Yiisoft\Files\FileHelper;
10
11
use function array_key_exists;
12
use function array_merge;
13
use function escapeshellarg;
14
use function fclose;
15
use function is_file;
16
use function proc_close;
17
use function proc_open;
18
use function stream_get_contents;
19
use function strrpos;
20
use function strtr;
21
use function substr;
22
23
/**
24
 * AssetConverter supports conversion of several popular script formats into JavaScript or CSS.
25
 *
26
 * It is used by {@see AssetManager} to convert files after they have been published.
27
 */
28
final class AssetConverter implements AssetConverterInterface
29
{
30
    private Aliases $aliases;
31
    private LoggerInterface $logger;
32
33
    /**
34
     * @var array The commands that are used to perform the asset conversion.
35
     * The keys are the asset file extension names, and the values are the corresponding
36
     * target script types (either "css" or "js") and the commands used for the conversion.
37
     */
38
    private array $commands = [
39
        'less' => ['css', 'lessc {from} {to} --no-color --source-map'],
40
        'scss' => ['css', 'sass {options} {from} {to}'],
41
        'sass' => ['css', 'sass {options} {from} {to}'],
42
        'styl' => ['css', 'stylus < {from} > {to}'],
43
        'coffee' => ['js', 'coffee -p {from} > {to}'],
44
        'ts' => ['js', 'tsc --out {to} {from}'],
45
    ];
46
47
    /**
48
     * @var bool Whether the source asset file should be converted even if its result already exists.
49
     */
50
    private bool $forceConvert;
51
52
    /**
53
     * @var callable|null A PHP callback, which should be invoked to check whether asset conversion result is outdated.
54
     */
55
    private $isOutdatedCallback = null;
56
57
    /**
58
     * @param Aliases $aliases The aliases instance.
59
     * @param LoggerInterface $logger The logger instance.
60
     * @param array $commands The commands that are used to perform the asset conversion.
61
     * The keys are the asset file extension names, and the values are the corresponding
62
     * target script types (either "css" or "js") and the commands used for the conversion.
63
     *
64
     * You may also use a {@see https://github.com/yiisoft/docs/blob/master/guide/en/concept/aliases.md}
65
     * to specify the location of the command:
66
     *
67
     * ```php
68
     * [
69
     *     'styl' => ['css', '@app/node_modules/bin/stylus < {from} > {to}'],
70
     * ]
71
     * ```
72
     * @param bool $forceConvert Whether the source asset file should be converted even if its result already exists.
73
     * See {@see withForceConvert()}.
74
     */
75 90
    public function __construct(
76
        Aliases $aliases,
77
        LoggerInterface $logger,
78
        array $commands = [],
79
        bool $forceConvert = false
80
    ) {
81 90
        $this->aliases = $aliases;
82 90
        $this->logger = $logger;
83 90
        $this->commands = array_merge($this->commands, $commands);
84 90
        $this->forceConvert = $forceConvert;
85 90
    }
86
87 20
    public function convert(string $asset, string $basePath, array $optionsConverter = []): string
88
    {
89 20
        $pos = strrpos($asset, '.');
90
91 20
        if ($pos !== false) {
92 20
            $srcExt = substr($asset, $pos + 1);
93
94 20
            $commandOptions = $this->buildConverterOptions($srcExt, $optionsConverter);
95
96 20
            if (isset($this->commands[$srcExt])) {
97 6
                [$ext, $command] = $this->commands[$srcExt];
98 6
                $result = substr($asset, 0, $pos + 1) . $ext;
99 6
                if ($this->forceConvert || $this->isOutdated($basePath, $asset, $result, $srcExt, $ext)) {
100 6
                    $this->runCommand($command, $basePath, $asset, $result, $commandOptions);
101
                }
102
103 6
                return $result;
104
            }
105
        }
106
107 15
        return $asset;
108
    }
109
110
    /**
111
     * Returns a new instance with the specified command.
112
     *
113
     * Allows you to set a command that is used to perform the asset conversion {@see $commands}.
114
     *
115
     * @param string $from The file extension of the format converting from.
116
     * @param string $to The file extension of the format converting to.
117
     * @param string $command The command to execute for conversion.
118
     *
119
     * Example:
120
     *
121
     * $converter = $converter->withCommand('scss', 'css', 'sass {options} {from} {to}');
122
     *
123
     * @return self
124
     */
125 7
    public function withCommand(string $from, string $to, string $command): self
126
    {
127 7
        $new = clone $this;
128 7
        $new->commands[$from] = [$to, $command];
129 7
        return $new;
130
    }
131
132
    /**
133
     * Returns a new instance with the specified force convert value.
134
     *
135
     * @param bool $forceConvert Whether the source asset file should be converted even if its result already exists.
136
     * Default is `false`. You may want to set this to be `true` during the development stage to make
137
     * sure the converted assets are always up-to-date. Do not set this to true on production servers
138
     * as it will significantly degrade the performance.
139
     *
140
     * @return self
141
     */
142 2
    public function withForceConvert(bool $forceConvert): self
143
    {
144 2
        $new = clone $this;
145 2
        $new->forceConvert = $forceConvert;
146 2
        return $new;
147
    }
148
149
    /**
150
     * Returns a new instance with a callback that is used to check for outdated result.
151
     *
152
     * @param callable $isOutdatedCallback A PHP callback, which should be invoked to check whether asset conversion result is outdated.
153
     * It will be invoked only if conversion target file exists and its modification time is older then the one of
154
     * source file.
155
     * Callback should match following signature:
156
     *
157
     * ```php
158
     * function (string $basePath, string $sourceFile, string $targetFile, string $sourceExtension, string $targetExtension) : bool
159
     * ```
160
     *
161
     * where $basePath is the asset source directory; $sourceFile is the asset source file path, relative to $basePath;
162
     * $targetFile is the asset target file path, relative to $basePath; $sourceExtension is the source asset file
163
     * extension and $targetExtension is the target asset file extension, respectively.
164
     *
165
     * It should return `true` is case asset should be reconverted.
166
     * For example:
167
     *
168
     * ```php
169
     * function ($basePath, $sourceFile, $targetFile, $sourceExtension, $targetExtension) {
170
     *     if (YII_ENV !== 'dev') {
171
     *         return false;
172
     *     }
173
     *
174
     *     $resultModificationTime = @filemtime("$basePath/$result");
175
     *     foreach (FileHelper::findFiles($basePath, ['only' => ["*.{$sourceExtension}"]]) as $filename) {
176
     *         if ($resultModificationTime < @filemtime($filename)) {
177
     *             return true;
178
     *         }
179
     *     }
180
     *
181
     *     return false;
182
     * }
183
     * ```
184
     *
185
     * @return self
186
     */
187 2
    public function withIsOutdatedCallback(callable $isOutdatedCallback): self
188
    {
189 2
        $new = clone $this;
190 2
        $new->isOutdatedCallback = $isOutdatedCallback;
191 2
        return $new;
192
    }
193
194
    /**
195
     * Checks whether asset convert result is outdated, and thus should be reconverted.
196
     *
197
     * @param string $basePath The directory the $asset is relative to.
198
     * @param string $sourceFile The asset source file path, relative to [[$basePath]].
199
     * @param string $targetFile The converted asset file path, relative to [[$basePath]].
200
     * @param string $sourceExtension Source asset file extension.
201
     * @param string $targetExtension Target asset file extension.
202
     *
203
     * @return bool Whether asset is outdated or not.
204
     */
205 6
    private function isOutdated(
206
        string $basePath,
207
        string $sourceFile,
208
        string $targetFile,
209
        string $sourceExtension,
210
        string $targetExtension
211
    ): bool {
212 6
        if (!is_file("$basePath/$targetFile")) {
213 6
            return true;
214
        }
215
216 2
        $resultModificationTime = FileHelper::lastModifiedTime("$basePath/$targetFile");
217
218 2
        if ($resultModificationTime < FileHelper::lastModifiedTime("$basePath/$sourceFile")) {
219 1
            return true;
220
        }
221
222 2
        if ($this->isOutdatedCallback === null) {
223 1
            return false;
224
        }
225
226 1
        return ($this->isOutdatedCallback)(
227 1
            $basePath,
228
            $sourceFile,
229
            $targetFile,
230
            $sourceExtension,
231
            $targetExtension
232
        );
233
    }
234
235
    /**
236
     * Runs a command to convert asset files.
237
     *
238
     * @param string $command The command to run. If prefixed with an `@` it will be treated as a
239
     * {@see https://github.com/yiisoft/docs/blob/master/guide/en/concept/aliases.md}.
240
     * @param string $basePath Asset base path and command working directory.
241
     * @param string $asset The name of the asset file.
242
     * @param string $result The name of the file to be generated by the converter command.
243
     * @param string|null $options
244
     *
245
     * @return bool True on success, false on failure. Failures will be logged.
246
     */
247 6
    private function runCommand(
248
        string $command,
249
        string $basePath,
250
        string $asset,
251
        string $result,
252
        string $options = null
253
    ): bool {
254 6
        $basePath = $this->aliases->get($basePath);
255
256 6
        $command = $this->aliases->get($command);
257
258 6
        $command = strtr($command, [
259 6
            '{options}' => $options,
260 6
            '{from}' => escapeshellarg("$basePath/$asset"),
261 6
            '{to}' => escapeshellarg("$basePath/$result"),
262
        ]);
263
264
        $descriptors = [
265 6
            1 => ['pipe', 'w'],
266
            2 => ['pipe', 'w'],
267
        ];
268
269 6
        $pipes = [];
270
271 6
        $proc = proc_open($command, $descriptors, $pipes, $basePath);
272
273 6
        $stdout = stream_get_contents($pipes[1]);
274
275 6
        $stderr = stream_get_contents($pipes[2]);
276
277 6
        foreach ($pipes as $pipe) {
278 6
            fclose($pipe);
279
        }
280
281 6
        $status = proc_close($proc);
282
283 6
        if ($status === 0) {
284 4
            $this->logger->debug(
285 4
                "Converted $asset into $result:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr",
286 4
                [__METHOD__]
287
            );
288
        } else {
289 2
            $this->logger->error(
290 2
                "AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr",
291 2
                [__METHOD__]
292
            );
293
        }
294
295 6
        return $status === 0;
296
    }
297
298 20
    private function buildConverterOptions(string $srcExt, array $options): string
299
    {
300 20
        $commandOptions = '';
301
302 20
        if (isset($options[$srcExt])) {
303 1
            if (array_key_exists('command', $options[$srcExt])) {
304 1
                $commandOptions .= $options[$srcExt]['command'] . ' ';
305
            }
306
307 1
            if (array_key_exists('path', $options[$srcExt])) {
308 1
                $path = $this->aliases->get($options[$srcExt]['path']);
309
310 1
                $commandOptions = strtr($commandOptions, [
311 1
                    '{path}' => $path,
312
                ]);
313
            }
314
        }
315
316 20
        return $commandOptions;
317
    }
318
}
319