RequestProcessor.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /**
  3. * @package Grav\Common\Processors
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Processors;
  9. use Grav\Common\Processors\Events\RequestHandlerEvent;
  10. use Grav\Common\Uri;
  11. use Psr\Http\Message\ResponseInterface;
  12. use Psr\Http\Message\ServerRequestInterface;
  13. use Psr\Http\Server\RequestHandlerInterface;
  14. class RequestProcessor extends ProcessorBase
  15. {
  16. public $id = 'request';
  17. public $title = 'Request';
  18. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
  19. {
  20. $this->startTimer();
  21. $header = $request->getHeaderLine('Content-Type');
  22. $type = trim(strstr($header, ';', true) ?: $header);
  23. if ($type === 'application/json') {
  24. $request = $request->withParsedBody(json_decode($request->getBody()->getContents(), true));
  25. }
  26. $uri = $request->getUri();
  27. $ext = mb_strtolower(pathinfo($uri->getPath(), PATHINFO_EXTENSION));
  28. $request = $request
  29. ->withAttribute('grav', $this->container)
  30. ->withAttribute('time', $_SERVER['REQUEST_TIME_FLOAT'] ?? GRAV_REQUEST_TIME)
  31. ->withAttribute('route', Uri::getCurrentRoute()->withExtension($ext))
  32. ->withAttribute('referrer', $this->container['uri']->referrer());
  33. $event = new RequestHandlerEvent(['request' => $request, 'handler' => $handler]);
  34. /** @var RequestHandlerEvent $event */
  35. $event = $this->container->fireEvent('onRequestHandlerInit', $event);
  36. $response = $event->getResponse();
  37. $this->stopTimer();
  38. if ($response) {
  39. return $response;
  40. }
  41. return $handler->handle($request);
  42. }
  43. }