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

/**
15 16
 * This command allows you to combine and compress your JavaScript and CSS files.
 *
Qiang Xue committed
17 18 19
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
20
class AssetController extends Controller
Qiang Xue committed
21
{
22 23 24
	/**
	 * @var string controller default action ID.
	 */
Qiang Xue committed
25
	public $defaultAction = 'compress';
26 27 28 29 30
	/**
	 * @var array list of asset bundles to be compressed.
	 * The keys are the bundle names, and the values are the configuration
	 * arrays for creating the [[yii\web\AssetBundle]] objects.
	 */
Qiang Xue committed
31
	public $bundles = array();
32 33 34 35
	/**
	 * @var array list of paths to the extensions, which assets should be also compressed.
	 * Each path should contain asset manifest file named "assets.php".
	 */
Qiang Xue committed
36 37
	public $extensions = array();
	/**
38 39 40
	 * @var array list of asset bundles, which represents output compressed files.
	 * You can specify the name of the output compressed file using 'css' and 'js' keys:
	 * For example:
Qiang Xue committed
41 42 43 44 45 46 47
	 * ~~~
	 * 'all' => array(
	 *     'css' => 'all.css',
	 *     'js' => 'js.css',
	 *     'depends' => array( ... ),
	 * )
	 * ~~~
48 49
	 * File names can contain placeholder "{ts}", which will be filled by current timestamp, while
	 * file creation.
Qiang Xue committed
50 51
	 */
	public $targets = array();
52 53 54 55
	/**
	 * @var array configuration for [[yii\web\AssetManager]] instance, which will be used
	 * for assets publishing.
	 */
Qiang Xue committed
56
	public $assetManager = array();
57 58 59 60 61 62 63 64 65
	/**
	 * @var string|callback Java Script file compressor.
	 * If a string, it is treated as shell command template, which should contain
	 * placeholders {from} - source file name - and {to} - output file name.
	 * If an array, it is treated as PHP callback, which should perform the compression.
	 *
	 * Default value relies on usage of "Closure Compiler"
	 * @see https://developers.google.com/closure/compiler/
	 */
66
	public $jsCompressor = 'java -jar compiler.jar --js {from} --js_output_file {to}';
67 68 69 70 71 72 73 74 75
	/**
	 * @var string|callback CSS file compressor.
	 * If a string, it is treated as shell command template, which should contain
	 * placeholders {from} - source file name - and {to} - output file name.
	 * If an array, it is treated as PHP callback, which should perform the compression.
	 *
	 * Default value relies on usage of "YUI Compressor"
	 * @see https://github.com/yui/yuicompressor/
	 */
76
	public $cssCompressor = 'java -jar yuicompressor.jar {from} -o {to}';
Qiang Xue committed
77

78
	/**
79
	 * Combines and compresses the asset files according to the given configuration.
80 81
	 * During the process new asset bundle configuration file will be created.
	 * You should replace your original asset bundle configuration with this file in order to use compressed files.
82
	 * @param string $configFile configuration file name.
83
	 * @param string $bundleFile output asset bundles configuration file name.
84
	 */
Qiang Xue committed
85 86 87 88
	public function actionCompress($configFile, $bundleFile)
	{
		$this->loadConfiguration($configFile);
		$bundles = $this->loadBundles($this->bundles, $this->extensions);
Qiang Xue committed
89
		$targets = $this->loadTargets($this->targets, $bundles);
90
		$this->publishBundles($bundles, $this->assetManager);
Qiang Xue committed
91
		$timestamp = time();
92 93
		foreach ($targets as $name => $target) {
			echo "Creating output bundle '{$name}':\n";
Qiang Xue committed
94
			if (!empty($target->js)) {
Qiang Xue committed
95 96
				$this->buildTarget($target, 'js', $bundles, $timestamp);
			}
Qiang Xue committed
97
			if (!empty($target->css)) {
Qiang Xue committed
98 99
				$this->buildTarget($target, 'css', $bundles, $timestamp);
			}
100
			echo "\n";
Qiang Xue committed
101 102 103
		}

		$targets = $this->adjustDependency($targets, $bundles);
Qiang Xue committed
104
		$this->saveTargets($targets, $bundleFile);
Qiang Xue committed
105 106
	}

107 108 109 110 111
	/**
	 * Applies configuration from the given file to self instance.
	 * @param string $configFile configuration file name.
	 * @throws \yii\console\Exception on failure.
	 */
Qiang Xue committed
112 113
	protected function loadConfiguration($configFile)
	{
114 115
		echo "Loading configuration from '{$configFile}'...\n";

Qiang Xue committed
116 117 118 119
		foreach (require($configFile) as $name => $value) {
			if (property_exists($this, $name)) {
				$this->$name = $value;
			} else {
Qiang Xue committed
120
				throw new Exception("Unknown configuration option: $name");
Qiang Xue committed
121 122 123
			}
		}

Qiang Xue committed
124 125
		if (!isset($this->assetManager['basePath'])) {
			throw new Exception("Please specify 'basePath' for the 'assetManager' option.");
Qiang Xue committed
126
		}
Qiang Xue committed
127 128
		if (!isset($this->assetManager['baseUrl'])) {
			throw new Exception("Please specify 'baseUrl' for the 'assetManager' option.");
Qiang Xue committed
129 130 131
		}
	}

132
	/**
133
	 * Creates full list of source asset bundles.
134 135
	 * @param array[] $bundles list of asset bundle configurations.
	 * @param array $extensions list of the extension paths.
136
	 * @return \yii\web\AssetBundle[] list of source asset bundles.
137
	 */
Qiang Xue committed
138 139
	protected function loadBundles($bundles, $extensions)
	{
140
		echo "Collecting source bundles information...\n";
Qiang Xue committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
		$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;
	}

161
	/**
162 163 164 165
	 * Creates full list of output asset bundles.
	 * @param array $targets output asset bundles configuration.
	 * @param \yii\web\AssetBundle[] $bundles list of source asset bundles.
	 * @return \yii\web\AssetBundle[] list of output asset bundles.
166 167
	 * @throws \yii\console\Exception on failure.
	 */
Qiang Xue committed
168 169
	protected function loadTargets($targets, $bundles)
	{
170
		// build the dependency order of bundles
Qiang Xue committed
171 172 173 174 175
		$registered = array();
		foreach ($bundles as $name => $bundle) {
			$this->registerBundle($bundles, $name, $registered);
		}
		$bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1));
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

		// 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
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
		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
222
	/**
223 224 225
	 * Publishes given asset bundles.
	 * @param \yii\web\AssetBundle[] $bundles asset bundles to be published.
	 * @param array $options assert manager instance configuration.
Qiang Xue committed
226 227
	 */
	protected function publishBundles($bundles, $options)
Qiang Xue committed
228
	{
229
		echo "\nPublishing bundles:\n";
Qiang Xue committed
230 231 232 233
		if (!isset($options['class'])) {
			$options['class'] = 'yii\\web\\AssetManager';
		}
		$am = Yii::createObject($options);
234
		foreach ($bundles as $name => $bundle) {
Qiang Xue committed
235
			$bundle->publish($am);
236
			echo "  '".$name."' published.\n";
Qiang Xue committed
237
		}
238
		echo "\n";
Qiang Xue committed
239 240 241
	}

	/**
242 243 244 245 246 247
	 * Builds output asset bundle.
	 * @param \yii\web\AssetBundle $target output asset bundle
	 * @param string $type either "js" or "css".
	 * @param \yii\web\AssetBundle[] $bundles source asset bundles.
	 * @param integer $timestamp current timestamp.
	 * @throws Exception on failure.
Qiang Xue committed
248
	 */
Qiang Xue committed
249
	protected function buildTarget($target, $type, $bundles, $timestamp)
Qiang Xue committed
250
	{
Qiang Xue committed
251
		$outputFile = strtr($target->$type, array(
Qiang Xue committed
252 253 254
			'{ts}' => $timestamp,
		));
		$inputFiles = array();
Qiang Xue committed
255 256

		foreach ($target->depends as $name) {
Qiang Xue committed
257 258
			if (isset($bundles[$name])) {
				foreach ($bundles[$name]->$type as $file) {
259
					$inputFiles[] = $bundles[$name]->basePath . '/' . $file;
Qiang Xue committed
260 261 262 263 264 265
				}
			} else {
				throw new Exception("Unknown bundle: $name");
			}
		}
		if ($type === 'js') {
Qiang Xue committed
266
			$this->compressJsFiles($inputFiles, $target->basePath . '/' . $outputFile);
Qiang Xue committed
267
		} else {
Qiang Xue committed
268
			$this->compressCssFiles($inputFiles, $target->basePath . '/' . $outputFile);
Qiang Xue committed
269
		}
Qiang Xue committed
270
		$target->$type = array($outputFile);
Qiang Xue committed
271 272
	}

273
	/**
274 275 276 277
	 * Adjust dependencies between asset bundles in the way source bundles begin to depend on output ones.
	 * @param \yii\web\AssetBundle[] $targets output asset bundles.
	 * @param \yii\web\AssetBundle[] $bundles source asset bundles.
	 * @return \yii\web\AssetBundle[] output asset bundles.
278
	 */
Qiang Xue committed
279 280
	protected function adjustDependency($targets, $bundles)
	{
281 282
		echo "Creating new bundle configuration...\n";

Qiang Xue committed
283 284 285
		$map = array();
		foreach ($targets as $name => $target) {
			foreach ($target->depends as $bundle) {
286
				$map[$bundle] = $name;
Qiang Xue committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
			}
		}

		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
313 314 315
		return $targets;
	}

316 317 318 319 320 321 322
	/**
	 * Registers asset bundles including their dependencies.
	 * @param \yii\web\AssetBundle[] $bundles asset bundles list.
	 * @param string $name bundle name.
	 * @param array $registered stores already registered names.
	 * @throws \yii\console\Exception if circular dependency is detected.
	 */
Qiang Xue committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	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'.");
		}
	}

338 339 340 341 342
	/**
	 * Saves new asset bundles configuration.
	 * @param \yii\web\AssetBundle[] $targets list of asset bundles to be saved.
	 * @param string $bundleFile output file name.
	 */
Qiang Xue committed
343 344 345 346 347 348 349 350 351 352 353 354
	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());
355
		$bytesWritten = file_put_contents($bundleFile, <<<EOD
Qiang Xue committed
356 357
<?php
/**
358
 * This file is generated by the "yii script" command.
359
 * DO NOT MODIFY THIS FILE DIRECTLY.
Qiang Xue committed
360 361 362 363 364
 * @version $version
 */
return $array;
EOD
		);
365 366 367 368
		if ($bytesWritten <= 0) {
			throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
		}
		echo "Output bundle configuration created at '{$bundleFile}'.\n";
Qiang Xue committed
369 370
	}

371 372 373 374
	/**
	 * Compresses given Java Script files and combines them into the single one.
	 * @param array $inputFiles list of source file names.
	 * @param string $outputFile output file name.
375
	 * @throws \yii\console\Exception on failure
376
	 */
Qiang Xue committed
377 378
	protected function compressJsFiles($inputFiles, $outputFile)
	{
379 380 381 382
		if (empty($inputFiles)) {
			return;
		}
		echo "  Compressing JavaScript files...\n";
383 384 385
		if (is_string($this->jsCompressor)) {
			$tmpFile = $outputFile . '.tmp';
			$this->combineJsFiles($inputFiles, $tmpFile);
386
			echo shell_exec(strtr($this->jsCompressor, array(
387 388
				'{from}' => escapeshellarg($tmpFile),
				'{to}' => escapeshellarg($outputFile),
389 390 391
			)));
			@unlink($tmpFile);
		} else {
392
			call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile);
393
		}
394 395 396 397
		if (!file_exists($outputFile)) {
			throw new Exception("Unable to compress JavaScript files into '{$outputFile}'.");
		}
		echo "  JavaScript files compressed into '{$outputFile}'.\n";
Qiang Xue committed
398 399
	}

400 401 402 403
	/**
	 * Compresses given CSS files and combines them into the single one.
	 * @param array $inputFiles list of source file names.
	 * @param string $outputFile output file name.
404
	 * @throws \yii\console\Exception on failure
405
	 */
Qiang Xue committed
406 407
	protected function compressCssFiles($inputFiles, $outputFile)
	{
408 409 410 411
		if (empty($inputFiles)) {
			return;
		}
		echo "  Compressing CSS files...\n";
412 413 414
		if (is_string($this->cssCompressor)) {
			$tmpFile = $outputFile . '.tmp';
			$this->combineCssFiles($inputFiles, $tmpFile);
415
			echo shell_exec(strtr($this->cssCompressor, array(
416 417
				'{from}' => escapeshellarg($tmpFile),
				'{to}' => escapeshellarg($outputFile),
418
			)));
419
			@unlink($tmpFile);
420
		} else {
421
			call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile);
422
		}
423 424 425 426
		if (!file_exists($outputFile)) {
			throw new Exception("Unable to compress CSS files into '{$outputFile}'.");
		}
		echo "  CSS files compressed into '{$outputFile}'.\n";
427 428
	}

429 430 431 432 433 434
	/**
	 * Combines Java Script files into a single one.
	 * @param array $inputFiles source file names.
	 * @param string $outputFile output file name.
	 */
	public function combineJsFiles($inputFiles, $outputFile)
435 436
	{
		$content = '';
437
		foreach ($inputFiles as $file) {
438 439 440 441
			$content .= "/*** BEGIN FILE: $file ***/\n"
				. file_get_contents($file)
				. "/*** END FILE: $file ***/\n";
		}
442
		file_put_contents($outputFile, $content);
443 444
	}

445 446 447 448 449 450
	/**
	 * Combines CSS files into a single one.
	 * @param array $inputFiles source file names.
	 * @param string $outputFile output file name.
	 */
	public function combineCssFiles($inputFiles, $outputFile)
451 452 453
	{
		// todo: adjust url() references in CSS files
		$content = '';
454
		foreach ($inputFiles as $file) {
455 456 457 458
			$content .= "/*** BEGIN FILE: $file ***/\n"
				. file_get_contents($file)
				. "/*** END FILE: $file ***/\n";
		}
459
		file_put_contents($outputFile, $content);
460 461
	}

462 463 464 465
	/**
	 * Creates template of configuration file for [[actionCompress]].
	 * @param string $configFile output file name.
	 */
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
	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
485

486 487 488 489 490 491
	'assetManager' => array(
		'basePath' => __DIR__,
		'baseUrl' => '/test',
	),
);
EOD;
492 493 494 495 496 497 498 499 500 501 502
		if (file_exists($configFile)) {
			if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
				return;
			}
		}
		$bytesWritten = file_put_contents($configFile, $template);
		if ($bytesWritten<=0) {
			echo "Error: unable to write file '{$configFile}'!\n\n";
		} else {
			echo "Configuration file template created at '{$configFile}'.\n\n";
		}
Qiang Xue committed
503
	}
Zander Baldwin committed
504
}