src/AtechNet/CoreBundle/Twig/CustomExtension.php line 128

Open in your IDE?
  1. <?php
  2. namespace App\AtechNet\CoreBundle\Twig;
  3. use App\AtechNet\CoreBundle\AtechNetCoreBundle;
  4. use App\AtechNet\CoreBundle\Entity\Customer;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. use Twig\Extension\AbstractExtension;
  10. use Twig\Node\Expression\ArrayExpression;
  11. use Twig\Node\Expression\ConstantExpression;
  12. use Twig\Node\Node;
  13. use Twig\TwigFilter;
  14. use Twig\TwigFunction;
  15. use Twig_SimpleFilter;
  16. class CustomExtension extends AbstractExtension
  17. {
  18.     private $requestStack;
  19.     private $session;
  20.     private $entityManager;
  21.     private $generator;
  22.     /**
  23.      * @param RequestStack $requestStack
  24.      * @param EntityManagerInterface $entityManager
  25.      */
  26.     public function __construct(RequestStack $requestStack, EntityManagerInterface $entityManager, UrlGeneratorInterface $generator)
  27.     {
  28.         $this->requestStack = $requestStack;
  29.         if (!is_null($this->requestStack->getCurrentRequest())) {
  30.             $this->session = $this->requestStack->getCurrentRequest()->getSession();
  31.         }
  32.         $this->generator = $generator;
  33.         $this->entityManager = $entityManager;
  34.     }
  35.     public function getFilters()
  36.     {
  37.         return [
  38.             new TwigFilter('price', [$this, 'formatPrice']),
  39.             new Twig_SimpleFilter('appendAssetCache', [$this, 'appendAssetCache']),
  40.             new Twig_SimpleFilter('ogLocale', [$this, 'getICULocale']),
  41.         ];
  42.     }
  43.     public function getFunctions()
  44.     {
  45.         return [
  46.             new TwigFunction('isLoggedIn', [$this, 'isLoggedIn']),
  47.             new TwigFunction('getLoggedInCustomer', [$this, 'getLoggedInCustomer']),
  48.             new TwigFunction('const', [$this, 'const']),
  49.             new TwigFunction('routePrefix', [$this, 'getRoutePrefix']),
  50.             new TwigFunction('path', [$this, 'getPath'], [
  51.                 'is_safe_callback' => [$this, 'isUrlGenerationSafe'],
  52.             ]),
  53.         ];
  54.     }
  55.     public function formatPrice($number, $currency = '', $decimals = 0, $dec_point = ',', $thousands_sep = ' ')
  56.     {
  57.         $price = number_format($number, $decimals, $dec_point, $thousands_sep);
  58.         $price = $price . ' ' . $currency;
  59.         return $price;
  60.     }
  61.     public function appendAssetCache($resourcePath)
  62.     {
  63.         return $resourcePath . '?v=' . AtechNetCoreBundle::$deploymentId;
  64.     }
  65.     /**
  66.      * @param string $locale
  67.      * @return string
  68.      */
  69.     public function getICULocale(string $locale): string
  70.     {
  71.         switch ($locale) {
  72.             case 'cz':
  73.                 return 'cs_CZ';
  74.             case 'en':
  75.                 return 'en_US';
  76.             case 'hu':
  77.                 return 'hu_HU';
  78.             case 'sk':
  79.                 return 'sk_SK';
  80.         }
  81.         return '';
  82.     }
  83.     /**
  84.      * @return bool
  85.      */
  86.     public function isLoggedIn()
  87.     {
  88.         $loggedInCustomerId = $this->session->get('customerId');
  89.         return !is_null($loggedInCustomerId) && is_numeric($loggedInCustomerId);
  90.     }
  91.     /**
  92.      * @return null|Customer
  93.      */
  94.     public function getLoggedInCustomer(): ?Customer
  95.     {
  96.         $customer = null;
  97.         if ($this->isLoggedIn()) {
  98.             $customer = $this->entityManager->getRepository(Customer::class)->findOneById($this->session->get('customerId'));
  99.         }
  100.         return $customer;
  101.     }
  102.     public function const($name)
  103.     {
  104.         return constant("App\\AtechNet\\CoreBundle\\Entity\\$name");
  105.     }
  106.     /**
  107.      * @return string
  108.      */
  109.     public function getRoutePrefix(): string
  110.     {
  111.         if ($this->session->get('defaultLocale') !== $this->session->get('_locale')) {
  112.             return $this->session->get('_locale');
  113.         }
  114.         return '';
  115.     }
  116.     /**
  117.      * Generates a URL from the given parameters.
  118.      * Overwrite the original function because of locale settings. !see: Symfony\Bridge\Twig\Extension\RoutingExtension
  119.      *
  120.      * @param string $route
  121.      * @param array $parameters
  122.      * @param int $referenceType
  123.      * @return string
  124.      */
  125.     public function getPath(string $name, array $parameters = [], bool $relative = false): string
  126.     {
  127.         // Use default locale if the _locale parameter is missing
  128.         if (!isset($parameters['_locale'])) {
  129.             $parameters['_locale'] = $this->getRoutePrefix();
  130.         }
  131.         // Add local flag if locale is set
  132.         if ($parameters['_locale'] !== '') {
  133.             try {
  134.                 // Return route with locale flag if it is exists
  135.                 return $this->generator->generate($name . '_locale', $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
  136.             } catch (RouteNotFoundException $e) {
  137.                 // Catch error if route with locale flag is not exists and do nothing
  138.             }
  139.             // Remove _locale parameter
  140.             unset($parameters['_locale']);
  141.         }
  142.         // Return route with default locale
  143.         return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
  144.     }
  145.     /**
  146.      * Determines at compile time whether the generated URL will be safe and thus
  147.      * saving the unneeded automatic escaping for performance reasons.
  148.      *
  149.      * The URL generation process percent encodes non-alphanumeric characters. So there is no risk
  150.      * that malicious/invalid characters are part of the URL. The only character within an URL that
  151.      * must be escaped in html is the ampersand ("&") which separates query params. So we cannot mark
  152.      * the URL generation as always safe, but only when we are sure there won't be multiple query
  153.      * params. This is the case when there are none or only one constant parameter given.
  154.      * E.g. we know beforehand this will be safe:
  155.      * - path('route')
  156.      * - path('route', {'param': 'value'})
  157.      * But the following may not:
  158.      * - path('route', var)
  159.      * - path('route', {'param': ['val1', 'val2'] }) // a sub-array
  160.      * - path('route', {'param1': 'value1', 'param2': 'value2'})
  161.      * If param1 and param2 reference placeholder in the route, it would still be safe. But we don't know.
  162.      *
  163.      * @param Node $argsNode The arguments of the path/url function
  164.      *
  165.      * @return array An array with the contexts the URL is safe
  166.      */
  167.     public function isUrlGenerationSafe(Node $argsNode): array
  168.     {
  169.         // support named arguments
  170.         $paramsNode = $argsNode->hasNode('parameters') ? $argsNode->getNode('parameters') : (
  171.             $argsNode->hasNode(1) ? $argsNode->getNode(1) : null
  172.         );
  173.         if (null === $paramsNode || $paramsNode instanceof ArrayExpression && \count($paramsNode) <= 2 &&
  174.             (!$paramsNode->hasNode(1) || $paramsNode->getNode(1) instanceof ConstantExpression)
  175.         ) {
  176.             return ['html'];
  177.         }
  178.         return [];
  179.     }
  180. }