99 lines
2.9 KiB
PHP
99 lines
2.9 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Kiri\Router;
|
|
|
|
use Closure;
|
|
use Exception;
|
|
use Psr\Container\ContainerExceptionInterface;
|
|
use Psr\Container\NotFoundExceptionInterface;
|
|
use ReflectionClass;
|
|
use ReflectionException;
|
|
use ReflectionMethod;
|
|
|
|
class ControllerInterpreter
|
|
{
|
|
|
|
|
|
/**
|
|
* @param object $class
|
|
* @param string|ReflectionMethod $method
|
|
* @param ReflectionClass|null $reflection
|
|
* @return Handler
|
|
* @throws ContainerExceptionInterface
|
|
* @throws NotFoundExceptionInterface
|
|
* @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 ContainerExceptionInterface
|
|
* @throws NotFoundExceptionInterface
|
|
*/
|
|
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 ContainerExceptionInterface
|
|
* @throws NotFoundExceptionInterface
|
|
* @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 ContainerExceptionInterface
|
|
* @throws NotFoundExceptionInterface
|
|
* @throws Exception
|
|
*/
|
|
public function resolveMethod(object $class, string|\ReflectionMethod $reflectionMethod, ReflectionClass $reflectionClass): Handler
|
|
{
|
|
if (is_string($reflectionMethod)) {
|
|
$reflectionMethod = $reflectionClass->getMethod($reflectionMethod);
|
|
}
|
|
|
|
$returnType = $reflectionMethod->getReturnType();
|
|
if ($returnType instanceof \ReflectionUnionType) {
|
|
throw new Exception("Return type error, cannot be multi type.");
|
|
}
|
|
|
|
$container = \Kiri::getDi();
|
|
$parameters = $container->getMethodParams($reflectionMethod);
|
|
|
|
return new Handler([$class, $reflectionMethod->getName()], $parameters, $returnType);
|
|
}
|
|
|
|
}
|