RequestHandler.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Opentalent\OtStats\Middleware;
  3. use Opentalent\OtCore\Website\OtWebsiteRepository;
  4. use Psr\Http\Message\ResponseInterface;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Psr\Http\Server\MiddlewareInterface;
  7. use Psr\Http\Server\RequestHandlerInterface;
  8. use TYPO3\CMS\Core\Http\Stream;
  9. use TYPO3\CMS\Core\Utility\GeneralUtility;
  10. use TYPO3\CMS\Extbase\Object\ObjectManager;
  11. use TYPO3\CMS\Fluid\View\StandaloneView;
  12. /**
  13. * Hooks into the frontend request to add the matomo script into
  14. * the request's header
  15. *
  16. * @internal
  17. */
  18. class RequestHandler implements MiddlewareInterface
  19. {
  20. const TEMPLATES_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Templates';
  21. const PARTIALS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Partials';
  22. const LAYOUTS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Layouts';
  23. const TEMPLATE_FILE = self::TEMPLATES_ROOT_PATHS . '/Header/Include.html';
  24. public function __construct(
  25. private readonly OtWebsiteRepository $otWebsiteRepository,
  26. ) {}
  27. /**
  28. * Process the frontend request to insert the matomo script in the header
  29. * if the stats module is activated
  30. *
  31. * @param ServerRequestInterface $request
  32. * @param RequestHandlerInterface $handler
  33. * @return ResponseInterface
  34. */
  35. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
  36. {
  37. // Retrieve the current matomo site's id if set
  38. $website = $this->otWebsiteRepository->getCurrentWebsiteFromFEGlobals();
  39. $matomoSiteId = $website['matomo_site_id'];
  40. if (!$matomoSiteId > 0) {
  41. // stats are not enabled, continue
  42. return $handler->handle($request);
  43. }
  44. // render view
  45. $view = GeneralUtility::makeInstance(StandaloneView::class);
  46. $view->setTemplateRootPaths([self::TEMPLATES_ROOT_PATHS]);
  47. $view->setPartialRootPaths([self::PARTIALS_ROOT_PATHS]);
  48. $view->setLayoutRootPaths([self::LAYOUTS_ROOT_PATHS]);
  49. $view->setTemplatePathAndFilename(
  50. GeneralUtility::getFileAbsFileName(self::TEMPLATE_FILE)
  51. );
  52. // Build the response
  53. $response = $handler->handle($request);
  54. // insert the rendered view in the body, just before the closing </html> tag
  55. $newSection = $view->render();
  56. $bodyContent = (string)$response->getBody();
  57. $bodyContent = str_replace('</head>', $newSection . '</head>', $bodyContent);
  58. $newBody = new Stream('php://temp', 'wb+');
  59. $newBody->write($bodyContent);
  60. $newBody->rewind();
  61. $response = $response->withBody($newBody);
  62. return $response;
  63. }
  64. }