RequestHandler.php 2.7 KB

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