-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPlugin.php
85 lines (70 loc) · 2.24 KB
/
Plugin.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
<?php
namespace OFFLINE\Vite;
use October\Rain\Support\Facades\Event;
use OFFLINE\Vite\Classes\Vite;
use System\Classes\PluginBase;
use Throwable;
/**
* Plugin Information File
*/
class Plugin extends PluginBase
{
/**
* Use this string to include a vite asset
* via the addJs/addCss methods.
*/
public const VITE_ASSET_TOKEN = 'vite:';
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'Vite',
'description' => 'Integrate Vite in October CMS',
'author' => 'OFFLINE',
'icon' => 'icon-bolt',
];
}
public function registerMarkupTags()
{
return [
'functions' => [
'vite' => [Vite::class, 'includeAssets'],
],
];
}
public function register()
{
Event::listen('cms.page.start', function () {
Vite::instance();
});
// Replace the `vite:` token when adding JS/CSS assets.
Event::listen('cms.assets.render', function ($type, &$result) {
$vite = Vite::instance();
$lines = array_map('trim', array_filter(explode("\n", $result)));
foreach ($lines as $number => $line) {
if (!str_contains($line, self::VITE_ASSET_TOKEN)) {
continue;
}
$matches = [];
preg_match(sprintf('/%s([^">]+)/', self::VITE_ASSET_TOKEN), $line, $matches);
if (count($matches) < 2) {
continue;
}
try {
$asset = $vite->resolveAsset($matches[1]);
} catch (Throwable $e) {
// Unfortunately, October swallows all exceptions from this event handler, so we can only log the error.
logger()->error("[OFFLINE.Vite] Failed to include asset '{$matches[1]}': {$e->getMessage()}", ['exception' => $e]);
return;
}
// Replace the original line with the included asset.
$lines[$number] = $asset->render();
}
$result = implode("\n", $lines);
});
}
}