AssetManager.php 11.6 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8 9 10 11 12 13
namespace yii\web;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
14
use yii\helpers\FileHelper;
Qiang Xue committed
15 16

/**
17
 * AssetManager manages asset bundles and asset publishing.
Qiang Xue committed
18
 *
Qiang Xue committed
19 20
 * @property AssetConverterInterface $converter The asset converter. Note that the type of this property
 * differs in getter and setter. See [[getConverter()]] and [[setConverter()]] for details.
21
 *
Qiang Xue committed
22
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
23
 * @since 2.0
Qiang Xue committed
24
 */
Qiang Xue committed
25
class AssetManager extends Component
Qiang Xue committed
26 27
{
	/**
28 29 30
	 * @var array list of available asset bundles. The keys are the class names of the asset bundles,
	 * and the values are either the configuration arrays for creating the [[AssetBundle]] objects
	 * or the corresponding asset bundle instances.
Qiang Xue committed
31
	 */
Alexander Makarov committed
32
	public $bundles = [];
Qiang Xue committed
33 34 35
	/**
	 * @return string the root directory storing the published asset files.
	 */
36
	public $basePath = '@webroot/assets';
Qiang Xue committed
37 38
	/**
	 * @return string the base URL through which the published asset files can be accessed.
Qiang Xue committed
39
	 */
40
	public $baseUrl = '@web/assets';
Qiang Xue committed
41 42
	/**
	 * @var boolean whether to use symbolic link to publish asset files. Defaults to false, meaning
Qiang Xue committed
43 44 45
	 * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published
	 * assets will always be consistent with the source assets and there is no copy operation required.
	 * This is especially useful during development.
Qiang Xue committed
46 47 48 49 50 51 52 53
	 *
	 * However, there are special requirements for hosting environments in order to use symbolic links.
	 * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
	 *
	 * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
	 * to Web users. For example, for Apache Web server, the following configuration directive should be added
	 * for the Web folder:
	 *
Qiang Xue committed
54 55 56
	 * ~~~
	 * Options FollowSymLinks
	 * ~~~
Qiang Xue committed
57
	 */
Qiang Xue committed
58
	public $linkAssets = false;
Qiang Xue committed
59
	/**
60
	 * @var integer the permission to be set for newly published asset files.
61
	 * This value will be used by PHP chmod() function. No umask will be applied.
62
	 * If not set, the permission will be determined by the current environment.
Qiang Xue committed
63
	 */
64
	public $fileMode;
Qiang Xue committed
65 66
	/**
	 * @var integer the permission to be set for newly generated asset directories.
67 68 69
	 * This value will be used by PHP chmod() function. No umask will be applied.
	 * Defaults to 0775, meaning the directory is read-writable by owner and group,
	 * but read-only for other users.
Qiang Xue committed
70
	 */
71
	public $dirMode = 0775;
72

Qiang Xue committed
73
	/**
74 75
	 * Initializes the component.
	 * @throws InvalidConfigException if [[basePath]] is invalid
Qiang Xue committed
76
	 */
Qiang Xue committed
77
	public function init()
Qiang Xue committed
78
	{
Qiang Xue committed
79 80 81 82 83 84 85
		parent::init();
		$this->basePath = Yii::getAlias($this->basePath);
		if (!is_dir($this->basePath)) {
			throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
		} elseif (!is_writable($this->basePath)) {
			throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
		} else {
Qiang Xue committed
86
			$this->basePath = realpath($this->basePath);
Qiang Xue committed
87
		}
Qiang Xue committed
88
		$this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
Qiang Xue committed
89 90 91
	}

	/**
92
	 * Returns the named asset bundle.
Qiang Xue committed
93
	 *
94 95
	 * This method will first look for the bundle in [[bundles]]. If not found,
	 * it will treat `$name` as the class of the asset bundle and create a new instance of it.
Qiang Xue committed
96
	 *
97
	 * @param string $name the class name of the asset bundle
98 99
	 * @param boolean $publish whether to publish the asset files in the asset bundle before it is returned.
	 * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files.
100 101
	 * @return AssetBundle the asset bundle instance
	 * @throws InvalidConfigException if $name does not refer to a valid asset bundle
Qiang Xue committed
102
	 */
103
	public function getBundle($name, $publish = true)
Qiang Xue committed
104
	{
105
		if (isset($this->bundles[$name])) {
Qiang Xue committed
106 107 108 109 110
			if ($this->bundles[$name] instanceof AssetBundle) {
				return $this->bundles[$name];
			} elseif (is_array($this->bundles[$name])) {
				$bundle = Yii::createObject(array_merge(array('class' => $name), $this->bundles[$name]));
			} else {
111
				throw new InvalidConfigException("Invalid asset bundle: $name");
Qiang Xue committed
112
			}
113
		} else {
Qiang Xue committed
114
			$bundle = Yii::createObject($name);
Qiang Xue committed
115
		}
116 117 118 119
		if ($publish) {
			/** @var AssetBundle $bundle */
			$bundle->publish($this);
		}
Qiang Xue committed
120
		return $this->bundles[$name] = $bundle;
Qiang Xue committed
121 122
	}

Qiang Xue committed
123 124
	private $_converter;

Qiang Xue committed
125
	/**
126
	 * Returns the asset converter.
127
	 * @return AssetConverterInterface the asset converter.
Qiang Xue committed
128
	 */
Qiang Xue committed
129
	public function getConverter()
Qiang Xue committed
130
	{
Qiang Xue committed
131
		if ($this->_converter === null) {
132
			$this->_converter = Yii::createObject(AssetConverter::className());
Qiang Xue committed
133 134
		} elseif (is_array($this->_converter) || is_string($this->_converter)) {
			$this->_converter = Yii::createObject($this->_converter);
135
		}
Qiang Xue committed
136 137 138
		return $this->_converter;
	}

139 140
	/**
	 * Sets the asset converter.
141 142
	 * @param array|AssetConverterInterface $value the asset converter. This can be either
	 * an object implementing the [[AssetConverterInterface]], or a configuration
143 144
	 * array that can be used to create the asset converter object.
	 */
Qiang Xue committed
145 146 147
	public function setConverter($value)
	{
		$this->_converter = $value;
Qiang Xue committed
148 149
	}

150 151 152
	/**
	 * @var array published assets
	 */
Alexander Makarov committed
153
	private $_published = [];
154

Qiang Xue committed
155 156
	/**
	 * Publishes a file or a directory.
157 158 159 160 161 162 163 164 165 166
	 *
	 * This method will copy the specified file or directory to [[basePath]] so that
	 * it can be accessed via the Web server.
	 *
	 * If the asset is a file, its file modification time will be checked to avoid
	 * unnecessary file copying.
	 *
	 * If the asset is a directory, all files and subdirectories under it will be published recursively.
	 * Note, in case $forceCopy is false the method only checks the existence of the target
	 * directory to avoid repetitive copying (which is very expensive).
Qiang Xue committed
167
	 *
Qiang Xue committed
168 169 170 171
	 * By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
	 * will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
	 * as explained in the `$options` parameter.
	 *
Qiang Xue committed
172 173 174 175 176 177 178 179
	 * Note: On rare scenario, a race condition can develop that will lead to a
	 * one-time-manifestation of a non-critical problem in the creation of the directory
	 * that holds the published assets. This problem can be avoided altogether by 'requesting'
	 * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
	 * that in the application deployment phase, before system goes live. See more in the following
	 * discussion: http://code.google.com/p/yii/issues/detail?id=2579
	 *
	 * @param string $path the asset (file or directory) to be published
Qiang Xue committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
	 * @param array $options the options to	be applied when publishing a directory.
	 * The following options are supported:
	 *
	 * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
	 *   This option is used only when publishing a directory. If the callback returns false, the copy
	 *   operation for the sub-directory or file will be cancelled.
	 *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
 	 *   file to be copied from, while `$to` is the copy target.
	 * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
	 *   This option is used only when publishing a directory. The signature of the callback is similar to that
	 *   of `beforeCopy`.
	 * - forceCopy: boolean, whether the directory being published should be copied even if
	 *   it is found in the target directory. This option is used only when publishing a directory.
	 *   You may want to set this to be true during the development stage to make sure the published
	 *   directory is always up-to-date. Do not set this to true on production servers as it will
	 *   significantly degrade the performance.
Qiang Xue committed
196
	 * @return array the path (directory or file path) and the URL that the asset is published as.
197
	 * @throws InvalidParamException if the asset to be published does not exist.
Qiang Xue committed
198
	 */
Alexander Makarov committed
199
	public function publish($path, $options = [])
Qiang Xue committed
200
	{
Qiang Xue committed
201
		if (isset($this->_published[$path])) {
Qiang Xue committed
202
			return $this->_published[$path];
Qiang Xue committed
203
		}
Qiang Xue committed
204

Qiang Xue committed
205 206 207 208 209 210
		$src = realpath($path);
		if ($src === false) {
			throw new InvalidParamException("The file or directory to be published does not exist: $path");
		}

		if (is_file($src)) {
211
			$dir = $this->hash(dirname($src) . filemtime($src));
Qiang Xue committed
212 213 214
			$fileName = basename($src);
			$dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
			$dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
Qiang Xue committed
215

Qiang Xue committed
216
			if (!is_dir($dstDir)) {
217
				FileHelper::createDirectory($dstDir, $this->dirMode, true);
Qiang Xue committed
218
			}
Qiang Xue committed
219

Qiang Xue committed
220 221 222 223
			if ($this->linkAssets) {
				if (!is_file($dstFile)) {
					symlink($src, $dstFile);
				}
Qiang Xue committed
224
			} elseif (@filemtime($dstFile) < @filemtime($src)) {
Qiang Xue committed
225
				copy($src, $dstFile);
226 227 228
				if ($this->fileMode !== null) {
					@chmod($dstFile, $this->fileMode);
				}
Qiang Xue committed
229 230
			}

Alexander Makarov committed
231
			return $this->_published[$path] = [$dstFile, $this->baseUrl . "/$dir/$fileName"];
Qiang Xue committed
232
		} else {
233
			$dir = $this->hash($src . filemtime($src));
Qiang Xue committed
234 235 236 237 238
			$dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
			if ($this->linkAssets) {
				if (!is_dir($dstDir)) {
					symlink($src, $dstDir);
				}
Qiang Xue committed
239
			} elseif (!is_dir($dstDir) || !empty($options['forceCopy'])) {
Alexander Makarov committed
240
				$opts = [
241 242
					'dirMode' => $this->dirMode,
					'fileMode' => $this->fileMode,
Alexander Makarov committed
243
				];
Qiang Xue committed
244 245
				if (isset($options['beforeCopy'])) {
					$opts['beforeCopy'] = $options['beforeCopy'];
Qiang Xue committed
246 247 248 249
				} else {
					$opts['beforeCopy'] = function ($from, $to) {
						return strncmp(basename($from), '.', 1) !== 0;
					};
Qiang Xue committed
250 251 252 253 254
				}
				if (isset($options['afterCopy'])) {
					$opts['afterCopy'] = $options['afterCopy'];
				}
				FileHelper::copyDirectory($src, $dstDir, $opts);
Qiang Xue committed
255
			}
Qiang Xue committed
256

Alexander Makarov committed
257
			return $this->_published[$path] = [$dstDir, $this->baseUrl . '/' . $dir];
Qiang Xue committed
258 259 260 261 262 263 264 265 266 267
		}
	}

	/**
	 * Returns the published path of a file path.
	 * This method does not perform any publishing. It merely tells you
	 * if the file or directory is published, where it will go.
	 * @param string $path directory or file path being published
	 * @return string the published file path. False if the file or directory does not exist
	 */
268
	public function getPublishedPath($path)
Qiang Xue committed
269
	{
Qiang Xue committed
270 271 272
		if (isset($this->_published[$path])) {
			return $this->_published[$path][0];
		}
Qiang Xue committed
273
		if (($path = realpath($path)) !== false) {
Qiang Xue committed
274
			$base = $this->basePath . DIRECTORY_SEPARATOR;
Qiang Xue committed
275
			if (is_file($path)) {
276
				return $base . $this->hash(dirname($path) . filemtime($path)) . DIRECTORY_SEPARATOR . basename($path);
Qiang Xue committed
277
			} else {
278
				return $base . $this->hash($path . filemtime($path));
Qiang Xue committed
279 280
			}
		} else {
Qiang Xue committed
281
			return false;
Qiang Xue committed
282
		}
Qiang Xue committed
283 284 285 286 287 288 289 290 291
	}

	/**
	 * Returns the URL of a published file path.
	 * This method does not perform any publishing. It merely tells you
	 * if the file path is published, what the URL will be to access it.
	 * @param string $path directory or file path being published
	 * @return string the published URL for the file or directory. False if the file or directory does not exist.
	 */
292
	public function getPublishedUrl($path)
Qiang Xue committed
293
	{
Qiang Xue committed
294
		if (isset($this->_published[$path])) {
Qiang Xue committed
295
			return $this->_published[$path][1];
Qiang Xue committed
296
		}
Qiang Xue committed
297 298
		if (($path = realpath($path)) !== false) {
			if (is_file($path)) {
299
				return $this->baseUrl . '/' . $this->hash(dirname($path) . filemtime($path)) . '/' . basename($path);
Qiang Xue committed
300
			} else {
301
				return $this->baseUrl . '/' . $this->hash($path . filemtime($path));
Qiang Xue committed
302 303
			}
		} else {
Qiang Xue committed
304
			return false;
Qiang Xue committed
305
		}
Qiang Xue committed
306 307 308 309 310 311 312 313 314 315
	}

	/**
	 * Generate a CRC32 hash for the directory path. Collisions are higher
	 * than MD5 but generates a much smaller hash string.
	 * @param string $path string to be hashed.
	 * @return string hashed string.
	 */
	protected function hash($path)
	{
Qiang Xue committed
316
		return sprintf('%x', crc32($path . Yii::getVersion()));
Qiang Xue committed
317 318
	}
}