protected function doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs) { if ($condition) { eval('$ret = ' . $condition . ';'); if (!$ret) { $this->markTestSkipped($condition); } } $loader = new IfwPsn_Vendor_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 IfwPsn_Vendor_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 IfwPsn_Vendor_Twig_Error_Syntax) { $e->setTemplateFile($file); throw $e; } throw new IfwPsn_Vendor_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 IfwPsn_Vendor_Twig_Error_Syntax) { $e->setTemplateFile($file); } else { $e = new IfwPsn_Vendor_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 . ')'); } }
/** * Loads a template from a string. * * <pre> * {{ include(template_from_string("Hello {{ name }}")) }} * </pre> * * @param IfwPsn_Vendor_Twig_Environment $env A IfwPsn_Vendor_Twig_Environment instance * @param string $template A template as a string * * @return IfwPsn_Vendor_Twig_Template A IfwPsn_Vendor_Twig_Template instance */ function ifwpsn_twig_template_from_string(IfwPsn_Vendor_Twig_Environment $env, $template) { $name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false)); $loader = new IfwPsn_Vendor_Twig_Loader_Chain(array(new IfwPsn_Vendor_Twig_Loader_Array(array($name => $template)), $current = $env->getLoader())); $env->setLoader($loader); try { $template = $env->loadTemplate($name); } catch (Exception $e) { $env->setLoader($current); throw $e; } $env->setLoader($current); return $template; }