1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Devanych\View\Extension; |
6
|
|
|
|
7
|
|
|
use RuntimeException; |
8
|
|
|
|
9
|
|
|
use function file_exists; |
10
|
|
|
use function filemtime; |
11
|
|
|
use function ltrim; |
12
|
|
|
use function rtrim; |
13
|
|
|
use function sprintf; |
14
|
|
|
|
15
|
|
|
final class AssetExtension implements ExtensionInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var string root directory storing the published asset files. |
19
|
|
|
*/ |
20
|
|
|
private string $basePath; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var string base URL through which the published asset files can be accessed. |
24
|
|
|
*/ |
25
|
|
|
private string $baseUrl; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var bool whether to append a timestamp to the URL of every published asset. |
29
|
|
|
*/ |
30
|
|
|
private bool $appendTimestamp; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param string $basePath root directory storing the published asset files. |
34
|
|
|
* @param string $baseUrl base URL through which the published asset files can be accessed. |
35
|
|
|
* @param bool $appendTimestamp whether to append a timestamp to the URL of every published asset. |
36
|
|
|
*/ |
37
|
4 |
|
public function __construct(string $basePath, string $baseUrl = '', bool $appendTimestamp = false) |
38
|
|
|
{ |
39
|
4 |
|
$this->basePath = rtrim($basePath, '\/'); |
40
|
4 |
|
$this->baseUrl = rtrim($baseUrl, '/'); |
41
|
4 |
|
$this->appendTimestamp = $appendTimestamp; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* {@inheritDoc} |
46
|
|
|
*/ |
47
|
|
|
public function getFunctions(): array |
48
|
|
|
{ |
49
|
|
|
return [ |
50
|
|
|
'asset' => [$this, 'assetFile'], |
51
|
|
|
]; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Includes the asset file and appends a timestamp with the last modification of that file. |
56
|
|
|
* |
57
|
|
|
* @param string $file |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
4 |
|
public function assetFile(string $file): string |
61
|
|
|
{ |
62
|
4 |
|
$url = $this->baseUrl . '/' . ltrim($file, '/'); |
63
|
4 |
|
$path = $this->basePath . '/' . ltrim($file, '/'); |
64
|
|
|
|
65
|
4 |
|
if (!file_exists($path)) { |
66
|
1 |
|
throw new RuntimeException(sprintf( |
67
|
1 |
|
'Asset file "%s" does not exist.', |
68
|
1 |
|
$path |
69
|
1 |
|
)); |
70
|
|
|
} |
71
|
|
|
|
72
|
3 |
|
if ($this->appendTimestamp) { |
73
|
2 |
|
return $url . '?v=' . filemtime($path); |
74
|
|
|
} |
75
|
|
|
|
76
|
2 |
|
return $url; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|