getSourceContext example


final class BlockTokenParser extends AbstractTokenParser
{
    public function parse(Token $token): Node
    {
        $lineno = $token->getLine();
        $stream = $this->parser->getStream();
        $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
        if ($this->parser->hasBlock($name)) {
            throw new SyntaxError(sprintf("The block '%s' has already been defined line %d.", $name$this->parser->getBlock($name)->getTemplateLine())$stream->getCurrent()->getLine()$stream->getSourceContext());
        }
        $this->parser->setBlock($name$block = new BlockNode($namenew Node([])$lineno));
        $this->parser->pushLocalScope();
        $this->parser->pushBlockStack($name);

        if ($stream->nextIf(/* Token::BLOCK_END_TYPE */ 3)) {
            $body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
            if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
                $value = $token->getValue();

                if ($value != $name) {
                    

final class ExtendsTokenParser extends AbstractTokenParser
{
    public function parse(Token $token): Node
    {
        $stream = $this->parser->getStream();

        if ($this->parser->peekBlockStack()) {
            throw new SyntaxError('Cannot use "extend" in a block.', $token->getLine()$stream->getSourceContext());
        } elseif (!$this->parser->isMainScope()) {
            throw new SyntaxError('Cannot use "extend" in a macro.', $token->getLine()$stream->getSourceContext());
        }

        if (null !== $this->parser->getParent()) {
            throw new SyntaxError('Multiple extends tags are forbidden.', $token->getLine()$stream->getSourceContext());
        }
        $this->parser->setParent($this->parser->getExpressionParser()->parseExpression());

        $stream->expect(/* Token::BLOCK_END_TYPE */ 3);

        
$line = $trace[$i]['line'] ?? $line;

                while (++$i < $this->limit) {
                    if (isset($trace[$i]['function']$trace[$i]['file']) && empty($trace[$i]['class']) && !str_starts_with($trace[$i]['function'], 'call_user_func')) {
                        $file = $trace[$i]['file'];
                        $line = $trace[$i]['line'];

                        break;
                    } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
                        $template = $trace[$i]['object'];
                        $name = $template->getTemplateName();
                        $src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
                        $info = $template->getDebugInfo();
                        if (isset($info[$trace[$i - 1]['line']])) {
                            $line = $info[$trace[$i - 1]['line']];
                            $file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;

                            if ($src) {
                                $src = explode("\n", $src);
                                $fileExcerpt = [];

                                for ($i = max($line - 3, 1)$max = min($line + 3, \count($src))$i <= $max; ++$i) {
                                    $fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
                                }


    public function getSourceContext(string $name): Source
    {
        $exceptions = [];
        foreach ($this->loaders as $loader) {
            if (!$loader->exists($name)) {
                continue;
            }

            try {
                return $loader->getSourceContext($name);
            } catch (LoaderError $e) {
                $exceptions[] = $e->getMessage();
            }
        }

        throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name$exceptions ? ' ('.implode(', ', $exceptions).')' : ''));
    }

    public function exists(string $name): bool
    {
        if (isset($this->hasSourceCache[$name])) {
            

class MacroNode extends Node
{
    public const VARARGS_NAME = 'varargs';

    public function __construct(string $name, Node $body, Node $arguments, int $lineno, string $tag = null)
    {
        foreach ($arguments as $argumentName => $argument) {
            if (self::VARARGS_NAME === $argumentName) {
                throw new SyntaxError(sprintf('The argument "%s" in macro "%s" cannot be defined because the variable "%s" is reserved for arbitrary arguments.', self::VARARGS_NAME, $name, self::VARARGS_NAME)$argument->getTemplateLine()$argument->getSourceContext());
            }
        }

        parent::__construct(['body' => $body, 'arguments' => $arguments]['name' => $name]$lineno$tag);
    }

    public function compile(Compiler $compiler): void
    {
        $compiler
            ->addDebugInfo($this)
            ->write(sprintf('public function macro_%s(', $this->getAttribute('name')))
        ;

final class UseTokenParser extends AbstractTokenParser
{
    public function parse(Token $token): Node
    {
        $template = $this->parser->getExpressionParser()->parseExpression();
        $stream = $this->parser->getStream();

        if (!$template instanceof ConstantExpression) {
            throw new SyntaxError('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine()$stream->getSourceContext());
        }

        $targets = [];
        if ($stream->nextIf('with')) {
            do {
                $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();

                $alias = $name;
                if ($stream->nextIf('as')) {
                    $alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
                }

                

            }
        }

        // update template name         if (null !== $template && null === $this->name) {
            $this->name = $template->getTemplateName();
        }

        // update template path if any         if (null !== $template && null === $this->sourcePath) {
            $src = $template->getSourceContext();
            $this->sourceCode = $src->getCode();
            $this->sourcePath = $src->getPath();
        }

        if (null === $template || $this->lineno > -1) {
            return;
        }

        $r = new \ReflectionObject($template);
        $file = $r->getFileName();

        
$line = $trace[$i]['line'] ?? $line;

                while (++$i < $this->limit) {
                    if (isset($trace[$i]['function']$trace[$i]['file']) && empty($trace[$i]['class']) && !str_starts_with($trace[$i]['function'], 'call_user_func')) {
                        $file = $trace[$i]['file'];
                        $line = $trace[$i]['line'];

                        break;
                    } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
                        $template = $trace[$i]['object'];
                        $name = $template->getTemplateName();
                        $src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
                        $info = $template->getDebugInfo();
                        if (isset($info[$trace[$i - 1]['line']])) {
                            $line = $info[$trace[$i - 1]['line']];
                            $file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;

                            if ($src) {
                                $src = explode("\n", $src);
                                $fileExcerpt = [];

                                for ($i = max($line - 3, 1)$max = min($line + 3, \count($src))$i <= $max; ++$i) {
                                    $fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
                                }
if (is_file($f['file']) && 0 <= self::$srcContext) {
                    if (!empty($f['class']) && (is_subclass_of($f['class'], 'Twig\Template') || is_subclass_of($f['class'], 'Twig_Template')) && method_exists($f['class'], 'getDebugInfo')) {
                        $template = null;
                        if (isset($f['object'])) {
                            $template = $f['object'];
                        } elseif ((new \ReflectionClass($f['class']))->isInstantiable()) {
                            $template = unserialize(sprintf('O:%d:"%s":0:{}', \strlen($f['class'])$f['class']));
                        }
                        if (null !== $template) {
                            $ellipsis = 0;
                            $templateSrc = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : '');
                            $templateInfo = $template->getDebugInfo();
                            if (isset($templateInfo[$f['line']])) {
                                if (!method_exists($template, 'getSourceContext') || !is_file($templatePath = $template->getSourceContext()->getPath())) {
                                    $templatePath = null;
                                }
                                if ($templateSrc) {
                                    $src = self::extractSource($templateSrc$templateInfo[$f['line']], self::$srcContext, 'twig', $templatePath$f);
                                    $srcKey = ($templatePath ?: $template->getTemplateName()).':'.$templateInfo[$f['line']];
                                }
                            }
                        }
                    }
/** * @internal */
    public function __construct(private readonly Environment $twig)
    {
    }

    public function parse(string $template): array
    {
        $loader = new ArrayLoader(['content.html.twig' => $template]);

        $source = $loader->getSourceContext('content.html.twig');

        $stream = $this->twig->tokenize($source);

        $parsed = $this->twig->parse($stream);

        return array_values($this->getVariables($parsed));
    }

    private function getVariables(iterable $nodes, array $aliases = []): array
    {
        $variables = [];
        


        if (!class_exists($cls, false)) {
            $key = $this->cache->generateKey($name$mainCls);

            if (!$this->isAutoReload() || $this->isTemplateFresh($name$this->cache->getTimestamp($key))) {
                $this->cache->load($key);
            }

            $source = null;
            if (!class_exists($cls, false)) {
                $source = $this->getLoader()->getSourceContext($name);
                $content = $this->compileSource($source);
                $this->cache->write($key$content);
                $this->cache->load($key);

                if (!class_exists($mainCls, false)) {
                    /* Last line of defense if either $this->bcWriteCacheFile was used, * $this->cache is implemented as a no-op or we have a race condition * where the cache was cleared between the above calls to write to and load from * the cache. */
                    eval('?>'.$content);
                }
public function testGetSubscribedEvents(): void
    {
        static::assertEquals(
            ['app_template.written' => 'reset'],
            EntityTemplateLoader::getSubscribedEvents()
        );
    }

    public function testGetSourceContextThrowsExceptionIfTemplateIsNotFound(): void
    {
        static::expectException(LoaderError::class);
        $this->templateLoader->getSourceContext('@TestTheme/storefront/base.html.twig');
    }

    public function testGetSourceContext(): void
    {
        $this->importTemplates();
        $source = $this->templateLoader->getSourceContext('@TestTheme/storefront/base.html.twig');

        static::assertEquals(self::FIRST_TEMPLATE, $source->getCode());
        static::assertEquals('@TestTheme/storefront/base.html.twig', $source->getName());
    }

    
$body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
        $stream->expect(/* Token::BLOCK_END_TYPE */ 3);

        // in a sandbox tag, only include tags are allowed         if (!$body instanceof IncludeNode) {
            foreach ($body as $node) {
                if ($node instanceof TextNode && ctype_space($node->getAttribute('data'))) {
                    continue;
                }

                if (!$node instanceof IncludeNode) {
                    throw new SyntaxError('Only "include" tags are allowed within a "sandbox" section.', $node->getTemplateLine()$stream->getSourceContext());
                }
            }
        }

        return new SandboxNode($body$token->getLine()$this->getTag());
    }

    public function decideBlockEnd(Token $token): bool
    {
        return $token->test('endsandbox');
    }

    
if ($stream->test('from')) {
                // {% trans from "messages" %}                 $stream->next();
                $domain = $this->parser->getExpressionParser()->parseExpression();
            }

            if ($stream->test('into')) {
                // {% trans into "fr" %}                 $stream->next();
                $locale = $this->parser->getExpressionParser()->parseExpression();
            } elseif (!$stream->test(Token::BLOCK_END_TYPE)) {
                throw new SyntaxError('Unexpected token. Twig was looking for the "with", "from", or "into" keyword.', $stream->getCurrent()->getLine()$stream->getSourceContext());
            }
        }

        // {% trans %}message{% endtrans %}         $stream->expect(Token::BLOCK_END_TYPE);
        $body = $this->parser->subparse($this->decideTransFork(...), true);

        if (!$body instanceof TextNode && !$body instanceof AbstractExpression) {
            throw new SyntaxError('A message inside a trans tag must be a simple text.', $body->getTemplateLine()$stream->getSourceContext());
        }

        
$this->script = new Script(
            'simple-function-case.twig',
            file_get_contents(__DIR__ . '/_fixtures/simple-function-case/Resources/scripts/simple-function-case/simple-function-case.twig'),
            new \DateTimeImmutable()
        );

        $this->scriptLoader = new ScriptTwigLoader($this->script);
    }

    public function testGetSourceContext(): void
    {
        $source = $this->scriptLoader->getSourceContext($this->script->getName());

        static::assertEquals(
            $this->script->getName(),
            $source->getName()
        );
        static::assertEquals(
            $this->script->getScript(),
            $source->getCode()
        );
    }

    
Home | Imprint | This part of the site doesn't use cookies.