AssetController.php 27.6 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12
<?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;
13
use yii\helpers\Console;
14
use yii\helpers\VarDumper;
15
use yii\web\AssetBundle;
Qiang Xue committed
16 17

/**
18
 * Allows you to combine and compress your JavaScript and CSS files.
19
 *
20
 * Usage:
21
 *
22 23
 * 1. Create a configuration file using the `template` action:
 *
24
 *    yii asset/template /path/to/myapp/config.php
25
 *
26 27
 * 2. Edit the created config file, adjusting it for your web application needs.
 * 3. Run the 'compress' action, using created config:
28
 *
29
 *    yii asset /path/to/myapp/config.php /path/to/myapp/config/assets_compressed.php
30
 *
31 32
 * 4. Adjust your web application config to use compressed assets.
 *
33
 * Note: in the console environment some path aliases like `@webroot` and `@web` may not exist,
34 35 36 37 38
 * 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.
 *
39 40
 * @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.
41
 *
Qiang Xue committed
42 43 44
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
45
class AssetController extends Controller
Qiang Xue committed
46
{
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    /**
     * @var string controller default action ID.
     */
    public $defaultAction = 'compress';
    /**
     * @var array list of asset bundles to be compressed.
     */
    public $bundles = [];
    /**
     * @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:
     *
     * ~~~
     * 'app\config\AllAsset' => [
62 63
     *     'js' => 'js/all-{hash}.js',
     *     'css' => 'css/all-{hash}.css',
64 65 66 67
     *     'depends' => [ ... ],
     * ]
     * ~~~
     *
68
     * File names can contain placeholder "{hash}", which will be filled by the hash of the resulting file.
69 70 71 72 73 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 99
     *
     * You may specify several target bundles in order to compress different groups of assets.
     * In this case you should use 'depends' key to specify, which bundles should be covered with particular
     * target bundle. You may leave 'depends' to be empty for single bundle, which will compress all remaining
     * bundles in this case.
     * For example:
     *
     * ~~~
     * 'app\config\AllShared' => [
     *     'js' => 'js/all-shared-{hash}.js',
     *     'css' => 'css/all-shared-{hash}.css',
     *     'depends' => [
     *         // Include all assets shared between 'backend' and 'frontend'
     *         'yii\web\YiiAsset',
     *         'app\assets\SharedAsset',
     *     ],
     * ],
     * 'app\config\AllBackEnd' => [
     *     'js' => 'js/all-{hash}.js',
     *     'css' => 'css/all-{hash}.css',
     *     'depends' => [
     *         // Include only 'backend' assets:
     *         'app\assets\AdminAsset'
     *     ],
     * ],
     * 'app\config\AllFrontEnd' => [
     *     'js' => 'js/all-{hash}.js',
     *     'css' => 'css/all-{hash}.css',
     *     'depends' => [], // Include all remaining assets
     * ],
     * ~~~
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
     */
    public $targets = [];
    /**
     * @var string|callable JavaScript 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.
     * Otherwise, 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/
     */
    public $jsCompressor = 'java -jar compiler.jar --js {from} --js_output_file {to}';
    /**
     * @var string|callable 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.
     * Otherwise, 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/
     */
    public $cssCompressor = 'java -jar yuicompressor.jar --type css {from} -o {to}';

    /**
     * @var array|\yii\web\AssetManager [[\yii\web\AssetManager]] instance or its array configuration, which will be used
     * for assets processing.
     */
    private $_assetManager = [];

129

130 131 132
    /**
     * Returns the asset manager instance.
     * @throws \yii\console\Exception on invalid configuration.
133
     * @return \yii\web\AssetManager asset manager instance.
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
     */
    public function getAssetManager()
    {
        if (!is_object($this->_assetManager)) {
            $options = $this->_assetManager;
            if (!isset($options['class'])) {
                $options['class'] = 'yii\\web\\AssetManager';
            }
            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.");
            }
            $this->_assetManager = Yii::createObject($options);
        }

        return $this->_assetManager;
    }

    /**
     * Sets asset manager instance or configuration.
156 157
     * @param \yii\web\AssetManager|array $assetManager asset manager instance or its array configuration.
     * @throws \yii\console\Exception on invalid argument type.
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
     */
    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;
    }

    /**
     * Combines and compresses the asset files according to the given configuration.
     * 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.
     * @param string $configFile configuration file name.
     * @param string $bundleFile output asset bundles configuration file name.
     */
    public function actionCompress($configFile, $bundleFile)
    {
        $this->loadConfiguration($configFile);
        $bundles = $this->loadBundles($this->bundles);
        $targets = $this->loadTargets($this->targets, $bundles);
        foreach ($targets as $name => $target) {
180
            $this->stdout("Creating output bundle '{$name}':\n");
181
            if (!empty($target->js)) {
182
                $this->buildTarget($target, 'js', $bundles);
183 184
            }
            if (!empty($target->css)) {
185
                $this->buildTarget($target, 'css', $bundles);
186
            }
187
            $this->stdout("\n");
188 189 190 191 192 193 194 195
        }

        $targets = $this->adjustDependency($targets, $bundles);
        $this->saveTargets($targets, $bundleFile);
    }

    /**
     * Applies configuration from the given file to self instance.
196
     * @param string $configFile configuration file name.
197 198 199 200
     * @throws \yii\console\Exception on failure.
     */
    protected function loadConfiguration($configFile)
    {
201
        $this->stdout("Loading configuration from '{$configFile}'...\n");
202 203 204 205 206 207 208 209 210 211 212 213 214
        foreach (require($configFile) as $name => $value) {
            if (property_exists($this, $name) || $this->canSetProperty($name)) {
                $this->$name = $value;
            } else {
                throw new Exception("Unknown configuration option: $name");
            }
        }

        $this->getAssetManager(); // check if asset manager configuration is correct
    }

    /**
     * Creates full list of source asset bundles.
215
     * @param string[] $bundles list of asset bundle names
216 217 218 219
     * @return \yii\web\AssetBundle[] list of source asset bundles.
     */
    protected function loadBundles($bundles)
    {
220
        $this->stdout("Collecting source bundles information...\n");
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

        $am = $this->getAssetManager();
        $result = [];
        foreach ($bundles as $name) {
            $result[$name] = $am->getBundle($name);
        }
        foreach ($result as $bundle) {
            $this->loadDependency($bundle, $result);
        }

        return $result;
    }

    /**
     * Loads asset bundle dependencies recursively.
236 237 238
     * @param \yii\web\AssetBundle $bundle bundle instance
     * @param array $result already loaded bundles list.
     * @throws Exception on failure.
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
     */
    protected function loadDependency($bundle, &$result)
    {
        $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'.");
            }
        }
    }

    /**
     * Creates full list of output asset bundles.
257 258
     * @param array $targets output asset bundles configuration.
     * @param \yii\web\AssetBundle[] $bundles list of source asset bundles.
259
     * @return \yii\web\AssetBundle[] list of output asset bundles.
260
     * @throws Exception on failure.
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
     */
    protected function loadTargets($targets, $bundles)
    {
        // build the dependency order of bundles
        $registered = [];
        foreach ($bundles as $name => $bundle) {
            $this->registerBundle($bundles, $name, $registered);
        }
        $bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1));

        // fill up the target which has empty 'depends'.
        $referenced = [];
        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
        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;
                }
            });
310 311 312
            if (!isset($target['class'])) {
                $target['class'] = $name;
            }
313 314 315 316 317 318 319 320
            $targets[$name] = Yii::createObject($target);
        }

        return $targets;
    }

    /**
     * Builds output asset bundle.
321 322 323 324
     * @param \yii\web\AssetBundle $target output asset bundle
     * @param string $type either 'js' or 'css'.
     * @param \yii\web\AssetBundle[] $bundles source asset bundles.
     * @throws Exception on failure.
325
     */
326
    protected function buildTarget($target, $type, $bundles)
327
    {
328
        $tempFile = $target->basePath . '/' . strtr($target->$type, ['{hash}' => 'temp']);
329 330 331 332
        $inputFiles = [];

        foreach ($target->depends as $name) {
            if (isset($bundles[$name])) {
333 334 335 336
                if (!$this->isBundleExternal($bundles[$name])) {
                    foreach ($bundles[$name]->$type as $file) {
                        $inputFiles[] = $bundles[$name]->basePath . '/' . $file;
                    }
337 338 339 340 341 342
                }
            } else {
                throw new Exception("Unknown bundle: '{$name}'");
            }
        }
        if ($type === 'js') {
343
            $this->compressJsFiles($inputFiles, $tempFile);
344
        } else {
345
            $this->compressCssFiles($inputFiles, $tempFile);
346
        }
347

348 349
        $targetFile = strtr($target->$type, ['{hash}' => md5_file($tempFile)]);
        $outputFile = $target->basePath . '/' . $targetFile;
350
        rename($tempFile, $outputFile);
351
        $target->$type = [$targetFile];
352 353 354 355
    }

    /**
     * Adjust dependencies between asset bundles in the way source bundles begin to depend on output ones.
356 357
     * @param \yii\web\AssetBundle[] $targets output asset bundles.
     * @param \yii\web\AssetBundle[] $bundles source asset bundles.
358 359 360 361
     * @return \yii\web\AssetBundle[] output asset bundles.
     */
    protected function adjustDependency($targets, $bundles)
    {
362
        $this->stdout("Creating new bundle configuration...\n");
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

        $map = [];
        foreach ($targets as $name => $target) {
            foreach ($target->depends as $bundle) {
                $map[$bundle] = $name;
            }
        }

        foreach ($targets as $name => $target) {
            $depends = [];
            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 = [];
            $this->registerBundle($targets, $name, $registered);
        }

        foreach ($map as $bundle => $target) {
389 390 391 392 393
            $sourceBundle = $bundles[$bundle];
            $depends = $sourceBundle->depends;
            if (!$this->isBundleExternal($sourceBundle)) {
                $depends[] = $target;
            }
394
            $targets[$bundle] = Yii::createObject([
395
                'class' => strpos($bundle, '\\') !== false ? $bundle : 'yii\\web\\AssetBundle',
396
                'depends' => $depends,
397 398 399 400 401 402 403 404
            ]);
        }

        return $targets;
    }

    /**
     * Registers asset bundles including their dependencies.
405 406 407 408
     * @param \yii\web\AssetBundle[] $bundles asset bundles list.
     * @param string $name bundle name.
     * @param array $registered stores already registered names.
     * @throws Exception if circular dependency is detected.
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
     */
    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'.");
        }
    }

    /**
     * Saves new asset bundles configuration.
427 428
     * @param \yii\web\AssetBundle[] $targets list of asset bundles to be saved.
     * @param string $bundleFile output file name.
429 430 431 432 433 434
     * @throws \yii\console\Exception on failure.
     */
    protected function saveTargets($targets, $bundleFile)
    {
        $array = [];
        foreach ($targets as $name => $target) {
435 436 437 438 439 440 441 442 443
            if (isset($this->targets[$name])) {
                $array[$name] = [
                    'class' => get_class($target),
                    'basePath' => $this->targets[$name]['basePath'],
                    'baseUrl' => $this->targets[$name]['baseUrl'],
                    'js' => $target->js,
                    'css' => $target->css,
                ];
            } else {
444 445 446 447 448 449 450 451 452 453
                if ($this->isBundleExternal($target)) {
                    $array[$name] = $this->composeBundleConfig($target);
                } else {
                    $array[$name] = [
                        'sourcePath' => null,
                        'js' => [],
                        'css' => [],
                        'depends' => $target->depends,
                    ];
                }
454 455
            }
        }
456
        $array = VarDumper::export($array);
457 458
        $version = date('Y-m-d H:i:s', time());
        $bundleFileContent = <<<EOD
Qiang Xue committed
459 460
<?php
/**
461
 * This file is generated by the "yii {$this->id}" command.
462
 * DO NOT MODIFY THIS FILE DIRECTLY.
463
 * @version {$version}
Qiang Xue committed
464
 */
465
return {$array};
466
EOD;
467 468 469
        if (!file_put_contents($bundleFile, $bundleFileContent)) {
            throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
        }
470
        $this->stdout("Output bundle configuration created at '{$bundleFile}'.\n", Console::FG_GREEN);
471 472 473 474
    }

    /**
     * Compresses given JavaScript files and combines them into the single one.
475 476
     * @param array $inputFiles list of source file names.
     * @param string $outputFile output file name.
477 478 479 480 481 482 483
     * @throws \yii\console\Exception on failure
     */
    protected function compressJsFiles($inputFiles, $outputFile)
    {
        if (empty($inputFiles)) {
            return;
        }
484
        $this->stdout("  Compressing JavaScript files...\n");
485 486 487
        if (is_string($this->jsCompressor)) {
            $tmpFile = $outputFile . '.tmp';
            $this->combineJsFiles($inputFiles, $tmpFile);
488
            $this->stdout(shell_exec(strtr($this->jsCompressor, [
489 490
                '{from}' => escapeshellarg($tmpFile),
                '{to}' => escapeshellarg($outputFile),
491
            ])));
492 493 494 495 496 497 498
            @unlink($tmpFile);
        } else {
            call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile);
        }
        if (!file_exists($outputFile)) {
            throw new Exception("Unable to compress JavaScript files into '{$outputFile}'.");
        }
499
        $this->stdout("  JavaScript files compressed into '{$outputFile}'.\n");
500 501 502 503
    }

    /**
     * Compresses given CSS files and combines them into the single one.
504 505
     * @param array $inputFiles list of source file names.
     * @param string $outputFile output file name.
506 507 508 509 510 511 512
     * @throws \yii\console\Exception on failure
     */
    protected function compressCssFiles($inputFiles, $outputFile)
    {
        if (empty($inputFiles)) {
            return;
        }
513
        $this->stdout("  Compressing CSS files...\n");
514 515 516
        if (is_string($this->cssCompressor)) {
            $tmpFile = $outputFile . '.tmp';
            $this->combineCssFiles($inputFiles, $tmpFile);
517
            $this->stdout(shell_exec(strtr($this->cssCompressor, [
518 519
                '{from}' => escapeshellarg($tmpFile),
                '{to}' => escapeshellarg($outputFile),
520
            ])));
521 522 523 524 525 526 527
            @unlink($tmpFile);
        } else {
            call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile);
        }
        if (!file_exists($outputFile)) {
            throw new Exception("Unable to compress CSS files into '{$outputFile}'.");
        }
528
        $this->stdout("  CSS files compressed into '{$outputFile}'.\n");
529 530 531 532
    }

    /**
     * Combines JavaScript files into a single one.
533 534
     * @param array $inputFiles source file names.
     * @param string $outputFile output file name.
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
     * @throws \yii\console\Exception on failure.
     */
    public function combineJsFiles($inputFiles, $outputFile)
    {
        $content = '';
        foreach ($inputFiles as $file) {
            $content .= "/*** BEGIN FILE: $file ***/\n"
                . file_get_contents($file)
                . "/*** END FILE: $file ***/\n";
        }
        if (!file_put_contents($outputFile, $content)) {
            throw new Exception("Unable to write output JavaScript file '{$outputFile}'.");
        }
    }

    /**
     * Combines CSS files into a single one.
552 553
     * @param array $inputFiles source file names.
     * @param string $outputFile output file name.
554 555 556 557 558
     * @throws \yii\console\Exception on failure.
     */
    public function combineCssFiles($inputFiles, $outputFile)
    {
        $content = '';
559
        $outputFilePath = dirname($this->findRealPath($outputFile));
560 561
        foreach ($inputFiles as $file) {
            $content .= "/*** BEGIN FILE: $file ***/\n"
562
                . $this->adjustCssUrl(file_get_contents($file), dirname($this->findRealPath($file)), $outputFilePath)
563 564 565 566 567 568 569 570 571
                . "/*** END FILE: $file ***/\n";
        }
        if (!file_put_contents($outputFile, $content)) {
            throw new Exception("Unable to write output CSS file '{$outputFile}'.");
        }
    }

    /**
     * Adjusts CSS content allowing URL references pointing to the original resources.
572 573 574
     * @param string $cssContent source CSS content.
     * @param string $inputFilePath input CSS file name.
     * @param string $outputFilePath output CSS file name.
575 576 577 578
     * @return string adjusted CSS content.
     */
    protected function adjustCssUrl($cssContent, $inputFilePath, $outputFilePath)
    {
579 580 581
        $inputFilePath = str_replace('\\', '/', $inputFilePath);
        $outputFilePath = str_replace('\\', '/', $outputFilePath);

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        $sharedPathParts = [];
        $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 {
                break;
            }
        }
        $sharedPath = implode('/', $sharedPathParts);

        $inputFileRelativePath = trim(str_replace($sharedPath, '', $inputFilePath), '/');
        $outputFileRelativePath = trim(str_replace($sharedPath, '', $outputFilePath), '/');
598 599 600 601 602 603 604 605 606 607
        if (empty($inputFileRelativePath)) {
            $inputFileRelativePathParts = [];
        } else {
            $inputFileRelativePathParts = explode('/', $inputFileRelativePath);
        }
        if (empty($outputFileRelativePath)) {
            $outputFileRelativePathParts = [];
        } else {
            $outputFileRelativePathParts = explode('/', $outputFileRelativePath);
        }
608 609 610 611 612

        $callback = function ($matches) use ($inputFileRelativePathParts, $outputFileRelativePathParts) {
            $fullMatch = $matches[0];
            $inputUrl = $matches[1];

613
            if (strpos($inputUrl, '/') === 0 || preg_match('/^https?:\/\//is', $inputUrl) || preg_match('/^data:/is', $inputUrl)) {
614 615
                return $fullMatch;
            }
616 617 618
            if ($inputFileRelativePathParts === $outputFileRelativePathParts) {
                return $fullMatch;
            }
619

620 621 622 623 624
            if (empty($outputFileRelativePathParts)) {
                $outputUrlParts = [];
            } else {
                $outputUrlParts = array_fill(0, count($outputFileRelativePathParts), '..');
            }
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
            $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);

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

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

        return $cssContent;
    }

    /**
     * Creates template of configuration file for [[actionCompress]].
651
     * @param string $configFile output file name.
652
     * @return integer CLI exit code
653 654 655 656
     * @throws \yii\console\Exception on failure.
     */
    public function actionTemplate($configFile)
    {
657 658
        $jsCompressor = VarDumper::export($this->jsCompressor);
        $cssCompressor = VarDumper::export($this->cssCompressor);
659

660
        $template = <<<EOD
661
<?php
662 663 664
/**
 * Configuration file for the "yii asset" console command.
 */
Alexander Makarov committed
665 666

// In the console environment, some path aliases may not exist. Please define these:
667 668 669
// Yii::setAlias('@webroot', __DIR__ . '/../web');
// Yii::setAlias('@web', '/');

Alexander Makarov committed
670
return [
671 672 673 674
    // Adjust command/callback for JavaScript files compressing:
    'jsCompressor' => {$jsCompressor},
    // Adjust command/callback for CSS files compressing:
    'cssCompressor' => {$cssCompressor},
675 676
    // The list of asset bundles to compress:
    'bundles' => [
677
        // 'app\assets\AppAsset',
678 679 680 681 682
        // 'yii\web\YiiAsset',
        // 'yii\web\JqueryAsset',
    ],
    // Asset bundle for compression output:
    'targets' => [
683 684 685 686
        'all' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot/assets',
            'baseUrl' => '@web/assets',
687 688
            'js' => 'js/all-{hash}.js',
            'css' => 'css/all-{hash}.css',
689 690 691 692
        ],
    ],
    // Asset manager configuration:
    'assetManager' => [
693 694
        //'basePath' => '@webroot/assets',
        //'baseUrl' => '@web/assets',
695
    ],
Qiang Xue committed
696
];
697
EOD;
698 699
        if (file_exists($configFile)) {
            if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
700
                return self::EXIT_CODE_NORMAL;
701 702 703 704 705
            }
        }
        if (!file_put_contents($configFile, $template)) {
            throw new Exception("Unable to write template file '{$configFile}'.");
        } else {
706
            $this->stdout("Configuration file template created at '{$configFile}'.\n\n", Console::FG_GREEN);
707
            return self::EXIT_CODE_NORMAL;
708 709
        }
    }
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

    /**
     * Returns canonicalized absolute pathname.
     * Unlike regular `realpath()` this method does not expand symlinks and does not check path existence.
     * @param string $path raw path
     * @return string canonicalized absolute pathname
     */
    private function findRealPath($path)
    {
        $path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
        $pathParts = explode(DIRECTORY_SEPARATOR, $path);

        $realPathParts = [];
        foreach ($pathParts as $pathPart) {
            if ($pathPart === '..') {
                array_pop($realPathParts);
            } else {
                array_push($realPathParts, $pathPart);
            }
        }
        return implode(DIRECTORY_SEPARATOR, $realPathParts);
    }
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751

    /**
     * @param AssetBundle $bundle
     * @return boolean whether asset bundle external or not.
     */
    private function isBundleExternal($bundle)
    {
        return (empty($bundle->sourcePath) && empty($bundle->basePath));
    }

    /**
     * @param AssetBundle $bundle asset bundle instance.
     * @return array bundle configuration.
     */
    private function composeBundleConfig($bundle)
    {
        $config = Yii::getObjectVars($bundle);
        $config['class'] = get_class($bundle);
        return $config;
    }
Zander Baldwin committed
752
}