<?php
namespace App\Twig\Extension;
use Pimcore\Model\DataObject\Policy;
use Pimcore\Model\DataObject\Policyholder;
use Twig\TwigFunction;
use Twig\Extension\AbstractExtension;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class HeroReplacementExtension extends AbstractExtension
{
private TokenStorageInterface $tokenStorage;
private RequestStack $requestStack;
public const CODE_403 = 403;
public function __construct(TokenStorageInterface $tokenStorage, RequestStack $requestStack)
{
$this->tokenStorage = $tokenStorage;
$this->requestStack = $requestStack;
}
public function getFunctions(): array
{
return [
new TwigFunction('replaceHeroVars', [$this, 'replaceHeroVars']),
];
}
public function replaceHeroVars(string $heroText): string
{
$session = $this->requestStack->getSession();
$sessionData = json_decode($session->get('mvk_angular'));
if (!$sessionData) {
return $heroText;
}
$policyholder = $sessionData->policyHolderId ? Policyholder::getById($sessionData->policyHolderId) : null;
$policy = $sessionData->policyId ? Policy::getById($sessionData->policyId) : null;
$regex = "/##(firstName|lastName|partnerNr|bmsMembershipNo|policyNumber|policyType)##/";
preg_match_all($regex, $heroText, $matches);
foreach ($matches[1] as $match) {
switch ($match) {
case 'firstName':
if ($policyholder) {
$firstName = $policyholder->getFirstname();
$heroText = str_replace('##firstName##', $firstName, $heroText);
}
break;
case 'lastName':
if ($policyholder) {
$lastName = $policyholder->getName();
$heroText = str_replace('##lastName##', $lastName, $heroText);
}
break;
case 'partnerNr':
if ($policyholder) {
$partnerNr = $policyholder->getPartnerNr();
$heroText = str_replace('##partnerNr##', $partnerNr, $heroText);
}
break;
case 'bmsMembershipNo':
if ($policyholder) {
$bmsMembershipNo = $policyholder->getBmsMembershipNo();
$heroText = str_replace('##bmsMembershipNo##', $bmsMembershipNo, $heroText);
}
break;
case 'policyNumber':
if ($policy) {
$policyNumber = $policy->getPoliceNr();
$heroText = str_replace('##policyNumber##', $policyNumber, $heroText);
}
break;
case 'policyType':
if ($policy) {
$policyType = $policy->getPolicyType();
$heroText = str_replace('##policyType##', $policyType, $heroText);
}
break;
}
}
return $heroText;
}
}