<?php
// src/Twig/AppExtension.php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use App\Service\isAllowedService;
use App\Service\DataProductFinder;
use Symfony\Component\Security\Core\Security;
class AppExtension extends AbstractExtension
{
private $security;
private $isAllowedService;
public function __construct(Security $security, isAllowedService $isAllowedService, DataProductFinder $dataProductFinder)
{
// Avoid calling getUser() in the constructor: auth may not
// be complete yet. Instead, store the entire Security object.
$this->security = $security;
$this->isAllowedService = $isAllowedService;
$this->dataProductFinder = $dataProductFinder;
}
public function getFilters()
{
return [
new TwigFilter('is_allowed', [$this, 'isAllowed']),
new TwigFilter('is_allowed_customer', [$this, 'isAllowedCustomer']),
new TwigFilter('format_currency_custom', [$this, 'formatCurrency']),
new TwigFilter('product_details', [$this, 'productDetails']),
];
}
public function isAllowed($route)
{
$route = substr($route, + 6);
$removedAllParams=false;
while($removedAllParams!=true){
if (preg_match('~[0-9]+~', $route)) {
$idPos=strrpos($route, '/');
$id = substr($route, $idPos+1);
$route = substr($route, 0, $idPos);
}
else{
$removedAllParams=true;
}
}
$user = $this->security->getUser();
$roles= $user->getRoles();
return $this->isAllowedService->isAllowedFunction($route, $roles, null);
}
public function isAllowedCustomer($route)
{
$route = substr($route, + 6);
$removedAllParams=false;
while($removedAllParams!=true){
if (preg_match('~[0-9]+~', $route)) {
$idPos=strrpos($route, '/');
$id = substr($route, $idPos+1);
$route = substr($route, 0, $idPos);
}
else{
$removedAllParams=true;
}
}
$user = $this->security->getUser();
$roles= $user->getRoles();
$customerAccess=null;
if($user->getCustomer())
{
$parameters = $user->getCustomer()->getPartner()->getParameters() ? $user->getCustomer()->getPartner()->getParameters() : [];
if(array_key_exists('customerAccess', $parameters)){
$customerAccess=$parameters['customerAccess'];
}
}
return $this->isAllowedService->isAllowedFunction($route, $roles, $customerAccess);
}
public function formatCurrency(float $amount, string $currency, string $locale = 'en_US', bool $useSymbol = true): string
{
// Crear el formateador de números
$formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
if (!$useSymbol) {
// Reemplazar el símbolo por el código ISO de la moneda
$formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $currency);
}
// Formatear el valor como moneda
return $formatter->formatCurrency($amount, $currency);
}
public function productDetails($pbw, $atribute): string
{
return $this->dataProductFinder->getAtributeDetail($pbw, $atribute);
}
}