RequestHandler.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Opentalent\OtStats\Middleware;
  3. use Opentalent\OtCore\Page\OtPageRepository;
  4. use Opentalent\OtStats\Settings\StatsSettingsRepository;
  5. use Psr\Http\Message\ResponseInterface;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. use Psr\Http\Server\MiddlewareInterface;
  8. use Psr\Http\Server\RequestHandlerInterface;
  9. use TYPO3\CMS\Core\Http\Stream;
  10. use TYPO3\CMS\Core\Utility\GeneralUtility;
  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 LAYOUTS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Layouts';
  22. const TEMPLATE_FILE = self::TEMPLATES_ROOT_PATHS . '/Header/Matomo.html';
  23. /**
  24. *
  25. * @param ServerRequestInterface $request
  26. * @param RequestHandlerInterface $handler
  27. * @return ResponseInterface
  28. */
  29. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
  30. {
  31. // Retrieve the current matomo site's id if set
  32. $otPageRepository = GeneralUtility::makeInstance(OtPageRepository::class);
  33. $rootPageUid = $otPageRepository->getCurrentSiteRootPageId();
  34. $statsSettingsRepository = GeneralUtility::makeInstance(StatsSettingsRepository::class);
  35. $matomoSiteId = $statsSettingsRepository->getMatomoSiteId($rootPageUid);
  36. if (!$matomoSiteId > 0) {
  37. // stats are not enabled, continue
  38. return $handler->handle($request);
  39. }
  40. // render view
  41. $view = GeneralUtility::makeInstance(StandaloneView::class);
  42. $view->setTemplateRootPaths([self::TEMPLATES_ROOT_PATHS]);
  43. $view->setLayoutRootPaths([self::LAYOUTS_ROOT_PATHS]);
  44. $view->setTemplatePathAndFilename(
  45. GeneralUtility::getFileAbsFileName(self::TEMPLATE_FILE)
  46. );
  47. // Build the response
  48. $response = $handler->handle($request);
  49. // insert the rendered view in the body, just before the closing </html> tag
  50. $newSection = $view->render();
  51. $bodyContent = (string)$response->getBody();
  52. $bodyContent = str_replace('</head>', $newSection . '</head>', $bodyContent);
  53. $newBody = new Stream('php://temp', 'wb+');
  54. $newBody->write($bodyContent);
  55. $newBody->rewind();
  56. $response = $response->withBody($newBody);
  57. return $response;
  58. }
  59. }