Completed
Pull Request — master (#50)
by Wilmer
01:46
created

AssetManager::setBeforeCopy()   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
eloc 1
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Yiisoft\Asset;
5
6
use Psr\Log\LoggerInterface;
7
use Yiisoft\Aliases\Aliases;
8
use Yiisoft\Asset\AssetBundle;
9
use Yiisoft\Asset\AssetConverterInterface;
10
use Yiisoft\Files\FileHelper;
11
use YiiSoft\Html\Html;
12
13
/**
14
 * AssetManager manages asset bundle configuration and loading.
15
 *
16
 * AssetManager is configured in config/web.php. You can access that instance via $container->get(AssetManager::class).
17
 *
18
 * You can modify its configuration by adding an array to your application config under `components` as shown in the
19
 * following example:
20
 *
21
 * ```php
22
23
 * ```
24
 *
25
 * @property AssetConverterInterface $converter The asset converter. Note that the type of this property differs in
26
 *                                   getter and setter. See {@see getConverter()} and {@see setConverter()} for
27
 *                                   details.
28
 */
29
class AssetManager
30
{
31
    /**
32
     * @var callable a PHP callback that is called after a sub-directory or file is successfully copied. This option is
33
     *               used only when publishing a directory. The signature of the callback is the same as for
34
     *               {@see {beforeCopy}.
35
     *               This is passed as a parameter `afterCopy` to {@see \Yiisoft\Files\FileHelper::copyDirectory()}.
36
     */
37
    private $afterCopy;
38
39
    /**
40
     * Aliases component.
41
     *
42
     * @var Aliases $aliase
43
     */
44
    private $aliases;
45
46
    /**
47
     * directory path node_modules.
48
     *
49
     * @var array $alternatives
50
     */
51
    private $alternatives = [
52
        '@npm' => '@root/node_modules',
53
    ];
54
55
    /**
56
     * @var bool whether to append a timestamp to the URL of every published asset. When this is true, the URL of a
57
     *           published asset may look like `/path/to/asset?v=timestamp`, where `timestamp` is the last modification
58
     *           time of the published asset file. You normally would want to set this property to true when you have
59
     *           enabled HTTP caching for assets, because it allows you to bust caching when the assets are updated.
60
     */
61
    private $appendTimestamp = false;
62
63
    /**
64
     * @var array mapping from source asset files (keys) to target asset files (values).
65
     *
66
     * This property is provided to support fixing incorrect asset file paths in some asset bundles. When an asset
67
     * bundle is registered with a view, each relative asset file in its {@see AssetBundle::css|css} and
68
     * {@see AssetBundle::js|js} arrays will be examined against this map. If any of the keys is found to be the last
69
     * part of an asset file (which is prefixed with {@see {AssetBundle::sourcePath} if available), the corresponding
70
     * value will replace the asset and be registered with the view. For example, an asset file `my/path/to/jquery.js`
71
     * matches a key `jquery.js`.
72
     *
73
     * Note that the target asset files should be absolute URLs, domain relative URLs (starting from '/') or paths
74
     * relative to {@see baseUrl} and {@see basePath}.
75
     *
76
     * In the following example, any assets ending with `jquery.min.js` will be replaced with `jquery/dist/jquery.js`
77
     * which is relative to {@see baseUrl} and {@see basePath}.
78
     *
79
     * ```php
80
     * [
81
     *     'jquery.min.js' => 'jquery/dist/jquery.js',
82
     * ]
83
     * ```
84
     *
85
     * You may also use aliases while specifying map value, for example:
86
     *
87
     * ```php
88
     * [
89
     *     'jquery.min.js' => '@web/js/jquery/jquery.js',
90
     * ]
91
     * ```
92
     */
93
    private $assetMap = [];
94
95
    /**
96
     * @var string the root directory storing the published asset files.
97
     */
98
    private $basePath = '@public/assets';
99
100
    /**
101
     * @var string the base URL through which the published asset files can be accessed.
102
     */
103
    private $baseUrl = '@web/assets';
104
105
    /**
106
     * @var callable a PHP callback that is called before copying each sub-directory or file. This option is used only
107
     *               when publishing a directory. If the callback returns false, the copy operation for the
108
     *               sub-directory or file will be cancelled.
109
     *
110
     * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or file to
111
     * be copied from, while `$to` is the copy target.
112
     *
113
     * This is passed as a parameter `beforeCopy` to {@see Yiisoft\Files\FileHelper::copyDirectory()}.
114
     */
115
    private $beforeCopy;
116
117
    /**
118
     * @var array|bool list of asset bundle configurations. This property is provided to customize asset bundles.
119
     *                 When a bundle is being loaded by {@see getBundle()}, if it has a corresponding configuration
120
     *                 specified here, the configuration will be applied to the bundle.
121
     *
122
     * The array keys are the asset bundle names, which typically are asset bundle class names without leading
123
     * backslash. The array values are the corresponding configurations. If a value is false, it means the corresponding
124
     * asset bundle is disabled and {@see getBundle()} should return null.
125
     *
126
     * If this property is false, it means the whole asset bundle feature is disabled and {@see {getBundle()} will
127
     * always return null.
128
     *
129
     * The following example shows how to disable the bootstrap css file used by Bootstrap widgets (because you want to
130
     * use your own styles):
131
     *
132
     * ```php
133
     * [
134
     *     \Yiisoft\Bootstrap4\BootstrapAsset::class => [
135
     *         'css' => [],
136
     *     ],
137
     * ]
138
     * ```
139
     */
140
    private $bundles = [];
141
142
    /**
143
     * AssetConverter component.
144
     *
145
     * @var AssetConverterInterface $converter
146
     */
147
    private $converter;
148
149
    /**
150
     * @var int the permission to be set for newly generated asset directories. This value will be used by PHP chmod()
151
     *          function. No umask will be applied. Defaults to 0775, meaning the directory is read-writable by owner
152
     *          and group, but read-only for other users.
153
     */
154
    private $dirMode = 0775;
155
156
    /**
157
     * @var AssetBundle $dummyBundles
158
     */
159
    private $dummyBundles;
160
161
    /**
162
     * @var int the permission to be set for newly published asset files. This value will be used by PHP chmod()
163
     *          function. No umask will be applied. If not set, the permission will be determined by the current
164
     *          environment.
165
     */
166
    private $fileMode;
167
168
    /**
169
     * @var bool whether the directory being published should be copied even if it is found in the target directory.
170
     *           This option is used only when publishing a directory. You may want to set this to be `true` during the
171
     *           development stage to make sure the published directory is always up-to-date. Do not set this to true
172
     *           on production servers as it will significantly degrade the performance.
173
     */
174
    private $forceCopy = false;
175
176
    /**
177
     * @var callable a callback that will be called to produce hash for asset directory generation. The signature of the
178
     *               callback should be as follows:
179
     *
180
     * ```
181
     * function ($path)
182
     * ```
183
     *
184
     * where `$path` is the asset path. Note that the `$path` can be either directory where the asset files reside or a
185
     * single file. For a CSS file that uses relative path in `url()`, the hash implementation should use the directory
186
     * path of the file instead of the file path to include the relative asset files in the copying.
187
     *
188
     * If this is not set, the asset manager will use the default CRC32 and filemtime in the `hash` method.
189
     *
190
     * Example of an implementation using MD4 hash:
191
     *
192
     * ```php
193
     * function ($path) {
194
     *     return hash('md4', $path);
195
     * }
196
     * ```
197
     */
198
    private $hashCallback;
199
200
    /**
201
     * @var bool whether to use symbolic link to publish asset files. Defaults to false, meaning asset files are copied
202
     *           to {@see basePath}. Using symbolic links has the benefit that the published assets will always be
203
     *           consistent with the source assets and there is no copy operation required. This is especially useful
204
     *           during development.
205
     *
206
     * However, there are special requirements for hosting environments in order to use symbolic links. In particular,
207
     * symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
208
     *
209
     * Moreover, some Web servers need to be properly configured so that the linked assets are accessible to Web users.
210
     * For example, for Apache Web server, the following configuration directive should be added for the Web folder:
211
     *
212
     * ```apache
213
     * Options FollowSymLinks
214
     * ```
215
     */
216
    private $linkAssets = true;
217
218
    /**
219
     * @var LoggerInterface $logger
220
     */
221
    private $logger;
222
223
    /**
224
     * @var array published assets
225
     */
226
    private $published = [];
227
228
    /**
229
     * @var string $realBasePath
230
     */
231
    private $realBasePath;
232
233
    /**
234
     * AssetManager constructor.
235
     *
236
     * @param Aliases $aliases
237
     */
238 51
    public function __construct(Aliases $aliases, LoggerInterface $logger)
239
    {
240 51
        $this->aliases = $aliases;
241 51
        $this->logger = $logger;
242 51
        $this->setDefaultPaths();
243
    }
244
245
    /**
246
     * Returns the actual URL for the specified asset.
247
     * The actual URL is obtained by prepending either {@see AssetBundle::$baseUrl} or {@see AssetManager::$baseUrl} to
248
     * the given asset path.
249
     *
250
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
251
     * @param string      $asset the asset path. This should be one of the assets listed in {@see AssetBundle::$js} or
252
     *                    {@see AssetBundle::$css}.
253
     *
254
     * @return string the actual URL for the specified asset.
255
     */
256 8
    public function getAssetUrl(AssetBundle $bundle, string $asset): string
257
    {
258 8
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
259
            if (strncmp((string) $actualAsset, '@web/', 5) === 0) {
260
                $asset = substr((string) $actualAsset, 5);
261
                $basePath = $this->aliases->get('@public');
262
                $baseUrl = $this->aliases->get('@web');
263
            } else {
264
                $asset = $this->aliases->get($actualAsset);
0 ignored issues
show
Bug introduced by
It seems like $actualAsset can also be of type true; however, parameter $alias of Yiisoft\Aliases\Aliases::get() 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

264
                $asset = $this->aliases->get(/** @scrutinizer ignore-type */ $actualAsset);
Loading history...
265
                $basePath = $this->getRealBasePath();
266
                $baseUrl = $this->baseUrl;
267
            }
268
        } else {
269 8
            $basePath = $this->aliases->get($bundle->basePath);
270 8
            $baseUrl = $this->aliases->get($bundle->baseUrl);
271
        }
272
273 8
        if (!$this->isRelative($asset) || strncmp($asset, '/', 1) === 0) {
274
            return $asset;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $asset could return the type boolean which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
275
        }
276
277 8
        if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) {
278
            return "$baseUrl/$asset?v=$timestamp";
279
        }
280
281 8
        return "$baseUrl/$asset";
282
    }
283
284
    /**
285
     * Returns the actual file path for the specified asset.
286
     *
287
     * @param AssetBundle $bundle the asset bundle which the asset file belongs to
288
     * @param string      $asset  the asset path. This should be one of the assets listed in {@see AssetBundle::$js} or
289
     *                    {@see AssetBundle::$css}.
290
     *
291
     * @return false|string the actual file path, or `false` if the asset is specified as an absolute URL
292
     */
293
    public function getAssetPath(AssetBundle $bundle, string $asset)
294
    {
295
        if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
296
            return $this->isRelative((string) $actualAsset) ? $this->getRealBasePath() . '/' . $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

296
            return $this->isRelative((string) $actualAsset) ? $this->getRealBasePath() . '/' . /** @scrutinizer ignore-type */ $actualAsset : false;
Loading history...
297
        }
298
299
        return $this->isRelative($asset) ? $bundle->basePath . '/' .$asset : false;
300
    }
301
302
    /**
303
     * Returns the named asset bundle.
304
     *
305
     * This method will first look for the bundle in {@see bundles()}. If not found, it will treat `$name` as the class
306
     * of the asset bundle and create a new instance of it.
307
     *
308
     * @param string $name    the class name of the asset bundle (without the leading backslash)
309
     * @param bool   $publish whether to publish the asset files in the asset bundle before it is returned. If you set
310
     *                        this false, you must manually call `AssetBundle::publish()` to publish the asset files.
311
     *
312
     * @return AssetBundle the asset bundle instance
313
     *
314
     * @throws \InvalidArgumentException
315
     */
316 12
    public function getBundle(string $name, bool $publish = true): AssetBundle
317
    {
318 12
        if ($this->bundles === false) {
319
            return $this->loadDummyBundle($name);
320
        }
321
322 12
        if (!isset($this->bundles[$name])) {
323 12
            return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
324
        }
325
326
        if ($this->bundles[$name] instanceof AssetBundle) {
327
            return $this->bundles[$name];
328
        }
329
330
        if (is_array($this->bundles[$name])) {
331
            return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
332
        }
333
334
        if ($this->bundles[$name] === false) {
335
            return $this->loadDummyBundle($name);
336
        }
337
338
        throw new \InvalidArgumentException("Invalid asset bundle configuration: $name");
339
    }
340
341
    /**
342
     * Returns the asset converter.
343
     *
344
     * @return AssetConverterInterface the asset converter.
345
     */
346 13
    public function getConverter(): AssetConverterInterface
347
    {
348 13
        if ($this->converter === null) {
349 13
            $this->converter = new AssetConverter($this->aliases, $this->logger);
350 11
        } 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...
351
            if (is_array($this->converter) && !isset($this->converter['__class'])) {
352
                $this->converter['__class'] = AssetConverter::class;
353
            }
354
            $this->converter = new $this->converter($this->aliases, $this->logger);
355
        }
356
357 13
        return $this->converter;
358
    }
359
360
    /**
361
     * Returns the published path of a file path.
362
     *
363
     * This method does not perform any publishing. It merely tells you if the file or directory is published, where it
364
     * will go.
365
     *
366
     * @param string $path directory or file path being published
367
     *
368
     * @return string|bool string the published file path. False if the file or directory does not exist
369
     */
370
    public function getPublishedPath(string $path)
371
    {
372
        $path = $this->aliases->get($path);
373
374
        if (isset($this->published[$path])) {
375
            return $this->published[$path][0];
376
        }
377
        if (is_string($path) && ($path = realpath($path)) !== false) {
378
            return $this->getRealBasePath() . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ?
379
                   DIRECTORY_SEPARATOR . basename($path) : '');
380
        }
381
382
        return false;
383
    }
384
385
    /**
386
     * Returns the URL of a published file path.
387
     *
388
     * This method does not perform any publishing. It merely tells you if the file path is published, what the URL will
389
     * be to access it.
390
     *
391
     * @param string $path directory or file path being published
392
     *
393
     * @return string|bool string the published URL for the file or directory. False if the file or directory does not
394
     *                     exist.
395
     */
396
    public function getPublishedUrl(string $path)
397
    {
398
        if (isset($this->published[$path])) {
399
            return $this->published[$path][1];
400
        }
401
        if (is_string($path) && ($path = realpath($path)) !== false) {
402
            return $this->baseUrl.'/'.$this->hash($path).(is_file($path) ? '/'.basename($path) : '');
403
        }
404
405
        return false;
406
    }
407
408
    /**
409
     * Get RealBasePath.
410
     *
411
     * @return bool|string
412
     */
413 2
    public function getRealBasePath()
414
    {
415 2
        if ($this->realBasePath === null) {
416 2
            $this->realBasePath = (string) $this->prepareBasePath($this->basePath);
417
        }
418
419 2
        return $this->realBasePath;
420
    }
421
422
    /**
423
     * prepareBasePath
424
     *
425
     * @param string $basePath
426
     *
427
     * @throws \InvalidArgumentException
428
     *
429
     * @return string|bool
430
     */
431 2
    public function prepareBasePath(string $basePath)
432
    {
433 2
        $basePath = $this->aliases->get($basePath);
434
435 2
        if (!is_dir($basePath)) {
436
            throw new \InvalidArgumentException("The directory does not exist: {$basePath}");
437
        }
438
439 2
        if (!is_writable($basePath)) {
440
            throw new \InvalidArgumentException("The directory is not writable by the Web process: {$basePath}");
441
        }
442
443 2
        return realpath($basePath);
444
    }
445
446
    /**
447
     * Publishes a file or a directory.
448
     *
449
     * This method will copy the specified file or directory to {@see basePath} so that it can be accessed via the Web
450
     * server.
451
     *
452
     * If the asset is a file, its file modification time will be checked to avoid unnecessary file copying.
453
     *
454
     * If the asset is a directory, all files and subdirectories under it will be published recursively. Note, in case
455
     * $forceCopy is false the method only checks the existence of the target directory to avoid repetitive copying
456
     * (which is very expensive).
457
     *
458
     * By default, when publishing a directory, subdirectories and files whose name starts with a dot "." will NOT be
459
     * published. If you want to change this behavior, you may specify the "beforeCopy" option as explained in the
460
     * `$options` parameter.
461
     *
462
     * Note: On rare scenario, a race condition can develop that will lead to a  one-time-manifestation of a
463
     * non-critical problem in the creation of the directory that holds the published assets. This problem can be
464
     * avoided altogether by 'requesting' in advance all the resources that are supposed to trigger a 'publish()' call,
465
     * and doing that in the application deployment phase, before system goes live. See more in the following
466
     * discussion: http://code.google.com/p/yii/issues/detail?id=2579
467
     *
468
     * @param string $path    the asset (file or directory) to be published
469
     * @param array  $options the options to be applied when publishing a directory. The following options are
470
     *               supported:
471
     *
472
     * - only: array, list of patterns that the file paths should match if they want to be copied.
473
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from
474
     *   being copied.
475
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to
476
     *   true.
477
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
478
     *   This overrides {@see beforeCopy} if set.
479
     * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied. This
480
     *   overrides {@seee afterCopy} if set.
481
     * - forceCopy: boolean, whether the directory being published should be copied even if it is found in the target
482
     *   directory. This option is used only when publishing a directory. This overrides {@see forceCopy} if set.
483
     *
484
     * @throws \InvalidArgumentException if the asset to be published does not exist.
485
     *
486
     * @return array the path (directory or file path) and the URL that the asset is published as.
487
     */
488 2
    public function publish(string $path, array $options = []): array
489
    {
490 2
        $path = $this->aliases->get($path);
491
492 2
        if (isset($this->published[$path])) {
493
            return $this->published[$path];
494
        }
495
496 2
        if (!is_string($path) || ($src = realpath($path)) === false) {
497
            throw new \InvalidArgumentException("The file or directory to be published does not exist: $path");
498
        }
499
500 2
        if (is_file($src)) {
501
            return $this->published[$path] = $this->publishFile($src);
502
        }
503
504 2
        return $this->published[$path] = $this->publishDirectory($src, $options);
505
    }
506
507
    /**
508
     * Set afterCopy.
509
     *
510
     * @param callable $value
511
     *
512
     * @return void
513
     *
514
     * {@see afterCopy}
515
     */
516
    public function setAfterCopy(callable $value): void
517
    {
518
        $this->afterCopy = $value;
519
    }
520
521
    /**
522
     * Set alternatives.
523
     *
524
     * @param array $value
525
     *
526
     * @return void
527
     *
528
     * {@see alternatives}
529
     */
530
    public function setAlternatives(array $value): void
531
    {
532
        $this->alternatives = $value;
533
        $this->setAlternativesAlias();
534
    }
535
536
    /**
537
     * Set appendTimestamp.
538
     *
539
     * @param bool $value
540
     *
541
     * @return void
542
     *
543
     * {@see appendTimestamp}
544
     */
545 20
    public function setAppendTimestamp(bool $value): void
546
    {
547 20
        $this->appendTimestamp = $value;
548
    }
549
550
    /**
551
     * Set assetMap.
552
     *
553
     * @param array $value
554
     *
555
     * @return void
556
     *
557
     * {@see assetMap}
558
     */
559
    public function setAssetMap(array $value): void
560
    {
561
        $this->assetMap = $value;
562
    }
563
564
    /**
565
     * Set basePath.
566
     *
567
     * @param string $value
568
     *
569
     * @return void
570
     *
571
     * {@see basePath}
572
     */
573
    public function setBasePath(string $value): void
574
    {
575
        $this->basePath = $value;
576
    }
577
578
    /**
579
     * Set baseUrl.
580
     *
581
     * @param string $value
582
     *
583
     * @return void
584
     *
585
     * {@see baseUrl}
586
     */
587
    public function setBaseUrl(string $value): void
588
    {
589
        $this->baseUrl = $value;
590
    }
591
592
    /**
593
     * Set beforeCopy.
594
     *
595
     * @param callable $value
596
     *
597
     * @return void
598
     *
599
     * {@see beforeCopy}
600
     */
601
    public function setBeforeCopy(callable $value): void
602
    {
603
        $this->beforeCopy = $value;
604
    }
605
606
    /**
607
     * Set bundles.
608
     *
609
     * @param array $value
610
     *
611
     * @return void
612
     *
613
     * {@see beforeCopy}
614
     */
615
    public function setBundles(array $value): void
616
    {
617
        $this->bundles = $value;
618
    }
619
620
    /**
621
     * Sets the asset converter.
622
     *
623
     * @param AssetConverterInterface $value the asset converter. This can be eitheran object implementing the
624
     *                                      {@see AssetConverterInterface}, or a configuration array that can be used
625
     *                                      to create the asset converter object.
626
     */
627
    public function setConverter(AssetConverterInterface $value): void
628
    {
629
        $this->converter = $value;
630
    }
631
632
    /**
633
     * Set dirMode.
634
     *
635
     * @param int $value
636
     *
637
     * @return void
638
     *
639
     * {@see dirMode}
640
     */
641
    public function setDirMode(int $value): void
642
    {
643
        $this->dirMode = $value;
644
    }
645
646
    /**
647
     * Set fileMode.
648
     *
649
     * @param int $value
650
     *
651
     * @return void
652
     *
653
     * {@see fileMode}
654
     */
655
    public function setFileMode(int $value): void
656
    {
657
        $this->fileMode = $value;
658
    }
659
660
    /**
661
     * Set hashCallback.
662
     *
663
     * @param callable $value
664
     *
665
     * @return void
666
     *
667
     * {@see hashCallback}
668
     */
669 1
    public function setHashCallback(callable $value): void
670
    {
671 1
        $this->hashCallback = $value;
672
    }
673
674
    /**
675
     * Set linkAssets.
676
     *
677
     * @param bool $value
678
     *
679
     * @return void
680
     *
681
     * {@see linkAssets}
682
     */
683 1
    public function setLinkAssets(bool $value): void
684
    {
685 1
        $this->linkAssets = $value;
686
    }
687
688
    /**
689
     * Returns a value indicating whether a URL is relative.
690
     * A relative URL does not have host info part.
691
     * @param string $url the URL to be checked
692
     * @return bool whether the URL is relative
693
     */
694 8
    protected function isRelative($url)
695
    {
696 8
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
697
    }
698
699
    /**
700
     * Generate a CRC32 hash for the directory path. Collisions are higher than MD5 but generates a much smaller hash
701
     * string.
702
     *
703
     * @param string $path string to be hashed.
704
     *
705
     * @return string hashed string.
706
     */
707 2
    protected function hash(string $path): string
708
    {
709 2
        if (is_callable($this->hashCallback)) {
710 1
            return call_user_func($this->hashCallback, $path);
711
        }
712 1
        $path = (is_file($path) ? dirname($path) : $path).filemtime($path);
713
714 1
        return sprintf('%x', crc32($path . '|' . $this->linkAssets));
715
    }
716
717
    /**
718
     * Loads asset bundle class by name.
719
     *
720
     * @param string $name    bundle name
721
     * @param array  $config  bundle object configuration
722
     * @param bool   $publish if bundle should be published
723
     *
724
     * @return AssetBundle
725
     */
726 12
    protected function loadBundle(string $name, array $config = [], bool $publish = true): AssetBundle
727
    {
728 12
        if (!isset($config['__class'])) {
729 12
            $config['__class'] = $name;
730
        }
731
732
        /* @var $bundle AssetBundle */
733 12
        $bundle = new $config['__class']();
734
735 12
        if ($publish) {
736 12
            $bundle->publish($this);
737
        }
738
739 12
        return $bundle;
740
    }
741
742
    /**
743
     * Loads dummy bundle by name.
744
     *
745
     * @param string $name
746
     *
747
     * @return AssetBundle
748
     */
749
    protected function loadDummyBundle(string $name): AssetBundle
750
    {
751
        if (!isset($this->dummyBundles[$name])) {
752
            $this->dummyBundles[$name] = $this->loadBundle($name, [
753
                'sourcePath' => null,
754
                'js'         => [],
755
                'css'        => [],
756
                'depends'    => [],
757
            ]);
758
        }
759
760
        return $this->dummyBundles[$name];
761
    }
762
763
    /**
764
     * Publishes a file.
765
     *
766
     * @param string $src the asset file to be published
767
     *
768
     * @throws \Exception if the asset to be published does not exist.
769
     *
770
     * @return array the path and the URL that the asset is published as.
771
     */
772
    protected function publishFile(string $src): array
773
    {
774
        $dir = $this->hash($src);
775
        $fileName = basename($src);
776
        $dstDir = $this->getRealBasePath() .DIRECTORY_SEPARATOR . $dir;
777
        $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
778
779
        if (!is_dir($dstDir)) {
780
            FileHelper::createDirectory($dstDir, $this->dirMode);
781
        }
782
783
        if ($this->linkAssets) {
784
            if (!is_file($dstFile)) {
785
                try { // fix #6226 symlinking multi threaded
786
                    symlink($src, $dstFile);
787
                } catch (\Exception $e) {
788
                    if (!is_file($dstFile)) {
789
                        throw $e;
790
                    }
791
                }
792
            }
793
        } elseif (@filemtime($dstFile) < @filemtime($src)) {
794
            copy($src, $dstFile);
795
            if ($this->fileMode !== null) {
796
                @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

796
                /** @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...
797
            }
798
        }
799
800
        return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
801
    }
802
803
    /**
804
     * Publishes a directory.
805
     *
806
     * @param string $src     the asset directory to be published
807
     * @param array  $options the options to be applied when publishing a directory. The following options are
808
     *                        supported:
809
     *
810
     * - only: array, list of patterns that the file paths should match if they want to be copied.
811
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from
812
     *   being copied.
813
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults
814
     *   to true.
815
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. This overrides
816
     *   {@see beforeCopy} if set.
817
     * - afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied. This
818
     *   overrides {@see afterCopy} if set.
819
     * - forceCopy: boolean, whether the directory being published should be copied even if it is found in the target
820
     *   directory. This option is used only when publishing a directory. This overrides {@see forceCopy} if set.
821
     *
822
     * @throws \Exception if the asset to be published does not exist.
823
     *
824
     * @return array the path directory and the URL that the asset is published as.
825
     */
826 2
    protected function publishDirectory(string $src, array $options): array
827
    {
828 2
        $dir = $this->hash($src);
829 2
        $dstDir = $this->getRealBasePath() . DIRECTORY_SEPARATOR . $dir;
830
831 2
        if ($this->linkAssets) {
832 2
            if (!is_dir($dstDir)) {
833 2
                FileHelper::createDirectory(dirname($dstDir), $this->dirMode);
834
835
                try { // fix #6226 symlinking multi threaded
836 2
                    symlink($src, $dstDir);
837
                } catch (\Exception $e) {
838
                    if (!is_dir($dstDir)) {
839 2
                        throw $e;
840
                    }
841
                }
842
            }
843
        } elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
844
            $opts = array_merge(
845
                $options,
846
                [
847
                    'dirMode'              => $this->dirMode,
848
                    'fileMode'             => $this->fileMode,
849
                    'copyEmptyDirectories' => false,
850
                ]
851
            );
852
853
            if (!isset($opts['beforeCopy'])) {
854
                if ($this->beforeCopy !== null) {
855
                    $opts['beforeCopy'] = $this->beforeCopy;
856
                } else {
857
                    $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

857
                    $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...
858
                        return strncmp(basename($from), '.', 1) !== 0;
859
                    };
860
                }
861
            }
862
863
            if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
864
                $opts['afterCopy'] = $this->afterCopy;
865
            }
866
867
            FileHelper::copyDirectory($src, $dstDir, $opts);
868
        }
869
870
871 2
        return [$dstDir, $this->baseUrl.'/'.$dir];
872
    }
873
874
    /**
875
     * @param AssetBundle $bundle
876
     * @param string      $asset
877
     *
878
     * @return string|bool
879
     */
880 8
    protected function resolveAsset(AssetBundle $bundle, string $asset)
881
    {
882 8
        if (isset($this->assetMap[$asset])) {
883
            return $this->assetMap[$asset];
884
        }
885
886 8
        if ($bundle->sourcePath !== null && $this->isRelative($asset)) {
887
            $asset = $bundle->sourcePath . '/' . $asset;
888
        }
889
890 8
        $n = mb_strlen($asset, 'utf-8');
891
892 8
        foreach ($this->assetMap as $from => $to) {
893
            $n2 = mb_strlen($from, 'utf-8');
894
            if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
895
                return $to;
896
            }
897
        }
898
899 8
        return false;
900
    }
901
902
    /**
903
     * Set default paths asset manager.
904
     *
905
     * @return void
906
     */
907 51
    private function setDefaultPaths(): void
908
    {
909 51
        $this->setAlternativesAlias();
910
911 51
        $this->basePath = $this->aliases->get($this->basePath);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->aliases->get($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...
912
913 51
        if (!is_dir($this->basePath)) {
914
            throw new \InvalidArgumentException("The directory does not exist: {$this->basePath}");
915
        }
916
917 51
        $this->basePath = (string) realpath($this->basePath);
918 51
        $this->baseUrl = rtrim($this->aliases->get($this->baseUrl), '/');
919
    }
920
921
    /**
922
     * Set alternatives aliases.
923
     *
924
     * @return void
925
     */
926 51
    protected function setAlternativesAlias(): void
927
    {
928 51
        foreach ($this->alternatives as $alias => $path) {
929 51
            $this->aliases->set($alias, $path);
930
        }
931
    }
932
}
933