CoreMiddleware.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\RpcServer;
  12. use Closure;
  13. use FastRoute\Dispatcher;
  14. use Hyperf\Contract\NormalizerInterface;
  15. use Hyperf\HttpMessage\Stream\SwooleStream;
  16. use Hyperf\HttpServer\Router\Dispatched;
  17. use Hyperf\Rpc\Protocol;
  18. use Hyperf\RpcServer\Router\DispatcherFactory;
  19. use Psr\Container\ContainerInterface;
  20. use Psr\Http\Message\ServerRequestInterface;
  21. use function Hyperf\Support\make;
  22. class CoreMiddleware extends \Hyperf\HttpServer\CoreMiddleware
  23. {
  24. protected Protocol $protocol;
  25. public function __construct(ContainerInterface $container, Protocol $protocol, string $serverName)
  26. {
  27. $this->protocol = $protocol;
  28. parent::__construct($container, $serverName);
  29. }
  30. public function getNormalizer(): NormalizerInterface
  31. {
  32. return $this->protocol->getNormalizer();
  33. }
  34. protected function createDispatcher(string $serverName): Dispatcher
  35. {
  36. $factory = make(DispatcherFactory::class, [
  37. 'pathGenerator' => $this->protocol->getPathGenerator(),
  38. ]);
  39. return $factory->getDispatcher($serverName);
  40. }
  41. protected function handleFound(Dispatched $dispatched, ServerRequestInterface $request): mixed
  42. {
  43. if ($dispatched->handler->callback instanceof Closure) {
  44. $callback = $dispatched->handler->callback;
  45. $response = $callback();
  46. } else {
  47. [$controller, $action] = $this->prepareHandler($dispatched->handler->callback);
  48. $controllerInstance = $this->container->get($controller);
  49. if (! method_exists($controller, $action)) {
  50. // Route found, but the handler does not exist.
  51. return $this->response()->withStatus(500)->withBody(new SwooleStream('Method of class does not exist.'));
  52. }
  53. $parameters = $this->parseMethodParameters($controller, $action, $request->getParsedBody());
  54. $response = $controllerInstance->{$action}(...$parameters);
  55. }
  56. return $response;
  57. }
  58. }