forked from lubomirblazekcz/nette-vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Service.php
104 lines (79 loc) 路 2.17 KB
/
Service.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php declare(strict_types=1);
namespace MMEE\Vite;
use Nette\Http\Request;
use Nette\Utils\FileSystem;
use Nette\Utils\Html;
use Nette\Utils\Json;
final class Service
{
private string $viteServer;
private string $manifestFile;
private bool $debugMode;
private string $basePath;
private Request $httpRequest;
public function __construct(
string $viteServer,
string $manifestFile,
bool $debugMode,
string $basePath,
Request $httpRequest
)
{
$this->viteServer = $viteServer;
$this->manifestFile = $manifestFile;
$this->debugMode = $debugMode;
$this->basePath = $basePath;
$this->httpRequest = $httpRequest;
}
public function getAsset(string $entrypoint): string
{
if ($this->isEnabled()) {
$baseUrl = $this->viteServer . '/';
$asset = $entrypoint;
} else {
$baseUrl = $this->basePath;
$asset = '';
if (file_exists($this->manifestFile)) {
$manifest = Json::decode(FileSystem::read($this->manifestFile), Json::FORCE_ARRAY);
$asset = $manifest[$entrypoint]['file'];
} else {
trigger_error('Missing manifest file: ' . $this->manifestFile, E_USER_WARNING);
}
}
return $baseUrl . $asset;
}
/**
* @return array<string, string>
*/
public function getCssAssets(string $entrypoint): array
{
$assets = [];
if (!$this->isEnabled()) {
if (file_exists($this->manifestFile)) {
$manifest = Json::decode(FileSystem::read($this->manifestFile), Json::FORCE_ARRAY);
$assets = $manifest[$entrypoint]['css'] ?? [];
} else {
trigger_error('Missing manifest file: ' . $this->manifestFile, E_USER_WARNING);
}
}
return $assets;
}
public function isEnabled(): bool
{
return $this->debugMode && $this->httpRequest->getCookie('netteVite') === 'true';
}
public function printTags(string $entrypoint): void
{
$scripts = [$this->getAsset($entrypoint)];
$styles = $this->getCssAssets($entrypoint);
if ($this->isEnabled()) {
echo Html::el('script')->type('module')->src($this->viteServer . '/' . '@vite/client');
}
foreach ($styles as $path) {
echo Html::el('link')->rel('stylesheet')->href($path);
}
foreach ($scripts as $path) {
echo Html::el('script')->type('module')->src($path);
}
}
}