getLoader() public méthode

public getLoader ( )
 /**
  * @param string $template
  * @return array
  * @throws \Werkint\Bundle\TemplatingBundle\Exception\TemplateNotFoundException
  */
 public function parse($template)
 {
     $modules = [$template];
     $worked = [];
     while ($name = array_shift($modules)) {
         if (isset($worked[$name])) {
             continue;
         }
         try {
             $source = $this->templating->getLoader()->getSource($name);
         } catch (\Twig_Error_Loader $exception) {
             throw new TemplateNotFoundException($template);
         }
         // Инклуды
         preg_match_all('!%\\s*(include|extends)\\s*(.+?)\\s+!', $source, $m);
         $m = array_map(function ($name) {
             return substr($name, 1, strlen($name) - 2);
         }, array_filter($m[2], function ($name) {
             return preg_match('!^[\'"].+?[\'"]$!', $name);
         }));
         $modules = array_merge($modules, $m);
         $worked[$name] = $source;
     }
     return $worked;
 }
 public function parse($buffer, $context = array())
 {
     /** @var \Twig_Loader_Array $loader */
     $loader = $this->twigEnvironment->getLoader();
     $loader->setTemplate('__TEMPLATE__', $buffer);
     return $this->twigEnvironment->render('__TEMPLATE__', $context);
 }
 /**
  * Get the template name.
  *
  * @return string
  */
 public function getTemplateName()
 {
     $template = $this->configuration['template'];
     if (!$this->environment->getLoader()->exists($template)) {
         $this->environment->getLoader()->addPath(__DIR__ . '/../Resources/views');
     }
     return $template;
 }
 /**
  * {@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();
 }
 /**
  * Get the template name.
  *
  * @return string
  */
 public function getTemplateName()
 {
     $template = 'bs_breadcrumb/breadcrumb.html.twig';
     if (!$this->environment->getLoader()->exists($template)) {
         $this->environment->getLoader()->addPath(__DIR__ . '/../Resources/views');
     }
     return $template;
 }
Exemple #6
0
 public function file($path, $data = array(), $mergeData = array())
 {
     if (!file_exists($path)) {
         return false;
     }
     $filePath = dirname($path);
     $fileName = basename($path);
     $this->twig->getLoader()->addPath($filePath);
     return new TwigView($this, $fileName, $data);
 }
 public function testFormatter()
 {
     $loader = new MyStringLoader();
     $twig = new \Twig_Environment($loader);
     $formatter = new TwigFormatter($twig);
     // Checking, that formatter can process twig template, passed as string
     $this->assertEquals('0,1,2,3,', $formatter->transform('{% for i in range(0, 3) %}{{ i }},{% endfor %}'));
     // Checking, that formatter does not changed loader
     $this->assertNotInstanceOf('\\Twig_Loader_String', $twig->getLoader());
     $this->assertInstanceOf('Sonata\\FormatterBundle\\Tests\\Formatter\\MyStringLoader', $twig->getLoader());
 }
 /**
  * {@inheritdoc}
  */
 public function transform($text)
 {
     // Here we temporary changing twig environment loader to Chain loader with Twig_Loader_Array as first loader, which contains only one our template reference
     $oldLoader = $this->twig->getLoader();
     $hash = sha1($text);
     $chainLoader = new \Twig_Loader_Chain();
     $chainLoader->addLoader(new \Twig_Loader_Array(array($hash => $text)));
     $chainLoader->addLoader($oldLoader);
     $this->twig->setLoader($chainLoader);
     $result = $this->twig->render($hash);
     $this->twig->setLoader($oldLoader);
     return $result;
 }
 public function boot()
 {
     $configPath = __DIR__ . '/../config/form.php';
     $this->publishes([$configPath => config_path('form.php')], 'config');
     if ($this->app->bound(\Twig_Environment::class)) {
         /** @var \Twig_Environment $twig */
         $twig = $this->app->make(\Twig_Environment::class);
     } else {
         $twig = new \Twig_Environment(new \Twig_Loader_Chain([]));
     }
     $loader = $twig->getLoader();
     // If the loader is not already a chain, make it one
     if (!$loader instanceof \Twig_Loader_Chain) {
         $loader = new \Twig_Loader_Chain([$loader]);
         $twig->setLoader($loader);
     }
     $reflected = new \ReflectionClass(FormExtension::class);
     $path = dirname($reflected->getFileName()) . '/../Resources/views/Form';
     $loader->addLoader(new \Twig_Loader_Filesystem($path));
     /** @var TwigRenderer $renderer */
     $renderer = $this->app->make(TwigRendererInterface::class);
     $renderer->setEnvironment($twig);
     // Add the extension
     $twig->addExtension(new FormExtension($renderer));
     // trans filter is used in the forms
     $twig->addFilter(new \Twig_SimpleFilter('trans', 'trans'));
     // csrf_token needs to be replaced for Laravel
     $twig->addFunction(new \Twig_SimpleFunction('csrf_token', 'csrf_token'));
     $this->registerBladeDirectives();
 }
    function it_should_generate_code_for_the_given_metadata(Twig $view, Filesystem $fileSystem, Loader $loader)
    {
        $view->getLoader()->willReturn($loader);
        $this->beConstructedWith($view, $fileSystem);
        $formMetadata = new FormMetadata();
        $formMetadata->populate('My\\Awesome\\LoginForm', ['username' => ['type' => 'text', 'optional' => false, 'multipleSelection' => false, 'value' => null], 'languages' => ['type' => 'select', 'optional' => true, 'multipleSelection' => true, 'value' => null], 'remember_me' => ['type' => 'checkbox', 'optional' => true, 'multipleSelection' => false, 'value' => null]]);
        $formMetadata->setTargetDirectory('src/');
        $view->render('templates/class.php.twig', ['form' => $formMetadata])->willReturn($code = <<<CODE
<?php
namespace My\\Awesome;

use EasyForms\\Elements\\Text;
use EasyForms\\Elements\\Select;
use EasyForms\\Elements\\Checkbox;
use EasyForms\\Form;

class LoginForm extends Form
{
    public function __construct()
    {
        \$this
            ->add(new Text('username'))
            ->add((new Select('languages'))->makeOptional()->enableMultipleSelection())
            ->add((new Checkbox('remember_me', 'remember'))->makeOptional())
        ;
    }
}
CODE
);
        $this->generate($formMetadata);
        $fileSystem->mkdir('src/My/Awesome')->shouldHaveBeenCalled();
        $fileSystem->dumpFile('src/My/Awesome/LoginForm.php', $code)->shouldHaveBeenCalled();
    }
Exemple #11
0
 /**
  * Adds extensions required for proper work with FormFactory to Twig template engine
  * @param CsrfTokenManager $csrfTokenManager
  */
 private function extendTwig($csrfTokenManager)
 {
     $translator = new Translator($this->lang);
     $translator->addLoader('xlf', new XliffFileLoader());
     $translator->addResource('xlf', $this->componentDir['form'] . '/Resources/translations/validators.en.xlf', 'en', 'validators');
     $translator->addResource('xlf', $this->componentDir['validator'] . '/Resources/translations/validators.en.xlf', 'en', 'validators');
     $formTheme = 'bootstrap_3_layout.html.twig';
     //'form_div_layout.html.twig';
     $formEngine = new TwigRendererEngine([$formTheme]);
     $twigLoader = $this->twig->getLoader();
     $newTwigLoader = new \Twig_Loader_Chain([$twigLoader, new \Twig_Loader_Filesystem([$this->componentDir['twigBridge'] . '/Resources/views/Form'])]);
     $this->twig->setLoader($newTwigLoader);
     $formEngine->setEnvironment($this->twig);
     $this->twig->addExtension(new TranslationExtension($translator));
     $this->twig->addExtension(new FormExtension(new TwigRenderer($formEngine, $csrfTokenManager)));
 }
 /**
  * Evaluate $string through the $environment and return its results
  *
  * @oaram \Twig_Environment $environment
  * @param array $context
  * @param string $string
  *
  * @return string
  */
 public function evaluateFilter(\Twig_Environment $environment, $context, $string)
 {
     $loader = $environment->getLoader();
     $parsed = $this->parseString($environment, $context, $string);
     $environment->setLoader($loader);
     return $parsed;
 }
 /**
  * @param Twig $view
  * @param Filesystem $fileSystem
  */
 public function __construct(Twig $view, Filesystem $fileSystem)
 {
     $class = new ReflectionClass($this);
     $view->getLoader()->addPath(dirname($class->getFileName()) . '/../Resources');
     $this->view = $view;
     $this->fileSystem = $fileSystem;
 }
 public function initRuntime(\Twig_Environment $environment)
 {
     $this->twigEnvironment = $environment;
     $loader = new \Twig_Loader_Filesystem();
     $loader->addPath(__DIR__ . '/../Resorces/views', 'np_navigation');
     $environment->getLoader()->addLoader($loader);
 }
Exemple #15
0
 /**
  * @return array[string => mixed]
  */
 public static function before()
 {
     $user = null;
     // initialize session
     Session::init();
     // setup twig
     $twig = new \Twig_Environment(new \Twig_Loader_Filesystem());
     $twig->getLoader()->addPath(__DIR__ . '/Twig');
     $twig->addGlobal('asset', Settings::load('settings')->get('asset-url'));
     $twig->addGlobal('base_url', NekoPHP::getBaseUrl());
     // add the current user object to twig, if it exists
     $user_id = Session::get('user_id');
     // set the user if a user_id is set
     if ($user_id > 0) {
         $user = new \NekoPHP\Modules\User\Models\User($user_id);
         $twig->addGlobal('cuser', $user);
     }
     // add one-time alerts
     foreach (['success', 'info', 'warning', 'error'] as $alert) {
         if (Session::existsOnce($alert)) {
             $twig->addGlobal('alert_' . $alert, Session::getOnce($alert));
         }
     }
     return ['cuser' => $user, 'twig' => $twig];
 }
 /**
  * Render a single file from a template to an output path
  *
  * @param string $templateName Name of the template for Twig
  * @param string $outputPath Relative path to render to
  * @param array $context Twig context
  */
 public function renderFile($templateName, $outputPath, array $context)
 {
     $template = $this->twig->loadTemplate($templateName);
     $this->manager->addResource(new TwigResource($this->twig->getLoader(), $templateName), 'twig');
     $event = new RenderEvent($this, $template, $context);
     $this->dispatcher->dispatch(BrancherEvents::RENDER, $event);
     $rendered = $template->render($event->context);
     $this->filesystem->dumpFile("{$this->outputDir}/{$outputPath}", $rendered);
 }
Exemple #17
0
 /**
  * @param string $string
  * @return string
  */
 public function renderString($string)
 {
     // no rendering if empty
     if (empty($string)) {
         return $string;
     }
     // see Twig\Extensions\Twig_Extension_StringLoader
     $name = '__twig_string__';
     // get current loader
     $loader = $this->environment->getLoader();
     // set loader chain with new array loader
     $this->environment->setLoader(new Twig_Loader_Chain(array(new Twig_Loader_Array(array($name => $string)), $loader)));
     // render string
     $rendered = $this->environment->render($name);
     // reset current loader
     $this->environment->setLoader($loader);
     return $rendered;
 }
 /**
  * {@inheritdoc}
  *
  * It also supports \Twig_Template as name parameter.
  */
 public function exists($name)
 {
     if ($name instanceof \Twig_Template) {
         return true;
     }
     $loader = $this->environment->getLoader();
     if ($loader instanceof \Twig_ExistsLoaderInterface) {
         return $loader->exists((string) $name);
     }
     try {
         // cast possible TemplateReferenceInterface to string because the
         // EngineInterface supports them but Twig_LoaderInterface does not
         $loader->getSource((string) $name);
     } catch (\Twig_Error_Loader $e) {
         return false;
     }
     return true;
 }
Exemple #19
0
 /**
  * Load template from string using the shared environment.
  *
  * @param string $template
  * @return Curry_Twig_Template
  */
 public static function loadTemplateString($template)
 {
     self::getSharedEnvironment();
     $loader = self::$twig->getLoader();
     self::$twig->setLoader(new Twig_Loader_String());
     $tpl = self::$twig->loadTemplate($template);
     self::$twig->setLoader($loader);
     return $tpl;
 }
 /**
  * Add a new namespace to the loader.
  *
  * @param  \TwigBridge\StringView\StringView  $view
  * @return \TwigBridge\Twig\Template
  */
 public function resolveTemplate(StringView $view)
 {
     $currentLoader = $this->twig->getLoader();
     $loader = new Loader($view);
     $this->twig->setLoader($loader);
     $template = $this->twig->resolveTemplate($view->getName());
     $this->twig->setLoader($currentLoader);
     return $template;
 }
Exemple #21
0
 public function add_to_twig(\Twig_Environment $twig, \Twig_Loader_Filesystem $loader = null)
 {
     $gantry = \Gantry\Framework\Gantry::instance();
     /** @var UniformResourceLocator $locator */
     $locator = $gantry['locator'];
     if (!$loader) {
         $loader = $twig->getLoader();
     }
     $loader->setPaths($locator->findResources('gantry-admin://templates'), 'gantry-admin');
     $twig->addExtension(new TwigExtension());
     return $twig;
 }
 /**
  * Extract files locatable within provided Twig Environment.
  *
  * @param Twig_Environment $twig Instance to check.
  *
  * @return array Map of files => Twig templates.
  */
 public function get_files(Twig_Environment $twig)
 {
     $files = array();
     try {
         $paths = $twig->getLoader()->getPaths();
         foreach ($paths as $path) {
             $files += $this->read_files($path, strlen($path) + 1);
         }
     } catch (Exception $excpt) {
     }
     return $files;
 }
 /**
  * @param  \Twig_Environment $env
  * @param                    $context
  * @param  FormView          $form
  * @param  string            $formVariableName
  * @return array
  */
 public function render(\Twig_Environment $env, $context, FormView $form, $formVariableName = 'form')
 {
     $this->formVariableName = $formVariableName;
     $this->formConfig = new FormConfig();
     $this->context = $context;
     $this->env = $env;
     $tmpLoader = $env->getLoader();
     $env->setLoader(new \Twig_Loader_Chain([$tmpLoader, new \Twig_Loader_String()]));
     $this->renderBlock($form);
     $env->setLoader($tmpLoader);
     return $this->formConfig->toArray();
 }
 public function applyFilter(Twig_Environment $env, $context = array(), $value, $filters)
 {
     $old_env = $env->getLoader();
     $env = new Twig_Environment(new Twig_Loader_String(), array('cache' => false, 'autoescape' => false));
     $name = 'apply_filter_' . md5($filters);
     $template = sprintf('{{ %s|%s }}', $name, $filters);
     $template = $env->loadTemplate($template);
     $context[$name] = $value;
     $finale = $template->render($context);
     $env = $env->setLoader($old_env);
     return $finale;
 }
Exemple #25
0
 /**
  * Define twig environment.
  *
  * @param \Twig_Environment $twig
  * @param \Twig_Loader_Filesystem $loader
  * @return \Twig_Environment
  */
 public function extendTwig(\Twig_Environment $twig, \Twig_Loader_Filesystem $loader = null)
 {
     if (!$loader) {
         $loader = $twig->getLoader();
     }
     $this->setTwigLoaderPaths($loader);
     $twig->addExtension(new TwigExtension());
     if (method_exists($this, 'toGrid')) {
         $twig->addFilter('toGrid', new \Twig_Filter_Function([$this, 'toGrid']));
     }
     return $twig;
 }
Exemple #26
0
 /**
  * Compiles the node to PHP.
  *
  * @param \Twig_Compiler A Twig_Compiler instance
  */
 public function compile(\Twig_Compiler $compiler)
 {
     $compiler->addDebugInfo($this);
     $location = $this->listener_directory . $this->getNode('expr')->getAttribute('name');
     foreach ($this->environment->get_phpbb_extensions() as $ext_namespace => $ext_path) {
         $ext_namespace = str_replace('/', '_', $ext_namespace);
         if (defined('DEBUG')) {
             // If debug mode is enabled, lets check for new/removed EVENT
             //  templates on page load rather than at compile. This is
             //  slower, but makes developing extensions easier (no need to
             //  purge the cache when a new event template file is added)
             $compiler->write("if (\$this->env->getLoader()->exists('@{$ext_namespace}/{$location}.html')) {\n")->indent();
         }
         if (defined('DEBUG') || $this->environment->getLoader()->exists('@' . $ext_namespace . '/' . $location . '.html')) {
             $compiler->write("\$previous_look_up_order = \$this->env->getNamespaceLookUpOrder();\n")->write("\$this->env->setNamespaceLookUpOrder(array('{$ext_namespace}', '__main__'));\n")->write("\$this->env->loadTemplate('@{$ext_namespace}/{$location}.html')->display(\$context);\n")->write("\$this->env->setNamespaceLookUpOrder(\$previous_look_up_order);\n");
         }
         if (defined('DEBUG')) {
             $compiler->outdent()->write("}\n\n");
         }
     }
 }
 private function registerWidgetTemplates(\Twig_Environment &$twigEnvironment)
 {
     $currentLoader = $twigEnvironment->getLoader();
     if ($currentLoader instanceof \Twig_Loader_Filesystem) {
         $currentLoader->addPath(__DIR__ . '/../widgets', 'assetwidgets');
     } elseif ($currentLoader instanceof \Twig_Loader_Chain) {
         $fsloader = new \Twig_Loader_Filesystem();
         $fsloader->addPath(__DIR__ . '/../widgets', 'assetwidgets');
         $currentLoader->addLoader($fsloader);
     }
     $twigEnvironment->setLoader($currentLoader);
 }
 /**
  * @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));
 }
 /**
  * checks if a template with given name exists.
  *
  * @param string $template
  *
  * @return bool
  */
 protected function templateExists($template)
 {
     $loader = $this->twig->getLoader();
     if ($loader instanceof \Twig_ExistsLoaderInterface) {
         return $loader->exists($template);
     }
     try {
         $loader->getSource($template);
         return true;
     } catch (\Twig_Error_Loader $e) {
         return false;
     }
 }
 /**
  * @param \Twig_Environment $env
  * @param array             $context
  * @param FormView          $form
  * @param string            $formVariableName
  *
  * @return array
  */
 public function render(\Twig_Environment $env, $context, FormView $form, $formVariableName = 'form')
 {
     // remember current loader
     $originalLoader = $env->getLoader();
     // replace the loader
     $env->setLoader(new \Twig_Loader_Chain(array($originalLoader, new \Twig_Loader_String())));
     // build blocks
     $builder = new DataBlockBuilder(new TwigTemplateRenderer($env, $context), $formVariableName);
     $result = $builder->build($form);
     // restore the original loader
     $env->setLoader($originalLoader);
     return $result->toArray();
 }