61 lines
1.6 KiB
PHP
61 lines
1.6 KiB
PHP
|
<?php
|
||
|
namespace Common\Service;
|
||
|
|
||
|
use function Safe\{json_encode, json_decode, file_get_contents, file_put_contents};
|
||
|
use ProVM\Concept\API\Route\Route;
|
||
|
use ProVM\Implement\API\Route\Route as RouteObj;
|
||
|
|
||
|
class Documenter
|
||
|
{
|
||
|
public function __construct(string $filename)
|
||
|
{
|
||
|
$this->setFilename($filename);
|
||
|
}
|
||
|
|
||
|
protected string $filename;
|
||
|
public function setFilename(string $filename): Documenter
|
||
|
{
|
||
|
$this->filename = $filename;
|
||
|
return $this;
|
||
|
}
|
||
|
public function getFilename(): string
|
||
|
{
|
||
|
return $this->filename;
|
||
|
}
|
||
|
|
||
|
protected array $routes;
|
||
|
public function setRoutes(array $routes): Documenter
|
||
|
{
|
||
|
foreach ($routes as $path => $route) {
|
||
|
$this->addRoute($path, $route);
|
||
|
}
|
||
|
return $this;
|
||
|
}
|
||
|
public function addRoute(string $path, Route $route): Documenter
|
||
|
{
|
||
|
$this->routes[$path] = $route;
|
||
|
return $this;
|
||
|
}
|
||
|
public function getRoutes(): array
|
||
|
{
|
||
|
return $this->routes;
|
||
|
}
|
||
|
|
||
|
protected function load(): mixed
|
||
|
{
|
||
|
$json = json_decode(trim(file_get_contents($this->getFilename())), JSON_OBJECT_AS_ARRAY);
|
||
|
foreach ($json['paths'] as $path => $data) {
|
||
|
$route = RouteObj::add($data);
|
||
|
$this->addRoute($path, $route);
|
||
|
}
|
||
|
return $json;
|
||
|
}
|
||
|
public function save(): void
|
||
|
{
|
||
|
$json = $this->load();
|
||
|
$json['paths'] = $this->getRoutes();
|
||
|
ksort($json['paths']);
|
||
|
file_put_contents($this->getFilename(), json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||
|
}
|
||
|
}
|