Completed
Push — master ( 197fee...572e5f )
by Alexander
12:48
created

AssetManager::publish()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6.2163

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 9
cts 11
cp 0.8182
rs 8.9457
c 0
b 0
f 0
cc 6
nc 5
nop 2
crap 6.2163
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
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidArgumentException;
13
use yii\base\InvalidConfigException;
14
use yii\helpers\FileHelper;
15
use yii\helpers\Url;
16
17
/**
18
 * AssetManager manages asset bundle configuration and loading.
19
 *
20
 * AssetManager is configured as an application component in [[\yii\web\Application]] by default.
21
 * You can access that instance via `Yii::$app->assetManager`.
22
 *
23
 * You can modify its configuration by adding an array to your application config under `components`
24
 * as shown in the following example:
25
 *
26
 * ```php
27
 * 'assetManager' => [
28
 *     'bundles' => [
29
 *         // you can override AssetBundle configs here
30
 *     ],
31
 * ]
32
 * ```
33
 *
34
 * For more details and usage information on AssetManager, see the [guide article on assets](guide:structure-assets).
35
 *
36
 * @property AssetConverterInterface $converter The asset converter. Note that the type of this property
37
 * differs in getter and setter. See [[getConverter()]] and [[setConverter()]] for details.
38
 *
39
 * @author Qiang Xue <[email protected]>
40
 * @since 2.0
41
 */
42
class AssetManager extends Component
43
{
44
    /**
45
     * @var array|bool list of asset bundle configurations. This property is provided to customize asset bundles.
46
     * When a bundle is being loaded by [[getBundle()]], if it has a corresponding configuration specified here,
47
     * the configuration will be applied to the bundle.
48
     *
49
     * The array keys are the asset bundle names, which typically are asset bundle class names without leading backslash.
50
     * The array values are the corresponding configurations. If a value is false, it means the corresponding asset
51
     * bundle is disabled and [[getBundle()]] should return null.
52
     *
53
     * If this property is false, it means the whole asset bundle feature is disabled and [[getBundle()]]
54
     * will always return null.
55
     *
56
     * The following example shows how to disable the bootstrap css file used by Bootstrap widgets
57
     * (because you want to use your own styles):
58
     *
59
     * ```php
60
     * [
61
     *     'yii\bootstrap\BootstrapAsset' => [
62
     *         'css' => [],
63
     *     ],
64
     * ]
65
     * ```
66
     */
67
    public $bundles = [];
68
    /**
69
     * @var string the root directory storing the published asset files.
70
     */
71
    public $basePath = '@webroot/assets';
72
    /**
73
     * @var string the base URL through which the published asset files can be accessed.
74
     */
75
    public $baseUrl = '@web/assets';
76
    /**
77
     * @var array mapping from source asset files (keys) to target asset files (values).
78
     *
79
     * This property is provided to support fixing incorrect asset file paths in some asset bundles.
80
     * When an asset bundle is registered with a view, each relative asset file in its [[AssetBundle::css|css]]
81
     * and [[AssetBundle::js|js]] arrays will be examined against this map. If any of the keys is found
82
     * to be the last part of an asset file (which is prefixed with [[AssetBundle::sourcePath]] if available),
83
     * the corresponding value will replace the asset and be registered with the view.
84
     * For example, an asset file `my/path/to/jquery.js` matches a key `jquery.js`.
85
     *
86
     * Note that the target asset files should be absolute URLs, domain relative URLs (starting from '/') or paths
87
     * relative to [[baseUrl]] and [[basePath]].
88
     *
89
     * In the following example, any assets ending with `jquery.min.js` will be replaced with `jquery/dist/jquery.js`
90
     * which is relative to [[baseUrl]] and [[basePath]].
91
     *
92
     * ```php
93
     * [
94
     *     'jquery.min.js' => 'jquery/dist/jquery.js',
95
     * ]
96
     * ```
97
     *
98
     * You may also use aliases while specifying map value, for example:
99
     *
100
     * ```php
101
     * [
102
     *     'jquery.min.js' => '@web/js/jquery/jquery.js',
103
     * ]
104
     * ```
105
     */
106
    public $assetMap = [];
107
    /**
108
     * @var bool whether to use symbolic link to publish asset files. Defaults to false, meaning
109
     * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published
110
     * assets will always be consistent with the source assets and there is no copy operation required.
111
     * This is especially useful during development.
112
     *
113
     * However, there are special requirements for hosting environments in order to use symbolic links.
114
     * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
115
     *
116
     * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
117
     * to Web users. For example, for Apache Web server, the following configuration directive should be added
118
     * for the Web folder:
119
     *
120
     * ```apache
121
     * Options FollowSymLinks
122
     * ```
123
     */
124
    public $linkAssets = false;
125
    /**
126
     * @var int the permission to be set for newly published asset files.
127
     * This value will be used by PHP chmod() function. No umask will be applied.
128
     * If not set, the permission will be determined by the current environment.
129
     */
130
    public $fileMode;
131
    /**
132
     * @var int the permission to be set for newly generated asset directories.
133
     * This value will be used by PHP chmod() function. No umask will be applied.
134
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
135
     * but read-only for other users.
136
     */
137
    public $dirMode = 0775;
138
    /**
139
     * @var callback a PHP callback that is called before copying each sub-directory or file.
140
     * This option is used only when publishing a directory. If the callback returns false, the copy
141
     * operation for the sub-directory or file will be cancelled.
142
     *
143
     * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
144
     * file to be copied from, while `$to` is the copy target.
145
     *
146
     * This is passed as a parameter `beforeCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
147
     */
148
    public $beforeCopy;
149
    /**
150
     * @var callback a PHP callback that is called after a sub-directory or file is successfully copied.
151
     * This option is used only when publishing a directory. The signature of the callback is the same as
152
     * for [[beforeCopy]].
153
     * This is passed as a parameter `afterCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
154
     */
155
    public $afterCopy;
156
    /**
157
     * @var bool whether the directory being published should be copied even if
158
     * it is found in the target directory. This option is used only when publishing a directory.
159
     * You may want to set this to be `true` during the development stage to make sure the published
160
     * directory is always up-to-date. Do not set this to true on production servers as it will
161
     * significantly degrade the performance.
162
     */
163
    public $forceCopy = false;
164
    /**
165
     * @var bool whether to append a timestamp to the URL of every published asset. When this is true,
166
     * the URL of a published asset may look like `/path/to/asset?v=timestamp`, where `timestamp` is the
167
     * last modification time of the published asset file.
168
     * You normally would want to set this property to true when you have enabled HTTP caching for assets,
169
     * because it allows you to bust caching when the assets are updated.
170
     * @since 2.0.3
171
     */
172
    public $appendTimestamp = false;
173
    /**
174
     * @var callable a callback that will be called to produce hash for asset directory generation.
175
     * The signature of the callback should be as follows:
176
     *
177
     * ```
178
     * function ($path)
179
     * ```
180
     *
181
     * where `$path` is the asset path. Note that the `$path` can be either directory where the asset
182
     * files reside or a single file. For a CSS file that uses relative path in `url()`, the hash
183
     * implementation should use the directory path of the file instead of the file path to include
184
     * the relative asset files in the copying.
185
     *
186
     * If this is not set, the asset manager will use the default CRC32 and filemtime in the `hash`
187
     * method.
188
     *
189
     * Example of an implementation using MD4 hash:
190
     *
191
     * ```php
192
     * function ($path) {
193
     *     return hash('md4', $path);
194
     * }
195
     * ```
196
     *
197
     * @since 2.0.6
198
     */
199
    public $hashCallback;
200
201
    private $_dummyBundles = [];
202
203
204
    /**
205
     * Initializes the component.
206
     * @throws InvalidConfigException if [[basePath]] is invalid
207
     */
208 88
    public function init()
209
    {
210 88
        parent::init();
211 88
        $this->basePath = Yii::getAlias($this->basePath);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($this->basePath) can also be of type boolean. However, the property $basePath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
212 88
        if (!is_dir($this->basePath)) {
213
            throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
214
        }
215
216 88
        $this->basePath = realpath($this->basePath);
217 88
        $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
218 88
    }
219
220
    /**
221
     * Returns the named asset bundle.
222
     *
223
     * This method will first look for the bundle in [[bundles]]. If not found,
224
     * it will treat `$name` as the class of the asset bundle and create a new instance of it.
225
     *
226
     * @param string $name the class name of the asset bundle (without the leading backslash)
227
     * @param bool $publish whether to publish the asset files in the asset bundle before it is returned.
228
     * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files.
229
     * @return AssetBundle the asset bundle instance
230
     * @throws InvalidConfigException if $name does not refer to a valid asset bundle
231
     */
232 34
    public function getBundle($name, $publish = true)
233
    {
234 34
        if ($this->bundles === false) {
235
            return $this->loadDummyBundle($name);
236 34
        } elseif (!isset($this->bundles[$name])) {
237 26
            return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
238 21
        } elseif ($this->bundles[$name] instanceof AssetBundle) {
239
            return $this->bundles[$name];
240 21
        } elseif (is_array($this->bundles[$name])) {
241 13
            return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
242 8
        } elseif ($this->bundles[$name] === false) {
243 8
            return $this->loadDummyBundle($name);
244
        }
245
246
        throw new InvalidConfigException("Invalid asset bundle configuration: $name");
247
    }
248
249
    /**
250
     * Loads asset bundle class by name.
251
     *
252
     * @param string $name bundle name
253
     * @param array $config bundle object configuration
254
     * @param bool $publish if bundle should be published
255
     * @return AssetBundle
256
     * @throws InvalidConfigException if configuration isn't valid
257
     */
258 34
    protected function loadBundle($name, $config = [], $publish = true)
259
    {
260 34
        if (!isset($config['class'])) {
261 34
            $config['class'] = $name;
262
        }
263
        /* @var $bundle AssetBundle */
264 34
        $bundle = Yii::createObject($config);
265 34
        if ($publish) {
266 34
            $bundle->publish($this);
267
        }
268
269 34
        return $bundle;
270
    }
271
272
    /**
273
     * Loads dummy bundle by name.
274
     *
275
     * @param string $name
276
     * @return AssetBundle
277
     */
278 8
    protected function loadDummyBundle($name)
279
    {
280 8
        if (!isset($this->_dummyBundles[$name])) {
281 8
            $this->_dummyBundles[$name] = $this->loadBundle($name, [
282 8
                'sourcePath' => null,
283
                'js' => [],
284
                'css' => [],
285
                'depends' => [],
286
            ]);
287
        }
288
289 8
        return $this->_dummyBundles[$name];
290
    }
291
292
    /**
293
     * Returns the actual URL for the specified asset.
294
     * The actual URL is obtained by prepending either [[AssetBundle::$baseUrl]] or [[AssetManager::$baseUrl]] to the given asset path.
295
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
296
     * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
297
     * @return string the actual URL for the specified asset.
298
     */
299 10
    public function getAssetUrl($bundle, $asset)
300
    {
301 10
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
302
            if (strncmp($actualAsset, '@web/', 5) === 0) {
303
                $asset = substr($actualAsset, 5);
304
                $basePath = Yii::getAlias('@webroot');
305
                $baseUrl = Yii::getAlias('@web');
306
            } else {
307
                $asset = Yii::getAlias($actualAsset);
0 ignored issues
show
Bug introduced by
It seems like $actualAsset defined by $this->resolveAsset($bundle, $asset) on line 301 can also be of type boolean; however, yii\BaseYii::getAlias() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug Compatibility introduced by
The expression \Yii::getAlias($actualAsset); of type string|boolean adds the type boolean to the return on line 317 which is incompatible with the return type documented by yii\web\AssetManager::getAssetUrl of type string.
Loading history...
308
                $basePath = $this->basePath;
309
                $baseUrl = $this->baseUrl;
310
            }
311
        } else {
312 10
            $basePath = $bundle->basePath;
313 10
            $baseUrl = $bundle->baseUrl;
314
        }
315
316 10
        if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) {
0 ignored issues
show
Bug introduced by
It seems like $asset defined by \Yii::getAlias($actualAsset) on line 307 can also be of type boolean; however, yii\helpers\BaseUrl::isRelative() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
317
            return $asset;
318
        }
319
320 10
        if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) {
321
            return "$baseUrl/$asset?v=$timestamp";
322
        }
323
324 10
        return "$baseUrl/$asset";
325
    }
326
327
    /**
328
     * Returns the actual file path for the specified asset.
329
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
330
     * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
331
     * @return string|false the actual file path, or `false` if the asset is specified as an absolute URL
332
     */
333
    public function getAssetPath($bundle, $asset)
334
    {
335
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
336
            return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false;
0 ignored issues
show
Bug introduced by
It seems like $actualAsset defined by $this->resolveAsset($bundle, $asset) on line 335 can also be of type boolean; however, yii\helpers\BaseUrl::isRelative() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
337
        }
338
339
        return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
340
    }
341
342
    /**
343
     * @param AssetBundle $bundle
344
     * @param string $asset
345
     * @return string|bool
346
     */
347 10
    protected function resolveAsset($bundle, $asset)
348
    {
349 10
        if (isset($this->assetMap[$asset])) {
350
            return $this->assetMap[$asset];
351
        }
352 10
        if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
353
            $asset = $bundle->sourcePath . '/' . $asset;
354
        }
355
356 10
        $n = mb_strlen($asset, Yii::$app->charset);
357 10
        foreach ($this->assetMap as $from => $to) {
358
            $n2 = mb_strlen($from, Yii::$app->charset);
359
            if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
360
                return $to;
361
            }
362
        }
363
364 10
        return false;
365
    }
366
367
    private $_converter;
368
369
    /**
370
     * Returns the asset converter.
371
     * @return AssetConverterInterface the asset converter.
372
     */
373 28
    public function getConverter()
374
    {
375 28
        if ($this->_converter === null) {
376 28
            $this->_converter = Yii::createObject(AssetConverter::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
377 21
        } elseif (is_array($this->_converter) || is_string($this->_converter)) {
378
            if (is_array($this->_converter) && !isset($this->_converter['class'])) {
379
                $this->_converter['class'] = AssetConverter::className();
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
380
            }
381
            $this->_converter = Yii::createObject($this->_converter);
382
        }
383
384 28
        return $this->_converter;
385
    }
386
387
    /**
388
     * Sets the asset converter.
389
     * @param array|AssetConverterInterface $value the asset converter. This can be either
390
     * an object implementing the [[AssetConverterInterface]], or a configuration
391
     * array that can be used to create the asset converter object.
392
     */
393
    public function setConverter($value)
394
    {
395
        $this->_converter = $value;
396
    }
397
398
    /**
399
     * @var array published assets
400
     */
401
    private $_published = [];
402
403
    /**
404
     * Publishes a file or a directory.
405
     *
406
     * This method will copy the specified file or directory to [[basePath]] so that
407
     * it can be accessed via the Web server.
408
     *
409
     * If the asset is a file, its file modification time will be checked to avoid
410
     * unnecessary file copying.
411
     *
412
     * If the asset is a directory, all files and subdirectories under it will be published recursively.
413
     * Note, in case $forceCopy is false the method only checks the existence of the target
414
     * directory to avoid repetitive copying (which is very expensive).
415
     *
416
     * By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
417
     * will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
418
     * as explained in the `$options` parameter.
419
     *
420
     * Note: On rare scenario, a race condition can develop that will lead to a
421
     * one-time-manifestation of a non-critical problem in the creation of the directory
422
     * that holds the published assets. This problem can be avoided altogether by 'requesting'
423
     * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
424
     * that in the application deployment phase, before system goes live. See more in the following
425
     * discussion: http://code.google.com/p/yii/issues/detail?id=2579
426
     *
427
     * @param string $path the asset (file or directory) to be published
428
     * @param array  $options the options to be applied when publishing a directory.
429
     * The following options are supported:
430
     *
431
     * - only: array, list of patterns that the file paths should match if they want to be copied.
432
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
433
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
434
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
435
     *   This overrides [[beforeCopy]] if set.
436
     * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
437
     *   This overrides [[afterCopy]] if set.
438
     * - forceCopy: boolean, whether the directory being published should be copied even if
439
     *   it is found in the target directory. This option is used only when publishing a directory.
440
     *   This overrides [[forceCopy]] if set.
441
     *
442
     * @return array the path (directory or file path) and the URL that the asset is published as.
443
     * @throws InvalidArgumentException if the asset to be published does not exist.
444
     * @throws InvalidConfigException
445
     */
446 9
    public function publish($path, $options = [])
447
    {
448 9
        $path = Yii::getAlias($path);
449
450 9
        if (isset($this->_published[$path])) {
451 1
            return $this->_published[$path];
452
        }
453
454 9
        if (!is_string($path) || ($src = realpath($path)) === false) {
455
            throw new InvalidArgumentException("The file or directory to be published does not exist: $path");
456
        }
457
458 9
        if (!is_writable($this->basePath)) {
459 1
            throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
460
        }
461
462 8
        if (is_file($src)) {
463
            return $this->_published[$path] = $this->publishFile($src);
464
        }
465
466 8
        return $this->_published[$path] = $this->publishDirectory($src, $options);
467
    }
468
469
    /**
470
     * Publishes a file.
471
     * @param string $src the asset file to be published
472
     * @return string[] the path and the URL that the asset is published as.
473
     * @throws InvalidArgumentException if the asset to be published does not exist.
474
     */
475
    protected function publishFile($src)
476
    {
477
        $dir = $this->hash($src);
478
        $fileName = basename($src);
479
        $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
480
        $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
481
482
        if (!is_dir($dstDir)) {
483
            FileHelper::createDirectory($dstDir, $this->dirMode, true);
484
        }
485
486
        if ($this->linkAssets) {
487
            if (!is_file($dstFile)) {
488
                try { // fix #6226 symlinking multi threaded
489
                    symlink($src, $dstFile);
490
                } catch (\Exception $e) {
491
                    if (!is_file($dstFile)) {
492
                        throw $e;
493
                    }
494
                }
495
            }
496
        } elseif (@filemtime($dstFile) < @filemtime($src)) {
497
            copy($src, $dstFile);
498
            if ($this->fileMode !== null) {
499
                @chmod($dstFile, $this->fileMode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
500
            }
501
        }
502
503
        return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
504
    }
505
506
    /**
507
     * Publishes a directory.
508
     * @param string $src the asset directory to be published
509
     * @param array $options the options to be applied when publishing a directory.
510
     * The following options are supported:
511
     *
512
     * - only: array, list of patterns that the file paths should match if they want to be copied.
513
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
514
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
515
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
516
     *   This overrides [[beforeCopy]] if set.
517
     * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
518
     *   This overrides [[afterCopy]] if set.
519
     * - forceCopy: boolean, whether the directory being published should be copied even if
520
     *   it is found in the target directory. This option is used only when publishing a directory.
521
     *   This overrides [[forceCopy]] if set.
522
     *
523
     * @return string[] the path directory and the URL that the asset is published as.
524
     * @throws InvalidArgumentException if the asset to be published does not exist.
525
     */
526 8
    protected function publishDirectory($src, $options)
527
    {
528 8
        $dir = $this->hash($src);
529 8
        $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
530 8
        if ($this->linkAssets) {
531 2
            if (!is_dir($dstDir)) {
532 2
                FileHelper::createDirectory(dirname($dstDir), $this->dirMode, true);
533
                try { // fix #6226 symlinking multi threaded
534 2
                    symlink($src, $dstDir);
535
                } catch (\Exception $e) {
536
                    if (!is_dir($dstDir)) {
537 2
                        throw $e;
538
                    }
539
                }
540
            }
541 6
        } elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
542 6
            $opts = array_merge(
543 6
                $options,
544
                [
545 6
                    'dirMode' => $this->dirMode,
546 6
                    'fileMode' => $this->fileMode,
547
                    'copyEmptyDirectories' => false,
548
                ]
549
            );
550 6
            if (!isset($opts['beforeCopy'])) {
551 5
                if ($this->beforeCopy !== null) {
552 1
                    $opts['beforeCopy'] = $this->beforeCopy;
553
                } else {
554 4
                    $opts['beforeCopy'] = function ($from, $to) {
0 ignored issues
show
Unused Code introduced by
The parameter $to is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
555 4
                        return strncmp(basename($from), '.', 1) !== 0;
556
                    };
557
                }
558
            }
559 6
            if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
560
                $opts['afterCopy'] = $this->afterCopy;
561
            }
562 6
            FileHelper::copyDirectory($src, $dstDir, $opts);
563
        }
564
565 8
        return [$dstDir, $this->baseUrl . '/' . $dir];
566
    }
567
568
    /**
569
     * Returns the published path of a file path.
570
     * This method does not perform any publishing. It merely tells you
571
     * if the file or directory is published, where it will go.
572
     * @param string $path directory or file path being published
573
     * @return string|false string the published file path. False if the file or directory does not exist
574
     */
575
    public function getPublishedPath($path)
576
    {
577
        $path = Yii::getAlias($path);
578
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
586
        return false;
587
    }
588
589
    /**
590
     * Returns the URL of a published file path.
591
     * This method does not perform any publishing. It merely tells you
592
     * if the file path is published, what the URL will be to access it.
593
     * @param string $path directory or file path being published
594
     * @return string|false string the published URL for the file or directory. False if the file or directory does not exist.
595
     */
596
    public function getPublishedUrl($path)
597
    {
598
        $path = Yii::getAlias($path);
599
600
        if (isset($this->_published[$path])) {
601
            return $this->_published[$path][1];
602
        }
603
        if (is_string($path) && ($path = realpath($path)) !== false) {
604
            return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
605
        }
606
607
        return false;
608
    }
609
610
    /**
611
     * Generate a CRC32 hash for the directory path. Collisions are higher
612
     * than MD5 but generates a much smaller hash string.
613
     * @param string $path string to be hashed.
614
     * @return string hashed string.
615
     */
616 8
    protected function hash($path)
617
    {
618 8
        if (is_callable($this->hashCallback)) {
619 1
            return call_user_func($this->hashCallback, $path);
620
        }
621 7
        $path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
622 7
        return sprintf('%x', crc32($path . Yii::getVersion() . '|' . $this->linkAssets));
623
    }
624
}
625