vendor/shopware/core/Framework/Adapter/Twig/TwigVariableParser.php line 29

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Framework\Adapter\Twig;
  3. use Twig\Environment;
  4. use Twig\Loader\ArrayLoader;
  5. use Twig\Node\Expression\AssignNameExpression;
  6. use Twig\Node\Expression\ConstantExpression;
  7. use Twig\Node\Expression\GetAttrExpression;
  8. use Twig\Node\Expression\NameExpression;
  9. use Twig\Node\ForNode;
  10. use Twig\Node\Node;
  11. /**
  12.  * @package core
  13.  */
  14. class TwigVariableParser
  15. {
  16.     private Environment $twig;
  17.     /**
  18.      * @internal
  19.      */
  20.     public function __construct(Environment $twig)
  21.     {
  22.         $this->twig $twig;
  23.     }
  24.     public function parse(string $template): array
  25.     {
  26.         $loader = new ArrayLoader(['content.html.twig' => $template]);
  27.         $source $loader->getSourceContext('content.html.twig');
  28.         $stream $this->twig->tokenize($source);
  29.         $parsed $this->twig->parse($stream);
  30.         return array_values($this->getVariables($parsed));
  31.     }
  32.     private function getVariables(iterable $nodes, array $aliases = []): array
  33.     {
  34.         $variables = [];
  35.         foreach ($nodes as $node) {
  36.             if ($node instanceof AssignNameExpression) {
  37.                 continue;
  38.             }
  39.             if ($node instanceof NameExpression) {
  40.                 $name $node->getAttribute('name');
  41.                 if (isset($aliases[$name])) {
  42.                     $name $aliases[$name];
  43.                 }
  44.                 $variables[$name] = $name;
  45.                 continue;
  46.             }
  47.             if ($node instanceof ConstantExpression && $nodes instanceof GetAttrExpression) {
  48.                 $value $node->getAttribute('value');
  49.                 if (!empty($value) && \is_string($value)) {
  50.                     $variables[$value] = $value;
  51.                 }
  52.                 continue;
  53.             }
  54.             if ($node instanceof GetAttrExpression) {
  55.                 $path implode('.'$this->getVariables($node$aliases));
  56.                 if (!empty($path)) {
  57.                     $variables[$path] = $path;
  58.                 }
  59.                 continue;
  60.             }
  61.             if ($node instanceof ForNode) {
  62.                 $target implode('.'$this->getVariables($node->getNode('seq'), $aliases));
  63.                 $source $node->getNode('value_target')->getAttribute('name');
  64.                 $aliases[$source] = $target;
  65.             }
  66.             if ($node instanceof Node) {
  67.                 $variables += $this->getVariables($node$aliases);
  68.             }
  69.         }
  70.         return $variables;
  71.     }
  72. }