AssetController.php 9.17 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\console\controllers;

use Yii;
use yii\console\Exception;
use yii\console\Controller;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
18
class AssetController extends Controller
Qiang Xue committed
19
{
Qiang Xue committed
20
	public $defaultAction = 'compress';
Qiang Xue committed
21

Qiang Xue committed
22 23 24 25 26 27 28 29 30 31 32 33 34
	public $bundles = array();
	public $extensions = array();
	/**
	 * @var array
	 * ~~~
	 * 'all' => array(
	 *     'css' => 'all.css',
	 *     'js' => 'js.css',
	 *     'depends' => array( ... ),
	 * )
	 * ~~~
	 */
	public $targets = array();
Qiang Xue committed
35
	public $assetManager = array();
36 37
	public $jsCompressor = 'java -jar compiler.jar --js {from} --js_output_file {to}';
	public $cssCompressor = 'java -jar yuicompressor.jar {from} -o {to}';
Qiang Xue committed
38 39 40 41 42

	public function actionCompress($configFile, $bundleFile)
	{
		$this->loadConfiguration($configFile);
		$bundles = $this->loadBundles($this->bundles, $this->extensions);
Qiang Xue committed
43
		$targets = $this->loadTargets($this->targets, $bundles);
44
		$this->publishBundles($bundles, $this->publishOptions);
Qiang Xue committed
45
		$timestamp = time();
Qiang Xue committed
46 47
		foreach ($targets as $target) {
			if (!empty($target->js)) {
Qiang Xue committed
48 49
				$this->buildTarget($target, 'js', $bundles, $timestamp);
			}
Qiang Xue committed
50
			if (!empty($target->css)) {
Qiang Xue committed
51 52 53 54 55
				$this->buildTarget($target, 'css', $bundles, $timestamp);
			}
		}

		$targets = $this->adjustDependency($targets, $bundles);
Qiang Xue committed
56
		$this->saveTargets($targets, $bundleFile);
Qiang Xue committed
57 58 59 60 61 62 63 64
	}

	protected function loadConfiguration($configFile)
	{
		foreach (require($configFile) as $name => $value) {
			if (property_exists($this, $name)) {
				$this->$name = $value;
			} else {
Qiang Xue committed
65
				throw new Exception("Unknown configuration option: $name");
Qiang Xue committed
66 67 68
			}
		}

Qiang Xue committed
69 70
		if (!isset($this->assetManager['basePath'])) {
			throw new Exception("Please specify 'basePath' for the 'assetManager' option.");
Qiang Xue committed
71
		}
Qiang Xue committed
72 73
		if (!isset($this->assetManager['baseUrl'])) {
			throw new Exception("Please specify 'baseUrl' for the 'assetManager' option.");
Qiang Xue committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
		}
	}

	protected function loadBundles($bundles, $extensions)
	{
		$result = array();
		foreach ($bundles as $name => $bundle) {
			$bundle['class'] = 'yii\\web\\AssetBundle';
			$result[$name] = Yii::createObject($bundle);
		}
		foreach ($extensions as $path) {
			$manifest = $path . '/assets.php';
			if (!is_file($manifest)) {
				continue;
			}
			foreach (require($manifest) as $name => $bundle) {
				if (!isset($result[$name])) {
					$bundle['class'] = 'yii\\web\\AssetBundle';
					$result[$name] = Yii::createObject($bundle);
				}
			}
		}
		return $result;
	}

Qiang Xue committed
99 100
	protected function loadTargets($targets, $bundles)
	{
101
		// build the dependency order of bundles
Qiang Xue committed
102 103 104 105 106
		$registered = array();
		foreach ($bundles as $name => $bundle) {
			$this->registerBundle($bundles, $name, $registered);
		}
		$bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1));
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

		// fill up the target which has empty 'depends'.
		$referenced = array();
		foreach ($targets as $name => $target) {
			if (empty($target['depends'])) {
				if (!isset($all)) {
					$all = $name;
				} else {
					throw new Exception("Only one target can have empty 'depends' option. Found two now: $all, $name");
				}
			} else {
				foreach ($target['depends'] as $bundle) {
					if (!isset($referenced[$bundle])) {
						$referenced[$bundle] = $name;
					} else {
						throw new Exception("Target '{$referenced[$bundle]}' and '$name' cannot contain the bundle '$bundle' at the same time.");
					}
				}
			}
		}
		if (isset($all)) {
			$targets[$all]['depends'] = array_diff(array_keys($registered), array_keys($referenced));
		}

		// adjust the 'depends' order for each target according to the dependency order of bundles
		// create an AssetBundle object for each target
Qiang Xue committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
		foreach ($targets as $name => $target) {
			if (!isset($target['basePath'])) {
				throw new Exception("Please specify 'basePath' for the '$name' target.");
			}
			if (!isset($target['baseUrl'])) {
				throw new Exception("Please specify 'baseUrl' for the '$name' target.");
			}
			usort($target['depends'], function ($a, $b) use ($bundleOrders) {
				if ($bundleOrders[$a] == $bundleOrders[$b]) {
					return 0;
				} else {
					return $bundleOrders[$a] > $bundleOrders[$b] ? 1 : -1;
				}
			});
			$target['class'] = 'yii\\web\\AssetBundle';
			$targets[$name] = Yii::createObject($target);
		}
		return $targets;
	}

Qiang Xue committed
153 154 155 156 157
	/**
	 * @param \yii\web\AssetBundle[] $bundles
	 * @param array $options
	 */
	protected function publishBundles($bundles, $options)
Qiang Xue committed
158
	{
Qiang Xue committed
159 160 161 162 163 164 165 166 167 168
		if (!isset($options['class'])) {
			$options['class'] = 'yii\\web\\AssetManager';
		}
		$am = Yii::createObject($options);
		foreach ($bundles as $bundle) {
			$bundle->publish($am);
		}
	}

	/**
Qiang Xue committed
169
	 * @param \yii\web\AssetBundle $target
Qiang Xue committed
170 171 172 173 174
	 * @param string $type either "js" or "css"
	 * @param \yii\web\AssetBundle[] $bundles
	 * @param integer $timestamp
	 * @throws Exception
	 */
Qiang Xue committed
175
	protected function buildTarget($target, $type, $bundles, $timestamp)
Qiang Xue committed
176
	{
Qiang Xue committed
177
		$outputFile = strtr($target->$type, array(
Qiang Xue committed
178 179 180
			'{ts}' => $timestamp,
		));
		$inputFiles = array();
Qiang Xue committed
181 182

		foreach ($target->depends as $name) {
Qiang Xue committed
183 184 185 186 187 188 189 190 191
			if (isset($bundles[$name])) {
				foreach ($bundles[$name]->$type as $file) {
					$inputFiles[] = $bundles[$name]->basePath . '/' . $file;
				}
			} else {
				throw new Exception("Unknown bundle: $name");
			}
		}
		if ($type === 'js') {
Qiang Xue committed
192
			$this->compressJsFiles($inputFiles, $target->basePath . '/' . $outputFile);
Qiang Xue committed
193
		} else {
Qiang Xue committed
194
			$this->compressCssFiles($inputFiles, $target->basePath . '/' . $outputFile);
Qiang Xue committed
195
		}
Qiang Xue committed
196
		$target->$type = array($outputFile);
Qiang Xue committed
197 198 199 200
	}

	protected function adjustDependency($targets, $bundles)
	{
Qiang Xue committed
201 202 203
		$map = array();
		foreach ($targets as $name => $target) {
			foreach ($target->depends as $bundle) {
204
				$map[$bundle] = $name;
Qiang Xue committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
			}
		}

		foreach ($targets as $name => $target) {
			$depends = array();
			foreach ($target->depends as $bn) {
				foreach ($bundles[$bn]->depends as $bundle) {
					$depends[$map[$bundle]] = true;
				}
			}
			unset($depends[$name]);
			$target->depends = array_keys($depends);
		}

		// detect possible circular dependencies
		foreach ($targets as $name => $target) {
			$registered = array();
			$this->registerBundle($targets, $name, $registered);
		}

		foreach ($map as $bundle => $target) {
			$targets[$bundle] = Yii::createObject(array(
				'class' => 'yii\\web\\AssetBundle',
				'depends' => array($target),
			));
		}
Qiang Xue committed
231 232 233
		return $targets;
	}

Qiang Xue committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	protected function registerBundle($bundles, $name, &$registered)
	{
		if (!isset($registered[$name])) {
			$registered[$name] = false;
			$bundle = $bundles[$name];
			foreach ($bundle->depends as $depend) {
				$this->registerBundle($bundles, $depend, $registered);
			}
			unset($registered[$name]);
			$registered[$name] = true;
		} elseif ($registered[$name] === false) {
			throw new Exception("A circular dependency is detected for target '$name'.");
		}
	}

	protected function saveTargets($targets, $bundleFile)
	{
		$array = array();
		foreach ($targets as $name => $target) {
			foreach (array('js', 'css', 'depends', 'basePath', 'baseUrl') as $prop) {
				if (!empty($target->$prop)) {
					$array[$name][$prop] = $target->$prop;
				}
			}
		}
		$array = var_export($array, true);
		$version = date('Y-m-d H:i:s', time());
		file_put_contents($bundleFile, <<<EOD
<?php
/**
264 265
 * This file is generated by the "yiic script" command.
 * DO NOT MODIFY THIS FILE DIRECTLY.
Qiang Xue committed
266 267 268 269 270 271 272
 * @version $version
 */
return $array;
EOD
		);
	}

Qiang Xue committed
273 274
	protected function compressJsFiles($inputFiles, $outputFile)
	{
275 276 277 278 279 280 281 282 283 284 285
		if (is_string($this->jsCompressor)) {
			$tmpFile = $outputFile . '.tmp';
			$this->combineJsFiles($inputFiles, $tmpFile);
			$log = shell_exec(strtr($this->jsCompressor, array(
				'{from}' => $tmpFile,
				'{to}' => $outputFile,
			)));
			@unlink($tmpFile);
		} else {
			$log = call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile);
		}
Qiang Xue committed
286 287 288 289
	}

	protected function compressCssFiles($inputFiles, $outputFile)
	{
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
		if (is_string($this->cssCompressor)) {
			$tmpFile = $outputFile . '.tmp';
			$this->combineCssFiles($inputFiles, $tmpFile);
			$log = shell_exec(strtr($this->cssCompressor, array(
				'{from}' => $inputFiles,
				'{to}' => $outputFile,
			)));
		} else {
			$log = call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile);
		}
	}

	public function combineJsFiles($files, $tmpFile)
	{
		$content = '';
		foreach ($files as $file) {
			$content .= "/*** BEGIN FILE: $file ***/\n"
				. file_get_contents($file)
				. "/*** END FILE: $file ***/\n";
		}
		file_put_contents($tmpFile, $content);
	}

	public function combineCssFiles($files, $tmpFile)
	{
		// todo: adjust url() references in CSS files
		$content = '';
		foreach ($files as $file) {
			$content .= "/*** BEGIN FILE: $file ***/\n"
				. file_get_contents($file)
				. "/*** END FILE: $file ***/\n";
		}
		file_put_contents($tmpFile, $content);
	}

	public function actionTemplate($configFile)
	{
		$template = <<<EOD
<?php

return array(
	//
	'bundles' => require('path/to/bundles.php'),
	//
	'extensions' => require('path/to/namespaces.php'),
	//
	'targets' => array(
		'all' => array(
			'basePath' => __DIR__,
			'baseUrl' => '/test',
			'js' => 'all-{ts}.js',
			'css' => 'all-{ts}.css',
		),
	),
Qiang Xue committed
344

345 346 347 348 349 350 351
	'assetManager' => array(
		'basePath' => __DIR__,
		'baseUrl' => '/test',
	),
);
EOD;
		file_put_contents($configFile, $template);
Qiang Xue committed
352
	}
Zander Baldwin committed
353
}