AssetController.php 31 KB

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