AssetManager.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. if (!is_dir($this->basePath)) {
  207. throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
  208. }
  209. $this->basePath = realpath($this->basePath);
  210. $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
  211. }
  212. /**
  213. * Returns the named asset bundle.
  214. *
  215. * This method will first look for the bundle in [[bundles]]. If not found,
  216. * it will treat `$name` as the class of the asset bundle and create a new instance of it.
  217. *
  218. * @param string $name the class name of the asset bundle (without the leading backslash)
  219. * @param bool $publish whether to publish the asset files in the asset bundle before it is returned.
  220. * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files.
  221. * @return AssetBundle the asset bundle instance
  222. * @throws InvalidConfigException if $name does not refer to a valid asset bundle
  223. */
  224. public function getBundle($name, $publish = true)
  225. {
  226. if ($this->bundles === false) {
  227. return $this->loadDummyBundle($name);
  228. } elseif (!isset($this->bundles[$name])) {
  229. return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
  230. } elseif ($this->bundles[$name] instanceof AssetBundle) {
  231. return $this->bundles[$name];
  232. } elseif (is_array($this->bundles[$name])) {
  233. return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
  234. } elseif ($this->bundles[$name] === false) {
  235. return $this->loadDummyBundle($name);
  236. }
  237. throw new InvalidConfigException("Invalid asset bundle configuration: $name");
  238. }
  239. /**
  240. * Loads asset bundle class by name.
  241. *
  242. * @param string $name bundle name
  243. * @param array $config bundle object configuration
  244. * @param bool $publish if bundle should be published
  245. * @return AssetBundle
  246. * @throws InvalidConfigException if configuration isn't valid
  247. */
  248. protected function loadBundle($name, $config = [], $publish = true)
  249. {
  250. if (!isset($config['class'])) {
  251. $config['class'] = $name;
  252. }
  253. /* @var $bundle AssetBundle */
  254. $bundle = Yii::createObject($config);
  255. if ($publish) {
  256. $bundle->publish($this);
  257. }
  258. return $bundle;
  259. }
  260. /**
  261. * Loads dummy bundle by name.
  262. *
  263. * @param string $name
  264. * @return AssetBundle
  265. */
  266. protected function loadDummyBundle($name)
  267. {
  268. if (!isset($this->_dummyBundles[$name])) {
  269. $this->_dummyBundles[$name] = $this->loadBundle($name, [
  270. 'sourcePath' => null,
  271. 'js' => [],
  272. 'css' => [],
  273. 'depends' => [],
  274. ]);
  275. }
  276. return $this->_dummyBundles[$name];
  277. }
  278. /**
  279. * Returns the actual URL for the specified asset.
  280. * The actual URL is obtained by prepending either [[AssetBundle::$baseUrl]] or [[AssetManager::$baseUrl]] to the given asset path.
  281. * @param AssetBundle $bundle the asset bundle which the asset file belongs to
  282. * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
  283. * @return string the actual URL for the specified asset.
  284. */
  285. public function getAssetUrl($bundle, $asset)
  286. {
  287. if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
  288. if (strncmp($actualAsset, '@web/', 5) === 0) {
  289. $asset = substr($actualAsset, 5);
  290. $basePath = Yii::getAlias('@webroot');
  291. $baseUrl = Yii::getAlias('@web');
  292. } else {
  293. $asset = Yii::getAlias($actualAsset);
  294. $basePath = $this->basePath;
  295. $baseUrl = $this->baseUrl;
  296. }
  297. } else {
  298. $basePath = $bundle->basePath;
  299. $baseUrl = $bundle->baseUrl;
  300. }
  301. if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) {
  302. return $asset;
  303. }
  304. if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) {
  305. return "$baseUrl/$asset?v=$timestamp";
  306. }
  307. return "$baseUrl/$asset";
  308. }
  309. /**
  310. * Returns the actual file path for the specified asset.
  311. * @param AssetBundle $bundle the asset bundle which the asset file belongs to
  312. * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
  313. * @return string|false the actual file path, or `false` if the asset is specified as an absolute URL
  314. */
  315. public function getAssetPath($bundle, $asset)
  316. {
  317. if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
  318. return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false;
  319. }
  320. return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
  321. }
  322. /**
  323. * @param AssetBundle $bundle
  324. * @param string $asset
  325. * @return string|bool
  326. */
  327. protected function resolveAsset($bundle, $asset)
  328. {
  329. if (isset($this->assetMap[$asset])) {
  330. return $this->assetMap[$asset];
  331. }
  332. if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
  333. $asset = $bundle->sourcePath . '/' . $asset;
  334. }
  335. $n = mb_strlen($asset, Yii::$app->charset);
  336. foreach ($this->assetMap as $from => $to) {
  337. $n2 = mb_strlen($from, Yii::$app->charset);
  338. if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
  339. return $to;
  340. }
  341. }
  342. return false;
  343. }
  344. private $_converter;
  345. /**
  346. * Returns the asset converter.
  347. * @return AssetConverterInterface the asset converter.
  348. */
  349. public function getConverter()
  350. {
  351. if ($this->_converter === null) {
  352. $this->_converter = Yii::createObject(AssetConverter::className());
  353. } elseif (is_array($this->_converter) || is_string($this->_converter)) {
  354. if (is_array($this->_converter) && !isset($this->_converter['class'])) {
  355. $this->_converter['class'] = AssetConverter::className();
  356. }
  357. $this->_converter = Yii::createObject($this->_converter);
  358. }
  359. return $this->_converter;
  360. }
  361. /**
  362. * Sets the asset converter.
  363. * @param array|AssetConverterInterface $value the asset converter. This can be either
  364. * an object implementing the [[AssetConverterInterface]], or a configuration
  365. * array that can be used to create the asset converter object.
  366. */
  367. public function setConverter($value)
  368. {
  369. $this->_converter = $value;
  370. }
  371. /**
  372. * @var array published assets
  373. */
  374. private $_published = [];
  375. /**
  376. * Publishes a file or a directory.
  377. *
  378. * This method will copy the specified file or directory to [[basePath]] so that
  379. * it can be accessed via the Web server.
  380. *
  381. * If the asset is a file, its file modification time will be checked to avoid
  382. * unnecessary file copying.
  383. *
  384. * If the asset is a directory, all files and subdirectories under it will be published recursively.
  385. * Note, in case $forceCopy is false the method only checks the existence of the target
  386. * directory to avoid repetitive copying (which is very expensive).
  387. *
  388. * By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
  389. * will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
  390. * as explained in the `$options` parameter.
  391. *
  392. * Note: On rare scenario, a race condition can develop that will lead to a
  393. * one-time-manifestation of a non-critical problem in the creation of the directory
  394. * that holds the published assets. This problem can be avoided altogether by 'requesting'
  395. * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
  396. * that in the application deployment phase, before system goes live. See more in the following
  397. * discussion: http://code.google.com/p/yii/issues/detail?id=2579
  398. *
  399. * @param string $path the asset (file or directory) to be published
  400. * @param array $options the options to be applied when publishing a directory.
  401. * The following options are supported:
  402. *
  403. * - only: array, list of patterns that the file paths should match if they want to be copied.
  404. * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  405. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  406. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  407. * This overrides [[beforeCopy]] if set.
  408. * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
  409. * This overrides [[afterCopy]] if set.
  410. * - forceCopy: boolean, whether the directory being published should be copied even if
  411. * it is found in the target directory. This option is used only when publishing a directory.
  412. * This overrides [[forceCopy]] if set.
  413. *
  414. * @return array the path (directory or file path) and the URL that the asset is published as.
  415. * @throws InvalidArgumentException if the asset to be published does not exist.
  416. * @throws InvalidConfigException if the target directory [[basePath]] is not writeable.
  417. */
  418. public function publish($path, $options = [])
  419. {
  420. $path = Yii::getAlias($path);
  421. if (isset($this->_published[$path])) {
  422. return $this->_published[$path];
  423. }
  424. if (!is_string($path) || ($src = realpath($path)) === false) {
  425. throw new InvalidArgumentException("The file or directory to be published does not exist: $path");
  426. }
  427. if (!is_writable($this->basePath)) {
  428. throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
  429. }
  430. if (is_file($src)) {
  431. return $this->_published[$path] = $this->publishFile($src);
  432. }
  433. return $this->_published[$path] = $this->publishDirectory($src, $options);
  434. }
  435. /**
  436. * Publishes a file.
  437. * @param string $src the asset file to be published
  438. * @return string[] the path and the URL that the asset is published as.
  439. * @throws InvalidArgumentException if the asset to be published does not exist.
  440. */
  441. protected function publishFile($src)
  442. {
  443. $dir = $this->hash($src);
  444. $fileName = basename($src);
  445. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  446. $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
  447. if (!is_dir($dstDir)) {
  448. FileHelper::createDirectory($dstDir, $this->dirMode, true);
  449. }
  450. if ($this->linkAssets) {
  451. if (!is_file($dstFile)) {
  452. try { // fix #6226 symlinking multi threaded
  453. symlink($src, $dstFile);
  454. } catch (\Exception $e) {
  455. if (!is_file($dstFile)) {
  456. throw $e;
  457. }
  458. }
  459. }
  460. } elseif (@filemtime($dstFile) < @filemtime($src)) {
  461. copy($src, $dstFile);
  462. if ($this->fileMode !== null) {
  463. @chmod($dstFile, $this->fileMode);
  464. }
  465. }
  466. if ($this->appendTimestamp && ($timestamp = @filemtime($dstFile)) > 0) {
  467. $fileName = $fileName . "?v=$timestamp";
  468. }
  469. return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
  470. }
  471. /**
  472. * Publishes a directory.
  473. * @param string $src the asset directory to be published
  474. * @param array $options the options to be applied when publishing a directory.
  475. * The following options are supported:
  476. *
  477. * - only: array, list of patterns that the file paths should match if they want to be copied.
  478. * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  479. * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  480. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  481. * This overrides [[beforeCopy]] if set.
  482. * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
  483. * This overrides [[afterCopy]] if set.
  484. * - forceCopy: boolean, whether the directory being published should be copied even if
  485. * it is found in the target directory. This option is used only when publishing a directory.
  486. * This overrides [[forceCopy]] if set.
  487. *
  488. * @return string[] the path directory and the URL that the asset is published as.
  489. * @throws InvalidArgumentException if the asset to be published does not exist.
  490. */
  491. protected function publishDirectory($src, $options)
  492. {
  493. $dir = $this->hash($src);
  494. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  495. if ($this->linkAssets) {
  496. if (!is_dir($dstDir)) {
  497. FileHelper::createDirectory(dirname($dstDir), $this->dirMode, true);
  498. try { // fix #6226 symlinking multi threaded
  499. symlink($src, $dstDir);
  500. } catch (\Exception $e) {
  501. if (!is_dir($dstDir)) {
  502. throw $e;
  503. }
  504. }
  505. }
  506. } elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
  507. $opts = array_merge(
  508. $options,
  509. [
  510. 'dirMode' => $this->dirMode,
  511. 'fileMode' => $this->fileMode,
  512. 'copyEmptyDirectories' => false,
  513. ]
  514. );
  515. if (!isset($opts['beforeCopy'])) {
  516. if ($this->beforeCopy !== null) {
  517. $opts['beforeCopy'] = $this->beforeCopy;
  518. } else {
  519. $opts['beforeCopy'] = function ($from, $to) {
  520. return strncmp(basename($from), '.', 1) !== 0;
  521. };
  522. }
  523. }
  524. if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
  525. $opts['afterCopy'] = $this->afterCopy;
  526. }
  527. FileHelper::copyDirectory($src, $dstDir, $opts);
  528. }
  529. return [$dstDir, $this->baseUrl . '/' . $dir];
  530. }
  531. /**
  532. * Returns the published path of a file path.
  533. * This method does not perform any publishing. It merely tells you
  534. * if the file or directory is published, where it will go.
  535. * @param string $path directory or file path being published
  536. * @return string|false string the published file path. False if the file or directory does not exist
  537. */
  538. public function getPublishedPath($path)
  539. {
  540. $path = Yii::getAlias($path);
  541. if (isset($this->_published[$path])) {
  542. return $this->_published[$path][0];
  543. }
  544. if (is_string($path) && ($path = realpath($path)) !== false) {
  545. return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : '');
  546. }
  547. return false;
  548. }
  549. /**
  550. * Returns the URL of a published file path.
  551. * This method does not perform any publishing. It merely tells you
  552. * if the file path is published, what the URL will be to access it.
  553. * @param string $path directory or file path being published
  554. * @return string|false string the published URL for the file or directory. False if the file or directory does not exist.
  555. */
  556. public function getPublishedUrl($path)
  557. {
  558. $path = Yii::getAlias($path);
  559. if (isset($this->_published[$path])) {
  560. return $this->_published[$path][1];
  561. }
  562. if (is_string($path) && ($path = realpath($path)) !== false) {
  563. return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
  564. }
  565. return false;
  566. }
  567. /**
  568. * Generate a CRC32 hash for the directory path. Collisions are higher
  569. * than MD5 but generates a much smaller hash string.
  570. * @param string $path string to be hashed.
  571. * @return string hashed string.
  572. */
  573. protected function hash($path)
  574. {
  575. if (is_callable($this->hashCallback)) {
  576. return call_user_func($this->hashCallback, $path);
  577. }
  578. $path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
  579. return sprintf('%x', crc32($path . Yii::getVersion() . '|' . $this->linkAssets));
  580. }
  581. }