1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
use Yii;
use yii\base\Component;
/**
* AssetConverter supports conversion of several popular script formats into JS or CSS scripts.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class AssetConverter extends Component implements AssetConverterInterface
{
/**
* @var array the commands that are used to perform the asset conversion.
* The keys are the asset file extension names, and the values are the corresponding
* target script types (either "css" or "js") and the commands used for the conversion.
*/
public $commands = [
'less' => ['css', 'lessc {from} {to}'],
'scss' => ['css', 'sass {from} {to}'],
'sass' => ['css', 'sass {from} {to}'],
'styl' => ['js', 'stylus < {from} > {to}'],
];
/**
* Converts a given asset file into a CSS or JS file.
* @param string $asset the asset file path, relative to $basePath
* @param string $basePath the directory the $asset is relative to.
* @return string the converted asset file path, relative to $basePath.
*/
public function convert($asset, $basePath)
{
$pos = strrpos($asset, '.');
if ($pos !== false) {
$ext = substr($asset, $pos + 1);
if (isset($this->commands[$ext])) {
list ($ext, $command) = $this->commands[$ext];
$result = substr($asset, 0, $pos + 1) . $ext;
if (@filemtime("$basePath/$result") < filemtime("$basePath/$asset")) {
$output = [];
$command = strtr($command, [
'{from}' => escapeshellarg("$basePath/$asset"),
'{to}' => escapeshellarg("$basePath/$result"),
]);
exec($command, $output);
Yii::trace("Converted $asset into $result: " . implode("\n", $output), __METHOD__);
}
return $result;
}
}
return $asset;
}
}