Files
kiri-router/src/ControllerInterpreter.php
T

94 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
2023-04-15 23:31:16 +08:00
namespace Kiri\Router;
2023-04-15 23:29:27 +08:00
2023-04-15 23:31:16 +08:00
use Closure;
2023-04-19 12:35:39 +08:00
use Exception;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
2023-04-15 23:29:27 +08:00
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
class ControllerInterpreter
{
2023-09-13 12:30:57 +08:00
/**
* @param object $class
* @param string|ReflectionMethod $method
* @param ReflectionClass|null $reflection
* @return Handler
* @throws ReflectionException
*/
public function addRouteByString(object $class, string|ReflectionMethod $method, ?ReflectionClass $reflection = null): Handler
{
if (is_null($reflection)) {
$reflection = \Kiri::getDi()->getReflectionClass($class::class);
}
return $this->resolveMethod($class, $method, $reflection);
}
/**
* @param Closure $method
* @return Handler
* @throws ReflectionException
* @throws Exception
*/
public function addRouteByClosure(Closure $method): Handler
{
$reflection = new \ReflectionFunction($method);
$params = \Kiri::getDi()->resolveMethodParams($reflection);
return new Handler($method, $params, $reflection->getReturnType());
}
/**
* @param object $class
* @param string|ReflectionMethod $method
* @param ReflectionClass|null $reflection
* @return Handler
* @throws ReflectionException
*/
public function addRouteByObject(object $class, string|ReflectionMethod $method, ?ReflectionClass $reflection = null): Handler
{
if (is_null($reflection)) {
$reflection = \Kiri::getDi()->getReflectionClass($class::class);
}
return $this->resolveMethod($class, $method, $reflection);
}
/**
* @param object $class
* @param string|ReflectionMethod $reflectionMethod
* @param ReflectionClass $reflectionClass
* @return Handler
* @throws ReflectionException
* @throws Exception
*/
public function resolveMethod(object $class, string|\ReflectionMethod $reflectionMethod, ReflectionClass $reflectionClass): Handler
{
2023-10-17 14:50:46 +08:00
$returnType = $reflectionMethod->getReturnType();
if ($returnType instanceof \ReflectionUnionType) {
throw new Exception("Return type error, cannot be multi type.");
}
2023-09-13 12:30:57 +08:00
if (empty($reflectionMethod)) {
2023-10-17 14:50:46 +08:00
return new Handler([$class, $reflectionMethod], [], $returnType);
2023-09-13 12:30:57 +08:00
}
if (is_string($reflectionMethod)) {
$reflectionMethod = $reflectionClass->getMethod($reflectionMethod);
}
$container = \Kiri::getDi();
$parameters = $container->getMethodParams($reflectionMethod);
2023-10-17 14:50:46 +08:00
return new Handler([$class, $reflectionMethod->getName()], $parameters, $returnType);
2023-09-13 12:30:57 +08:00
}
2023-04-15 23:29:27 +08:00
}