AssetManager   F
last analyzed

Complexity

Total Complexity 86

Size/Duplication

Total Lines 639
Duplicated Lines 0 %

Test Coverage

Coverage 72.89%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 167
dl 0
loc 639
ccs 121
cts 166
cp 0.7289
rs 2
c 2
b 0
f 0
wmc 86

17 Methods

Rating   Name   Duplication   Size   Complexity  
A getConverter() 0 12 6
A getBundle() 0 15 6
A loadDummyBundle() 0 12 2
B resolveAsset() 0 18 7
A getAssetUrl() 0 15 5
A loadBundle() 0 12 3
A setConverter() 0 3 1
A getAssetPath() 0 7 4
A checkBasePathPermission() 0 16 4
A init() 0 7 1
A hash() 0 7 3
B publishFile() 0 35 10
A getPublishedUrl() 0 12 5
A getPublishedPath() 0 12 5
A getActualAssetUrl() 0 19 5
A publish() 0 21 6
C publishDirectory() 0 42 13

How to fix   Complexity   

Complex Class

Complex classes like AssetManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AssetManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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|false 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 string[] 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|null 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 callable|null 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 callable|null 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|null 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
    /**
202
     * @var array
203
     */
204
    private $_dummyBundles = [];
205
206
207
    /**
208
     * Initializes the component.
209
     * @throws InvalidConfigException if [[basePath]] does not exist.
210
     */
211 100
    public function init()
212
    {
213 100
        parent::init();
214 100
        $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 false. 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...
215
216 100
        $this->basePath = realpath($this->basePath);
0 ignored issues
show
Bug introduced by
It seems like $this->basePath can also be of type false; however, parameter $path of realpath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

216
        $this->basePath = realpath(/** @scrutinizer ignore-type */ $this->basePath);
Loading history...
217 100
        $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
0 ignored issues
show
Bug introduced by
It seems like Yii::getAlias($this->baseUrl) can also be of type false; however, parameter $string of rtrim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

217
        $this->baseUrl = rtrim(/** @scrutinizer ignore-type */ Yii::getAlias($this->baseUrl), '/');
Loading history...
218
    }
219
220
    /**
221
     * @var bool|null
222
     */
223
    private $_isBasePathPermissionChecked;
224
225
    /**
226
     * Check whether the basePath exists and is writeable.
227
     *
228
     * @since 2.0.40
229
     */
230 14
    public function checkBasePathPermission()
231
    {
232
        // if the check is been done already, skip further checks
233 14
        if ($this->_isBasePathPermissionChecked) {
234
            return;
235
        }
236
237 14
        if (!is_dir($this->basePath)) {
238
            throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
239
        }
240
241 14
        if (!is_writable($this->basePath)) {
242 1
            throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
243
        }
244
245 13
        $this->_isBasePathPermissionChecked = true;
246
    }
247
248
    /**
249
     * Returns the named asset bundle.
250
     *
251
     * This method will first look for the bundle in [[bundles]]. If not found,
252
     * it will treat `$name` as the class of the asset bundle and create a new instance of it.
253
     *
254
     * @param string $name the class name of the asset bundle (without the leading backslash)
255
     * @param bool $publish whether to publish the asset files in the asset bundle before it is returned.
256
     * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files.
257
     * @return AssetBundle the asset bundle instance
258
     * @throws InvalidConfigException if $name does not refer to a valid asset bundle
259
     */
260 39
    public function getBundle($name, $publish = true)
261
    {
262 39
        if ($this->bundles === false) {
263
            return $this->loadDummyBundle($name);
264 39
        } elseif (!isset($this->bundles[$name])) {
265 35
            return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
266 25
        } elseif ($this->bundles[$name] instanceof AssetBundle) {
267 4
            return $this->bundles[$name];
268 21
        } elseif (is_array($this->bundles[$name])) {
269 13
            return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
270 8
        } elseif ($this->bundles[$name] === false) {
271 8
            return $this->loadDummyBundle($name);
272
        }
273
274
        throw new InvalidConfigException("Invalid asset bundle configuration: $name");
275
    }
276
277
    /**
278
     * Loads asset bundle class by name.
279
     *
280
     * @param string $name bundle name
281
     * @param array $config bundle object configuration
282
     * @param bool $publish if bundle should be published
283
     * @return AssetBundle
284
     * @throws InvalidConfigException if configuration isn't valid
285
     */
286 36
    protected function loadBundle($name, $config = [], $publish = true)
287
    {
288 36
        if (!isset($config['class'])) {
289 36
            $config['class'] = $name;
290
        }
291
        /* @var $bundle AssetBundle */
292 36
        $bundle = Yii::createObject($config);
293 36
        if ($publish) {
294 36
            $bundle->publish($this);
295
        }
296
297 36
        return $bundle;
298
    }
299
300
    /**
301
     * Loads dummy bundle by name.
302
     *
303
     * @param string $name
304
     * @return AssetBundle
305
     */
306 8
    protected function loadDummyBundle($name)
307
    {
308 8
        if (!isset($this->_dummyBundles[$name])) {
309 8
            $bundle = Yii::createObject(['class' => $name]);
310 8
            $bundle->sourcePath = null;
311 8
            $bundle->js = [];
312 8
            $bundle->css = [];
313
314 8
            $this->_dummyBundles[$name] = $bundle;
315
        }
316
317 8
        return $this->_dummyBundles[$name];
318
    }
319
320
    /**
321
     * Returns the actual URL for the specified asset.
322
     * The actual URL is obtained by prepending either [[AssetBundle::$baseUrl]] or [[AssetManager::$baseUrl]] to the given asset path.
323
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
324
     * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
325
     * @param bool|null $appendTimestamp Whether to append timestamp to the URL.
326
     * @return string the actual URL for the specified asset.
327
     */
328 15
    public function getAssetUrl($bundle, $asset, $appendTimestamp = null)
329
    {
330 15
        $assetUrl = $this->getActualAssetUrl($bundle, $asset);
331 15
        $assetPath = $this->getAssetPath($bundle, $asset);
332
333 15
        $withTimestamp = $this->appendTimestamp;
334 15
        if ($appendTimestamp !== null) {
335 2
            $withTimestamp = $appendTimestamp;
336
        }
337
338 15
        if ($withTimestamp && $assetPath && ($timestamp = @filemtime($assetPath)) > 0) {
339 3
            return "$assetUrl?v=$timestamp";
340
        }
341
342 14
        return $assetUrl;
343
    }
344
345
    /**
346
     * Returns the actual file path for the specified asset.
347
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
348
     * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
349
     * @return string|false the actual file path, or `false` if the asset is specified as an absolute URL
350
     */
351 15
    public function getAssetPath($bundle, $asset)
352
    {
353 15
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
354
            return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false;
355
        }
356
357 15
        return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
358
    }
359
360
    /**
361
     * @param AssetBundle $bundle
362
     * @param string $asset
363
     * @return string|false
364
     */
365 15
    protected function resolveAsset($bundle, $asset)
366
    {
367 15
        if (isset($this->assetMap[$asset])) {
368
            return $this->assetMap[$asset];
369
        }
370 15
        if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
371
            $asset = $bundle->sourcePath . '/' . $asset;
372
        }
373
374 15
        $n = mb_strlen($asset, Yii::$app->charset);
375 15
        foreach ($this->assetMap as $from => $to) {
376
            $n2 = mb_strlen($from, Yii::$app->charset);
377
            if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
378
                return $to;
379
            }
380
        }
381
382 15
        return false;
383
    }
384
385
    /**
386
     * @var AssetConverterInterface
387
     */
388
    private $_converter;
389
390
    /**
391
     * Returns the asset converter.
392
     * @return AssetConverterInterface the asset converter.
393
     */
394 33
    public function getConverter()
395
    {
396 33
        if ($this->_converter === null) {
397 33
            $this->_converter = Yii::createObject(AssetConverter::className());
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

397
            $this->_converter = Yii::createObject(/** @scrutinizer ignore-deprecated */ AssetConverter::className());

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

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

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

522
                /** @scrutinizer ignore-unhandled */ @chmod($dstFile, $this->fileMode);

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...
523
            }
524
        }
525
526 1
        if ($this->appendTimestamp && ($timestamp = @filemtime($dstFile)) > 0) {
527 1
            $fileName = $fileName . "?v=$timestamp";
528
        }
529
530 1
        return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
531
    }
532
533
    /**
534
     * Publishes a directory.
535
     * @param string $src the asset directory to be published
536
     * @param array $options the options to be applied when publishing a directory.
537
     * The following options are supported:
538
     *
539
     * - only: array, list of patterns that the file paths should match if they want to be copied.
540
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
541
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
542
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
543
     *   This overrides [[beforeCopy]] if set.
544
     * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
545
     *   This overrides [[afterCopy]] if set.
546
     * - forceCopy: boolean, whether the directory being published should be copied even if
547
     *   it is found in the target directory. This option is used only when publishing a directory.
548
     *   This overrides [[forceCopy]] if set.
549
     *
550
     * @return string[] the path directory and the URL that the asset is published as.
551
     * @throws InvalidArgumentException if the asset to be published does not exist.
552
     */
553 13
    protected function publishDirectory($src, $options)
554
    {
555 13
        $this->checkBasePathPermission();
556
557 12
        $dir = $this->hash($src);
558 12
        $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
559 12
        if ($this->linkAssets) {
560 2
            if (!is_dir($dstDir)) {
561 2
                FileHelper::createDirectory(dirname($dstDir), $this->dirMode, true);
562
                try { // fix #6226 symlinking multi threaded
563 2
                    symlink($src, $dstDir);
564
                } catch (\Exception $e) {
565
                    if (!is_dir($dstDir)) {
566 2
                        throw $e;
567
                    }
568
                }
569
            }
570 10
        } elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
571 6
            $opts = array_merge(
572 6
                $options,
573 6
                [
574 6
                    'dirMode' => $this->dirMode,
575 6
                    'fileMode' => $this->fileMode,
576 6
                    'copyEmptyDirectories' => false,
577 6
                ]
578 6
            );
579 6
            if (!isset($opts['beforeCopy'])) {
580 5
                if ($this->beforeCopy !== null) {
581 1
                    $opts['beforeCopy'] = $this->beforeCopy;
582
                } else {
583 4
                    $opts['beforeCopy'] = function ($from, $to) {
0 ignored issues
show
Unused Code introduced by
The parameter $to is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

583
                    $opts['beforeCopy'] = function ($from, /** @scrutinizer ignore-unused */ $to) {

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

Loading history...
584 4
                        return strncmp(basename($from), '.', 1) !== 0;
585 4
                    };
586
                }
587
            }
588 6
            if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
589
                $opts['afterCopy'] = $this->afterCopy;
590
            }
591 6
            FileHelper::copyDirectory($src, $dstDir, $opts);
592
        }
593
594 12
        return [$dstDir, $this->baseUrl . '/' . $dir];
595
    }
596
597
    /**
598
     * Returns the published path of a file path.
599
     * This method does not perform any publishing. It merely tells you
600
     * if the file or directory is published, where it will go.
601
     * @param string $path directory or file path being published
602
     * @return string|false string the published file path. False if the file or directory does not exist
603
     */
604
    public function getPublishedPath($path)
605
    {
606
        $path = Yii::getAlias($path);
607
608
        if (isset($this->_published[$path])) {
609
            return $this->_published[$path][0];
610
        }
611
        if (is_string($path) && ($path = realpath($path)) !== false) {
612
            return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : '');
613
        }
614
615
        return false;
616
    }
617
618
    /**
619
     * Returns the URL of a published file path.
620
     * This method does not perform any publishing. It merely tells you
621
     * if the file path is published, what the URL will be to access it.
622
     * @param string $path directory or file path being published
623
     * @return string|false string the published URL for the file or directory. False if the file or directory does not exist.
624
     */
625
    public function getPublishedUrl($path)
626
    {
627
        $path = Yii::getAlias($path);
628
629
        if (isset($this->_published[$path])) {
630
            return $this->_published[$path][1];
631
        }
632
        if (is_string($path) && ($path = realpath($path)) !== false) {
633
            return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
634
        }
635
636
        return false;
637
    }
638
639
    /**
640
     * Generate a CRC32 hash for the directory path. Collisions are higher
641
     * than MD5 but generates a much smaller hash string.
642
     * @param string $path string to be hashed.
643
     * @return string hashed string.
644
     */
645 13
    protected function hash($path)
646
    {
647 13
        if (is_callable($this->hashCallback)) {
648 1
            return call_user_func($this->hashCallback, $path);
0 ignored issues
show
Bug introduced by
It seems like $this->hashCallback can also be of type null; however, parameter $callback of call_user_func() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

648
            return call_user_func(/** @scrutinizer ignore-type */ $this->hashCallback, $path);
Loading history...
649
        }
650 12
        $path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
651 12
        return sprintf('%x', crc32($path . Yii::getVersion() . '|' . $this->linkAssets));
652
    }
653
654
    /**
655
     * Returns the actual URL for the specified asset. Without parameters.
656
     * The actual URL is obtained by prepending either [[AssetBundle::$baseUrl]] or [[AssetManager::$baseUrl]] to the given asset path.
657
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
658
     * @param string $asset the asset path. This should be one of the assets listed in [[AssetBundle::$js]] or [[AssetBundle::$css]].
659
     * @return string the actual URL for the specified asset.
660
     * @since 2.0.39
661
     */
662 15
    public function getActualAssetUrl($bundle, $asset)
663
    {
664 15
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
665
            if (strncmp($actualAsset, '@web/', 5) === 0) {
666
                $asset = substr($actualAsset, 5);
667
                $baseUrl = Yii::getAlias('@web');
668
            } else {
669
                $asset = Yii::getAlias($actualAsset);
670
                $baseUrl = $this->baseUrl;
671
            }
672
        } else {
673 15
            $baseUrl = $bundle->baseUrl;
674
        }
675
676 15
        if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) {
0 ignored issues
show
Bug introduced by
It seems like $asset can also be of type false; however, parameter $url of yii\helpers\BaseUrl::isRelative() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

676
        if (!Url::isRelative(/** @scrutinizer ignore-type */ $asset) || strncmp($asset, '/', 1) === 0) {
Loading history...
Bug introduced by
It seems like $asset can also be of type false; however, parameter $string1 of strncmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

676
        if (!Url::isRelative($asset) || strncmp(/** @scrutinizer ignore-type */ $asset, '/', 1) === 0) {
Loading history...
677 2
            return $asset;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $asset could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
678
        }
679
680 15
        return "$baseUrl/$asset";
681
    }
682
}
683