web-base/core/Objects/Router/DocumentRoute.class.php

91 lines
2.4 KiB
PHP
Raw Normal View History

2022-06-01 09:47:31 +02:00
<?php
namespace Objects\Router;
use Elements\Document;
2022-08-20 22:17:17 +02:00
use Objects\Context;
use Objects\Search\Searchable;
use Objects\Search\SearchQuery;
2022-06-01 09:47:31 +02:00
use ReflectionException;
class DocumentRoute extends AbstractRoute {
2022-08-20 22:17:17 +02:00
use Searchable;
2022-06-01 09:47:31 +02:00
private string $className;
private array $args;
private ?\ReflectionClass $reflectionClass;
public function __construct(string $pattern, bool $exact, string $className, ...$args) {
parent::__construct($pattern, $exact);
$this->className = $className;
$this->args = $args;
$this->reflectionClass = null;
}
private function loadClass(): bool {
if ($this->reflectionClass === null) {
try {
$file = getClassPath($this->className);
if (file_exists($file)) {
$this->reflectionClass = new \ReflectionClass($this->className);
if ($this->reflectionClass->isSubclassOf(Document::class)) {
return true;
}
}
} catch (ReflectionException $exception) {
$this->reflectionClass = null;
2022-08-20 22:17:17 +02:00
throw $exception;
2022-06-01 09:47:31 +02:00
}
$this->reflectionClass = null;
return false;
}
return true;
}
public function match(string $url) {
$match = parent::match($url);
if ($match === false || !$this->loadClass()) {
return false;
}
return $match;
}
protected function getArgs(): array {
return array_merge(parent::getArgs(), [$this->className], $this->args);
}
public function call(Router $router, array $params): string {
try {
2022-08-20 22:17:17 +02:00
if (!$this->loadClass()) {
return $router->returnStatusCode(500, [ "message" => "Error loading class: $this->className"]);
}
$args = array_merge([$router], $this->args, $params);
2022-06-01 09:47:31 +02:00
$document = $this->reflectionClass->newInstanceArgs($args);
2022-08-20 22:17:17 +02:00
return $document->load($params);
2022-06-01 09:47:31 +02:00
} catch (\ReflectionException $e) {
return $router->returnStatusCode(500, [ "message" => "Error loading class $this->className: " . $e->getMessage()]);
}
}
2022-08-20 22:17:17 +02:00
public function doSearch(Context $context, SearchQuery $query): array {
try {
if ($this->loadClass()) {
$args = array_merge([$context->router], $this->args);
$document = $this->reflectionClass->newInstanceArgs($args);
if ($document->isSearchable()) {
return $document->doSearch($query, $this);
}
}
return [];
} catch (\ReflectionException) {
return [];
}
}
2022-06-01 09:47:31 +02:00
}