Files
car/asset-version.php

81 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
$service = 'car';
$root = __DIR__;
$scanRoots = [
'.' => ['php', 'js', 'css', 'webmanifest', 'svg', 'png', 'ico'],
];
function collect_asset_files(string $root, array $scanRoots): array
{
$files = [];
$rootPath = realpath($root);
if (!$rootPath) {
return $files;
}
foreach ($scanRoots as $relativeRoot => $extensions) {
$base = realpath($rootPath . DIRECTORY_SEPARATOR . $relativeRoot);
if (!$base || strpos($base, $rootPath) !== 0) {
continue;
}
$allowed = array_fill_keys(array_map('strtolower', $extensions), true);
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if (!$file instanceof SplFileInfo || !$file->isFile()) {
continue;
}
$extension = strtolower($file->getExtension());
if (!isset($allowed[$extension])) {
continue;
}
$path = $file->getRealPath();
if ($path && strpos($path, $rootPath . DIRECTORY_SEPARATOR) === 0) {
$files[] = $path;
}
}
}
sort($files, SORT_STRING);
return array_values(array_unique($files));
}
clearstatcache();
$rootPath = realpath($root);
$fingerprints = [];
$assets = [];
foreach (collect_asset_files($root, $scanRoots) as $fullPath) {
$relativePath = ltrim(str_replace($rootPath ?: $root, '', $fullPath), DIRECTORY_SEPARATOR);
$fileHash = is_readable($fullPath) ? (hash_file('sha256', $fullPath) ?: 'hash-failed') : 'unreadable';
$fileVersion = (string)filemtime($fullPath) . '-' . substr($fileHash, 0, 10);
$publicPath = '/car/' . str_replace(DIRECTORY_SEPARATOR, '/', $relativePath);
$fingerprints[] = implode('|', [
ltrim($publicPath, '/'),
(string)filesize($fullPath),
(string)filemtime($fullPath),
$fileHash,
]);
$assets[$publicPath] = $fileVersion;
}
echo json_encode([
'result' => 'ok',
'service' => $service,
'version' => hash('sha256', implode("\n", $fingerprints)),
'assets' => $assets,
'count' => count($fingerprints),
'generatedAt' => time(),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);