AssetController.php 19.5 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
 * Allows you to combine and compress your JavaScript and CSS files.
16
 *
17 18 19 20 21 22 23 24
 * Usage:
 * 1. Create a configuration file using 'template' action:
 *    yii asset/template /path/to/myapp/config.php
 * 2. Edit the created config file, adjusting it for your web application needs.
 * 3. Run the 'compress' action, using created config:
 *    yii asset /path/to/myapp/config.php /path/to/myapp/config/assets_compressed.php
 * 4. Adjust your web application config to use compressed assets.
 *
25
 * Note: in the console environment some path aliases like '@webroot' and '@web' may not exist,
26 27 28 29 30
 * so corresponding paths inside the configuration should be specified directly.
 *
 * Note: by default this command relies on an external tools to perform actual files compression,
 * check [[jsCompressor]] and [[cssCompressor]] for more details.
 *
31 32
 * @property \yii\web\AssetManager $assetManager Asset manager instance. Note that the type of this property
 * differs in getter and setter. See [[getAssetManager()]] and [[setAssetManager()]] for details.
33
 *
Qiang Xue committed
34 35 36
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
37
class AssetController extends Controller
Qiang Xue committed
38
{
39 40 41
	/**
	 * @var string controller default action ID.
	 */
Qiang Xue committed
42
	public $defaultAction = 'compress';
43 44 45
	/**
	 * @var array list of asset bundles to be compressed.
	 */
Alexander Makarov committed
46
	public $bundles = [];
Qiang Xue committed
47
	/**
48 49 50
	 * @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
51
	 *
Qiang Xue committed
52
	 * ~~~
Alexander Makarov committed
53
	 * 'app\config\AllAsset' => [
Qiang Xue committed
54 55
	 *     'js' => 'js/all-{ts}.js',
	 *     'css' => 'css/all-{ts}.css',
Alexander Makarov committed
56 57
	 *     'depends' => [ ... ],
	 * ]
Qiang Xue committed
58
	 * ~~~
Qiang Xue committed
59
	 *
60 61
	 * File names can contain placeholder "{ts}", which will be filled by current timestamp, while
	 * file creation.
Qiang Xue committed
62
	 */
Alexander Makarov committed
63
	public $targets = [];
64
	/**
Carsten Brandt committed
65
	 * @var string|callable JavaScript file compressor.
66 67
	 * If a string, it is treated as shell command template, which should contain
	 * placeholders {from} - source file name - and {to} - output file name.
68
	 * Otherwise, it is treated as PHP callback, which should perform the compression.
69 70 71 72
	 *
	 * Default value relies on usage of "Closure Compiler"
	 * @see https://developers.google.com/closure/compiler/
	 */
73
	public $jsCompressor = 'java -jar compiler.jar --js {from} --js_output_file {to}';
74
	/**
Carsten Brandt committed
75
	 * @var string|callable CSS file compressor.
76 77
	 * If a string, it is treated as shell command template, which should contain
	 * placeholders {from} - source file name - and {to} - output file name.
78
	 * Otherwise, it is treated as PHP callback, which should perform the compression.
79 80 81 82
	 *
	 * Default value relies on usage of "YUI Compressor"
	 * @see https://github.com/yui/yuicompressor/
	 */
83
	public $cssCompressor = 'java -jar yuicompressor.jar --type css {from} -o {to}';
Qiang Xue committed
84

Qiang Xue committed
85
	/**
86
	 * @var array|\yii\web\AssetManager [[\yii\web\AssetManager]] instance or its array configuration, which will be used
Qiang Xue committed
87 88
	 * for assets processing.
	 */
Alexander Makarov committed
89
	private $_assetManager = [];
Qiang Xue committed
90

Carsten Brandt committed
91

92
	/**
93 94
	 * Returns the asset manager instance.
	 * @throws \yii\console\Exception on invalid configuration.
95 96 97 98 99 100 101 102 103
	 * @return \yii\web\AssetManager asset manager instance.
	 */
	public function getAssetManager()
	{
		if (!is_object($this->_assetManager)) {
			$options = $this->_assetManager;
			if (!isset($options['class'])) {
				$options['class'] = 'yii\\web\\AssetManager';
			}
104 105 106 107 108 109
			if (!isset($options['basePath'])) {
				throw new Exception("Please specify 'basePath' for the 'assetManager' option.");
			}
			if (!isset($options['baseUrl'])) {
				throw new Exception("Please specify 'baseUrl' for the 'assetManager' option.");
			}
110 111 112 113 114 115
			$this->_assetManager = Yii::createObject($options);
		}
		return $this->_assetManager;
	}

	/**
116
	 * Sets asset manager instance or configuration.
117 118 119 120 121 122 123 124 125 126 127
	 * @param \yii\web\AssetManager|array $assetManager asset manager instance or its array configuration.
	 * @throws \yii\console\Exception on invalid argument type.
	 */
	public function setAssetManager($assetManager)
	{
		if (is_scalar($assetManager)) {
			throw new Exception('"' . get_class($this) . '::assetManager" should be either object or array - "' . gettype($assetManager) . '" given.');
		}
		$this->_assetManager = $assetManager;
	}

128
	/**
129
	 * Combines and compresses the asset files according to the given configuration.
130 131
	 * 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.
132
	 * @param string $configFile configuration file name.
133
	 * @param string $bundleFile output asset bundles configuration file name.
134
	 */
Qiang Xue committed
135 136 137
	public function actionCompress($configFile, $bundleFile)
	{
		$this->loadConfiguration($configFile);
Qiang Xue committed
138
		$bundles = $this->loadBundles($this->bundles);
Qiang Xue committed
139
		$targets = $this->loadTargets($this->targets, $bundles);
Qiang Xue committed
140
		$timestamp = time();
141 142
		foreach ($targets as $name => $target) {
			echo "Creating output bundle '{$name}':\n";
Qiang Xue committed
143
			if (!empty($target->js)) {
Qiang Xue committed
144 145
				$this->buildTarget($target, 'js', $bundles, $timestamp);
			}
Qiang Xue committed
146
			if (!empty($target->css)) {
Qiang Xue committed
147 148
				$this->buildTarget($target, 'css', $bundles, $timestamp);
			}
149
			echo "\n";
Qiang Xue committed
150 151 152
		}

		$targets = $this->adjustDependency($targets, $bundles);
Qiang Xue committed
153
		$this->saveTargets($targets, $bundleFile);
Qiang Xue committed
154 155
	}

156 157 158 159 160
	/**
	 * Applies configuration from the given file to self instance.
	 * @param string $configFile configuration file name.
	 * @throws \yii\console\Exception on failure.
	 */
Qiang Xue committed
161 162
	protected function loadConfiguration($configFile)
	{
163
		echo "Loading configuration from '{$configFile}'...\n";
Qiang Xue committed
164
		foreach (require($configFile) as $name => $value) {
165
			if (property_exists($this, $name) || $this->canSetProperty($name)) {
Qiang Xue committed
166 167
				$this->$name = $value;
			} else {
Qiang Xue committed
168
				throw new Exception("Unknown configuration option: $name");
Qiang Xue committed
169 170 171
			}
		}

172
		$this->getAssetManager(); // check if asset manager configuration is correct
Qiang Xue committed
173 174
	}

175
	/**
176
	 * Creates full list of source asset bundles.
Qiang Xue committed
177
	 * @param string[] $bundles list of asset bundle names
178
	 * @return \yii\web\AssetBundle[] list of source asset bundles.
179
	 */
Qiang Xue committed
180
	protected function loadBundles($bundles)
Qiang Xue committed
181
	{
182
		echo "Collecting source bundles information...\n";
183

Qiang Xue committed
184
		$am = $this->getAssetManager();
Alexander Makarov committed
185
		$result = [];
Qiang Xue committed
186 187
		foreach ($bundles as $name) {
			$result[$name] = $am->getBundle($name);
Qiang Xue committed
188
		}
Qiang Xue committed
189 190
		foreach ($result as $bundle) {
			$this->loadDependency($bundle, $result);
191 192
		}

Qiang Xue committed
193 194 195
		return $result;
	}

196 197 198 199
	/**
	 * Loads asset bundle dependencies recursively.
	 * @param \yii\web\AssetBundle $bundle bundle instance
	 * @param array $result already loaded bundles list.
Qiang Xue committed
200
	 * @throws Exception on failure.
201
	 */
Qiang Xue committed
202
	protected function loadDependency($bundle, &$result)
resurtm committed
203
	{
Qiang Xue committed
204 205 206 207 208 209 210 211 212
		$am = $this->getAssetManager();
		foreach ($bundle->depends as $name) {
			if (!isset($result[$name])) {
				$dependencyBundle = $am->getBundle($name);
				$result[$name] = false;
				$this->loadDependency($dependencyBundle, $result);
				$result[$name] = $dependencyBundle;
			} elseif ($result[$name] === false) {
				throw new Exception("A circular dependency is detected for bundle '$name'.");
213 214 215 216
			}
		}
	}

217
	/**
218 219 220 221
	 * 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.
Qiang Xue committed
222
	 * @throws Exception on failure.
223
	 */
Qiang Xue committed
224 225
	protected function loadTargets($targets, $bundles)
	{
226
		// build the dependency order of bundles
Alexander Makarov committed
227
		$registered = [];
Qiang Xue committed
228 229 230 231
		foreach ($bundles as $name => $bundle) {
			$this->registerBundle($bundles, $name, $registered);
		}
		$bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1));
232 233

		// fill up the target which has empty 'depends'.
Alexander Makarov committed
234
		$referenced = [];
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
		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
258 259 260 261 262 263 264 265 266 267 268 269 270 271
		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;
				}
			});
Qiang Xue committed
272
			$target['class'] = $name;
Qiang Xue committed
273 274 275 276 277
			$targets[$name] = Yii::createObject($target);
		}
		return $targets;
	}

Qiang Xue committed
278
	/**
279 280
	 * Builds output asset bundle.
	 * @param \yii\web\AssetBundle $target output asset bundle
281
	 * @param string $type either 'js' or 'css'.
282 283 284
	 * @param \yii\web\AssetBundle[] $bundles source asset bundles.
	 * @param integer $timestamp current timestamp.
	 * @throws Exception on failure.
Qiang Xue committed
285
	 */
Qiang Xue committed
286
	protected function buildTarget($target, $type, $bundles, $timestamp)
Qiang Xue committed
287
	{
Alexander Makarov committed
288
		$outputFile = strtr($target->$type, [
Qiang Xue committed
289
			'{ts}' => $timestamp,
Alexander Makarov committed
290 291
		]);
		$inputFiles = [];
Qiang Xue committed
292 293

		foreach ($target->depends as $name) {
Qiang Xue committed
294 295
			if (isset($bundles[$name])) {
				foreach ($bundles[$name]->$type as $file) {
296
					$inputFiles[] = $bundles[$name]->basePath . '/' . $file;
Qiang Xue committed
297 298
				}
			} else {
299
				throw new Exception("Unknown bundle: '{$name}'");
Qiang Xue committed
300 301 302
			}
		}
		if ($type === 'js') {
Qiang Xue committed
303
			$this->compressJsFiles($inputFiles, $target->basePath . '/' . $outputFile);
Qiang Xue committed
304
		} else {
Qiang Xue committed
305
			$this->compressCssFiles($inputFiles, $target->basePath . '/' . $outputFile);
Qiang Xue committed
306
		}
Alexander Makarov committed
307
		$target->$type = [$outputFile];
Qiang Xue committed
308 309
	}

310
	/**
311 312 313 314
	 * 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.
315
	 */
Qiang Xue committed
316 317
	protected function adjustDependency($targets, $bundles)
	{
318 319
		echo "Creating new bundle configuration...\n";

Alexander Makarov committed
320
		$map = [];
Qiang Xue committed
321 322
		foreach ($targets as $name => $target) {
			foreach ($target->depends as $bundle) {
323
				$map[$bundle] = $name;
Qiang Xue committed
324 325 326 327
			}
		}

		foreach ($targets as $name => $target) {
Alexander Makarov committed
328
			$depends = [];
Qiang Xue committed
329 330 331 332 333 334 335 336 337 338 339
			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) {
Alexander Makarov committed
340
			$registered = [];
Qiang Xue committed
341 342 343 344
			$this->registerBundle($targets, $name, $registered);
		}

		foreach ($map as $bundle => $target) {
Alexander Makarov committed
345
			$targets[$bundle] = Yii::createObject([
Qiang Xue committed
346
				'class' => 'yii\\web\\AssetBundle',
Alexander Makarov committed
347 348
				'depends' => [$target],
			]);
Qiang Xue committed
349
		}
Qiang Xue committed
350 351 352
		return $targets;
	}

353 354 355 356 357
	/**
	 * 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.
Qiang Xue committed
358
	 * @throws Exception if circular dependency is detected.
359
	 */
Qiang Xue committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
	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'.");
		}
	}

375 376 377 378
	/**
	 * Saves new asset bundles configuration.
	 * @param \yii\web\AssetBundle[] $targets list of asset bundles to be saved.
	 * @param string $bundleFile output file name.
379
	 * @throws \yii\console\Exception on failure.
380
	 */
Qiang Xue committed
381 382
	protected function saveTargets($targets, $bundleFile)
	{
Alexander Makarov committed
383
		$array = [];
Qiang Xue committed
384
		foreach ($targets as $name => $target) {
385
			foreach (['basePath', 'baseUrl', 'js', 'css', 'depends'] as $prop) {
Qiang Xue committed
386 387
				if (!empty($target->$prop)) {
					$array[$name][$prop] = $target->$prop;
388 389
				} elseif (in_array($prop, ['js', 'css'])) {
					$array[$name][$prop] = [];
Qiang Xue committed
390 391 392 393 394
				}
			}
		}
		$array = var_export($array, true);
		$version = date('Y-m-d H:i:s', time());
395
		$bundleFileContent = <<<EOD
Qiang Xue committed
396 397
<?php
/**
398
 * This file is generated by the "yii {$this->id}" command.
399
 * DO NOT MODIFY THIS FILE DIRECTLY.
400
 * @version {$version}
Qiang Xue committed
401
 */
402
return {$array};
403 404
EOD;
		if (!file_put_contents($bundleFile, $bundleFileContent)) {
405 406 407
			throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
		}
		echo "Output bundle configuration created at '{$bundleFile}'.\n";
Qiang Xue committed
408 409
	}

410
	/**
411
	 * Compresses given JavaScript files and combines them into the single one.
412 413
	 * @param array $inputFiles list of source file names.
	 * @param string $outputFile output file name.
414
	 * @throws \yii\console\Exception on failure
415
	 */
Qiang Xue committed
416 417
	protected function compressJsFiles($inputFiles, $outputFile)
	{
418 419 420 421
		if (empty($inputFiles)) {
			return;
		}
		echo "  Compressing JavaScript files...\n";
422 423 424
		if (is_string($this->jsCompressor)) {
			$tmpFile = $outputFile . '.tmp';
			$this->combineJsFiles($inputFiles, $tmpFile);
Alexander Makarov committed
425
			echo shell_exec(strtr($this->jsCompressor, [
426 427
				'{from}' => escapeshellarg($tmpFile),
				'{to}' => escapeshellarg($outputFile),
Alexander Makarov committed
428
			]));
429 430
			@unlink($tmpFile);
		} else {
431
			call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile);
432
		}
433 434 435 436
		if (!file_exists($outputFile)) {
			throw new Exception("Unable to compress JavaScript files into '{$outputFile}'.");
		}
		echo "  JavaScript files compressed into '{$outputFile}'.\n";
Qiang Xue committed
437 438
	}

439 440 441 442
	/**
	 * 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.
443
	 * @throws \yii\console\Exception on failure
444
	 */
Qiang Xue committed
445 446
	protected function compressCssFiles($inputFiles, $outputFile)
	{
447 448 449 450
		if (empty($inputFiles)) {
			return;
		}
		echo "  Compressing CSS files...\n";
451 452 453
		if (is_string($this->cssCompressor)) {
			$tmpFile = $outputFile . '.tmp';
			$this->combineCssFiles($inputFiles, $tmpFile);
Alexander Makarov committed
454
			echo shell_exec(strtr($this->cssCompressor, [
455 456
				'{from}' => escapeshellarg($tmpFile),
				'{to}' => escapeshellarg($outputFile),
Alexander Makarov committed
457
			]));
458
			@unlink($tmpFile);
459
		} else {
460
			call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile);
461
		}
462 463 464 465
		if (!file_exists($outputFile)) {
			throw new Exception("Unable to compress CSS files into '{$outputFile}'.");
		}
		echo "  CSS files compressed into '{$outputFile}'.\n";
466 467
	}

468
	/**
469
	 * Combines JavaScript files into a single one.
470 471
	 * @param array $inputFiles source file names.
	 * @param string $outputFile output file name.
472
	 * @throws \yii\console\Exception on failure.
473 474
	 */
	public function combineJsFiles($inputFiles, $outputFile)
475 476
	{
		$content = '';
477
		foreach ($inputFiles as $file) {
478 479 480 481
			$content .= "/*** BEGIN FILE: $file ***/\n"
				. file_get_contents($file)
				. "/*** END FILE: $file ***/\n";
		}
482
		if (!file_put_contents($outputFile, $content)) {
483
			throw new Exception("Unable to write output JavaScript file '{$outputFile}'.");
484
		}
485 486
	}

487 488 489 490
	/**
	 * Combines CSS files into a single one.
	 * @param array $inputFiles source file names.
	 * @param string $outputFile output file name.
491
	 * @throws \yii\console\Exception on failure.
492 493
	 */
	public function combineCssFiles($inputFiles, $outputFile)
494 495
	{
		$content = '';
496
		foreach ($inputFiles as $file) {
497
			$content .= "/*** BEGIN FILE: $file ***/\n"
498
				. $this->adjustCssUrl(file_get_contents($file), dirname($file), dirname($outputFile))
499 500
				. "/*** END FILE: $file ***/\n";
		}
501 502 503
		if (!file_put_contents($outputFile, $content)) {
			throw new Exception("Unable to write output CSS file '{$outputFile}'.");
		}
504 505
	}

506 507 508 509 510 511 512 513 514
	/**
	 * Adjusts CSS content allowing URL references pointing to the original resources.
	 * @param string $cssContent source CSS content.
	 * @param string $inputFilePath input CSS file name.
	 * @param string $outputFilePath output CSS file name.
	 * @return string adjusted CSS content.
	 */
	protected function adjustCssUrl($cssContent, $inputFilePath, $outputFilePath)
	{
Alexander Makarov committed
515
		$sharedPathParts = [];
516 517 518 519 520 521 522 523
		$inputFilePathParts = explode('/', $inputFilePath);
		$inputFilePathPartsCount = count($inputFilePathParts);
		$outputFilePathParts = explode('/', $outputFilePath);
		$outputFilePathPartsCount = count($outputFilePathParts);
		for ($i =0; $i < $inputFilePathPartsCount && $i < $outputFilePathPartsCount; $i++) {
			if ($inputFilePathParts[$i] == $outputFilePathParts[$i]) {
				$sharedPathParts[] = $inputFilePathParts[$i];
			} else {
524 525 526
				break;
			}
		}
527 528
		$sharedPath = implode('/', $sharedPathParts);

529 530 531 532 533
		$inputFileRelativePath = trim(str_replace($sharedPath, '', $inputFilePath), '/');
		$outputFileRelativePath = trim(str_replace($sharedPath, '', $outputFilePath), '/');
		$inputFileRelativePathParts = explode('/', $inputFileRelativePath);
		$outputFileRelativePathParts = explode('/', $outputFileRelativePath);

resurtm committed
534
		$callback = function ($matches) use ($inputFileRelativePathParts, $outputFileRelativePathParts) {
535 536 537
			$fullMatch = $matches[0];
			$inputUrl = $matches[1];

538 539 540 541
			if (preg_match('/https?:\/\//is', $inputUrl)) {
				return $fullMatch;
			}

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
			$outputUrlParts = array_fill(0, count($outputFileRelativePathParts), '..');
			$outputUrlParts = array_merge($outputUrlParts, $inputFileRelativePathParts);

			if (strpos($inputUrl, '/') !== false) {
				$inputUrlParts = explode('/', $inputUrl);
				foreach ($inputUrlParts as $key => $inputUrlPart) {
					if ($inputUrlPart == '..') {
						array_pop($outputUrlParts);
						unset($inputUrlParts[$key]);
					}
				}
				$outputUrlParts[] = implode('/', $inputUrlParts);
			} else {
				$outputUrlParts[] = $inputUrl;
			}
			$outputUrl = implode('/', $outputUrlParts);
558 559

			return str_replace($inputUrl, $outputUrl, $fullMatch);
560
		};
561

562
		$cssContent = preg_replace_callback('/url\(["\']?([^)^"^\']*)["\']?\)/is', $callback, $cssContent);
563 564 565 566

		return $cssContent;
	}

567 568 569
	/**
	 * Creates template of configuration file for [[actionCompress]].
	 * @param string $configFile output file name.
570
	 * @throws \yii\console\Exception on failure.
571
	 */
572 573 574 575
	public function actionTemplate($configFile)
	{
		$template = <<<EOD
<?php
576 577
/**
 * Configuration file for the "yii asset" console command.
578
 * Note that in the console environment, some path aliases like '@webroot' and '@web' may not exist.
Qiang Xue committed
579
 * Please define these missing path aliases.
580
 */
Alexander Makarov committed
581
return [
582
	// The list of asset bundles to compress:
Alexander Makarov committed
583
	'bundles' => [
Qiang Xue committed
584 585
		// 'yii\web\YiiAsset',
		// 'yii\web\JqueryAsset',
Alexander Makarov committed
586
	],
587
	// Asset bundle for compression output:
Alexander Makarov committed
588
	'targets' => [
589
		'app\assets\AllAsset' => [
590
			'basePath' => 'path/to/web',
Qiang Xue committed
591 592 593
			'baseUrl' => '',
			'js' => 'js/all-{ts}.js',
			'css' => 'css/all-{ts}.css',
Alexander Makarov committed
594 595
		],
	],
596
	// Asset manager configuration:
Alexander Makarov committed
597
	'assetManager' => [
598
		'basePath' => __DIR__,
Qiang Xue committed
599
		'baseUrl' => '',
Alexander Makarov committed
600
	],
Qiang Xue committed
601
];
602
EOD;
603 604 605 606 607
		if (file_exists($configFile)) {
			if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
				return;
			}
		}
608 609
		if (!file_put_contents($configFile, $template)) {
			throw new Exception("Unable to write template file '{$configFile}'.");
610 611 612
		} else {
			echo "Configuration file template created at '{$configFile}'.\n\n";
		}
Qiang Xue committed
613
	}
Zander Baldwin committed
614
}