AssetConverter.php 1.83 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13
<?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;

/**
Qiang Xue committed
14 15
 * AssetConverter supports conversion of several popular script formats into JS or CSS scripts.
 *
Qiang Xue committed
16 17 18
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
19
class AssetConverter extends Component implements AssetConverterInterface
Qiang Xue committed
20
{
Qiang Xue committed
21 22 23 24 25
	/**
	 * @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.
	 */
Alexander Makarov committed
26 27 28 29 30 31
	public $commands = [
		'less' => ['css', 'lessc {from} {to}'],
		'scss' => ['css', 'sass {from} {to}'],
		'sass' => ['css', 'sass {from} {to}'],
		'styl' => ['js', 'stylus < {from} > {to}'],
	];
Qiang Xue committed
32

Qiang Xue committed
33 34 35 36
	/**
	 * 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.
37
	 * @return string the converted asset file path, relative to $basePath.
Qiang Xue committed
38
	 */
39
	public function convert($asset, $basePath)
Qiang Xue committed
40 41
	{
		$pos = strrpos($asset, '.');
42
		if ($pos !== false) {
Qiang Xue committed
43 44 45 46 47
			$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")) {
Alexander Makarov committed
48 49
					$output = [];
					$command = strtr($command, [
50 51
						'{from}' => escapeshellarg("$basePath/$asset"),
						'{to}' => escapeshellarg("$basePath/$result"),
Alexander Makarov committed
52
					]);
Qiang Xue committed
53
					exec($command, $output);
Qiang Xue committed
54
					Yii::trace("Converted $asset into $result: " . implode("\n", $output), __METHOD__);
Qiang Xue committed
55
				}
56
				return $result;
Qiang Xue committed
57 58
			}
		}
59
		return $asset;
Qiang Xue committed
60
	}
Zander Baldwin committed
61
}