misc_pterodactyl-panel/app/Services/Helpers/AssetHashService.php

123 lines
3.1 KiB
PHP
Raw Normal View History

<?php
namespace Pterodactyl\Services\Helpers;
use Illuminate\Support\Arr;
use Illuminate\Filesystem\FilesystemManager;
class AssetHashService
{
/**
* Location of the manifest file generated by gulp.
*/
public const MANIFEST_PATH = './assets/manifest.json';
/**
* @var \Illuminate\Contracts\Filesystem\Filesystem
*/
private $filesystem;
/**
2020-06-28 22:43:44 +00:00
* @var array|null
*/
protected static $manifest;
/**
* AssetHashService constructor.
*/
2022-02-14 00:04:11 +00:00
public function __construct(FilesystemManager $filesystem)
{
$this->filesystem = $filesystem->createLocalDriver(['root' => public_path()]);
}
/**
* Modify a URL to append the asset hash.
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function url(string $resource): string
{
$file = last(explode('/', $resource));
$data = Arr::get($this->manifest(), $file) ?? $file;
return str_replace($file, Arr::get($data, 'src') ?? $file, $resource);
2018-06-04 02:35:50 +00:00
}
/**
* Return the data integrity hash for a resource.
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function integrity(string $resource): string
{
$file = last(explode('/', $resource));
$data = array_get($this->manifest(), $file, $file);
return Arr::get($data, 'integrity') ?? '';
}
/**
* Return a built CSS import using the provided URL.
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function css(string $resource): string
{
$attributes = [
'href' => $this->url($resource),
'rel' => 'stylesheet preload',
'as' => 'style',
'crossorigin' => 'anonymous',
'referrerpolicy' => 'no-referrer',
];
if (config('pterodactyl.assets.use_hash')) {
$attributes['integrity'] = $this->integrity($resource);
}
$output = '<link';
foreach ($attributes as $key => $value) {
$output .= " $key=\"$value\"";
}
return $output . '>';
}
/**
* Return a built JS import using the provided URL.
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function js(string $resource): string
{
$attributes = [
'src' => $this->url($resource),
'crossorigin' => 'anonymous',
];
if (config('pterodactyl.assets.use_hash')) {
$attributes['integrity'] = $this->integrity($resource);
}
$output = '<script';
foreach ($attributes as $key => $value) {
$output .= " $key=\"$value\"";
}
return $output . '></script>';
}
/**
* Get the asset manifest and store it in the cache for quicker lookups.
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
protected function manifest(): array
{
return self::$manifest ?: self::$manifest = json_decode(
2021-01-23 20:33:34 +00:00
$this->filesystem->get(self::MANIFEST_PATH),
true
);
}
}