AssetManager.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidArgumentException;
  11. use yii\base\InvalidConfigException;
  12. use yii\helpers\FileHelper;
  13. use yii\helpers\Url;
  14. /**
  15. * AssetManager manages asset bundle configuration and loading.
  16. *
  17. * AssetManager is configured as an application component in [[\yii\web\Application]] by default.
  18. * You can access that instance via `Yii::$app->assetManager`.
  19. *
  20. * You can modify its configuration by adding an array to your application config under `components`
  21. * as shown in the following example:
  22. *
  23. * ```php
  24. * 'assetManager' => [
  25. * 'bundles' => [
  26. * // you can override AssetBundle configs here
  27. * ],
  28. * ]
  29. * ```
  30. *
  31. * For more details and usage information on AssetManager, see the [guide article on assets](guide:structure-assets).
  32. *
  33. * @property AssetConverterInterface $converter The asset converter. Note that the type of this property
  34. * differs in getter and setter. See [[getConverter()]] and [[setConverter()]] for details.
  35. *
  36. * @author Qiang Xue <qiang.xue@gmail.com>
  37. * @since 2.0
  38. *
  39. * @phpstan-type PublishOptions array{
  40. * only?: string[],
  41. * except?: string[],
  42. * caseSensitive?: bool,
  43. * beforeCopy?: callable,
  44. * afterCopy?: callable,
  45. * forceCopy?: bool,
  46. * }
  47. *
  48. * @psalm-type PublishOptions = array{
  49. * only?: string[],
  50. * except?: string[],
  51. * caseSensitive?: bool,
  52. * beforeCopy?: callable,
  53. * afterCopy?: callable,
  54. * forceCopy?: bool,
  55. * }
  56. */
  57. class AssetManager extends Component
  58. {
  59. /**
  60. * @var array|false list of asset bundle configurations. This property is provided to customize asset bundles.
  61. * When a bundle is being loaded by [[getBundle()]], if it has a corresponding configuration specified here,
  62. * the configuration will be applied to the bundle.
  63. *
  64. * The array keys are the asset bundle names, which typically are asset bundle class names without leading backslash.
  65. * The array values are the corresponding configurations. If a value is false, it means the corresponding asset
  66. * bundle is disabled and [[getBundle()]] should return null.
  67. *
  68. * If this property is false, it means the whole asset bundle feature is disabled and [[getBundle()]]
  69. * will always return null.
  70. *
  71. * The following example shows how to disable the bootstrap css file used by Bootstrap widgets
  72. * (because you want to use your own styles):
  73. *
  74. * ```php
  75. * [
  76. * 'yii\bootstrap\BootstrapAsset' => [
  77. * 'css' => [],
  78. * ],
  79. * ]
  80. * ```
  81. */
  82. public $bundles = [];
  83. /**
  84. * @var string the root directory storing the published asset files.
  85. */
  86. public $basePath = '@webroot/assets';
  87. /**
  88. * @var string the base URL through which the published asset files can be accessed.
  89. */
  90. public $baseUrl = '@web/assets';
  91. /**
  92. * @var string[] mapping from source asset files (keys) to target asset files (values).
  93. *
  94. * This property is provided to support fixing incorrect asset file paths in some asset bundles.
  95. * When an asset bundle is registered with a view, each relative asset file in its [[AssetBundle::css|css]]
  96. * and [[AssetBundle::js|js]] arrays will be examined against this map. If any of the keys is found
  97. * to be the last part of an asset file (which is prefixed with [[AssetBundle::sourcePath]] if available),
  98. * the corresponding value will replace the asset and be registered with the view.
  99. * For example, an asset file `my/path/to/jquery.js` matches a key `jquery.js`.
  100. *
  101. * Note that the target asset files should be absolute URLs, domain relative URLs (starting from '/') or paths
  102. * relative to [[baseUrl]] and [[basePath]].
  103. *
  104. * In the following example, any assets ending with `jquery.min.js` will be replaced with `jquery/dist/jquery.js`
  105. * which is relative to [[baseUrl]] and [[basePath]].
  106. *
  107. * ```php
  108. * [
  109. * 'jquery.min.js' => 'jquery/dist/jquery.js',
  110. * ]
  111. * ```
  112. *
  113. * You may also use aliases while specifying map value, for example:
  114. *
  115. * ```php
  116. * [
  117. * 'jquery.min.js' => '@web/js/jquery/jquery.js',
  118. * ]
  119. * ```
  120. */
  121. public $assetMap = [];
  122. /**
  123. * @var bool whether to use symbolic link to publish asset files. Defaults to false, meaning
  124. * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published
  125. * assets will always be consistent with the source assets and there is no copy operation required.
  126. * This is especially useful during development.
  127. *
  128. * However, there are special requirements for hosting environments in order to use symbolic links.
  129. * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
  130. *
  131. * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
  132. * to Web users. For example, for Apache Web server, the following configuration directive should be added
  133. * for the Web folder:
  134. *
  135. * ```apache
  136. * Options FollowSymLinks
  137. * ```
  138. */
  139. public $linkAssets = false;
  140. /**
  141. * @var int|null the permission to be set for newly published asset files.
  142. * This value will be used by PHP chmod() function. No umask will be applied.
  143. * If not set, the permission will be determined by the current environment.
  144. */
  145. public $fileMode;
  146. /**
  147. * @var int the permission to be set for newly generated asset directories.
  148. * This value will be used by PHP chmod() function. No umask will be applied.
  149. * Defaults to 0775, meaning the directory is read-writable by owner and group,
  150. * but read-only for other users.
  151. */
  152. public $dirMode = 0775;
  153. /**
  154. * @var callable|null a PHP callback that is called before copying each sub-directory or file.
  155. * This option is used only when publishing a directory. If the callback returns false, the copy
  156. * operation for the sub-directory or file will be cancelled.
  157. *
  158. * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
  159. * file to be copied from, while `$to` is the copy target.
  160. *
  161. * This is passed as a parameter `beforeCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
  162. */
  163. public $beforeCopy;
  164. /**
  165. * @var callable|null a PHP callback that is called after a sub-directory or file is successfully copied.
  166. * This option is used only when publishing a directory. The signature of the callback is the same as
  167. * for [[beforeCopy]].
  168. * This is passed as a parameter `afterCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
  169. */
  170. public $afterCopy;
  171. /**
  172. * @var bool whether the directory being published should be copied even if
  173. * it is found in the target directory. This option is used only when publishing a directory.
  174. * You may want to set this to be `true` during the development stage to make sure the published
  175. * directory is always up-to-date. Do not set this to true on production servers as it will
  176. * significantly degrade the performance.
  177. */
  178. public $forceCopy = false;
  179. /**
  180. * @var bool whether to append a timestamp to the URL of every published asset. When this is true,
  181. * the URL of a published asset may look like `/path/to/asset?v=timestamp`, where `timestamp` is the
  182. * last modification time of the published asset file.
  183. * You normally would want to set this property to true when you have enabled HTTP caching for assets,
  184. * because it allows you to bust caching when the assets are updated.
  185. * @since 2.0.3
  186. */
  187. public $appendTimestamp = false;
  188. /**
  189. * @var callable|null a callback that will be called to produce hash for asset directory generation.
  190. * The signature of the callback should be as follows:
  191. *
  192. * ```
  193. * function ($path)
  194. * ```
  195. *
  196. * where `$path` is the asset path. Note that the `$path` can be either directory where the asset
  197. * files reside or a single file. For a CSS file that uses relative path in `url()`, the hash
  198. * implementation should use the directory path of the file instead of the file path to include
  199. * the relative asset files in the copying.
  200. *
  201. * If this is not set, the asset manager will use the default CRC32 and filemtime in the `hash`
  202. * method.
  203. *
  204. * Example of an implementation using MD4 hash:
  205. *
  206. * ```php
  207. * function ($path) {
  208. * return hash('md4', $path);
  209. * }
  210. * ```
  211. *
  212. * @since 2.0.6
  213. */
  214. public $hashCallback;
  215. /**
  216. * @var array
  217. */
  218. private $_dummyBundles = [];
  219. /**
  220. * Initializes the component.
  221. * @throws InvalidConfigException if [[basePath]] does not exist.
  222. */
  223. public function init()
  224. {
  225. parent::init();
  226. $this->basePath = Yii::getAlias($this->basePath);
  227. $this->basePath = realpath($this->basePath);
  228. $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
  229. }
  230. /**
  231. * @var bool|null
  232. */
  233. private $_isBasePathPermissionChecked;
  234. /**
  235. * Check whether the basePath exists and is writeable.
  236. *
  237. * @since 2.0.40
  238. */
  239. public function checkBasePathPermission()
  240. {
  241. // if the check is been done already, skip further checks
  242. if ($this->_isBasePathPermissionChecked) {
  243. return;
  244. }
  245. if (!is_dir($this->basePath)) {
  246. throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
  247. }
  248. if (!is_writable($this->basePath)) {
  249. throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
  250. }
  251. $this->_isBasePathPermissionChecked = true;
  252. }
  253. /**
  254. * Returns the named asset bundle.
  255. *
  256. * This method will first look for the bundle in [[bundles]]. If not found,
  257. * it will treat `$name` as the class of the asset bundle and create a new instance of it.
  258. *
  259. * @param string $name the class name of the asset bundle (without the leading backslash)
  260. * @param bool $publish whether to publish the asset files in the asset bundle before it is returned.
  261. * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files.
  262. * @return AssetBundle the asset bundle instance
  263. * @throws InvalidConfigException if $name does not refer to a valid asset bundle
  264. */
  265. public function getBundle($name, $publish = true)
  266. {
  267. if ($this->bundles === false) {
  268. return $this->loadDummyBundle($name);
  269. } elseif (!isset($this->bundles[$name])) {
  270. return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
  271. } elseif ($this->bundles[$name] instanceof AssetBundle) {
  272. return $this->bundles[$name];
  273. } elseif (is_array($this->bundles[$name])) {
  274. return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
  275. } elseif ($this->bundles[$name] === false) {
  276. return $this->loadDummyBundle($name);
  277. }
  278. throw new InvalidConfigException("Invalid asset bundle configuration: $name");
  279. }
  280. /**
  281. * Loads asset bundle class by name.
  282. *
  283. * @param string $name bundle name
  284. * @param array $config bundle object configuration
  285. * @param bool $publish if bundle should be published
  286. * @return AssetBundle
  287. * @throws InvalidConfigException if configuration isn't valid
  288. */
  289. protected function loadBundle($name, $config = [], $publish = true)
  290. {
  291. if (!isset($config['class'])) {
  292. $config['class'] = $name;
  293. }
  294. /** @var AssetBundle $bundle */
  295. $bundle = Yii::createObject($config);
  296. if ($publish) {
  297. $bundle->publish($this);
  298. }
  299. return $bundle;
  300. }
  301. /**
  302. * Loads dummy bundle by name.
  303. *
  304. * @param string $name
  305. * @return AssetBundle
  306. */
  307. protected function loadDummyBundle($name)
  308. {
  309. if (!isset($this->_dummyBundles[$name])) {
  310. $bundle = Yii::createObject(['class' => $name]);
  311. $bundle->sourcePath = null;
  312. $bundle->js = [];
  313. $bundle->css = [];
  314. $this->_dummyBundles[$name] = $bundle;
  315. }
  316. return $this->_dummyBundles[$name];
  317. }
  318. /**
  319. * Returns the actual URL for the specified asset.
  320. * The actual URL is obtained by prepending either [[AssetBundle::$baseUrl]] or [[AssetManager::$baseUrl]] to the given asset path.
  321. * @param AssetBundle $bundle the asset bundle which the asset file belongs to
  322. * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
  323. * @param bool|null $appendTimestamp Whether to append timestamp to the URL.
  324. * @return string the actual URL for the specified asset.
  325. */
  326. public function getAssetUrl($bundle, $asset, $appendTimestamp = null)
  327. {
  328. $assetUrl = $this->getActualAssetUrl($bundle, $asset);
  329. $assetPath = $this->getAssetPath($bundle, $asset);
  330. $withTimestamp = $this->appendTimestamp;
  331. if ($appendTimestamp !== null) {
  332. $withTimestamp = $appendTimestamp;
  333. }
  334. if ($withTimestamp && $assetPath && ($timestamp = @filemtime($assetPath)) > 0) {
  335. return "$assetUrl?v=$timestamp";
  336. }
  337. return $assetUrl;
  338. }
  339. /**
  340. * Returns the actual file path for the specified asset.
  341. * @param AssetBundle $bundle the asset bundle which the asset file belongs to
  342. * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
  343. * @return string|false the actual file path, or `false` if the asset is specified as an absolute URL
  344. */
  345. public function getAssetPath($bundle, $asset)
  346. {
  347. if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
  348. return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false;
  349. }
  350. return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
  351. }
  352. /**
  353. * @param AssetBundle $bundle
  354. * @param string $asset
  355. * @return string|false
  356. */
  357. protected function resolveAsset($bundle, $asset)
  358. {
  359. if (isset($this->assetMap[$asset])) {
  360. return $this->assetMap[$asset];
  361. }
  362. if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
  363. $asset = $bundle->sourcePath . '/' . $asset;
  364. }
  365. $n = mb_strlen($asset, Yii::$app->charset);
  366. foreach ($this->assetMap as $from => $to) {
  367. $n2 = mb_strlen($from, Yii::$app->charset);
  368. if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
  369. return $to;
  370. }
  371. }
  372. return false;
  373. }
  374. /**
  375. * @var AssetConverterInterface
  376. */
  377. private $_converter;
  378. /**
  379. * Returns the asset converter.
  380. * @return AssetConverterInterface the asset converter.
  381. */
  382. public function getConverter()
  383. {
  384. if ($this->_converter === null) {
  385. $this->_converter = Yii::createObject(AssetConverter::className());
  386. } elseif (is_array($this->_converter) || is_string($this->_converter)) {
  387. if (is_array($this->_converter) && !isset($this->_converter['class'])) {
  388. $this->_converter['class'] = AssetConverter::className();
  389. }
  390. $this->_converter = Yii::createObject($this->_converter);
  391. }
  392. return $this->_converter;
  393. }
  394. /**
  395. * Sets the asset converter.
  396. * @param array|AssetConverterInterface $value the asset converter. This can be either
  397. * an object implementing the [[AssetConverterInterface]], or a configuration
  398. * array that can be used to create the asset converter object.
  399. */
  400. public function setConverter($value)
  401. {
  402. $this->_converter = $value;
  403. }
  404. /**
  405. * @var array published assets
  406. */
  407. private $_published = [];
  408. /**
  409. * Publishes a file or a directory.
  410. *
  411. * This method will copy the specified file or directory to [[basePath]] so that
  412. * it can be accessed via the Web server.
  413. *
  414. * If the asset is a file, its file modification time will be checked to avoid
  415. * unnecessary file copying.
  416. *
  417. * If the asset is a directory, all files and subdirectories under it will be published recursively.
  418. * Note, in case $forceCopy is false the method only checks the existence of the target
  419. * directory to avoid repetitive copying (which is very expensive).
  420. *
  421. * By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
  422. * will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
  423. * as explained in the `$options` parameter.
  424. *
  425. * Note: On rare scenario, a race condition can develop that will lead to a
  426. * one-time-manifestation of a non-critical problem in the creation of the directory
  427. * that holds the published assets. This problem can be avoided altogether by 'requesting'
  428. * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
  429. * that in the application deployment phase, before system goes live. See more in the following
  430. * discussion: https://code.google.com/archive/p/yii/issues/2579
  431. *
  432. * @param string $path the asset (file or directory) to be published
  433. * @param array $options the options to be applied when publishing a directory.
  434. * The following options are supported:
  435. *
  436. * - only: array, list of patterns that the file paths should match if they want to be copied.
  437. * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  438. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  439. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  440. * This overrides [[beforeCopy]] if set.
  441. * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
  442. * This overrides [[afterCopy]] if set.
  443. * - forceCopy: boolean, whether the directory being published should be copied even if
  444. * it is found in the target directory. This option is used only when publishing a directory.
  445. * This overrides [[forceCopy]] if set.
  446. *
  447. * @return array the path (directory or file path) and the URL that the asset is published as.
  448. * @throws InvalidArgumentException if the asset to be published does not exist.
  449. * @throws InvalidConfigException if the target directory [[basePath]] is not writeable.
  450. *
  451. * @phpstan-param PublishOptions $options
  452. * @psalm-param PublishOptions $options
  453. */
  454. public function publish($path, $options = [])
  455. {
  456. $path = Yii::getAlias($path);
  457. if (isset($this->_published[$path])) {
  458. return $this->_published[$path];
  459. }
  460. if (!is_string($path) || ($src = realpath($path)) === false) {
  461. throw new InvalidArgumentException("The file or directory to be published does not exist: $path");
  462. }
  463. if (!is_readable($path)) {
  464. throw new InvalidArgumentException("The file or directory to be published is not readable: $path");
  465. }
  466. if (is_file($src)) {
  467. return $this->_published[$path] = $this->publishFile($src);
  468. }
  469. return $this->_published[$path] = $this->publishDirectory($src, $options);
  470. }
  471. /**
  472. * Publishes a file.
  473. * @param string $src the asset file to be published
  474. * @return string[] the path and the URL that the asset is published as.
  475. * @throws InvalidArgumentException if the asset to be published does not exist.
  476. */
  477. protected function publishFile($src)
  478. {
  479. $this->checkBasePathPermission();
  480. $dir = $this->hash($src);
  481. $fileName = basename($src);
  482. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  483. $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
  484. if (!is_dir($dstDir)) {
  485. FileHelper::createDirectory($dstDir, $this->dirMode, true);
  486. }
  487. if ($this->linkAssets) {
  488. if (!is_file($dstFile)) {
  489. try { // fix #6226 symlinking multi threaded
  490. symlink($src, $dstFile);
  491. } catch (\Exception $e) {
  492. if (!is_file($dstFile)) {
  493. throw $e;
  494. }
  495. }
  496. }
  497. } elseif (@filemtime($dstFile) < @filemtime($src)) {
  498. copy($src, $dstFile);
  499. if ($this->fileMode !== null) {
  500. @chmod($dstFile, $this->fileMode);
  501. }
  502. }
  503. if ($this->appendTimestamp && ($timestamp = @filemtime($dstFile)) > 0) {
  504. $fileName = $fileName . "?v=$timestamp";
  505. }
  506. return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
  507. }
  508. /**
  509. * Publishes a directory.
  510. * @param string $src the asset directory to be published
  511. * @param array $options the options to be applied when publishing a directory.
  512. * The following options are supported:
  513. *
  514. * - only: array, list of patterns that the file paths should match if they want to be copied.
  515. * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  516. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  517. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  518. * This overrides [[beforeCopy]] if set.
  519. * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
  520. * This overrides [[afterCopy]] if set.
  521. * - forceCopy: boolean, whether the directory being published should be copied even if
  522. * it is found in the target directory. This option is used only when publishing a directory.
  523. * This overrides [[forceCopy]] if set.
  524. *
  525. * @return string[] the path directory and the URL that the asset is published as.
  526. * @throws InvalidArgumentException if the asset to be published does not exist.
  527. */
  528. protected function publishDirectory($src, $options)
  529. {
  530. $this->checkBasePathPermission();
  531. $dir = $this->hash($src);
  532. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  533. if ($this->linkAssets) {
  534. if (!is_dir($dstDir)) {
  535. FileHelper::createDirectory(dirname($dstDir), $this->dirMode, true);
  536. try { // fix #6226 symlinking multi threaded
  537. symlink($src, $dstDir);
  538. } catch (\Exception $e) {
  539. if (!is_dir($dstDir)) {
  540. throw $e;
  541. }
  542. }
  543. }
  544. } elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
  545. $opts = array_merge(
  546. $options,
  547. [
  548. 'dirMode' => $this->dirMode,
  549. 'fileMode' => $this->fileMode,
  550. 'copyEmptyDirectories' => false,
  551. ]
  552. );
  553. if (!isset($opts['beforeCopy'])) {
  554. if ($this->beforeCopy !== null) {
  555. $opts['beforeCopy'] = $this->beforeCopy;
  556. } else {
  557. $opts['beforeCopy'] = function ($from, $to) {
  558. return strncmp(basename($from), '.', 1) !== 0;
  559. };
  560. }
  561. }
  562. if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
  563. $opts['afterCopy'] = $this->afterCopy;
  564. }
  565. FileHelper::copyDirectory($src, $dstDir, $opts);
  566. }
  567. return [$dstDir, $this->baseUrl . '/' . $dir];
  568. }
  569. /**
  570. * Returns the published path of a file path.
  571. * This method does not perform any publishing. It merely tells you
  572. * if the file or directory is published, where it will go.
  573. * @param string $path directory or file path being published
  574. * @return string|false string the published file path. False if the file or directory does not exist
  575. */
  576. public function getPublishedPath($path)
  577. {
  578. $path = Yii::getAlias($path);
  579. if (isset($this->_published[$path])) {
  580. return $this->_published[$path][0];
  581. }
  582. if (is_string($path) && ($path = realpath($path)) !== false) {
  583. return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : '');
  584. }
  585. return false;
  586. }
  587. /**
  588. * Returns the URL of a published file path.
  589. * This method does not perform any publishing. It merely tells you
  590. * if the file path is published, what the URL will be to access it.
  591. * @param string $path directory or file path being published
  592. * @return string|false string the published URL for the file or directory. False if the file or directory does not exist.
  593. */
  594. public function getPublishedUrl($path)
  595. {
  596. $path = Yii::getAlias($path);
  597. if (isset($this->_published[$path])) {
  598. return $this->_published[$path][1];
  599. }
  600. if (is_string($path) && ($path = realpath($path)) !== false) {
  601. return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
  602. }
  603. return false;
  604. }
  605. /**
  606. * Generate a CRC32 hash for the directory path. Collisions are higher
  607. * than MD5 but generates a much smaller hash string.
  608. * @param string $path string to be hashed.
  609. * @return string hashed string.
  610. */
  611. protected function hash($path)
  612. {
  613. if (is_callable($this->hashCallback)) {
  614. return call_user_func($this->hashCallback, $path);
  615. }
  616. $path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
  617. return sprintf('%x', crc32($path . Yii::getVersion() . '|' . $this->linkAssets));
  618. }
  619. /**
  620. * Returns the actual URL for the specified asset. Without parameters.
  621. * The actual URL is obtained by prepending either [[AssetBundle::$baseUrl]] or [[AssetManager::$baseUrl]] to the given asset path.
  622. * @param AssetBundle $bundle the asset bundle which the asset file belongs to
  623. * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
  624. * @return string the actual URL for the specified asset.
  625. * @since 2.0.39
  626. */
  627. public function getActualAssetUrl($bundle, $asset)
  628. {
  629. if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
  630. if (strncmp($actualAsset, '@web/', 5) === 0) {
  631. $asset = substr($actualAsset, 5);
  632. $baseUrl = Yii::getAlias('@web');
  633. } else {
  634. $asset = Yii::getAlias($actualAsset);
  635. $baseUrl = $this->baseUrl;
  636. }
  637. } else {
  638. $baseUrl = $bundle->baseUrl;
  639. }
  640. if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) {
  641. return $asset;
  642. }
  643. return "$baseUrl/$asset";
  644. }
  645. }