AssetManager.php 26 KB

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