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.

833 lines
31KB

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