Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Services/Helpers/AssetHashService.php
10280 views
1
<?php
2
3
namespace Pterodactyl\Services\Helpers;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Filesystem\FilesystemManager;
7
use Illuminate\Contracts\Filesystem\Filesystem;
8
use Pterodactyl\Exceptions\ManifestDoesNotExistException;
9
10
class AssetHashService
11
{
12
/**
13
* Location of the manifest file generated by gulp.
14
*/
15
public const MANIFEST_PATH = './assets/manifest.json';
16
17
private Filesystem $filesystem;
18
19
protected static mixed $manifest = null;
20
21
/**
22
* AssetHashService constructor.
23
*/
24
public function __construct(FilesystemManager $filesystem)
25
{
26
$this->filesystem = $filesystem->createLocalDriver(['root' => public_path()]);
27
}
28
29
/**
30
* Modify a URL to append the asset hash.
31
*/
32
public function url(string $resource): string
33
{
34
$file = last(explode('/', $resource));
35
$data = Arr::get($this->manifest(), $file) ?? $file;
36
37
return str_replace($file, Arr::get($data, 'src') ?? $file, $resource);
38
}
39
40
/**
41
* Return the data integrity hash for a resource.
42
*/
43
public function integrity(string $resource): string
44
{
45
$file = last(explode('/', $resource));
46
$data = array_get($this->manifest(), $file, $file);
47
48
return Arr::get($data, 'integrity') ?? '';
49
}
50
51
/**
52
* Return a built CSS import using the provided URL.
53
*/
54
public function css(string $resource): string
55
{
56
$attributes = [
57
'href' => $this->url($resource),
58
'rel' => 'stylesheet preload',
59
'as' => 'style',
60
'crossorigin' => 'anonymous',
61
'referrerpolicy' => 'no-referrer',
62
];
63
64
if (config('pterodactyl.assets.use_hash')) {
65
$attributes['integrity'] = $this->integrity($resource);
66
}
67
68
$output = '<link';
69
foreach ($attributes as $key => $value) {
70
$output .= " $key=\"$value\"";
71
}
72
73
return $output . '>';
74
}
75
76
/**
77
* Return a built JS import using the provided URL.
78
*/
79
public function js(string $resource): string
80
{
81
$attributes = [
82
'src' => $this->url($resource),
83
'crossorigin' => 'anonymous',
84
];
85
86
if (config('pterodactyl.assets.use_hash')) {
87
$attributes['integrity'] = $this->integrity($resource);
88
}
89
90
$output = '<script';
91
foreach ($attributes as $key => $value) {
92
$output .= " $key=\"$value\"";
93
}
94
95
return $output . '></script>';
96
}
97
98
/**
99
* Get the asset manifest and store it in the cache for quicker lookups.
100
*/
101
protected function manifest(): array
102
{
103
if (static::$manifest === null) {
104
self::$manifest = json_decode(
105
$this->filesystem->get(self::MANIFEST_PATH),
106
true
107
);
108
}
109
110
$manifest = static::$manifest;
111
if ($manifest === null) {
112
throw new ManifestDoesNotExistException();
113
}
114
115
return $manifest;
116
}
117
}
118
119