Passed
Push — fix-tests ( 6dd538...727178 )
by Alexander
195:41 queued 192:18
created

AssetManager::setConverter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
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]] does not exist.
207
     */
208 96
    public function init()
209
    {
210 96
        parent::init();
211 96
        $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 96
        if (!is_dir($this->basePath)) {
213 2
            throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
214
        }
215
216 94
        $this->basePath = realpath($this->basePath);
217 94
        $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
218 94
    }
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 36
    public function getBundle($name, $publish = true)
233
    {
234 36
        if ($this->bundles === false) {
235
            return $this->loadDummyBundle($name);
236 36
        } elseif (!isset($this->bundles[$name])) {
237 32
            return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
238 23
        } elseif ($this->bundles[$name] instanceof AssetBundle) {
239 2
            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 33
    protected function loadBundle($name, $config = [], $publish = true)
259
    {
260 33
        if (!isset($config['class'])) {
261 33
            $config['class'] = $name;
262
        }
263
        /* @var $bundle AssetBundle */
264 33
        $bundle = Yii::createObject($config);
265 33
        if ($publish) {
266 33
            $bundle->publish($this);
267
        }
268
269 33
        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
            $bundle = Yii::createObject(['class' => $name]);
282 8
            $bundle->sourcePath = null;
283 8
            $bundle->js = [];
284 8
            $bundle->css = [];
285
286 8
            $this->_dummyBundles[$name] = $bundle;
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 12
    public function getAssetUrl($bundle, $asset)
300
    {
301 12
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
302
            if (strncmp($actualAsset, '@web/', 5) === 0) {
0 ignored issues
show
Bug introduced by
It seems like $actualAsset can also be of type true; however, parameter $str1 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

302
            if (strncmp(/** @scrutinizer ignore-type */ $actualAsset, '@web/', 5) === 0) {
Loading history...
303
                $asset = substr($actualAsset, 5);
0 ignored issues
show
Bug introduced by
It seems like $actualAsset can also be of type true; however, parameter $string of substr() 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

303
                $asset = substr(/** @scrutinizer ignore-type */ $actualAsset, 5);
Loading history...
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 can also be of type true; however, parameter $alias of yii\BaseYii::getAlias() 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

307
                $asset = Yii::getAlias(/** @scrutinizer ignore-type */ $actualAsset);
Loading history...
308
                $basePath = $this->basePath;
309
                $baseUrl = $this->baseUrl;
310
            }
311
        } else {
312 12
            $basePath = $bundle->basePath;
313 12
            $baseUrl = $bundle->baseUrl;
314
        }
315
316 12
        if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) {
317 2
            return $asset;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $asset also could return the type boolean which is incompatible with the documented return type string.
Loading history...
318
        }
319
320 12
        if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) {
321 2
            return "$baseUrl/$asset?v=$timestamp";
322
        }
323
324 12
        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
Are you sure $actualAsset of type string|true can be used in concatenation? ( Ignorable by Annotation )

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

336
            return Url::isRelative($actualAsset) ? $this->basePath . '/' . /** @scrutinizer ignore-type */ $actualAsset : false;
Loading history...
Bug introduced by
It seems like $actualAsset can also be of type true; 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

336
            return Url::isRelative(/** @scrutinizer ignore-type */ $actualAsset) ? $this->basePath . '/' . $actualAsset : false;
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 12
    protected function resolveAsset($bundle, $asset)
348
    {
349 12
        if (isset($this->assetMap[$asset])) {
350
            return $this->assetMap[$asset];
351
        }
352 12
        if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
353
            $asset = $bundle->sourcePath . '/' . $asset;
354
        }
355
356 12
        $n = mb_strlen($asset, Yii::$app->charset);
357 12
        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 12
        return false;
365
    }
366
367
    private $_converter;
368
369
    /**
370
     * Returns the asset converter.
371
     * @return AssetConverterInterface the asset converter.
372
     */
373 32
    public function getConverter()
374
    {
375 32
        if ($this->_converter === null) {
376 32
            $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

376
            $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...
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 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

379
                $this->_converter['class'] = /** @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...
380
            }
381
            $this->_converter = Yii::createObject($this->_converter);
382
        }
383
384 32
        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 if the target directory [[basePath]] is not writeable.
445
     */
446 14
    public function publish($path, $options = [])
447
    {
448 14
        $path = Yii::getAlias($path);
449
450 14
        if (isset($this->_published[$path])) {
451 1
            return $this->_published[$path];
452
        }
453
454 14
        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 14
        if (!is_writable($this->basePath)) {
459 1
            throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
460
        }
461
462 13
        if (is_file($src)) {
463 1
            return $this->_published[$path] = $this->publishFile($src);
464
        }
465
466 12
        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 1
    protected function publishFile($src)
476
    {
477 1
        $dir = $this->hash($src);
478 1
        $fileName = basename($src);
479 1
        $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
480 1
        $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
481
482 1
        if (!is_dir($dstDir)) {
483 1
            FileHelper::createDirectory($dstDir, $this->dirMode, true);
484
        }
485
486 1
        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 1
        } elseif (@filemtime($dstFile) < @filemtime($src)) {
497 1
            copy($src, $dstFile);
498 1
            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 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

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

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