RequestHandler.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 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. /**
  25. *
  26. * @param ServerRequestInterface $request
  27. * @param RequestHandlerInterface $handler
  28. * @return ResponseInterface
  29. */
  30. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
  31. {
  32. // Retrieve the current matomo site's id if set
  33. $otPageRepository = GeneralUtility::makeInstance(OtPageRepository::class);
  34. $rootPageUid = $otPageRepository->getCurrentSiteRootPageId();
  35. $statsSettingsRepository = GeneralUtility::makeInstance(StatsSettingsRepository::class);
  36. $matomoSiteId = $statsSettingsRepository->getMatomoSiteId($rootPageUid);
  37. if (!$matomoSiteId > 0) {
  38. // stats are not enabled, continue
  39. return $handler->handle($request);
  40. }
  41. // render view
  42. $view = GeneralUtility::makeInstance(StandaloneView::class);
  43. $view->setTemplateRootPaths([self::TEMPLATES_ROOT_PATHS]);
  44. $view->setPartialRootPaths([self::PARTIALS_ROOT_PATHS]);
  45. $view->setLayoutRootPaths([self::LAYOUTS_ROOT_PATHS]);
  46. $view->setTemplatePathAndFilename(
  47. GeneralUtility::getFileAbsFileName(self::TEMPLATE_FILE)
  48. );
  49. // Build the response
  50. $response = $handler->handle($request);
  51. // insert the rendered view in the body, just before the closing </html> tag
  52. $newSection = $view->render();
  53. $bodyContent = (string)$response->getBody();
  54. $bodyContent = str_replace('</head>', $newSection . '</head>', $bodyContent);
  55. $newBody = new Stream('php://temp', 'wb+');
  56. $newBody->write($bodyContent);
  57. $newBody->rewind();
  58. $response = $response->withBody($newBody);
  59. return $response;
  60. }
  61. }