Passed
Push — master ( f68db4...f935c2 )
by Alexander
01:36
created

AssetConverter::runCommand()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 38
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3.0013

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
nc 4
nop 5
dl 0
loc 38
ccs 18
cts 19
cp 0.9474
c 1
b 0
f 0
cc 3
crap 3.0013
rs 9.584
1
<?php
2
declare(strict_types=1);
3
4
namespace Yiisoft\Assets;
5
6
use Psr\Log\LoggerInterface;
7
use Yiisoft\Aliases\Aliases;
8
9
/**
10
 * AssetConverter supports conversion of several popular script formats into JavaScript or CSS.
11
 *
12
 * It is used by {@see AssetManager} to convert files after they have been published.
13
 */
14
final class AssetConverter implements AssetConverterInterface
15
{
16
    /**
17
     * Aliases component
18
     */
19
    private Aliases $aliases;
20
21
    /**
22
     * @var array the commands that are used to perform the asset conversion.
23
     * The keys are the asset file extension names, and the values are the corresponding
24
     * target script types (either "css" or "js") and the commands used for the conversion.
25
     *
26
     * You may also use a [path alias](guide:concept-aliases) to specify the location of the command:
27
     *
28
     * ```php
29
     * [
30
     *     'styl' => ['css', '@app/node_modules/bin/stylus < {from} > {to}'],
31
     * ]
32
     * ```
33
     */
34
    private array $commands = [
35
        'less'   => ['css', 'lessc {from} {to} --no-color --source-map'],
36
        'scss'   => ['css', 'sass {options} {from} {to}'],
37
        'sass'   => ['css', 'sass {options} {from} {to}'],
38
        'styl'   => ['css', 'stylus < {from} > {to}'],
39
        'coffee' => ['js', 'coffee -p {from} > {to}'],
40
        'ts'     => ['js', 'tsc --out {to} {from}'],
41
    ];
42
43
    /**
44
     * @var bool whether the source asset file should be converted even if its result already exists.
45
     * You may want to set this to be `true` during the development stage to make sure the converted
46
     * assets are always up-to-date. Do not set this to true on production servers as it will
47
     * significantly degrade the performance.
48
     */
49
    private bool $forceConvert = false;
50
51
    /**
52
     * @var callable a PHP callback, which should be invoked to check whether asset conversion result is outdated.
53
     * It will be invoked only if conversion target file exists and its modification time is older then the one of
54
     * source file.
55
     * Callback should match following signature:
56
     *
57
     * ```php
58
     * function (string $basePath, string $sourceFile, string $targetFile, string $sourceExtension, string $targetExtension) : bool
59
     * ```
60
     *
61
     * where $basePath is the asset source directory; $sourceFile is the asset source file path, relative to $basePath;
62
     * $targetFile is the asset target file path, relative to $basePath; $sourceExtension is the source asset file
63
     * extension and $targetExtension is the target asset file extension, respectively.
64
     *
65
     * It should return `true` is case asset should be reconverted.
66
     * For example:
67
     *
68
     * ```php
69
     * function ($basePath, $sourceFile, $targetFile, $sourceExtension, $targetExtension) {
70
     *     if (YII_ENV !== 'dev') {
71
     *         return false;
72
     *     }
73
     *
74
     *     $resultModificationTime = @filemtime("$basePath/$result");
75
     *     foreach (FileHelper::findFiles($basePath, ['only' => ["*.{$sourceExtension}"]]) as $filename) {
76
     *         if ($resultModificationTime < @filemtime($filename)) {
77
     *             return true;
78
     *         }
79
     *     }
80
     *
81
     *     return false;
82
     * }
83
     * ```
84
     */
85
    private $isOutdatedCallback;
86
87
    private LoggerInterface $logger;
88
89 56
    public function __construct(Aliases $aliases, LoggerInterface $logger)
90
    {
91 56
        $this->aliases = $aliases;
92 56
        $this->logger = $logger;
93 56
    }
94
95
    /**
96
     * Converts a given asset file into a CSS or JS file.
97
     *
98
     * @param string $asset the asset file path, relative to $basePath
99
     * @param string $basePath the directory the $asset is relative to.
100
     * @param array $options additional options to pass to {@see AssetConverter::runCommand}
101
     *
102
     * @return string the converted asset file path, relative to $basePath.
103
     */
104 10
    public function convert(string $asset, string $basePath, array $options = []): string
105
    {
106 10
        $commandOptions = null;
107 10
        $pos = strrpos($asset, '.');
108
109 10
        if ($pos !== false) {
110 10
            $srcExt = substr($asset, $pos + 1);
111
112 10
            if (isset($options[$srcExt])) {
113
                $commandOptions = $options[$srcExt];
114
            }
115
116 10
            if (isset($this->commands[$srcExt])) {
117 4
                [$ext, $command] = $this->commands[$srcExt];
118 4
                $result = substr($asset, 0, $pos + 1).$ext;
119 4
                if ($this->forceConvert || $this->isOutdated($basePath, $asset, $result, $srcExt, $ext)) {
120 4
                    $this->runCommand($command, $basePath, $asset, $result, $commandOptions);
121
                }
122
123 4
                return $result;
124
            }
125
        }
126
127 6
        return $asset;
128
    }
129
130
    /**
131
     * Allows you to set a command that is used to perform the asset conversion.
132
     *
133
     * @param string $from file extension of the format converting from
134
     * @param string $to file extension of the format converting to
135
     * @param string $command command to execute for conversion
136
     *
137
     * Example:
138
     *
139
     * $converter->setCommand('scss', 'css', 'sass {options} {from} {to}');
140
     *
141
     * @return void
142
     */
143 4
    public function setCommand(string $from, string $to, string $command): void
144
    {
145 4
        $this->commands[$from] = [$to, $command];
146 4
    }
147
148
    /**
149
     * Make the conversion regardless of whether the asset already exists.
150
     *
151
     * @param bool $value
152
     * @return void
153
     */
154 1
    public function setForceConvert(bool $value): void
155
    {
156 1
        $this->forceConvert = $value;
157 1
    }
158
159
    /**
160
     * PHP callback, which should be invoked to check whether asset conversion result is outdated.
161
     *
162
     * @param callable $value
163
     *
164
     * @return void
165
     */
166 1
    public function setIsOutdatedCallback(callable $value): void
167
    {
168 1
        $this->isOutdatedCallback = $value;
169 1
    }
170
171
    /**
172
     * Checks whether asset convert result is outdated, and thus should be reconverted.
173
     *
174
     * @param string $basePath the directory the $asset is relative to.
175
     * @param string $sourceFile the asset source file path, relative to [[$basePath]].
176
     * @param string $targetFile the converted asset file path, relative to [[$basePath]].
177
     * @param string $sourceExtension source asset file extension.
178
     * @param string $targetExtension target asset file extension.
179
     *
180
     * @return bool whether asset is outdated or not.
181
     */
182 4
    private function isOutdated(string $basePath, string $sourceFile, string $targetFile, string $sourceExtension, string $targetExtension): bool
183
    {
184 4
        $resultModificationTime = @filemtime("$basePath/$targetFile");
185
186 4
        if ($resultModificationTime === false || $resultModificationTime === null) {
187 4
            return true;
188
        }
189
190 3
        if ($resultModificationTime < @filemtime("$basePath/$sourceFile")) {
191 1
            return true;
192
        }
193
194 3
        if ($this->isOutdatedCallback === null) {
195 2
            return false;
196
        }
197
198 1
        return \call_user_func($this->isOutdatedCallback, $basePath, $sourceFile, $targetFile, $sourceExtension, $targetExtension);
199
    }
200
201
    /**
202
     * Runs a command to convert asset files.
203
     *
204
     * @param string $command the command to run. If prefixed with an `@` it will be treated as a
205
     * [path alias](guide:concept-aliases).
206
     * @param string $basePath asset base path and command working directory
207
     * @param string $asset the name of the asset file
208
     * @param string $result the name of the file to be generated by the converter command
209
     *
210
     * @throws \Exception when the command fails and YII_DEBUG is true.
211
     * In production mode the error will be logged.
212
     *
213
     * @return bool true on success, false on failure. Failures will be logged.
214
     */
215 4
    private function runCommand(string $command, string $basePath, string $asset, string $result, ?string $options = null): bool
216
    {
217 4
        $basePath = $this->aliases->get($basePath);
218
219 4
        $command = $this->aliases->get($command);
220
221 4
        $command = strtr($command, [
0 ignored issues
show
Bug introduced by
It seems like $command can also be of type boolean; however, parameter $str of strtr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

221
        $command = strtr(/** @scrutinizer ignore-type */ $command, [
Loading history...
222 4
            '{options}' => escapeshellarg("$options"),
223 4
            '{from}' => escapeshellarg("$basePath/$asset"),
224 4
            '{to}'   => escapeshellarg("$basePath/$result"),
225
        ]);
226
227
        $descriptors = [
228 4
            1 => ['pipe', 'w'],
229
            2 => ['pipe', 'w'],
230
        ];
231
232 4
        $pipes = [];
233
234 4
        $proc = proc_open($command, $descriptors, $pipes, $basePath);
235
236 4
        $stdout = stream_get_contents($pipes[1]);
237
238 4
        $stderr = stream_get_contents($pipes[2]);
239
240 4
        foreach ($pipes as $pipe) {
241 4
            fclose($pipe);
242
        }
243
244 4
        $status = proc_close($proc);
0 ignored issues
show
Bug introduced by
It seems like $proc can also be of type false; however, parameter $process of proc_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

244
        $status = proc_close(/** @scrutinizer ignore-type */ $proc);
Loading history...
245
246 4
        if ($status === 0) {
247 4
            $this->logger->debug("Converted $asset into $result:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr", [__METHOD__]);
248
        } else {
249
            $this->logger->error("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr", [__METHOD__]);
250
        }
251
252 4
        return $status === 0;
253
    }
254
}
255