<?php
namespace App\AtechNet\CoreBundle\Twig;
use App\AtechNet\CoreBundle\AtechNetCoreBundle;
use App\AtechNet\CoreBundle\Entity\Customer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Extension\AbstractExtension;
use Twig\Node\Expression\ArrayExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Node;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig_SimpleFilter;
class CustomExtension extends AbstractExtension
{
private $requestStack;
private $session;
private $entityManager;
private $generator;
/**
* @param RequestStack $requestStack
* @param EntityManagerInterface $entityManager
*/
public function __construct(RequestStack $requestStack, EntityManagerInterface $entityManager, UrlGeneratorInterface $generator)
{
$this->requestStack = $requestStack;
if (!is_null($this->requestStack->getCurrentRequest())) {
$this->session = $this->requestStack->getCurrentRequest()->getSession();
}
$this->generator = $generator;
$this->entityManager = $entityManager;
}
public function getFilters()
{
return [
new TwigFilter('price', [$this, 'formatPrice']),
new Twig_SimpleFilter('appendAssetCache', [$this, 'appendAssetCache']),
new Twig_SimpleFilter('ogLocale', [$this, 'getICULocale']),
];
}
public function getFunctions()
{
return [
new TwigFunction('isLoggedIn', [$this, 'isLoggedIn']),
new TwigFunction('getLoggedInCustomer', [$this, 'getLoggedInCustomer']),
new TwigFunction('const', [$this, 'const']),
new TwigFunction('routePrefix', [$this, 'getRoutePrefix']),
new TwigFunction('path', [$this, 'getPath'], [
'is_safe_callback' => [$this, 'isUrlGenerationSafe'],
]),
];
}
public function formatPrice($number, $currency = '', $decimals = 0, $dec_point = ',', $thousands_sep = ' ')
{
$price = number_format($number, $decimals, $dec_point, $thousands_sep);
$price = $price . ' ' . $currency;
return $price;
}
public function appendAssetCache($resourcePath)
{
return $resourcePath . '?v=' . AtechNetCoreBundle::$deploymentId;
}
/**
* @param string $locale
* @return string
*/
public function getICULocale(string $locale): string
{
switch ($locale) {
case 'cz':
return 'cs_CZ';
case 'en':
return 'en_US';
case 'hu':
return 'hu_HU';
case 'sk':
return 'sk_SK';
}
return '';
}
/**
* @return bool
*/
public function isLoggedIn()
{
$loggedInCustomerId = $this->session->get('customerId');
return !is_null($loggedInCustomerId) && is_numeric($loggedInCustomerId);
}
/**
* @return null|Customer
*/
public function getLoggedInCustomer(): ?Customer
{
$customer = null;
if ($this->isLoggedIn()) {
$customer = $this->entityManager->getRepository(Customer::class)->findOneById($this->session->get('customerId'));
}
return $customer;
}
public function const($name)
{
return constant("App\\AtechNet\\CoreBundle\\Entity\\$name");
}
/**
* @return string
*/
public function getRoutePrefix(): string
{
if ($this->session->get('defaultLocale') !== $this->session->get('_locale')) {
return $this->session->get('_locale');
}
return '';
}
/**
* Generates a URL from the given parameters.
* Overwrite the original function because of locale settings. !see: Symfony\Bridge\Twig\Extension\RoutingExtension
*
* @param string $route
* @param array $parameters
* @param int $referenceType
* @return string
*/
public function getPath(string $name, array $parameters = [], bool $relative = false): string
{
// Use default locale if the _locale parameter is missing
if (!isset($parameters['_locale'])) {
$parameters['_locale'] = $this->getRoutePrefix();
}
// Add local flag if locale is set
if ($parameters['_locale'] !== '') {
try {
// Return route with locale flag if it is exists
return $this->generator->generate($name . '_locale', $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
} catch (RouteNotFoundException $e) {
// Catch error if route with locale flag is not exists and do nothing
}
// Remove _locale parameter
unset($parameters['_locale']);
}
// Return route with default locale
return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
}
/**
* Determines at compile time whether the generated URL will be safe and thus
* saving the unneeded automatic escaping for performance reasons.
*
* The URL generation process percent encodes non-alphanumeric characters. So there is no risk
* that malicious/invalid characters are part of the URL. The only character within an URL that
* must be escaped in html is the ampersand ("&") which separates query params. So we cannot mark
* the URL generation as always safe, but only when we are sure there won't be multiple query
* params. This is the case when there are none or only one constant parameter given.
* E.g. we know beforehand this will be safe:
* - path('route')
* - path('route', {'param': 'value'})
* But the following may not:
* - path('route', var)
* - path('route', {'param': ['val1', 'val2'] }) // a sub-array
* - path('route', {'param1': 'value1', 'param2': 'value2'})
* If param1 and param2 reference placeholder in the route, it would still be safe. But we don't know.
*
* @param Node $argsNode The arguments of the path/url function
*
* @return array An array with the contexts the URL is safe
*/
public function isUrlGenerationSafe(Node $argsNode): array
{
// support named arguments
$paramsNode = $argsNode->hasNode('parameters') ? $argsNode->getNode('parameters') : (
$argsNode->hasNode(1) ? $argsNode->getNode(1) : null
);
if (null === $paramsNode || $paramsNode instanceof ArrayExpression && \count($paramsNode) <= 2 &&
(!$paramsNode->hasNode(1) || $paramsNode->getNode(1) instanceof ConstantExpression)
) {
return ['html'];
}
return [];
}
}