AssetManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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\InvalidConfigException;
  11. use yii\base\InvalidParamException;
  12. use yii\helpers\FileHelper;
  13. /**
  14. * AssetManager manages asset bundles and asset publishing.
  15. *
  16. * AssetManager is configured as an application component in [[yii\web\Application]] by default.
  17. * You can access that instance via `Yii::$app->assetManager`.
  18. *
  19. * You can modify its configuration by adding an array to your application config under `components`
  20. * as it is shown in the following example:
  21. *
  22. * ~~~
  23. * 'assetManager' => [
  24. * 'bundles' => [
  25. * // you can override AssetBundle configs here
  26. * ],
  27. * //'linkAssets' => true,
  28. * // ...
  29. * ]
  30. * ~~~
  31. *
  32. * @property AssetConverterInterface $converter The asset converter. Note that the type of this property
  33. * differs in getter and setter. See [[getConverter()]] and [[setConverter()]] for details.
  34. *
  35. * @author Qiang Xue <[email protected]>
  36. * @since 2.0
  37. */
  38. class AssetManager extends Component
  39. {
  40. /**
  41. * @var array list of available asset bundles. The keys are the class names (without leading backslash)
  42. * of the asset bundles, and the values are either the configuration arrays for creating the [[AssetBundle]]
  43. * objects or the corresponding asset bundle instances. For example, the following code disables
  44. * the bootstrap css file used by Bootstrap widgets (because you want to use your own styles):
  45. *
  46. * ~~~
  47. * [
  48. * 'yii\bootstrap\BootstrapAsset' => [
  49. * 'css' => [],
  50. * ],
  51. * ]
  52. * ~~~
  53. */
  54. public $bundles = [];
  55. /**
  56. * @return string the root directory storing the published asset files.
  57. */
  58. public $basePath = '@webroot/assets';
  59. /**
  60. * @return string the base URL through which the published asset files can be accessed.
  61. */
  62. public $baseUrl = '@web/assets';
  63. /**
  64. * @var boolean whether to use symbolic link to publish asset files. Defaults to false, meaning
  65. * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published
  66. * assets will always be consistent with the source assets and there is no copy operation required.
  67. * This is especially useful during development.
  68. *
  69. * However, there are special requirements for hosting environments in order to use symbolic links.
  70. * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
  71. *
  72. * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
  73. * to Web users. For example, for Apache Web server, the following configuration directive should be added
  74. * for the Web folder:
  75. *
  76. * ~~~
  77. * Options FollowSymLinks
  78. * ~~~
  79. */
  80. public $linkAssets = false;
  81. /**
  82. * @var integer the permission to be set for newly published asset files.
  83. * This value will be used by PHP chmod() function. No umask will be applied.
  84. * If not set, the permission will be determined by the current environment.
  85. */
  86. public $fileMode;
  87. /**
  88. * @var integer the permission to be set for newly generated asset directories.
  89. * This value will be used by PHP chmod() function. No umask will be applied.
  90. * Defaults to 0775, meaning the directory is read-writable by owner and group,
  91. * but read-only for other users.
  92. */
  93. public $dirMode = 0775;
  94. /**
  95. * Initializes the component.
  96. * @throws InvalidConfigException if [[basePath]] is invalid
  97. */
  98. public function init()
  99. {
  100. parent::init();
  101. $this->basePath = Yii::getAlias($this->basePath);
  102. if (!is_dir($this->basePath)) {
  103. throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
  104. } elseif (!is_writable($this->basePath)) {
  105. throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
  106. } else {
  107. $this->basePath = realpath($this->basePath);
  108. }
  109. $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
  110. }
  111. /**
  112. * Returns the named asset bundle.
  113. *
  114. * This method will first look for the bundle in [[bundles]]. If not found,
  115. * it will treat `$name` as the class of the asset bundle and create a new instance of it.
  116. *
  117. * @param string $name the class name of the asset bundle
  118. * @param boolean $publish whether to publish the asset files in the asset bundle before it is returned.
  119. * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files.
  120. * @return AssetBundle the asset bundle instance
  121. * @throws InvalidConfigException if $name does not refer to a valid asset bundle
  122. */
  123. public function getBundle($name, $publish = true)
  124. {
  125. if (isset($this->bundles[$name])) {
  126. if ($this->bundles[$name] instanceof AssetBundle) {
  127. return $this->bundles[$name];
  128. } elseif (is_array($this->bundles[$name])) {
  129. $bundle = Yii::createObject(array_merge(['class' => $name], $this->bundles[$name]));
  130. } else {
  131. throw new InvalidConfigException("Invalid asset bundle: $name");
  132. }
  133. } else {
  134. $bundle = Yii::createObject($name);
  135. }
  136. if ($publish) {
  137. /** @var AssetBundle $bundle */
  138. $bundle->publish($this);
  139. }
  140. return $this->bundles[$name] = $bundle;
  141. }
  142. private $_converter;
  143. /**
  144. * Returns the asset converter.
  145. * @return AssetConverterInterface the asset converter.
  146. */
  147. public function getConverter()
  148. {
  149. if ($this->_converter === null) {
  150. $this->_converter = Yii::createObject(AssetConverter::className());
  151. } elseif (is_array($this->_converter) || is_string($this->_converter)) {
  152. $this->_converter = Yii::createObject($this->_converter);
  153. }
  154. return $this->_converter;
  155. }
  156. /**
  157. * Sets the asset converter.
  158. * @param array|AssetConverterInterface $value the asset converter. This can be either
  159. * an object implementing the [[AssetConverterInterface]], or a configuration
  160. * array that can be used to create the asset converter object.
  161. */
  162. public function setConverter($value)
  163. {
  164. $this->_converter = $value;
  165. }
  166. /**
  167. * @var array published assets
  168. */
  169. private $_published = [];
  170. /**
  171. * Publishes a file or a directory.
  172. *
  173. * This method will copy the specified file or directory to [[basePath]] so that
  174. * it can be accessed via the Web server.
  175. *
  176. * If the asset is a file, its file modification time will be checked to avoid
  177. * unnecessary file copying.
  178. *
  179. * If the asset is a directory, all files and subdirectories under it will be published recursively.
  180. * Note, in case $forceCopy is false the method only checks the existence of the target
  181. * directory to avoid repetitive copying (which is very expensive).
  182. *
  183. * By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
  184. * will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
  185. * as explained in the `$options` parameter.
  186. *
  187. * Note: On rare scenario, a race condition can develop that will lead to a
  188. * one-time-manifestation of a non-critical problem in the creation of the directory
  189. * that holds the published assets. This problem can be avoided altogether by 'requesting'
  190. * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
  191. * that in the application deployment phase, before system goes live. See more in the following
  192. * discussion: http://code.google.com/p/yii/issues/detail?id=2579
  193. *
  194. * @param string $path the asset (file or directory) to be published
  195. * @param array $options the options to be applied when publishing a directory.
  196. * The following options are supported:
  197. *
  198. * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  199. * This option is used only when publishing a directory. If the callback returns false, the copy
  200. * operation for the sub-directory or file will be cancelled.
  201. * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
  202. * file to be copied from, while `$to` is the copy target.
  203. * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
  204. * This option is used only when publishing a directory. The signature of the callback is similar to that
  205. * of `beforeCopy`.
  206. * - forceCopy: boolean, whether the directory being published should be copied even if
  207. * it is found in the target directory. This option is used only when publishing a directory.
  208. * You may want to set this to be true during the development stage to make sure the published
  209. * directory is always up-to-date. Do not set this to true on production servers as it will
  210. * significantly degrade the performance.
  211. * @return array the path (directory or file path) and the URL that the asset is published as.
  212. * @throws InvalidParamException if the asset to be published does not exist.
  213. */
  214. public function publish($path, $options = [])
  215. {
  216. if (isset($this->_published[$path])) {
  217. return $this->_published[$path];
  218. }
  219. $src = realpath($path);
  220. if ($src === false) {
  221. throw new InvalidParamException("The file or directory to be published does not exist: $path");
  222. }
  223. if (is_file($src)) {
  224. $dir = $this->hash(dirname($src) . filemtime($src));
  225. $fileName = basename($src);
  226. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  227. $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
  228. if (!is_dir($dstDir)) {
  229. FileHelper::createDirectory($dstDir, $this->dirMode, true);
  230. }
  231. if ($this->linkAssets) {
  232. if (!is_file($dstFile)) {
  233. symlink($src, $dstFile);
  234. }
  235. } elseif (@filemtime($dstFile) < @filemtime($src)) {
  236. copy($src, $dstFile);
  237. if ($this->fileMode !== null) {
  238. @chmod($dstFile, $this->fileMode);
  239. }
  240. }
  241. return $this->_published[$path] = [$dstFile, $this->baseUrl . "/$dir/$fileName"];
  242. } else {
  243. $dir = $this->hash($src . filemtime($src));
  244. $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
  245. if ($this->linkAssets) {
  246. if (!is_dir($dstDir)) {
  247. symlink($src, $dstDir);
  248. }
  249. } elseif (!is_dir($dstDir) || !empty($options['forceCopy'])) {
  250. $opts = [
  251. 'dirMode' => $this->dirMode,
  252. 'fileMode' => $this->fileMode,
  253. ];
  254. if (isset($options['beforeCopy'])) {
  255. $opts['beforeCopy'] = $options['beforeCopy'];
  256. } else {
  257. $opts['beforeCopy'] = function ($from, $to) {
  258. return strncmp(basename($from), '.', 1) !== 0;
  259. };
  260. }
  261. if (isset($options['afterCopy'])) {
  262. $opts['afterCopy'] = $options['afterCopy'];
  263. }
  264. FileHelper::copyDirectory($src, $dstDir, $opts);
  265. }
  266. return $this->_published[$path] = [$dstDir, $this->baseUrl . '/' . $dir];
  267. }
  268. }
  269. /**
  270. * Returns the published path of a file path.
  271. * This method does not perform any publishing. It merely tells you
  272. * if the file or directory is published, where it will go.
  273. * @param string $path directory or file path being published
  274. * @return string the published file path. False if the file or directory does not exist
  275. */
  276. public function getPublishedPath($path)
  277. {
  278. if (isset($this->_published[$path])) {
  279. return $this->_published[$path][0];
  280. }
  281. if (($path = realpath($path)) !== false) {
  282. $base = $this->basePath . DIRECTORY_SEPARATOR;
  283. if (is_file($path)) {
  284. return $base . $this->hash(dirname($path) . filemtime($path)) . DIRECTORY_SEPARATOR . basename($path);
  285. } else {
  286. return $base . $this->hash($path . filemtime($path));
  287. }
  288. } else {
  289. return false;
  290. }
  291. }
  292. /**
  293. * Returns the URL of a published file path.
  294. * This method does not perform any publishing. It merely tells you
  295. * if the file path is published, what the URL will be to access it.
  296. * @param string $path directory or file path being published
  297. * @return string the published URL for the file or directory. False if the file or directory does not exist.
  298. */
  299. public function getPublishedUrl($path)
  300. {
  301. if (isset($this->_published[$path])) {
  302. return $this->_published[$path][1];
  303. }
  304. if (($path = realpath($path)) !== false) {
  305. if (is_file($path)) {
  306. return $this->baseUrl . '/' . $this->hash(dirname($path) . filemtime($path)) . '/' . basename($path);
  307. } else {
  308. return $this->baseUrl . '/' . $this->hash($path . filemtime($path));
  309. }
  310. } else {
  311. return false;
  312. }
  313. }
  314. /**
  315. * Generate a CRC32 hash for the directory path. Collisions are higher
  316. * than MD5 but generates a much smaller hash string.
  317. * @param string $path string to be hashed.
  318. * @return string hashed string.
  319. */
  320. protected function hash($path)
  321. {
  322. return sprintf('%x', crc32($path . Yii::getVersion()));
  323. }
  324. }