ew_base/Classes/Hooks/UsercentricsPostRenderHook.php
2024-05-25 16:24:24 +02:00

110 lines
3.3 KiB
PHP
Executable File

<?php
/*
* This file is developed by evoWeb.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*/
namespace Evoweb\EwBase\Hooks;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Site\SiteFinder;
class UsercentricsPostRenderHook
{
private array $siteArguments = [
'id' => '',
'version' => 'loader',
'useBlocker' => false,
];
protected ?Site $site = null;
public function __construct(protected SiteFinder $siteFinder) {}
public function executePostRenderHook(array $params): void
{
$pageUid = $this->getRequest()->getAttribute('frontend.controller')->page['uid'] ?? 0;
if ($pageUid < 1) {
return;
}
$siteArguments = $this->getCurrentSiteArguments($pageUid);
$id = $siteArguments['id'] ?? '';
if ($id !== '') {
$extensionConfig = $this->getExtensionConfiguration($pageUid);
$preload = [];
$userCentrics = [];
// CMP 1, 2, ...
$version = $siteArguments['version'] ?? '';
if ($config = $extensionConfig[$version] ?? false) {
$preload[] = $config['preload'] ?? '';
$userCentrics[] = $config['template'] ?? '';
}
// Blocker
if (
($siteArguments['useBlocker'] ?? false)
&& $config = $extensionConfig['block'] ?? false
) {
$preload[] = $config['preload'] ?? '';
$userCentrics[] = $config['template'] ?? '';
}
$params['titleTag'] .= str_replace('###ID###', $id, implode(LF, array_merge($preload, $userCentrics)));
}
}
protected function getCurrentSiteArguments(int $pageUid): array
{
$siteArguments = $this->siteArguments;
$site = $this->getSiteByPageUid($pageUid);
try {
foreach ($site->getAttribute('usercentrics') as $usercentrics) {
if (str_contains($usercentrics['applicationContext'] ?? '', (string)Environment::getContext())) {
$siteArguments = $usercentrics;
break;
}
}
} catch (\Exception) {
$siteArguments = [];
}
return is_array($siteArguments) ? $siteArguments : [];
}
protected function getExtensionConfiguration($pageUid): array
{
$siteSettings = $this->getSiteByPageUid($pageUid)->getSettings();
$configuration = $siteSettings->has('ew-base') ? $siteSettings->get('ew-base') : [];
return is_array($configuration['userCentrics'] ?? false) ? $configuration['userCentrics'] : [];
}
protected function getSiteByPageUid(int $pageUid): Site
{
if (!$this->site) {
try {
$this->site = $this->siteFinder->getSiteByPageId($pageUid);
} catch (\Exception) {
}
}
return $this->site;
}
protected function getRequest(): ServerRequestInterface
{
return $GLOBALS['TYPO3_REQUEST'];
}
}