You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

786 lines
29KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\console\controllers;
  8. use Yii;
  9. use yii\console\Exception;
  10. use yii\console\Controller;
  11. use yii\helpers\Console;
  12. use yii\helpers\FileHelper;
  13. use yii\helpers\VarDumper;
  14. use yii\web\AssetBundle;
  15. /**
  16. * Allows you to combine and compress your JavaScript and CSS files.
  17. *
  18. * Usage:
  19. *
  20. * 1. Create a configuration file using the `template` action:
  21. *
  22. * yii asset/template /path/to/myapp/config.php
  23. *
  24. * 2. Edit the created config file, adjusting it for your web application needs.
  25. * 3. Run the 'compress' action, using created config:
  26. *
  27. * yii asset /path/to/myapp/config.php /path/to/myapp/config/assets_compressed.php
  28. *
  29. * 4. Adjust your web application config to use compressed assets.
  30. *
  31. * Note: in the console environment some path aliases like `@webroot` and `@web` may not exist,
  32. * so corresponding paths inside the configuration should be specified directly.
  33. *
  34. * Note: by default this command relies on an external tools to perform actual files compression,
  35. * check [[jsCompressor]] and [[cssCompressor]] for more details.
  36. *
  37. * @property \yii\web\AssetManager $assetManager Asset manager instance. Note that the type of this property
  38. * differs in getter and setter. See [[getAssetManager()]] and [[setAssetManager()]] for details.
  39. *
  40. * @author Qiang Xue <qiang.xue@gmail.com>
  41. * @since 2.0
  42. */
  43. class AssetController extends Controller
  44. {
  45. /**
  46. * @var string controller default action ID.
  47. */
  48. public $defaultAction = 'compress';
  49. /**
  50. * @var array list of asset bundles to be compressed.
  51. */
  52. public $bundles = [];
  53. /**
  54. * @var array list of asset bundles, which represents output compressed files.
  55. * You can specify the name of the output compressed file using 'css' and 'js' keys:
  56. * For example:
  57. *
  58. * ```php
  59. * 'app\config\AllAsset' => [
  60. * 'js' => 'js/all-{hash}.js',
  61. * 'css' => 'css/all-{hash}.css',
  62. * 'depends' => [ ... ],
  63. * ]
  64. * ```
  65. *
  66. * File names can contain placeholder "{hash}", which will be filled by the hash of the resulting file.
  67. *
  68. * You may specify several target bundles in order to compress different groups of assets.
  69. * In this case you should use 'depends' key to specify, which bundles should be covered with particular
  70. * target bundle. You may leave 'depends' to be empty for single bundle, which will compress all remaining
  71. * bundles in this case.
  72. * For example:
  73. *
  74. * ```php
  75. * 'allShared' => [
  76. * 'js' => 'js/all-shared-{hash}.js',
  77. * 'css' => 'css/all-shared-{hash}.css',
  78. * 'depends' => [
  79. * // Include all assets shared between 'backend' and 'frontend'
  80. * 'yii\web\YiiAsset',
  81. * 'app\assets\SharedAsset',
  82. * ],
  83. * ],
  84. * 'allBackEnd' => [
  85. * 'js' => 'js/all-{hash}.js',
  86. * 'css' => 'css/all-{hash}.css',
  87. * 'depends' => [
  88. * // Include only 'backend' assets:
  89. * 'app\assets\AdminAsset'
  90. * ],
  91. * ],
  92. * 'allFrontEnd' => [
  93. * 'js' => 'js/all-{hash}.js',
  94. * 'css' => 'css/all-{hash}.css',
  95. * 'depends' => [], // Include all remaining assets
  96. * ],
  97. * ```
  98. */
  99. public $targets = [];
  100. /**
  101. * @var string|callable JavaScript file compressor.
  102. * If a string, it is treated as shell command template, which should contain
  103. * placeholders {from} - source file name - and {to} - output file name.
  104. * Otherwise, it is treated as PHP callback, which should perform the compression.
  105. *
  106. * Default value relies on usage of "Closure Compiler"
  107. * @see https://developers.google.com/closure/compiler/
  108. */
  109. public $jsCompressor = 'java -jar compiler.jar --js {from} --js_output_file {to}';
  110. /**
  111. * @var string|callable CSS file compressor.
  112. * If a string, it is treated as shell command template, which should contain
  113. * placeholders {from} - source file name - and {to} - output file name.
  114. * Otherwise, it is treated as PHP callback, which should perform the compression.
  115. *
  116. * Default value relies on usage of "YUI Compressor"
  117. * @see https://github.com/yui/yuicompressor/
  118. */
  119. public $cssCompressor = 'java -jar yuicompressor.jar --type css {from} -o {to}';
  120. /**
  121. * @var array|\yii\web\AssetManager [[\yii\web\AssetManager]] instance or its array configuration, which will be used
  122. * for assets processing.
  123. */
  124. private $_assetManager = [];
  125. /**
  126. * Returns the asset manager instance.
  127. * @throws \yii\console\Exception on invalid configuration.
  128. * @return \yii\web\AssetManager asset manager instance.
  129. */
  130. public function getAssetManager()
  131. {
  132. if (!is_object($this->_assetManager)) {
  133. $options = $this->_assetManager;
  134. if (!isset($options['class'])) {
  135. $options['class'] = 'yii\\web\\AssetManager';
  136. }
  137. if (!isset($options['basePath'])) {
  138. throw new Exception("Please specify 'basePath' for the 'assetManager' option.");
  139. }
  140. if (!isset($options['baseUrl'])) {
  141. throw new Exception("Please specify 'baseUrl' for the 'assetManager' option.");
  142. }
  143. $this->_assetManager = Yii::createObject($options);
  144. }
  145. return $this->_assetManager;
  146. }
  147. /**
  148. * Sets asset manager instance or configuration.
  149. * @param \yii\web\AssetManager|array $assetManager asset manager instance or its array configuration.
  150. * @throws \yii\console\Exception on invalid argument type.
  151. */
  152. public function setAssetManager($assetManager)
  153. {
  154. if (is_scalar($assetManager)) {
  155. throw new Exception('"' . get_class($this) . '::assetManager" should be either object or array - "' . gettype($assetManager) . '" given.');
  156. }
  157. $this->_assetManager = $assetManager;
  158. }
  159. /**
  160. * Combines and compresses the asset files according to the given configuration.
  161. * During the process new asset bundle configuration file will be created.
  162. * You should replace your original asset bundle configuration with this file in order to use compressed files.
  163. * @param string $configFile configuration file name.
  164. * @param string $bundleFile output asset bundles configuration file name.
  165. */
  166. public function actionCompress($configFile, $bundleFile)
  167. {
  168. $this->loadConfiguration($configFile);
  169. $bundles = $this->loadBundles($this->bundles);
  170. $targets = $this->loadTargets($this->targets, $bundles);
  171. foreach ($targets as $name => $target) {
  172. $this->stdout("Creating output bundle '{$name}':\n");
  173. if (!empty($target->js)) {
  174. $this->buildTarget($target, 'js', $bundles);
  175. }
  176. if (!empty($target->css)) {
  177. $this->buildTarget($target, 'css', $bundles);
  178. }
  179. $this->stdout("\n");
  180. }
  181. $targets = $this->adjustDependency($targets, $bundles);
  182. $this->saveTargets($targets, $bundleFile);
  183. }
  184. /**
  185. * Applies configuration from the given file to self instance.
  186. * @param string $configFile configuration file name.
  187. * @throws \yii\console\Exception on failure.
  188. */
  189. protected function loadConfiguration($configFile)
  190. {
  191. $this->stdout("Loading configuration from '{$configFile}'...\n");
  192. foreach (require($configFile) as $name => $value) {
  193. if (property_exists($this, $name) || $this->canSetProperty($name)) {
  194. $this->$name = $value;
  195. } else {
  196. throw new Exception("Unknown configuration option: $name");
  197. }
  198. }
  199. $this->getAssetManager(); // check if asset manager configuration is correct
  200. }
  201. /**
  202. * Creates full list of source asset bundles.
  203. * @param string[] $bundles list of asset bundle names
  204. * @return \yii\web\AssetBundle[] list of source asset bundles.
  205. */
  206. protected function loadBundles($bundles)
  207. {
  208. $this->stdout("Collecting source bundles information...\n");
  209. $am = $this->getAssetManager();
  210. $result = [];
  211. foreach ($bundles as $name) {
  212. $result[$name] = $am->getBundle($name);
  213. }
  214. foreach ($result as $bundle) {
  215. $this->loadDependency($bundle, $result);
  216. }
  217. return $result;
  218. }
  219. /**
  220. * Loads asset bundle dependencies recursively.
  221. * @param \yii\web\AssetBundle $bundle bundle instance
  222. * @param array $result already loaded bundles list.
  223. * @throws Exception on failure.
  224. */
  225. protected function loadDependency($bundle, &$result)
  226. {
  227. $am = $this->getAssetManager();
  228. foreach ($bundle->depends as $name) {
  229. if (!isset($result[$name])) {
  230. $dependencyBundle = $am->getBundle($name);
  231. $result[$name] = false;
  232. $this->loadDependency($dependencyBundle, $result);
  233. $result[$name] = $dependencyBundle;
  234. } elseif ($result[$name] === false) {
  235. throw new Exception("A circular dependency is detected for bundle '{$name}': " . $this->composeCircularDependencyTrace($name, $result) . '.');
  236. }
  237. }
  238. }
  239. /**
  240. * Creates full list of output asset bundles.
  241. * @param array $targets output asset bundles configuration.
  242. * @param \yii\web\AssetBundle[] $bundles list of source asset bundles.
  243. * @return \yii\web\AssetBundle[] list of output asset bundles.
  244. * @throws Exception on failure.
  245. */
  246. protected function loadTargets($targets, $bundles)
  247. {
  248. // build the dependency order of bundles
  249. $registered = [];
  250. foreach ($bundles as $name => $bundle) {
  251. $this->registerBundle($bundles, $name, $registered);
  252. }
  253. $bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1));
  254. // fill up the target which has empty 'depends'.
  255. $referenced = [];
  256. foreach ($targets as $name => $target) {
  257. if (empty($target['depends'])) {
  258. if (!isset($all)) {
  259. $all = $name;
  260. } else {
  261. throw new Exception("Only one target can have empty 'depends' option. Found two now: $all, $name");
  262. }
  263. } else {
  264. foreach ($target['depends'] as $bundle) {
  265. if (!isset($referenced[$bundle])) {
  266. $referenced[$bundle] = $name;
  267. } else {
  268. throw new Exception("Target '{$referenced[$bundle]}' and '$name' cannot contain the bundle '$bundle' at the same time.");
  269. }
  270. }
  271. }
  272. }
  273. if (isset($all)) {
  274. $targets[$all]['depends'] = array_diff(array_keys($registered), array_keys($referenced));
  275. }
  276. // adjust the 'depends' order for each target according to the dependency order of bundles
  277. // create an AssetBundle object for each target
  278. foreach ($targets as $name => $target) {
  279. if (!isset($target['basePath'])) {
  280. throw new Exception("Please specify 'basePath' for the '$name' target.");
  281. }
  282. if (!isset($target['baseUrl'])) {
  283. throw new Exception("Please specify 'baseUrl' for the '$name' target.");
  284. }
  285. usort($target['depends'], function ($a, $b) use ($bundleOrders) {
  286. if ($bundleOrders[$a] == $bundleOrders[$b]) {
  287. return 0;
  288. } else {
  289. return $bundleOrders[$a] > $bundleOrders[$b] ? 1 : -1;
  290. }
  291. });
  292. if (!isset($target['class'])) {
  293. $target['class'] = $name;
  294. }
  295. $targets[$name] = Yii::createObject($target);
  296. }
  297. return $targets;
  298. }
  299. /**
  300. * Builds output asset bundle.
  301. * @param \yii\web\AssetBundle $target output asset bundle
  302. * @param string $type either 'js' or 'css'.
  303. * @param \yii\web\AssetBundle[] $bundles source asset bundles.
  304. * @throws Exception on failure.
  305. */
  306. protected function buildTarget($target, $type, $bundles)
  307. {
  308. $inputFiles = [];
  309. foreach ($target->depends as $name) {
  310. if (isset($bundles[$name])) {
  311. if (!$this->isBundleExternal($bundles[$name])) {
  312. foreach ($bundles[$name]->$type as $file) {
  313. if (is_array($file)) {
  314. $inputFiles[] = $bundles[$name]->basePath . '/' . $file[0];
  315. } else {
  316. $inputFiles[] = $bundles[$name]->basePath . '/' . $file;
  317. }
  318. }
  319. }
  320. } else {
  321. throw new Exception("Unknown bundle: '{$name}'");
  322. }
  323. }
  324. if (empty($inputFiles)) {
  325. $target->$type = [];
  326. } else {
  327. FileHelper::createDirectory($target->basePath, $this->getAssetManager()->dirMode);
  328. $tempFile = $target->basePath . '/' . strtr($target->$type, ['{hash}' => 'temp']);
  329. if ($type === 'js') {
  330. $this->compressJsFiles($inputFiles, $tempFile);
  331. } else {
  332. $this->compressCssFiles($inputFiles, $tempFile);
  333. }
  334. $targetFile = strtr($target->$type, ['{hash}' => md5_file($tempFile)]);
  335. $outputFile = $target->basePath . '/' . $targetFile;
  336. rename($tempFile, $outputFile);
  337. $target->$type = [$targetFile];
  338. }
  339. }
  340. /**
  341. * Adjust dependencies between asset bundles in the way source bundles begin to depend on output ones.
  342. * @param \yii\web\AssetBundle[] $targets output asset bundles.
  343. * @param \yii\web\AssetBundle[] $bundles source asset bundles.
  344. * @return \yii\web\AssetBundle[] output asset bundles.
  345. */
  346. protected function adjustDependency($targets, $bundles)
  347. {
  348. $this->stdout("Creating new bundle configuration...\n");
  349. $map = [];
  350. foreach ($targets as $name => $target) {
  351. foreach ($target->depends as $bundle) {
  352. $map[$bundle] = $name;
  353. }
  354. }
  355. foreach ($targets as $name => $target) {
  356. $depends = [];
  357. foreach ($target->depends as $bn) {
  358. foreach ($bundles[$bn]->depends as $bundle) {
  359. $depends[$map[$bundle]] = true;
  360. }
  361. }
  362. unset($depends[$name]);
  363. $target->depends = array_keys($depends);
  364. }
  365. // detect possible circular dependencies
  366. foreach ($targets as $name => $target) {
  367. $registered = [];
  368. $this->registerBundle($targets, $name, $registered);
  369. }
  370. foreach ($map as $bundle => $target) {
  371. $sourceBundle = $bundles[$bundle];
  372. $depends = $sourceBundle->depends;
  373. if (!$this->isBundleExternal($sourceBundle)) {
  374. $depends[] = $target;
  375. }
  376. $targets[$bundle] = Yii::createObject([
  377. 'class' => strpos($bundle, '\\') !== false ? $bundle : 'yii\\web\\AssetBundle',
  378. 'depends' => $depends,
  379. ]);
  380. }
  381. return $targets;
  382. }
  383. /**
  384. * Registers asset bundles including their dependencies.
  385. * @param \yii\web\AssetBundle[] $bundles asset bundles list.
  386. * @param string $name bundle name.
  387. * @param array $registered stores already registered names.
  388. * @throws Exception if circular dependency is detected.
  389. */
  390. protected function registerBundle($bundles, $name, &$registered)
  391. {
  392. if (!isset($registered[$name])) {
  393. $registered[$name] = false;
  394. $bundle = $bundles[$name];
  395. foreach ($bundle->depends as $depend) {
  396. $this->registerBundle($bundles, $depend, $registered);
  397. }
  398. unset($registered[$name]);
  399. $registered[$name] = $bundle;
  400. } elseif ($registered[$name] === false) {
  401. throw new Exception("A circular dependency is detected for target '{$name}': " . $this->composeCircularDependencyTrace($name, $registered) . '.');
  402. }
  403. }
  404. /**
  405. * Saves new asset bundles configuration.
  406. * @param \yii\web\AssetBundle[] $targets list of asset bundles to be saved.
  407. * @param string $bundleFile output file name.
  408. * @throws \yii\console\Exception on failure.
  409. */
  410. protected function saveTargets($targets, $bundleFile)
  411. {
  412. $array = [];
  413. foreach ($targets as $name => $target) {
  414. if (isset($this->targets[$name])) {
  415. $array[$name] = [
  416. 'class' => get_class($target),
  417. 'basePath' => $this->targets[$name]['basePath'],
  418. 'baseUrl' => $this->targets[$name]['baseUrl'],
  419. 'js' => $target->js,
  420. 'css' => $target->css,
  421. ];
  422. } else {
  423. if ($this->isBundleExternal($target)) {
  424. $array[$name] = $this->composeBundleConfig($target);
  425. } else {
  426. $array[$name] = [
  427. 'sourcePath' => null,
  428. 'js' => [],
  429. 'css' => [],
  430. 'depends' => $target->depends,
  431. ];
  432. }
  433. }
  434. }
  435. $array = VarDumper::export($array);
  436. $version = date('Y-m-d H:i:s', time());
  437. $bundleFileContent = <<<EOD
  438. <?php
  439. /**
  440. * This file is generated by the "yii {$this->id}" command.
  441. * DO NOT MODIFY THIS FILE DIRECTLY.
  442. * @version {$version}
  443. */
  444. return {$array};
  445. EOD;
  446. if (!file_put_contents($bundleFile, $bundleFileContent)) {
  447. throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
  448. }
  449. $this->stdout("Output bundle configuration created at '{$bundleFile}'.\n", Console::FG_GREEN);
  450. }
  451. /**
  452. * Compresses given JavaScript files and combines them into the single one.
  453. * @param array $inputFiles list of source file names.
  454. * @param string $outputFile output file name.
  455. * @throws \yii\console\Exception on failure
  456. */
  457. protected function compressJsFiles($inputFiles, $outputFile)
  458. {
  459. if (empty($inputFiles)) {
  460. return;
  461. }
  462. $this->stdout(" Compressing JavaScript files...\n");
  463. if (is_string($this->jsCompressor)) {
  464. $tmpFile = $outputFile . '.tmp';
  465. $this->combineJsFiles($inputFiles, $tmpFile);
  466. $this->stdout(shell_exec(strtr($this->jsCompressor, [
  467. '{from}' => escapeshellarg($tmpFile),
  468. '{to}' => escapeshellarg($outputFile),
  469. ])));
  470. @unlink($tmpFile);
  471. } else {
  472. call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile);
  473. }
  474. if (!file_exists($outputFile)) {
  475. throw new Exception("Unable to compress JavaScript files into '{$outputFile}'.");
  476. }
  477. $this->stdout(" JavaScript files compressed into '{$outputFile}'.\n");
  478. }
  479. /**
  480. * Compresses given CSS files and combines them into the single one.
  481. * @param array $inputFiles list of source file names.
  482. * @param string $outputFile output file name.
  483. * @throws \yii\console\Exception on failure
  484. */
  485. protected function compressCssFiles($inputFiles, $outputFile)
  486. {
  487. if (empty($inputFiles)) {
  488. return;
  489. }
  490. $this->stdout(" Compressing CSS files...\n");
  491. if (is_string($this->cssCompressor)) {
  492. $tmpFile = $outputFile . '.tmp';
  493. $this->combineCssFiles($inputFiles, $tmpFile);
  494. $this->stdout(shell_exec(strtr($this->cssCompressor, [
  495. '{from}' => escapeshellarg($tmpFile),
  496. '{to}' => escapeshellarg($outputFile),
  497. ])));
  498. @unlink($tmpFile);
  499. } else {
  500. call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile);
  501. }
  502. if (!file_exists($outputFile)) {
  503. throw new Exception("Unable to compress CSS files into '{$outputFile}'.");
  504. }
  505. $this->stdout(" CSS files compressed into '{$outputFile}'.\n");
  506. }
  507. /**
  508. * Combines JavaScript files into a single one.
  509. * @param array $inputFiles source file names.
  510. * @param string $outputFile output file name.
  511. * @throws \yii\console\Exception on failure.
  512. */
  513. public function combineJsFiles($inputFiles, $outputFile)
  514. {
  515. $content = '';
  516. foreach ($inputFiles as $file) {
  517. $content .= "/*** BEGIN FILE: $file ***/\n"
  518. . file_get_contents($file)
  519. . "/*** END FILE: $file ***/\n";
  520. }
  521. if (!file_put_contents($outputFile, $content)) {
  522. throw new Exception("Unable to write output JavaScript file '{$outputFile}'.");
  523. }
  524. }
  525. /**
  526. * Combines CSS files into a single one.
  527. * @param array $inputFiles source file names.
  528. * @param string $outputFile output file name.
  529. * @throws \yii\console\Exception on failure.
  530. */
  531. public function combineCssFiles($inputFiles, $outputFile)
  532. {
  533. $content = '';
  534. $outputFilePath = dirname($this->findRealPath($outputFile));
  535. foreach ($inputFiles as $file) {
  536. $content .= "/*** BEGIN FILE: $file ***/\n"
  537. . $this->adjustCssUrl(file_get_contents($file), dirname($this->findRealPath($file)), $outputFilePath)
  538. . "/*** END FILE: $file ***/\n";
  539. }
  540. if (!file_put_contents($outputFile, $content)) {
  541. throw new Exception("Unable to write output CSS file '{$outputFile}'.");
  542. }
  543. }
  544. /**
  545. * Adjusts CSS content allowing URL references pointing to the original resources.
  546. * @param string $cssContent source CSS content.
  547. * @param string $inputFilePath input CSS file name.
  548. * @param string $outputFilePath output CSS file name.
  549. * @return string adjusted CSS content.
  550. */
  551. protected function adjustCssUrl($cssContent, $inputFilePath, $outputFilePath)
  552. {
  553. $inputFilePath = str_replace('\\', '/', $inputFilePath);
  554. $outputFilePath = str_replace('\\', '/', $outputFilePath);
  555. $sharedPathParts = [];
  556. $inputFilePathParts = explode('/', $inputFilePath);
  557. $inputFilePathPartsCount = count($inputFilePathParts);
  558. $outputFilePathParts = explode('/', $outputFilePath);
  559. $outputFilePathPartsCount = count($outputFilePathParts);
  560. for ($i =0; $i < $inputFilePathPartsCount && $i < $outputFilePathPartsCount; $i++) {
  561. if ($inputFilePathParts[$i] == $outputFilePathParts[$i]) {
  562. $sharedPathParts[] = $inputFilePathParts[$i];
  563. } else {
  564. break;
  565. }
  566. }
  567. $sharedPath = implode('/', $sharedPathParts);
  568. $inputFileRelativePath = trim(str_replace($sharedPath, '', $inputFilePath), '/');
  569. $outputFileRelativePath = trim(str_replace($sharedPath, '', $outputFilePath), '/');
  570. if (empty($inputFileRelativePath)) {
  571. $inputFileRelativePathParts = [];
  572. } else {
  573. $inputFileRelativePathParts = explode('/', $inputFileRelativePath);
  574. }
  575. if (empty($outputFileRelativePath)) {
  576. $outputFileRelativePathParts = [];
  577. } else {
  578. $outputFileRelativePathParts = explode('/', $outputFileRelativePath);
  579. }
  580. $callback = function ($matches) use ($inputFileRelativePathParts, $outputFileRelativePathParts) {
  581. $fullMatch = $matches[0];
  582. $inputUrl = $matches[1];
  583. if (strpos($inputUrl, '/') === 0 || preg_match('/^https?:\/\//i', $inputUrl) || preg_match('/^data:/i', $inputUrl)) {
  584. return $fullMatch;
  585. }
  586. if ($inputFileRelativePathParts === $outputFileRelativePathParts) {
  587. return $fullMatch;
  588. }
  589. if (empty($outputFileRelativePathParts)) {
  590. $outputUrlParts = [];
  591. } else {
  592. $outputUrlParts = array_fill(0, count($outputFileRelativePathParts), '..');
  593. }
  594. $outputUrlParts = array_merge($outputUrlParts, $inputFileRelativePathParts);
  595. if (strpos($inputUrl, '/') !== false) {
  596. $inputUrlParts = explode('/', $inputUrl);
  597. foreach ($inputUrlParts as $key => $inputUrlPart) {
  598. if ($inputUrlPart === '..') {
  599. array_pop($outputUrlParts);
  600. unset($inputUrlParts[$key]);
  601. }
  602. }
  603. $outputUrlParts[] = implode('/', $inputUrlParts);
  604. } else {
  605. $outputUrlParts[] = $inputUrl;
  606. }
  607. $outputUrl = implode('/', $outputUrlParts);
  608. return str_replace($inputUrl, $outputUrl, $fullMatch);
  609. };
  610. $cssContent = preg_replace_callback('/url\(["\']?([^)^"^\']*)["\']?\)/i', $callback, $cssContent);
  611. return $cssContent;
  612. }
  613. /**
  614. * Creates template of configuration file for [[actionCompress]].
  615. * @param string $configFile output file name.
  616. * @return integer CLI exit code
  617. * @throws \yii\console\Exception on failure.
  618. */
  619. public function actionTemplate($configFile)
  620. {
  621. $jsCompressor = VarDumper::export($this->jsCompressor);
  622. $cssCompressor = VarDumper::export($this->cssCompressor);
  623. $template = <<<EOD
  624. <?php
  625. /**
  626. * Configuration file for the "yii asset" console command.
  627. */
  628. // In the console environment, some path aliases may not exist. Please define these:
  629. // Yii::setAlias('@webroot', __DIR__ . '/../web');
  630. // Yii::setAlias('@web', '/');
  631. return [
  632. // Adjust command/callback for JavaScript files compressing:
  633. 'jsCompressor' => {$jsCompressor},
  634. // Adjust command/callback for CSS files compressing:
  635. 'cssCompressor' => {$cssCompressor},
  636. // The list of asset bundles to compress:
  637. 'bundles' => [
  638. // 'app\assets\AppAsset',
  639. // 'yii\web\YiiAsset',
  640. // 'yii\web\JqueryAsset',
  641. ],
  642. // Asset bundle for compression output:
  643. 'targets' => [
  644. 'all' => [
  645. 'class' => 'yii\web\AssetBundle',
  646. 'basePath' => '@webroot/assets',
  647. 'baseUrl' => '@web/assets',
  648. 'js' => 'js/all-{hash}.js',
  649. 'css' => 'css/all-{hash}.css',
  650. ],
  651. ],
  652. // Asset manager configuration:
  653. 'assetManager' => [
  654. //'basePath' => '@webroot/assets',
  655. //'baseUrl' => '@web/assets',
  656. ],
  657. ];
  658. EOD;
  659. if (file_exists($configFile)) {
  660. if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
  661. return self::EXIT_CODE_NORMAL;
  662. }
  663. }
  664. if (!file_put_contents($configFile, $template)) {
  665. throw new Exception("Unable to write template file '{$configFile}'.");
  666. } else {
  667. $this->stdout("Configuration file template created at '{$configFile}'.\n\n", Console::FG_GREEN);
  668. return self::EXIT_CODE_NORMAL;
  669. }
  670. }
  671. /**
  672. * Returns canonicalized absolute pathname.
  673. * Unlike regular `realpath()` this method does not expand symlinks and does not check path existence.
  674. * @param string $path raw path
  675. * @return string canonicalized absolute pathname
  676. */
  677. private function findRealPath($path)
  678. {
  679. $path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
  680. $pathParts = explode(DIRECTORY_SEPARATOR, $path);
  681. $realPathParts = [];
  682. foreach ($pathParts as $pathPart) {
  683. if ($pathPart === '..') {
  684. array_pop($realPathParts);
  685. } else {
  686. $realPathParts[] = $pathPart;
  687. }
  688. }
  689. return implode(DIRECTORY_SEPARATOR, $realPathParts);
  690. }
  691. /**
  692. * @param AssetBundle $bundle
  693. * @return boolean whether asset bundle external or not.
  694. */
  695. private function isBundleExternal($bundle)
  696. {
  697. return (empty($bundle->sourcePath) && empty($bundle->basePath));
  698. }
  699. /**
  700. * @param AssetBundle $bundle asset bundle instance.
  701. * @return array bundle configuration.
  702. */
  703. private function composeBundleConfig($bundle)
  704. {
  705. $config = Yii::getObjectVars($bundle);
  706. $config['class'] = get_class($bundle);
  707. return $config;
  708. }
  709. /**
  710. * Composes trace info for bundle circular dependency.
  711. * @param string $circularDependencyName name of the bundle, which have circular dependency
  712. * @param array $registered list of bundles registered while detecting circular dependency.
  713. * @return string bundle circular dependency trace string.
  714. */
  715. private function composeCircularDependencyTrace($circularDependencyName, array $registered)
  716. {
  717. $dependencyTrace = [];
  718. $startFound = false;
  719. foreach ($registered as $name => $value) {
  720. if ($name === $circularDependencyName) {
  721. $startFound = true;
  722. }
  723. if ($startFound && $value === false) {
  724. $dependencyTrace[] = $name;
  725. }
  726. }
  727. $dependencyTrace[] = $circularDependencyName;
  728. return implode(' -> ', $dependencyTrace);
  729. }
  730. }