AssetConverter.php 1.86 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 19 20
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AssetConverter extends Component implements IAssetConverter
{
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.
	 */
Qiang Xue committed
26
	public $commands = array(
Qiang Xue committed
27 28 29 30
		'less' => array('css', 'lessc {from} {to}'),
		'scss' => array('css', 'sass {from} {to}'),
		'sass' => array('css', 'sass {from} {to}'),
		'styl' => array('js', 'stylus < {from} > {to}'),
Qiang Xue committed
31 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 48
			$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 = array();
Qiang Xue committed
49
					$command = strtr($command, array(
50 51
						'{from}' => escapeshellarg("$basePath/$asset"),
						'{to}' => escapeshellarg("$basePath/$result"),
Qiang Xue committed
52
					));
Qiang Xue committed
53 54 55
					exec($command, $output);
					Yii::info("Converted $asset into $result: " . implode("\n", $output), __METHOD__);
				}
56
				return $result;
Qiang Xue committed
57 58
			}
		}
59
		return $asset;
Qiang Xue committed
60
	}
Zander Baldwin committed
61
}