Exemple #1
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 . ')');
     }
 }
 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 . ')');
     }
 }
Exemple #3
0
 public function testTemplateReference()
 {
     $name = new Twig_Test_Loader_TemplateReference('foo');
     $loader = new Twig_Loader_Array(array('foo' => 'bar'));
     $loader->getCacheKey($name);
     $loader->getSource($name);
     $loader->isFresh($name, time());
     $loader->setTemplate($name, 'foobar');
 }
 /**
  * Render shortcodes.
  *
  * @param  string     $content The content to render.
  * @param  array      $options Options to be passed to the renderer.
  * @param  null|Page  $page    Null or an instance of \Grav\Common\Page.
  *
  * @return string              The modified contents.
  */
 public function render($content, $options = [], $page = null)
 {
     // Build an anonymous function to pass to twig `render` method
     $function = function ($tag, $body, $arguments) use($options, $page) {
         if (isset($this->shortcodes[$tag])) {
             $options = isset($options[$tag]) ? $options[$tag] : [];
         }
         $event = new Event(['body' => $body, 'options' => new Data(array_replace_recursive($options, $arguments)), 'grav' => self::getGrav(), 'shortcodes' => $this, 'page' => $page, 'tag' => $tag]);
         return $event;
     };
     // Wrapper for shortcodes filter function
     $filter_function = function ($name, $content, $context, $env) {
         return $this->filterShortcode($name, $content, $context, $env);
     };
     // Process in-page shortcodes Twig
     $name = '@Shortcodes:' . $page->path();
     $this->loader->setTemplate($name, $content);
     $vars = ['__shortcodes' => $function, '__shortcodes_filter' => $filter_function];
     try {
         $page_default = $this->page;
         $this->page = $page;
         $output = $this->twig->render($name, $vars);
     } catch (\Twig_Error_Loader $e) {
         throw new \RuntimeException($e->getRawMessage(), 404, $e);
     }
     $shortcodes = isset($page->header()->shortcodes) ? $page->header()->shortcodes : [];
     if (isset($shortcodes['extra'])) {
         /** @var Cache $cache */
         $cache = self::getGrav()['cache'];
         $cache_id = md5('shortcodes' . $page->id() . $cache->getKey());
         $cache->save($cache_id, $shortcodes['extra']);
     }
     $this->page = $page_default;
     return $output;
 }
 /**
  * @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 . ')');
     }
 }
Exemple #6
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)));
                 }
             }
         }
     }
 }
 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 $i => $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);
         }
         foreach ($this->getTwigFilters() as $filter) {
             $twig->addFilter($filter);
         }
         foreach ($this->getTwigTests() as $test) {
             $twig->addTest($test);
         }
         foreach ($this->getTwigFunctions() as $function) {
             $twig->addFunction($function);
         }
         // avoid using the same PHP class name for different cases
         // only for PHP 5.2+
         if (PHP_VERSION_ID >= 50300) {
             $p = new ReflectionProperty($twig, 'templateClassPrefix');
             $p->setAccessible(true);
             $p->setValue($twig, '__TwigTemplate_' . hash('sha256', uniqid(mt_rand(), true), false) . '_');
         }
         try {
             $template = $twig->loadTemplate('index.twig');
         } catch (Exception $e) {
             if (false !== $exception) {
                 $message = $e->getMessage();
                 $this->assertSame(trim($exception), trim(sprintf('%s: %s', get_class($e), $message)));
                 $this->assertSame('.', substr($message, strlen($message) - 1), $message, 'Exception message must end with a dot.');
                 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->assertSame(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) {
             printf("Compiled templates that failed on case %d:\n", $i + 1);
             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 . ')');
     }
 }
Exemple #8
0
 /**
  * Adds or overrides a template.
  *
  * @param string $name     The template name
  * @param string $template The template source
  */
 public function setTemplate($name, $template)
 {
     $this->loaderArray->setTemplate($name, $template);
 }
Exemple #9
0
$fixturesDir = realpath(dirname(__FILE__) . '/../fixtures/');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($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($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());
    $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 ");
        $t->is($output, $expected, $message);
        if ($output != $expected) {
            $t->comment('Compiled template that failed:');
            foreach (array_keys($templates) as $name) {
                list($source, ) = $loader->getSource($name);
                $t->comment($twig->compile($twig->parse($twig->tokenize($source, $name))));
            }
        }
Exemple #10
0
$fixturesDir = realpath(dirname(__FILE__) . '/../fixtures/');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($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($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 ");
        $t->is($output, $expected, $message);
        if ($output != $expected) {
            $t->comment('Compiled template that failed:');
            foreach (array_keys($templates) as $name) {
                $source = $loader->getSource($name);
                $t->comment($twig->compile($twig->parse($twig->tokenize($source, $name))));
            }
Exemple #11
0
 public function testIsFresh()
 {
     $loader = new Twig_Loader_Array(array('foo' => 'bar'));
     $this->assertTrue($loader->isFresh('foo', time()));
 }
Exemple #12
0
 /**
  * @expectedException Twig_Error_Loader
  */
 public function testIsFreshWhenTemplateDoesNotExist()
 {
     $loader = new Twig_Loader_Array(array());
     $loader->isFresh('foo', time());
 }
 /**
  * @return Twig_Environment
  */
 protected function getTwig()
 {
     if (null === $this->twig) {
         $loader = new Twig_Loader_Array(array());
         $loader->setTemplate('nx_object_list', file_get_contents(__DIR__ . '/resources/nx_object_list.twig'));
         $loader->setTemplate('nx_settings', file_get_contents(__DIR__ . '/resources/nx_settings.twig'));
         $this->twig = new Twig_Environment($loader);
         $this->twig->addFilter(new Twig_SimpleFilter('nx_parse_date', array($this, 'parse_date_filter')));
         $this->twig->addFilter(new Twig_SimpleFilter('nx_url', array($this, 'document_url_filter')));
         $this->twig->addFunction(new Twig_SimpleFunction('settings_fields', 'settings_fields'));
         $this->twig->addFunction(new Twig_SimpleFunction('do_settings_sections', 'do_settings_sections'));
         $this->twig->addFunction(new Twig_SimpleFunction('get_option', 'get_option'));
         $this->twig->addFunction(new Twig_SimpleFunction('_e', '_e'));
     }
     return $this->twig;
 }