Files
kiri-router/src/Handler.php
T

114 lines
2.7 KiB
PHP
Raw Normal View History

2023-04-15 23:29:27 +08:00
<?php
2023-04-16 01:24:30 +08:00
declare(strict_types=1);
2023-04-15 23:29:27 +08:00
namespace Kiri\Router;
2023-04-19 13:20:12 +08:00
use Closure;
2023-10-17 14:50:46 +08:00
use Kiri\Router\Format\ArrayFormat;
use Kiri\Router\Format\IFormat;
use Kiri\Router\Format\MixedFormat;
use Kiri\Router\Format\OtherFormat;
use Kiri\Router\Format\VoidFormat;
2023-04-15 23:31:16 +08:00
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use ReflectionException;
2023-09-13 12:30:57 +08:00
use ReflectionNamedType;
2023-04-15 23:31:16 +08:00
class Handler implements RequestHandlerInterface
2023-04-15 23:29:27 +08:00
{
2023-10-17 14:50:46 +08:00
/**
* @var array|string[]
*/
protected array $types = [
2023-10-17 15:52:14 +08:00
'Psr\Http\Message\ResponseInterface' => ResponseInterface::class,
'array' => ArrayFormat::class,
'mixed' => MixedFormat::class,
'object' => MixedFormat::class,
'int' => OtherFormat::class,
'string' => OtherFormat::class,
'bool' => OtherFormat::class,
'void' => VoidFormat::class,
2023-10-17 14:50:46 +08:00
];
/**
* @var IFormat
*/
protected IFormat $format;
2023-09-13 12:30:57 +08:00
/**
* @param array|Closure $handler
* @param array $parameter
2023-10-17 14:50:46 +08:00
* @param ReflectionNamedType $reflectionType
* @throws ReflectionException
2023-09-13 12:30:57 +08:00
*/
2023-10-17 14:50:46 +08:00
public function __construct(public array|Closure $handler, public array $parameter, public ReflectionNamedType $reflectionType)
2023-09-13 12:30:57 +08:00
{
2023-10-17 15:51:05 +08:00
$this->format = di($this->types[$this->reflectionType->getName()]);
2023-09-13 12:30:57 +08:00
}
/**
* @return bool
*/
public function isClosure(): bool
{
return $this->handler instanceof Closure;
}
/**
* @param string $interface
* @return bool
*/
public function implement(string $interface): bool
{
if (!$this->isClosure()) {
return $this->handler[0] instanceof $interface;
}
return false;
}
/**
* @return string|null
*/
public function getClass(): ?string
{
if ($this->isClosure()) {
return null;
}
return $this->handler[0]::class;
}
/**
* @return string|null
*/
public function getMethod(): ?string
{
if ($this->isClosure()) {
return null;
}
return $this->handler[1];
}
/**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws ReflectionException
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
2023-10-17 14:50:46 +08:00
$data = call_user_func($this->handler, ...$this->parameter);
2023-09-13 12:30:57 +08:00
2023-10-17 14:50:46 +08:00
return call_user_func([$this->format, 'call'], $data);
2023-09-13 12:30:57 +08:00
}
2023-04-15 23:31:16 +08:00
2023-04-15 23:29:27 +08:00
}