parse() public method

public parse ( Twig_TokenStream $tokens )
$tokens Twig_TokenStream
 public function testEmptyConstant()
 {
     $stream = $this->environment->parse($this->environment->tokenize('{{ constant("ExtensionTest::SOME_EMPTY_VALUE") }}', 'index'));
     $node = $stream->getNode('body')->getNode(0);
     $this->assertEquals(Twig_Node_Print::class, get_class($node));
     $this->assertEquals(ExtensionTest::SOME_EMPTY_VALUE, $node->getNode('expr')->getAttribute('value'));
 }
 /**
  * @param EmailTemplate                  $value
  * @param Constraint|EmailTemplateSyntax $constraint
  */
 public function validate($value, Constraint $constraint)
 {
     // prepare templates to be validated
     $itemsToValidate = [['field' => 'subject', 'locale' => null, 'template' => $value->getSubject()], ['field' => 'content', 'locale' => null, 'template' => $value->getContent()]];
     $translations = $value->getTranslations();
     foreach ($translations as $trans) {
         if (in_array($trans->getField(), ['subject', 'content'])) {
             $itemsToValidate[] = ['field' => $trans->getField(), 'locale' => $trans->getLocale(), 'template' => $trans->getContent()];
         }
     }
     /** @var \Twig_Extension_Sandbox $sandbox */
     $sandbox = $this->twig->getExtension('sandbox');
     $sandbox->enableSandbox();
     // validate templates' syntax
     $errors = [];
     foreach ($itemsToValidate as &$item) {
         try {
             $this->twig->parse($this->twig->tokenize($item['template']));
         } catch (\Twig_Error_Syntax $e) {
             $errors[] = ['field' => $item['field'], 'locale' => $item['locale'], 'error' => $e->getMessage()];
         }
     }
     $sandbox->disableSandbox();
     // add violations for found errors
     if (!empty($errors)) {
         foreach ($errors as $error) {
             $this->context->addViolation($constraint->message, ['{{ field }}' => $this->getFieldLabel(ClassUtils::getClass($value), $error['field']), '{{ locale }}' => $this->getLocaleName($error['locale']), '{{ error }}' => $error['error']]);
         }
     }
 }
Example #3
0
 /**
  * {@inheritDoc}
  */
 public function getPlaces($layoutSrc)
 {
     $tokenStream = $this->twig->tokenize($this->twig->getLoader()->getSource($layoutSrc));
     $collector = new PlaceHolderNodeCollector();
     $traverser = new \Twig_NodeTraverser($this->twig, array($collector));
     $traverser->traverse($this->twig->parse($tokenStream));
     return $collector->getCollectedNames();
 }
Example #4
0
 function visitFile(\SplFileInfo $file, MessageCatalogue $catalogue)
 {
     if ($file->getExtension() == 'twital' && ($adapter = $this->twitalLoader->getSourceAdapter((string) $file))) {
         $source = $this->twitalLoader->getTwital()->compile($adapter, file_get_contents((string) $file));
         $ast = $this->twig->parse($this->twig->tokenize($source, (string) $file));
         $this->visitTwigFile($file, $catalogue, $ast);
     }
 }
Example #5
0
 protected function extractTemplate($template, MessageCatalogue $catalogue)
 {
     $visitor = $this->twig->getExtension('Symfony\\Bridge\\Twig\\Extension\\TranslationExtension')->getTranslationNodeVisitor();
     $visitor->enable();
     $this->twig->parse($this->twig->tokenize(new \Twig_Source($template, '')));
     foreach ($visitor->getMessages() as $message) {
         $catalogue->set(trim($message[0]), $this->prefix . trim($message[0]), $message[1] ?: $this->defaultDomain);
     }
     $visitor->disable();
 }
Example #6
0
 protected function extractTemplate($template, MessageCatalogue $catalogue)
 {
     $visitor = $this->twig->getExtension('translator')->getTranslationNodeVisitor();
     $visitor->enable();
     $this->twig->parse($this->twig->tokenize($template));
     foreach ($visitor->getMessages() as $message) {
         $catalogue->set(trim($message[0]), $this->prefix . trim($message[0]), $message[1] ? $message[1] : $this->defaultDomain);
     }
     $visitor->disable();
 }
Example #7
0
 /**
  * {@inheritDoc}
  */
 public function extract($directory, MessageCatalogue $catalogue)
 {
     // load any existing translation files
     $finder = new Finder();
     $files = $finder->files()->name('*.twig')->in($directory);
     foreach ($files as $file) {
         $tree = $this->twig->parse($this->twig->tokenize(file_get_contents($file->getPathname())));
         $this->crawlNode($tree, $catalogue);
     }
 }
 /**
  * @dataProvider getEscapingTemplates
  */
 public function testEscaping($template, $mustBeEscaped)
 {
     $twig = new \Twig_Environment(null, array('debug' => true, 'cache' => false, 'autoescape' => true, 'optimizations' => 0));
     $twig->addExtension(new RoutingExtension($this->getMock('Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface')));
     $nodes = $twig->parse($twig->tokenize($template));
     $this->assertSame($mustBeEscaped, $nodes->getNode('body')->getNode(0)->getNode('expr') instanceof \Twig_Node_Expression_Filter);
 }
Example #9
0
 /**
  * @dataProvider getTests
  */
 public function testIntegration($file, $test, $message, $templates)
 {
     $loader = new Twig_Loader_Array($templates);
     $twig = new Twig_Environment($loader, array('trim_blocks' => true, 'cache' => false));
     $twig->addExtension(new Twig_Extension_Escaper());
     $twig->addExtension(new TestExtension());
     try {
         $template = $twig->loadTemplate('index.twig');
     } catch (Twig_SyntaxError $e) {
         $e->setFilename($file);
         throw $e;
     } catch (Exception $e) {
         throw new Twig_Error($e->getMessage() . ' (in ' . $file . ')');
     }
     preg_match_all('/--DATA--(.*?)--EXPECT--(.*?)(?=\\-\\-DATA\\-\\-|$)/s', $test, $matches, PREG_SET_ORDER);
     foreach ($matches as $match) {
         $output = trim($template->render(eval($match[1] . ';')), "\n ");
         $expected = trim($match[2], "\n ");
         if ($expected != $output) {
             echo 'Compiled template that failed:';
             foreach (array_keys($templates) as $name) {
                 echo "Template: {$name}\n";
                 $source = $loader->getSource($name);
                 echo $twig->compile($twig->parse($twig->tokenize($source, $name)));
             }
         }
         $this->assertEquals($expected, $output, $message . ' (in ' . $file . ')');
     }
 }
 /**
  * Tests the escaping
  *
  * @dataProvider providerTestEscaping
  */
 public function testEscaping($template, $expected)
 {
     $twig = new \Twig_Environment(NULL, array('debug' => TRUE, 'cache' => FALSE, 'autoescape' => TRUE, 'optimizations' => 0));
     $twig->addExtension((new TwigExtension())->setGenerators($this->getMock('Drupal\\Core\\Routing\\UrlGeneratorInterface')));
     $nodes = $twig->parse($twig->tokenize($template));
     $this->assertSame($expected, $nodes->getNode('body')->getNode(0)->getNode('expr') instanceof \Twig_Node_Expression_Filter);
 }
 /**
  * @dataProvider fixtureProvider
  */
 public function testCompile($source, $expected)
 {
     $twig = new \Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]);
     $twig->addExtension(new ElixirExtension('public', 'build'));
     $nodes = $twig->parse($twig->tokenize($source));
     $this->assertEquals($expected, $nodes->getNode('body')->getNode(0));
 }
 protected function doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs)
 {
     if ($condition) {
         eval('$ret = ' . $condition . ';');
         if (!$ret) {
             $this->markTestSkipped($condition);
         }
     }
     $loader = new Twig_Loader_Array($templates);
     foreach ($outputs as $match) {
         $config = array_merge(array('cache' => false, 'strict_variables' => true), $match[2] ? eval($match[2] . ';') : array());
         $twig = new Twig_Environment($loader, $config);
         $twig->addGlobal('global', 'global');
         foreach ($this->getExtensions() as $extension) {
             $twig->addExtension($extension);
         }
         try {
             $template = $twig->loadTemplate('index.twig');
         } catch (Exception $e) {
             if (false !== $exception) {
                 $this->assertEquals(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage())));
                 return;
             }
             if ($e instanceof Twig_Error_Syntax) {
                 $e->setTemplateFile($file);
                 throw $e;
             }
             throw new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e);
         }
         try {
             $output = trim($template->render(eval($match[1] . ';')), "\n ");
         } catch (Exception $e) {
             if (false !== $exception) {
                 $this->assertEquals(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage())));
                 return;
             }
             if ($e instanceof Twig_Error_Syntax) {
                 $e->setTemplateFile($file);
             } else {
                 $e = new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e);
             }
             $output = trim(sprintf('%s: %s', get_class($e), $e->getMessage()));
         }
         if (false !== $exception) {
             list($class, ) = explode(':', $exception);
             $this->assertThat(null, new PHPUnit_Framework_Constraint_Exception($class));
         }
         $expected = trim($match[3], "\n ");
         if ($expected != $output) {
             echo 'Compiled template that failed:';
             foreach (array_keys($templates) as $name) {
                 echo "Template: {$name}\n";
                 $source = $loader->getSource($name);
                 echo $twig->compile($twig->parse($twig->tokenize($source, $name)));
             }
         }
         $this->assertEquals($expected, $output, $message . ' (in ' . $file . ')');
     }
 }
Example #13
0
 /**
  * @dataProvider getTestsForForOptimizer
  */
 public function testForOptimizer($template, $expected)
 {
     $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false));
     $stream = $env->parse($env->tokenize($template, 'index'));
     foreach ($expected as $target => $withLoop) {
         $this->assertTrue($this->checkForConfiguration($stream, $target, $withLoop), sprintf('variable %s is %soptimized', $target, $withLoop ? 'not ' : ''));
     }
 }
 protected final function parse($file, $debug = false)
 {
     $content = file_get_contents(__DIR__ . '/Fixture/' . $file);
     $env = new \Twig_Environment();
     $env->addExtension(new SymfonyTranslationExtension($translator = new IdentityTranslator(new MessageSelector())));
     $env->addExtension(new TranslationExtension($translator, $debug));
     $env->setLoader(new \Twig_Loader_String());
     return $env->parse($env->tokenize($content));
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function isValid($template)
 {
     try {
         $this->twig->parse($this->twig->tokenize($template));
         return true;
     } catch (\Twig_Error_Syntax $e) {
         return false;
     }
 }
Example #16
0
 /**
  * @dataProvider getNodeVisitorAlterNothingIfNotNeededTests
  */
 public function testNodeVisitorAlterNothingIfNotNeeded($template)
 {
     $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false));
     $stream = $env->parse($env->tokenize($template));
     $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false));
     $env->addNodeVisitor(new Paginator());
     $streamWithNodeVisitorRegistred = $env->parse($env->tokenize($template));
     $this->assertSame((string) $stream, (string) $streamWithNodeVisitorRegistred);
 }
Example #17
0
 protected function validateTemplate(\Twig_Environment $twig, OutputInterface $output, $template, $file = null)
 {
     try {
         $twig->parse($twig->tokenize($template, $file ? (string) $file : null));
         $output->writeln('<info>OK</info>' . ($file ? sprintf(' in %s', $file) : ''));
     } catch (\Twig_Error $e) {
         $this->renderException($output, $template, $e, $file);
         return 1;
     }
     return 0;
 }
Example #18
0
 protected function validateTemplate(\Twig_Environment $twig, OutputInterface $output, $template, $file = null)
 {
     try {
         $twig->parse($twig->tokenize($template, $file ? (string) $file : null));
         $output->ok($template, $file);
     } catch (\Twig_Error $e) {
         $output->error($template, $e, $file);
         return 1;
     }
     return 0;
 }
 /**
  * @dataProvider getTransTests
  */
 public function testTrans($template, $expected, array $variables = array())
 {
     if ($expected != $this->getTemplate($template)->render($variables)) {
         print $template . "\n";
         $loader = new \Twig_Loader_Array(array('index' => $template));
         $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false));
         $twig->addExtension(new TranslationExtension(new Translator('en', new MessageSelector())));
         echo $twig->compile($twig->parse($twig->tokenize($twig->getLoader()->getSource('index'), 'index'))) . "\n\n";
         $this->assertEquals($expected, $this->getTemplate($template)->render($variables));
     }
     $this->assertEquals($expected, $this->getTemplate($template)->render($variables));
 }
Example #20
0
    public function testGetVarName()
    {
        $twig = new Twig_Environment($this->getMock('Twig_LoaderInterface'), array('autoescape' => false, 'optimizations' => 0));
        $twig->parse($twig->tokenize(<<<EOF
{% from _self import foo %}

{% macro foo() %}
    {{ foo }}
{% endmacro %}
EOF
));
    }
Example #21
0
    public function testGetVarName()
    {
        $twig = new Twig_Environment(null, ['autoescape' => false, 'optimizations' => 0]);
        $twig->parse($twig->tokenize(<<<EOF
{% from _self import foo %}

{% macro foo() %}
    {{ foo }}
{% endmacro %}
EOF
));
    }
 /**
  * Analyze resources and collect nodes of OroAsseticNode
  *
  * @return OroAsseticNode[]
  */
 protected function loadAssets()
 {
     $result = array();
     foreach ($this->am->getResources() as $resources) {
         if (!$resources instanceof IteratorResourceInterface) {
             $resources = array($resources);
         }
         /**@var $resource FileResource */
         foreach ($resources as $resource) {
             $tokens = $this->twig->tokenize($resource->getContent(), (string) $resource);
             $nodes = $this->twig->parse($tokens);
             $result += $this->loadNode($nodes);
         }
     }
     return $result;
 }
 /**
  * Extract messages from a single template
  *
  * @param                                                 $templatePath
  * @param \Symfony\Component\Translation\MessageCatalogue $catalogue
  * @return string
  */
 public function extractTemplate($templatePath, MessageCatalogue $catalogue)
 {
     $content = file_get_contents($templatePath);
     $translator = $this->twig->getExtension('translator');
     /**
      * @var TranslationNodeVisitor $visitor
      */
     $visitor = $translator->getTranslationNodeVisitor();
     $visitor->enable();
     $tokens = $this->twig->tokenize($content);
     $this->twig->parse($tokens);
     foreach ($visitor->getMessages() as $message) {
         $catalogue->set(trim($message[0]), $this->prefix . trim($message[0]), $message[1] ? $message[1] : $this->defaultDomain);
     }
     $visitor->disable();
     return $content;
 }
 /**
  * @dataProvider getTests
  */
 public function testIntegration($file, $message, $templates, $exception, $outputs)
 {
     $loader = new Twig_Loader_Array($templates);
     foreach ($outputs as $match) {
         $config = array_merge(array('cache' => false, 'strict_variables' => true), $match[2] ? eval($match[2] . ';') : array());
         $twig = new Twig_Environment($loader, $config);
         $twig->addExtension(new Twig_Extension_Escaper());
         $twig->addExtension(new TestExtension());
         try {
             $template = $twig->loadTemplate('index.twig');
         } catch (Exception $e) {
             if (false !== $exception) {
                 $this->assertEquals(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage())));
                 return;
             }
             if ($e instanceof Twig_Error_Syntax) {
                 $e->setTemplateFile($file);
                 throw $e;
             }
             throw new Twig_Error($e->getMessage() . ' (in ' . $file . ')');
         }
         try {
             $output = trim($template->render(eval($match[1] . ';')), "\n ");
         } catch (Exception $e) {
             $output = trim(sprintf('%s: %s', get_class($e), $e->getMessage()));
         }
         $expected = trim($match[3], "\n ");
         if ($expected != $output) {
             echo 'Compiled template that failed:';
             foreach (array_keys($templates) as $name) {
                 echo "Template: {$name}\n";
                 $source = $loader->getSource($name);
                 echo $twig->compile($twig->parse($twig->tokenize($source, $name)));
             }
         }
         $this->assertEquals($expected, $output, $message . ' (in ' . $file . ')');
     }
 }
Example #25
0
 public function testIntegration()
 {
     foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(self::$fixturesDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
         if (!preg_match('/\\.test$/', $file)) {
             continue;
         }
         $test = file_get_contents($file->getRealpath());
         if (!preg_match('/--TEST--\\s*(.*?)\\s*((?:--TEMPLATE(?:\\(.*?\\))?--(?:.*?))+)--DATA--.*?--EXPECT--.*/s', $test, $match)) {
             throw new InvalidArgumentException(sprintf('Test "%s" is not valid.', str_replace(self::$fixturesDir . '/', '', $file)));
         }
         $message = $match[1];
         $templates = array();
         preg_match_all('/--TEMPLATE(?:\\((.*?)\\))?--(.*?)(?=\\-\\-TEMPLATE|$)/s', $match[2], $matches, PREG_SET_ORDER);
         foreach ($matches as $match) {
             $templates[$match[1] ? $match[1] : 'index.twig'] = $match[2];
         }
         $loader = new Twig_Loader_Array($templates);
         $twig = new Twig_Environment($loader, array('trim_blocks' => true, 'cache' => false));
         $twig->addExtension(new Twig_Extension_Escaper());
         $twig->addExtension(new TestExtension());
         $template = $twig->loadTemplate('index.twig');
         preg_match_all('/--DATA--(.*?)--EXPECT--(.*?)(?=\\-\\-DATA\\-\\-|$)/s', $test, $matches, PREG_SET_ORDER);
         foreach ($matches as $match) {
             $output = trim($template->render(eval($match[1] . ';')), "\n ");
             $expected = trim($match[2], "\n ");
             $this->assertEquals($expected, $output, $message . ' (in ' . str_replace(self::$fixturesDir, '', $file) . ')');
             if ($output != $expected) {
                 echo 'Compiled template that failed:';
                 foreach (array_keys($templates) as $name) {
                     $source = $loader->getSource($name);
                     echo $twig->compile($twig->parse($twig->tokenize($source, $name)));
                 }
             }
         }
     }
 }
Example #26
0
    public function getTests()
    {
        $tests = array();
        $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false));
        $moduleNode = $env->parse($env->tokenize('{% do range(0, 100)|sort|reverse %}'));
        $node = $moduleNode->getNode('body')->getNode(0)->getNode('expr');
        $paginationNode = new Pagination();
        $paginationNode->addNodeToPaginate($node, 20);
        $tests[] = array($paginationNode, <<<'EOF'
public function getNbsItems(array $context)
{
    $context = $this->env->mergeGlobals($context);

    return array(
        count(twig_reverse_filter($this->env, twig_sort_filter(range(0, 100)))),
    );
}

public function getMaxesPerPage()
{
    return array(
        20,
    );
}
EOF
);
        $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false));
        $moduleNode = $env->parse($env->tokenize('{% do collection|reverse %}'));
        $node = $moduleNode->getNode('body')->getNode(0)->getNode('expr');
        $paginationNode = new Pagination();
        $paginationNode->addNodeToPaginate($node, 20);
        $tests[] = array($paginationNode, <<<'EOF'
public function getNbsItems(array $context)
{
    $context = $this->env->mergeGlobals($context);

    return array(
        count(twig_reverse_filter($this->env,         // line 1
(isset($context["collection"]) ? $context["collection"] : null))),
    );
}

public function getMaxesPerPage()
{
    return array(
        20,
    );
}
EOF
);
        $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false));
        $moduleNode = $env->parse($env->tokenize('{% do collection|reverse %}'));
        $node = $moduleNode->getNode('body')->getNode(0)->getNode('expr');
        $paginationNode = new Pagination();
        $paginationNode->addNodeToPaginate($node, 20);
        $paginationNode->addNodeToPaginate($node, 10);
        $tests[] = array($paginationNode, <<<'EOF'
public function getNbsItems(array $context)
{
    $context = $this->env->mergeGlobals($context);

    return array(
        count(twig_reverse_filter($this->env,         // line 1
(isset($context["collection"]) ? $context["collection"] : null))),
        count(twig_reverse_filter($this->env, (isset($context["collection"]) ? $context["collection"] : null))),
    );
}

public function getMaxesPerPage()
{
    return array(
        20,
        10,
    );
}
EOF
);
        return $tests;
    }
 /**
  * @expectedException Twig_Error
  * @expectedExceptionMessageRegExp #SOME_UNKNOWN_CONST#
  */
 public function testUnresolved()
 {
     $this->environment->parse($this->environment->tokenize('{{ constant("SOME_UNKNOWN_CONST") }}', 'index'));
 }
 /**
  * @return MessageCatalogue
  * @throws \Exception
  */
 public function extract()
 {
     if (!empty($this->removingTwigVisitor)) {
         $this->removingTwigVisitor->setEnabled(false);
     }
     if (!empty($this->defaultApplyingTwigVisitor)) {
         $this->defaultApplyingTwigVisitor->setEnabled(false);
     }
     $finder = Finder::create()->in($this->directory);
     foreach ($this->excludedDirs as $dir) {
         $finder->exclude($dir);
     }
     foreach ($this->excludedNames as $name) {
         $finder->notName($name);
     }
     if ($this->pattern) {
         $finder->name($this->pattern);
     }
     $curTwigLoader = $this->twig->getLoader();
     $this->twig->setLoader(new \Twig_Loader_String());
     try {
         $catalogue = new MessageCatalogue();
         foreach ($finder as $file) {
             $visitingMethod = 'visitFile';
             $visitingArgs = array($file, $catalogue);
             $this->logger->debug(sprintf('Parsing file "%s"', $file));
             if (false !== ($pos = strrpos($file, '.'))) {
                 $extension = substr($file, $pos + 1);
                 if ('php' === $extension) {
                     try {
                         $ast = $this->phpParser->parse(file_get_contents($file));
                     } catch (Error $ex) {
                         throw new \RuntimeException(sprintf('Could not parse "%s": %s', $file, $ex->getMessage()), $ex->getCode(), $ex);
                     }
                     $visitingMethod = 'visitPhpFile';
                     $visitingArgs[] = $ast;
                 } elseif ('twig' === $extension) {
                     $visitingMethod = 'visitTwigFile';
                     $visitingArgs[] = $this->twig->parse($this->twig->tokenize(file_get_contents($file), (string) $file));
                 }
             }
             foreach ($this->visitors as $visitor) {
                 call_user_func_array(array($visitor, $visitingMethod), $visitingArgs);
             }
         }
         if (null !== $curTwigLoader) {
             $this->twig->setLoader($curTwigLoader);
         }
         if (!empty($this->removingTwigVisitor)) {
             $this->removingTwigVisitor->setEnabled(true);
         }
         if (!empty($this->defaultApplyingTwigVisitor)) {
             $this->defaultApplyingTwigVisitor->setEnabled(true);
         }
         return $catalogue;
     } catch (\Exception $ex) {
         if (null !== $curTwigLoader) {
             $this->twig->setLoader($curTwigLoader);
         }
         throw $ex;
     }
 }
Example #29
0
 private function validate(\Twig_Environment $twig, $template, $file)
 {
     $realLoader = $twig->getLoader();
     try {
         $temporaryLoader = new \Twig_Loader_Array(array((string) $file => $template));
         $twig->setLoader($temporaryLoader);
         $nodeTree = $twig->parse($twig->tokenize($template, (string) $file));
         $twig->compile($nodeTree);
         $twig->setLoader($realLoader);
     } catch (\Twig_Error $e) {
         $twig->setLoader($realLoader);
         return array('template' => $template, 'file' => $file, 'valid' => false, 'exception' => $e);
     }
     return array('template' => $template, 'file' => $file, 'valid' => true);
 }
 private function extract($file, TwigFileExtractor $extractor = null)
 {
     if (!is_file($file = __DIR__ . '/Fixture/' . $file)) {
         throw new RuntimeException(sprintf('The file "%s" does not exist.', $file));
     }
     $env = new \Twig_Environment();
     $env->addExtension(new SymfonyTranslationExtension($translator = new IdentityTranslator(new MessageSelector())));
     $env->addExtension(new TranslationExtension($translator, true));
     $env->addExtension(new RoutingExtension(new UrlGenerator(new RouteCollection(), new RequestContext())));
     $env->addExtension(new FormExtension(new TwigRenderer(new TwigRendererEngine())));
     foreach ($env->getNodeVisitors() as $visitor) {
         if ($visitor instanceof DefaultApplyingNodeVisitor) {
             $visitor->setEnabled(false);
         }
         if ($visitor instanceof RemovingNodeVisitor) {
             $visitor->setEnabled(false);
         }
     }
     if (null === $extractor) {
         $extractor = new TwigFileExtractor($env);
     }
     $ast = $env->parse($env->tokenize(file_get_contents($file), $file));
     $catalogue = new MessageCatalogue();
     $extractor->visitTwigFile(new \SplFileInfo($file), $catalogue, $ast);
     return $catalogue;
 }