87 lines
2.3 KiB
PHP
87 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace MyCodebox\MariaCore\Cache;
|
|
|
|
/**
|
|
* RouteCache
|
|
*
|
|
* Verwaltet das Caching der Routen-Metadaten als JSON-Datei.
|
|
* Cacht nur serialisierbare Handler (Strings, Controller-Arrays), keine Closures!
|
|
*/
|
|
class RouteCache
|
|
{
|
|
private string $cacheFile;
|
|
|
|
/**
|
|
* Konstruktor.
|
|
*
|
|
* @param string $cacheFile Pfad zur Cache-Datei
|
|
*/
|
|
public function __construct(string $cacheFile)
|
|
{
|
|
$this->cacheFile = $cacheFile;
|
|
}
|
|
|
|
/**
|
|
* Schreibe cachebare Routen in die Cache-Datei.
|
|
*
|
|
* @param array $routes Das komplette $router->routes-Array
|
|
* @return void
|
|
*/
|
|
public function write(array $routes): void
|
|
{
|
|
$cache = [];
|
|
foreach ($routes as $method => $routesArr) {
|
|
foreach ($routesArr as $pattern => $info) {
|
|
if (
|
|
is_string($info['handler']) ||
|
|
(is_array($info['handler']) && isset($info['handler'][0]) && is_string($info['handler'][0]))
|
|
) {
|
|
$cache[] = [
|
|
'method' => $method,
|
|
'pattern' => $pattern,
|
|
'handler' => $info['handler'],
|
|
'name' => $info['name'] ?? null,
|
|
// Middleware nur als String/Array, keine Closures!
|
|
'middleware' => array_filter(
|
|
$info['middleware'],
|
|
fn($mw) => is_string($mw) || is_array($mw)
|
|
),
|
|
];
|
|
}
|
|
}
|
|
}
|
|
if (!is_dir(dirname($this->cacheFile))) {
|
|
mkdir(dirname($this->cacheFile), 0777, true);
|
|
}
|
|
file_put_contents(
|
|
$this->cacheFile,
|
|
json_encode($cache, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Lese die gecachten Routen aus der Cache-Datei.
|
|
*
|
|
* @return array|null
|
|
*/
|
|
public function read(): ?array
|
|
{
|
|
if (!file_exists($this->cacheFile)) {
|
|
return null;
|
|
}
|
|
return json_decode(file_get_contents($this->cacheFile), true);
|
|
}
|
|
|
|
/**
|
|
* Lösche die Cache-Datei.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function clear(): void
|
|
{
|
|
if (file_exists($this->cacheFile)) {
|
|
unlink($this->cacheFile);
|
|
}
|
|
}
|
|
}
|