| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- <?php
- namespace Opentalent\OtStats\Middleware;
- use Opentalent\OtCore\Page\OtPageRepository;
- use Opentalent\OtStats\Settings\StatsSettingsRepository;
- use Psr\Http\Message\ResponseInterface;
- use Psr\Http\Message\ServerRequestInterface;
- use Psr\Http\Server\MiddlewareInterface;
- use Psr\Http\Server\RequestHandlerInterface;
- use TYPO3\CMS\Core\Http\Stream;
- use TYPO3\CMS\Core\Utility\GeneralUtility;
- use TYPO3\CMS\Fluid\View\StandaloneView;
- /**
- * Hooks into the frontend request to add the matomo script into
- * the request's header
- *
- * @internal
- */
- class RequestHandler implements MiddlewareInterface
- {
- const TEMPLATES_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Templates';
- const LAYOUTS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Layouts';
- const TEMPLATE_FILE = self::TEMPLATES_ROOT_PATHS . '/Header/Matomo.html';
- /**
- *
- * @param ServerRequestInterface $request
- * @param RequestHandlerInterface $handler
- * @return ResponseInterface
- */
- public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
- {
- // Retrieve the current matomo site's id if set
- $otPageRepository = GeneralUtility::makeInstance(OtPageRepository::class);
- $rootPageUid = $otPageRepository->getCurrentSiteRootPageId();
- $statsSettingsRepository = GeneralUtility::makeInstance(StatsSettingsRepository::class);
- $matomoSiteId = $statsSettingsRepository->getMatomoSiteId($rootPageUid);
- if (!$matomoSiteId > 0) {
- // stats are not enabled, continue
- return $handler->handle($request);
- }
- // render view
- $view = GeneralUtility::makeInstance(StandaloneView::class);
- $view->setTemplateRootPaths([self::TEMPLATES_ROOT_PATHS]);
- $view->setLayoutRootPaths([self::LAYOUTS_ROOT_PATHS]);
- $view->setTemplatePathAndFilename(
- GeneralUtility::getFileAbsFileName(self::TEMPLATE_FILE)
- );
- // Build the response
- $response = $handler->handle($request);
- // insert the rendered view in the body, just before the closing </html> tag
- $newSection = $view->render();
- $bodyContent = (string)$response->getBody();
- $bodyContent = str_replace('</head>', $newSection . '</head>', $bodyContent);
- $newBody = new Stream('php://temp', 'wb+');
- $newBody->write($bodyContent);
- $newBody->rewind();
- $response = $response->withBody($newBody);
- return $response;
- }
- }
|