Files
dpl/app/Support/ThemeAssets.php
T

27 lines
1.4 KiB
PHP

<?php
namespace App\Support;
use Illuminate\Http\Request;
use RuntimeException;
final class ThemeAssets
{
public static function scripts(string $theme, Request $request): array
{
if (!preg_match('/\A[A-Za-z][A-Za-z0-9_-]*\z/D',$theme)) throw new RuntimeException('Invalid theme name.');
$root=base_path('theme/'.$theme);
$config=json_decode(file_get_contents($root.'/config.json'),true,flags:JSON_THROW_ON_ERROR);
$dev=$config['development']??[];
if (in_array($request->getHost(),$dev['hosts']??[],true) && isset($dev['marker'],$dev['origin'],$dev['port'])) {
$marker=storage_path('framework/'.$dev['marker']);
if(is_file($marker) && trim(file_get_contents($marker))===$dev['origin']) {
$socket=@fsockopen('127.0.0.1',(int)$dev['port'],$error,$message,0.1);
if($socket){fclose($socket);return ['scripts'=>$dev['scripts'],'styles'=>[]];}
}
}
$manifest=$root.'/assets/.vite/manifest.json';
if(!is_file($manifest)) throw new RuntimeException($theme.' assets missing; build this theme first.');
$entries=json_decode(file_get_contents($manifest),true,flags:JSON_THROW_ON_ERROR);
$entry=$entries['index.html'];
return ['scripts'=>['/theme/'.$theme.'/assets/'.$entry['file']],'styles'=>array_map(fn($file)=>'/theme/'.$theme.'/assets/'.$file,$entry['css']??[])];
}
}