Completed
Push — gridview-checkboxcolumn ( 5f8435...420708 )
by Dmitry
06:27 queued 20s
created

AssetManager   C

Complexity

Total Complexity 74

Size/Duplication

Total Lines 565
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 8

Test Coverage

Coverage 49.08%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 74
lcom 3
cbo 8
dl 0
loc 565
ccs 80
cts 163
cp 0.4908
rs 5.5244
c 3
b 1
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A setConverter() 0 4 1
A getAssetPath() 0 8 4
B getBundle() 0 16 6
A loadBundle() 0 12 3
A loadDummyBundle() 0 12 2
C getAssetUrl() 0 27 7
B resolveAsset() 0 19 7
B getConverter() 0 13 6
B publish() 0 18 5
B publishFile() 0 24 6
C publishDirectory() 0 34 11
B getPublishedPath() 0 13 5
B getPublishedUrl() 0 13 5
A hash() 0 8 3
A init() 0 13 3

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 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\InvalidConfigException;
13
use yii\base\InvalidParamException;
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
 * @property AssetConverterInterface $converter The asset converter. Note that the type of this property
35
 * differs in getter and setter. See [[getConverter()]] and [[setConverter()]] for details.
36
 *
37
 * @author Qiang Xue <[email protected]>
38
 * @since 2.0
39
 */
40
class AssetManager extends Component
41
{
42
    /**
43
     * @var array|boolean list of asset bundle configurations. This property is provided to customize asset bundles.
44
     * When a bundle is being loaded by [[getBundle()]], if it has a corresponding configuration specified here,
45
     * the configuration will be applied to the bundle.
46
     *
47
     * The array keys are the asset bundle names, which typically are asset bundle class names without leading backslash.
48
     * The array values are the corresponding configurations. If a value is false, it means the corresponding asset
49
     * bundle is disabled and [[getBundle()]] should return null.
50
     *
51
     * If this property is false, it means the whole asset bundle feature is disabled and [[getBundle()]]
52
     * will always return null.
53
     *
54
     * The following example shows how to disable the bootstrap css file used by Bootstrap widgets
55
     * (because you want to use your own styles):
56
     *
57
     * ```php
58
     * [
59
     *     'yii\bootstrap\BootstrapAsset' => [
60
     *         'css' => [],
61
     *     ],
62
     * ]
63
     * ```
64
     */
65
    public $bundles = [];
66
    /**
67
     * @var string the root directory storing the published asset files.
68
     */
69
    public $basePath = '@webroot/assets';
70
    /**
71
     * @var string the base URL through which the published asset files can be accessed.
72
     */
73
    public $baseUrl = '@web/assets';
74
    /**
75
     * @var array mapping from source asset files (keys) to target asset files (values).
76
     *
77
     * This property is provided to support fixing incorrect asset file paths in some asset bundles.
78
     * When an asset bundle is registered with a view, each relative asset file in its [[AssetBundle::css|css]]
79
     * and [[AssetBundle::js|js]] arrays will be examined against this map. If any of the keys is found
80
     * to be the last part of an asset file (which is prefixed with [[AssetBundle::sourcePath]] if available),
81
     * the corresponding value will replace the asset and be registered with the view.
82
     * For example, an asset file `my/path/to/jquery.js` matches a key `jquery.js`.
83
     *
84
     * Note that the target asset files should be absolute URLs, domain relative URLs (starting from '/') or paths
85
     * relative to [[baseUrl]] and [[basePath]].
86
     *
87
     * In the following example, any assets ending with `jquery.min.js` will be replaced with `jquery/dist/jquery.js`
88
     * which is relative to [[baseUrl]] and [[basePath]].
89
     *
90
     * ```php
91
     * [
92
     *     'jquery.min.js' => 'jquery/dist/jquery.js',
93
     * ]
94
     * ```
95
     *
96
     * You may also use aliases while specifying map value, for example:
97
     *
98
     * ```php
99
     * [
100
     *     'jquery.min.js' => '@web/js/jquery/jquery.js',
101
     * ]
102
     * ```
103
     */
104
    public $assetMap = [];
105
    /**
106
     * @var boolean whether to use symbolic link to publish asset files. Defaults to false, meaning
107
     * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published
108
     * assets will always be consistent with the source assets and there is no copy operation required.
109
     * This is especially useful during development.
110
     *
111
     * However, there are special requirements for hosting environments in order to use symbolic links.
112
     * In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
113
     *
114
     * Moreover, some Web servers need to be properly configured so that the linked assets are accessible
115
     * to Web users. For example, for Apache Web server, the following configuration directive should be added
116
     * for the Web folder:
117
     *
118
     * ```apache
119
     * Options FollowSymLinks
120
     * ```
121
     */
122
    public $linkAssets = false;
123
    /**
124
     * @var integer the permission to be set for newly published asset files.
125
     * This value will be used by PHP chmod() function. No umask will be applied.
126
     * If not set, the permission will be determined by the current environment.
127
     */
128
    public $fileMode;
129
    /**
130
     * @var integer the permission to be set for newly generated asset directories.
131
     * This value will be used by PHP chmod() function. No umask will be applied.
132
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
133
     * but read-only for other users.
134
     */
135
    public $dirMode = 0775;
136
    /**
137
     * @var callback a PHP callback that is called before copying each sub-directory or file.
138
     * This option is used only when publishing a directory. If the callback returns false, the copy
139
     * operation for the sub-directory or file will be cancelled.
140
     *
141
     * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
142
     * file to be copied from, while `$to` is the copy target.
143
     *
144
     * This is passed as a parameter `beforeCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
145
     */
146
    public $beforeCopy;
147
    /**
148
     * @var callback a PHP callback that is called after a sub-directory or file is successfully copied.
149
     * This option is used only when publishing a directory. The signature of the callback is the same as
150
     * for [[beforeCopy]].
151
     * This is passed as a parameter `afterCopy` to [[\yii\helpers\FileHelper::copyDirectory()]].
152
     */
153
    public $afterCopy;
154
    /**
155
     * @var boolean whether the directory being published should be copied even if
156
     * it is found in the target directory. This option is used only when publishing a directory.
157
     * You may want to set this to be `true` during the development stage to make sure the published
158
     * directory is always up-to-date. Do not set this to true on production servers as it will
159
     * significantly degrade the performance.
160
     */
161
    public $forceCopy = false;
162
    /**
163
     * @var boolean whether to append a timestamp to the URL of every published asset. When this is true,
164
     * the URL of a published asset may look like `/path/to/asset?v=timestamp`, where `timestamp` is the
165
     * last modification time of the published asset file.
166
     * You normally would want to set this property to true when you have enabled HTTP caching for assets,
167
     * because it allows you to bust caching when the assets are updated.
168
     * @since 2.0.3
169
     */
170
    public $appendTimestamp = false;
171
    /**
172
     * @var callable a callback that will be called to produce hash for asset directory generation.
173
     * The signature of the callback should be as follows:
174
     *
175
     * ```
176
     * function ($path)
177
     * ```
178
     *
179
     * where `$path` is the asset path. Note that the `$path` can be either directory where the asset
180
     * files reside or a single file. For a CSS file that uses relative path in `url()`, the hash
181
     * implementation should use the directory path of the file instead of the file path to include
182
     * the relative asset files in the copying.
183
     *
184
     * If this is not set, the asset manager will use the default CRC32 and filemtime in the `hash`
185
     * method.
186
     *
187
     * Example of an implementation using MD4 hash:
188
     *
189
     * ```php
190
     * function ($path) {
191
     *     return hash('md4', $path);
192
     * }
193
     * ```
194
     *
195
     * @since 2.0.6
196
     */
197
    public $hashCallback;
198
199
    private $_dummyBundles = [];
200
201
202
    /**
203
     * Initializes the component.
204
     * @throws InvalidConfigException if [[basePath]] is invalid
205
     */
206 43
    public function init()
207
    {
208 43
        parent::init();
209 43
        $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...
210 43
        if (!is_dir($this->basePath)) {
211 1
            throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
212 42
        } elseif (!is_writable($this->basePath)) {
213
            throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
214
        } else {
215 42
            $this->basePath = realpath($this->basePath);
216
        }
217 42
        $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
218 42
    }
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 boolean $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 24
    public function getBundle($name, $publish = true)
233
    {
234 24
        if ($this->bundles === false) {
235
            return $this->loadDummyBundle($name);
236 24
        } elseif (!isset($this->bundles[$name])) {
237 24
            return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
238 12
        } elseif ($this->bundles[$name] instanceof AssetBundle) {
239
            return $this->bundles[$name];
240 12
        } elseif (is_array($this->bundles[$name])) {
241 12
            return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
242
        } elseif ($this->bundles[$name] === false) {
243
            return $this->loadDummyBundle($name);
244
        } else {
245
            throw new InvalidConfigException("Invalid asset bundle configuration: $name");
246
        }
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 boolean $publish if bundle should be published
255
     * @return AssetBundle
256
     * @throws InvalidConfigException if configuration isn't valid
257
     */
258 24
    protected function loadBundle($name, $config = [], $publish = true)
259
    {
260 24
        if (!isset($config['class'])) {
261 24
            $config['class'] = $name;
262 24
        }
263
        /* @var $bundle AssetBundle */
264 24
        $bundle = Yii::createObject($config);
265 24
        if ($publish) {
266 24
            $bundle->publish($this);
267 24
        }
268 24
        return $bundle;
269
    }
270
271
    /**
272
     * Loads dummy bundle by name
273
     *
274
     * @param string $name
275
     * @return AssetBundle
276
     */
277
    protected function loadDummyBundle($name)
278
    {
279
        if (!isset($this->_dummyBundles[$name])) {
280
            $this->_dummyBundles[$name] = $this->loadBundle($name, [
281
                'sourcePath' => null,
282
                'js' => [],
283
                'css' => [],
284
                'depends' => [],
285
            ]);
286
        }
287
        return $this->_dummyBundles[$name];
288
    }
289
290
    /**
291
     * Returns the actual URL for the specified asset.
292
     * The actual URL is obtained by prepending either [[baseUrl]] or [[AssetManager::baseUrl]] to the given asset path.
293
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
294
     * @param string $asset the asset path. This should be one of the assets listed in [[js]] or [[css]].
295
     * @return string the actual URL for the specified asset.
296
     */
297 10
    public function getAssetUrl($bundle, $asset)
298
    {
299 10
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
300
            if (strncmp($actualAsset, '@web/', 5) === 0) {
301
                $asset = substr($actualAsset, 5);
302
                $basePath = Yii::getAlias('@webroot');
303
                $baseUrl = Yii::getAlias('@web');
304
            } else {
305
                $asset = Yii::getAlias($actualAsset);
0 ignored issues
show
Bug introduced by
It seems like $actualAsset defined by $this->resolveAsset($bundle, $asset) on line 299 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 315 which is incompatible with the return type documented by yii\web\AssetManager::getAssetUrl of type string.
Loading history...
306
                $basePath = $this->basePath;
307
                $baseUrl = $this->baseUrl;
308
            }
309
        } else {
310 10
            $basePath = $bundle->basePath;
311 10
            $baseUrl = $bundle->baseUrl;
312
        }
313
314 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 305 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...
315
            return $asset;
316
        }
317
318 10
        if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) {
319
            return "$baseUrl/$asset?v=$timestamp";
320
        } else {
321 10
            return "$baseUrl/$asset";
322
        }
323
    }
324
325
    /**
326
     * Returns the actual file path for the specified asset.
327
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
328
     * @param string $asset the asset path. This should be one of the assets listed in [[js]] or [[css]].
329
     * @return string|boolean the actual file path, or false if the asset is specified as an absolute URL
330
     */
331
    public function getAssetPath($bundle, $asset)
332
    {
333
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
334
            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 333 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...
335
        } else {
336
            return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
337
        }
338
    }
339
340
    /**
341
     * @param AssetBundle $bundle
342
     * @param string $asset
343
     * @return string|boolean
344
     */
345 10
    protected function resolveAsset($bundle, $asset)
346
    {
347 10
        if (isset($this->assetMap[$asset])) {
348
            return $this->assetMap[$asset];
349
        }
350 10
        if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
351
            $asset = $bundle->sourcePath . '/' . $asset;
352
        }
353
354 10
        $n = mb_strlen($asset, Yii::$app->charset);
355 10
        foreach ($this->assetMap as $from => $to) {
356
            $n2 = mb_strlen($from, Yii::$app->charset);
357
            if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
358
                return $to;
359
            }
360 10
        }
361
362 10
        return false;
363
    }
364
365
    private $_converter;
366
367
    /**
368
     * Returns the asset converter.
369
     * @return AssetConverterInterface the asset converter.
370
     */
371 25
    public function getConverter()
372
    {
373 25
        if ($this->_converter === null) {
374 25
            $this->_converter = Yii::createObject(AssetConverter::className());
375 25
        } elseif (is_array($this->_converter) || is_string($this->_converter)) {
376
            if (is_array($this->_converter) && !isset($this->_converter['class'])) {
377
                $this->_converter['class'] = AssetConverter::className();
378
            }
379
            $this->_converter = Yii::createObject($this->_converter);
380
        }
381
382 25
        return $this->_converter;
383
    }
384
385
    /**
386
     * Sets the asset converter.
387
     * @param array|AssetConverterInterface $value the asset converter. This can be either
388
     * an object implementing the [[AssetConverterInterface]], or a configuration
389
     * array that can be used to create the asset converter object.
390
     */
391
    public function setConverter($value)
392
    {
393
        $this->_converter = $value;
394
    }
395
396
    /**
397
     * @var array published assets
398
     */
399
    private $_published = [];
400
401
    /**
402
     * Publishes a file or a directory.
403
     *
404
     * This method will copy the specified file or directory to [[basePath]] so that
405
     * it can be accessed via the Web server.
406
     *
407
     * If the asset is a file, its file modification time will be checked to avoid
408
     * unnecessary file copying.
409
     *
410
     * If the asset is a directory, all files and subdirectories under it will be published recursively.
411
     * Note, in case $forceCopy is false the method only checks the existence of the target
412
     * directory to avoid repetitive copying (which is very expensive).
413
     *
414
     * By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
415
     * will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
416
     * as explained in the `$options` parameter.
417
     *
418
     * Note: On rare scenario, a race condition can develop that will lead to a
419
     * one-time-manifestation of a non-critical problem in the creation of the directory
420
     * that holds the published assets. This problem can be avoided altogether by 'requesting'
421
     * in advance all the resources that are supposed to trigger a 'publish()' call, and doing
422
     * that in the application deployment phase, before system goes live. See more in the following
423
     * discussion: http://code.google.com/p/yii/issues/detail?id=2579
424
     *
425
     * @param string $path the asset (file or directory) to be published
426
     * @param array $options the options to be applied when publishing a directory.
427
     * The following options are supported:
428
     *
429
     * - only: array, list of patterns that the file paths should match if they want to be copied.
430
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
431
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
432
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
433
     *   This overrides [[beforeCopy]] if set.
434
     * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
435
     *   This overrides [[afterCopy]] if set.
436
     * - forceCopy: boolean, whether the directory being published should be copied even if
437
     *   it is found in the target directory. This option is used only when publishing a directory.
438
     *   This overrides [[forceCopy]] if set.
439
     *
440
     * @return array the path (directory or file path) and the URL that the asset is published as.
441
     * @throws InvalidParamException if the asset to be published does not exist.
442
     */
443 5
    public function publish($path, $options = [])
444
    {
445 5
        $path = Yii::getAlias($path);
446
447 5
        if (isset($this->_published[$path])) {
448
            return $this->_published[$path];
449
        }
450
451 5
        if (!is_string($path) || ($src = realpath($path)) === false) {
452
            throw new InvalidParamException("The file or directory to be published does not exist: $path");
453
        }
454
455 5
        if (is_file($src)) {
456
            return $this->_published[$path] = $this->publishFile($src);
457
        } else {
458 5
            return $this->_published[$path] = $this->publishDirectory($src, $options);
459
        }
460
    }
461
462
    /**
463
     * Publishes a file.
464
     * @param string $src the asset file to be published
465
     * @return array the path and the URL that the asset is published as.
466
     * @throws InvalidParamException if the asset to be published does not exist.
467
     */
468
    protected function publishFile($src)
469
    {
470
        $dir = $this->hash($src);
471
        $fileName = basename($src);
472
        $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
473
        $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
474
475
        if (!is_dir($dstDir)) {
476
            FileHelper::createDirectory($dstDir, $this->dirMode, true);
477
        }
478
479
        if ($this->linkAssets) {
480
            if (!is_file($dstFile)) {
481
                symlink($src, $dstFile);
482
            }
483
        } elseif (@filemtime($dstFile) < @filemtime($src)) {
484
            copy($src, $dstFile);
485
            if ($this->fileMode !== null) {
486
                @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...
487
            }
488
        }
489
490
        return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
491
    }
492
493
    /**
494
     * Publishes a directory.
495
     * @param string $src the asset directory to be published
496
     * @param array $options the options to be applied when publishing a directory.
497
     * The following options are supported:
498
     *
499
     * - only: array, list of patterns that the file paths should match if they want to be copied.
500
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
501
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
502
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
503
     *   This overrides [[beforeCopy]] if set.
504
     * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied.
505
     *   This overrides [[afterCopy]] if set.
506
     * - forceCopy: boolean, whether the directory being published should be copied even if
507
     *   it is found in the target directory. This option is used only when publishing a directory.
508
     *   This overrides [[forceCopy]] if set.
509
     *
510
     * @return array the path directory and the URL that the asset is published as.
511
     * @throws InvalidParamException if the asset to be published does not exist.
512
     */
513 5
    protected function publishDirectory($src, $options)
514
    {
515 5
        $dir = $this->hash($src);
516 5
        $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
517 5
        if ($this->linkAssets) {
518 2
            if (!is_dir($dstDir)) {
519 2
                FileHelper::createDirectory(dirname($dstDir), $this->dirMode, true);
520 2
                symlink($src, $dstDir);
521 2
            }
522 5
        } elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
523 3
            $opts = array_merge(
524 3
                $options,
525
                [
526 3
                    'dirMode' => $this->dirMode,
527 3
                    'fileMode' => $this->fileMode,
528
                ]
529 3
            );
530 3
            if (!isset($opts['beforeCopy'])) {
531 2
                if ($this->beforeCopy !== null) {
532 1
                    $opts['beforeCopy'] = $this->beforeCopy;
533 1
                } else {
534 1
                    $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...
535 1
                        return strncmp(basename($from), '.', 1) !== 0;
536
                    };
537
                }
538 2
            }
539 3
            if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
540
                $opts['afterCopy'] = $this->afterCopy;
541
            }
542 3
            FileHelper::copyDirectory($src, $dstDir, $opts);
543 3
        }
544
545 5
        return [$dstDir, $this->baseUrl . '/' . $dir];
546
    }
547
548
    /**
549
     * Returns the published path of a file path.
550
     * This method does not perform any publishing. It merely tells you
551
     * if the file or directory is published, where it will go.
552
     * @param string $path directory or file path being published
553
     * @return string|false string the published file path. False if the file or directory does not exist
554
     */
555
    public function getPublishedPath($path)
556
    {
557
        $path = Yii::getAlias($path);
558
559
        if (isset($this->_published[$path])) {
560
            return $this->_published[$path][0];
561
        }
562
        if (is_string($path) && ($path = realpath($path)) !== false) {
563
            return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : '');
564
        } else {
565
            return false;
566
        }
567
    }
568
569
    /**
570
     * Returns the URL of a published file path.
571
     * This method does not perform any publishing. It merely tells you
572
     * if the file path is published, what the URL will be to access it.
573
     * @param string $path directory or file path being published
574
     * @return string|false string the published URL for the file or directory. False if the file or directory does not exist.
575
     */
576
    public function getPublishedUrl($path)
577
    {
578
        $path = Yii::getAlias($path);
579
580
        if (isset($this->_published[$path])) {
581
            return $this->_published[$path][1];
582
        }
583
        if (is_string($path) && ($path = realpath($path)) !== false) {
584
            return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
585
        } else {
586
            return false;
587
        }
588
    }
589
590
    /**
591
     * Generate a CRC32 hash for the directory path. Collisions are higher
592
     * than MD5 but generates a much smaller hash string.
593
     * @param string $path string to be hashed.
594
     * @return string hashed string.
595
     */
596 5
    protected function hash($path)
597
    {
598 5
        if (is_callable($this->hashCallback)) {
599 1
            return call_user_func($this->hashCallback, $path);
600
        }
601 4
        $path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
602 4
        return sprintf('%x', crc32($path . Yii::getVersion()));
603
    }
604
}
605