addExtension() public method

Registers an extension.
public addExtension ( Twig_ExtensionInterface $extension )
$extension Twig_ExtensionInterface A Twig_ExtensionInterface instance
Ejemplo n.º 1
1
 /**
  * @return \Twig_Environment
  */
 private function getTemplateEngine()
 {
     if (!$this->templateEngine instanceof \Twig_Environment) {
         $this->templateEngine = new \Twig_Environment($this->getFilesystemLoader(), ['cache' => realpath(PATH_CACHE), 'auto_reload' => true]);
         $this->templateEngine->addExtension(new \Twig_Extensions_Extension_I18n());
     }
     return $this->templateEngine;
 }
Ejemplo n.º 2
0
 public function register(Application $app, array $options = array())
 {
     $config = $app->getConfig();
     if (!empty($config[$this->name])) {
         $fs_twig_loader = new \Twig_Loader_Filesystem(__DIR__ . '/../../../../../../src/' . $config[$this->name]['path']);
         $loader = new \Twig_Loader_Chain(array($fs_twig_loader));
         $twig = new \Twig_Environment($loader);
         // this extension includes the asset() function
         $twig->addExtension(new TwigCoreExtension($app));
         // the routing extension is required to reference routes in twig templates
         // e.g <a href="{{ path('Some_route')}}">click</a>
         $twig->addExtension(new RoutingExtension($app->shared['url.generator']));
         if ($app->getProvider('translator') !== null) {
             $twig->addExtension(new TranslationExtension($app->getProvider('translator')));
         }
         if ($app->getProvider('form')) {
             $twig_form_templates = array('form_div_layout.html.twig');
             $twig_form_engine = new TwigRendererEngine($twig_form_templates);
             $twig_form_renderer = new TwigRenderer($twig_form_engine, $app->shared['csrf_provider']);
             $twig->addExtension(new FormExtension($twig_form_renderer));
             // add loader for Symfony built-in form templates
             $reflected = new \ReflectionClass('Symfony\\Bridge\\Twig\\Extension\\FormExtension');
             $path = dirname($reflected->getFileName()) . '/../Resources/views/Form';
             $loader->addLoader(new \Twig_Loader_Filesystem($path));
         }
         return $twig;
     }
     return false;
 }
 public function setUp()
 {
     $this->loader = new \Twig_Loader_Filesystem(array(realpath(__DIR__ . '/../Resources/twig')));
     $this->environment = new \Twig_Environment($this->loader, array());
     $this->environment->addExtension(new Extension(array('nodes' => array('RunOpenCode\\Twig\\BufferizedTemplate\\Tests\\Mockup\\DummyTwigNode' => 20))));
     $this->environment->addExtension(new DummyTwigExtension());
 }
Ejemplo n.º 4
0
 public function register(Application $app)
 {
     $app['twig.options'] = array();
     $app['twig.form.templates'] = array('form_div_layout.html.twig');
     $app['twig.path'] = array();
     $app['twig.templates'] = array();
     $app['twig'] = $app->share(function ($app) {
         $app['twig.options'] = array_replace(array('charset' => "UTF-8", 'debug' => isset($app['debug']) ? $app['debug'] : false, 'strict_variables' => isset($app['debug']) ? $app['debug'] : false), $app['twig.options']);
         $twig = new \Twig_Environment($app['twig.loader'], $app['twig.options']);
         $twig->addGlobal('app', $app);
         $twig->addExtension(new TwigCoreExtension());
         if (isset($app['debug']) && $app['debug']) {
             $twig->addExtension(new \Twig_Extension_Debug());
         }
         return $twig;
     });
     $app['twig.loader.filesystem'] = $app->share(function ($app) {
         return new \Twig_Loader_Filesystem($app['twig.path']);
     });
     $app['twig.loader.array'] = $app->share(function ($app) {
         return new \Twig_Loader_Array($app['twig.templates']);
     });
     $app['twig.loader.string'] = $app->share(function ($app) {
         return new \Twig_Loader_String();
     });
     $app['twig.loader'] = $app->share(function ($app) {
         return new \Twig_Loader_Chain(array($app['twig.loader.filesystem'], $app['twig.loader.array'], $app['twig.loader.string']));
     });
 }
Ejemplo n.º 5
0
 /**
  * @param Configuration  $configuration
  * @param ServiceManager $serviceManager
  */
 public function __construct(Configuration $configuration, ServiceManager $serviceManager)
 {
     if (!$configuration->get('twig', null)) {
         return;
     }
     $cachePath = $configuration->getApplicationPath() . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
     $options = [];
     if ($configuration->get('cache.config.enabled', false)) {
         $options['cache'] = $cachePath;
     }
     $paths = $configuration->get('twig.paths', []);
     foreach ($paths as $offset => $path) {
         $paths[$offset] = dirname($configuration->getApplicationPath()) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . $path;
     }
     $loader = new \Twig_Loader_Filesystem($paths);
     $this->twig = new \Twig_Environment($loader, $options + $configuration->get('twig.options', []));
     if (isset($configuration->get('twig.options', [])['debug']) && $configuration->get('twig.options', [])['debug']) {
         $this->twig->addExtension(new \Twig_Extension_Debug());
     }
     foreach ($configuration->get('twig.helpers', []) as $functionName => $helperClass) {
         $func = new \Twig_SimpleFunction($functionName, function () use($helperClass, $serviceManager) {
             $instance = $serviceManager->load($helperClass);
             return call_user_func_array($instance, func_get_args());
         });
         $this->twig->addFunction($func);
     }
     foreach ($configuration->get('twig.filters', []) as $functionName => $helperClass) {
         $func = new \Twig_SimpleFilter($functionName, function () use($helperClass, $serviceManager) {
             $instance = $serviceManager->load($helperClass);
             return call_user_func_array($instance, func_get_args());
         });
         $this->twig->addFilter($func);
     }
 }
Ejemplo n.º 6
0
 /**
  * @dataProvider getTests
  */
 public function testIntegration($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->addExtension(new TestExtension());
         $twig->addExtension(new Twig_Extension_Debug());
         $policy = new Twig_Sandbox_SecurityPolicy(array(), array(), array(), array(), array());
         $twig->addExtension(new Twig_Extension_Sandbox($policy, false));
         $twig->addGlobal('global', 'global');
         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 . ')');
     }
 }
Ejemplo n.º 7
0
 public function init()
 {
     $loader = $this->getTwigFilesystemLoader();
     $this->environment = new Twig_Environment($loader, ['debug' => $this->config->get('twig.debug'), 'cache' => $this->config->get('twig.cache')]);
     if (!$this->config->isEmpty('twig.debug')) {
         $this->environment->addExtension(new Twig_Extension_Debug());
     }
     $this->environment->addExtension(new HerbieExtension());
     $this->addTwigPlugins();
     foreach (Hook::trigger(Hook::CONFIG, 'addTwigFunction') as $function) {
         try {
             list($name, $callable, $options) = $function;
             $this->environment->addFunction(new \Twig_SimpleFunction($name, $callable, (array) $options));
         } catch (\Exception $e) {
             /*do nothing else yet*/
         }
     }
     foreach (Hook::trigger(Hook::CONFIG, 'addTwigFilter') as $filter) {
         try {
             list($name, $callable, $options) = $filter;
             $this->environment->addFilter(new \Twig_SimpleFilter($name, $callable, (array) $options));
         } catch (\Exception $e) {
             /*do nothing else yet*/
         }
     }
     foreach (Hook::trigger(Hook::CONFIG, 'addTwigTest') as $test) {
         try {
             list($name, $callable, $options) = $test;
             $this->environment->addTest(new \Twig_SimpleTest($name, $callable, (array) $options));
         } catch (\Exception $e) {
             /*do nothing else yet*/
         }
     }
     $this->initialized = true;
 }
 /**
  * @param string $path Relative path to layout file
  */
 protected function configureLayout($path)
 {
     $loader = new Loader([str_replace('tests', 'src', __DIR__)]);
     $this->environment = new Environment($loader, ['debug' => true, 'strict_variables' => true]);
     $this->renderer = new FormRenderer(new FormTheme($this->environment, $path));
     $this->environment->addExtension(new FormExtension($this->renderer));
 }
 /**
  * Create twig environment and add the extension.
  */
 protected function setUpTwig()
 {
     $this->twig = new Twig_Environment(new Twig_Loader_Filesystem(array(self::getTemplatesPath())));
     $this->componentExtension = new ComponentExtension();
     $this->componentExtension->addComponent(new NamedComponent('test'));
     $this->twig->addExtension($this->componentExtension);
 }
Ejemplo n.º 10
0
    protected function setUp()
    {
        $this->env = new \Twig_Environment(
            new \Twig_Loader_Array(
                array(
                    'state'       => '{{ finite_state(object) }}',
                    'transitions' => '{% for transition in finite_transitions(object) %}{{ transition }}{% endfor %}',
                    'properties'  => '{% for property, val in finite_properties(object) %}{{ property }}{% endfor %}',
                    'has'         => '{{ finite_has(object, property) ? "yes" : "no" }}',
                    'can'         => '{{ finite_can(object, transition) ? "yes" : "no" }}'
                )
            )
        );

        $container = new \Pimple(array(
            'state_machine' => function() {
                $sm =  new StateMachine;
                $sm->addState(new State('s1', State::TYPE_INITIAL, array(), array('foo' => true, 'bar' => false)));
                $sm->addTransition('t12', 's1', 's2');
                $sm->addTransition('t23', 's2', 's3');

                return $sm;
            }
        ));

        $this->context = new Context(new PimpleFactory($container, 'state_machine'));;
        $this->env->addExtension(new FiniteExtension($this->context));
    }
 /**
  * @param ContainerInterface $container
  * @return TwigRenderer
  */
 public function __invoke(ContainerInterface $container)
 {
     $config = $container->has('config') ? $container->get('config') : [];
     $debug = array_key_exists('debug', $config) ? (bool) $config['debug'] : false;
     $config = isset($config['templates']) ? $config['templates'] : [];
     $cacheDir = isset($config['cache_dir']) ? $config['cache_dir'] : false;
     // Create the engine instance
     $loader = new TwigLoader();
     $environment = new TwigEnvironment($loader, ['cache' => $debug ? false : $cacheDir, 'debug' => $debug, 'strict_variables' => $debug, 'auto_reload' => $debug]);
     // Add extensions
     if ($container->has(RouterInterface::class)) {
         $environment->addExtension(new TwigExtension($container->get(RouterInterface::class), isset($config['assets_url']) ? $config['assets_url'] : '', isset($config['assets_version']) ? $config['assets_version'] : ''));
     }
     if ($debug) {
         $environment->addExtension(new TwigExtensionDebug());
     }
     // Inject environment
     $twig = new TwigRenderer($environment, isset($config['extension']) ? $config['extension'] : 'html.twig');
     // Add template paths
     $allPaths = isset($config['paths']) && is_array($config['paths']) ? $config['paths'] : [];
     foreach ($allPaths as $namespace => $paths) {
         $namespace = is_numeric($namespace) ? null : $namespace;
         foreach ((array) $paths as $path) {
             $twig->addPath($path, $namespace);
         }
     }
     return $twig;
 }
 protected function setUp()
 {
     $loader = new \Twig_Loader_Array(array());
     $this->extension = new TwigExtension();
     $this->twig = new \Twig_Environment($loader);
     $this->twig->addExtension($this->extension);
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     if (!in_array($this->type, array('form', 'filter'))) {
         throw new \Exception('Please override $this->type in your test class specifying template to use (either form or filter)');
     }
     $rendererEngine = new TwigRendererEngine(array($this->type . '_admin_fields.html.twig'));
     $csrfManagerClass = interface_exists('Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface') ? 'Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface' : 'Symfony\\Component\\Form\\Extension\\Csrf\\CsrfProvider\\CsrfProviderInterface';
     $renderer = new TwigRenderer($rendererEngine, $this->getMock($csrfManagerClass));
     $this->extension = new FormExtension($renderer);
     $twigPaths = array(__DIR__ . '/../../../Resources/views/Form');
     //this is ugly workaround for different build strategies and, possibly,
     //different TwigBridge installation directories
     if (is_dir(__DIR__ . '/../../../vendor/symfony/twig-bridge/Resources/views/Form')) {
         $twigPaths[] = __DIR__ . '/../../../vendor/symfony/twig-bridge/Resources/views/Form';
     } elseif (is_dir(__DIR__ . '/../../../vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form')) {
         $twigPaths[] = __DIR__ . '/../../../vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form';
     } else {
         $twigPaths[] = __DIR__ . '/../../../../../symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form';
     }
     $loader = new StubFilesystemLoader($twigPaths);
     $this->environment = new \Twig_Environment($loader, array('strict_variables' => true));
     $this->environment->addGlobal('sonata_admin', $this->getSonataAdmin());
     $this->environment->addExtension(new TranslationExtension(new StubTranslator()));
     $this->environment->addExtension($this->extension);
     $this->extension->initRuntime($this->environment);
 }
Ejemplo n.º 14
0
 /**
  * Gets the Twig instance.
  *
  * @param  string            $loaderClass The template loader class to use with the environment.
  * @return \Twig_Environment
  */
 public function getTwig($loaderClass = null)
 {
     if (!$loaderClass) {
         $loaderClass = __NAMESPACE__ . '\\TemplateLoader';
     }
     if (!isset($this->_twigs[$loaderClass])) {
         // Is this the first Twig instance EVER?
         if (!isset($this->_twigs)) {
             $this->registerTwigAutoloader();
         }
         $loader = new $loaderClass();
         $options = $this->_getTwigOptions();
         $twig = new \Twig_Environment($loader, $options);
         $twig->addExtension(new \Twig_Extension_StringLoader());
         $twig->addExtension(new CraftTwigExtension());
         if (craft()->config->get('devMode')) {
             $twig->addExtension(new \Twig_Extension_Debug());
         }
         // Give plugins a chance to add their own Twig extensions
         // All plugins may not have been loaded yet if an exception is being thrown
         // or a plugin is loading a template as part of of its init() function.
         if (craft()->plugins->arePluginsLoaded()) {
             $pluginExtensions = craft()->plugins->call('addTwigExtension');
             foreach ($pluginExtensions as $extension) {
                 $twig->addExtension($extension);
             }
         } else {
             // Wait around for plugins to actually be loaded,
             // then do it for all Twig environments that have been created.
             craft()->on('plugins.loadPlugins', array($this, '_onPluginsLoaded'));
         }
         $this->_twigs[$loaderClass] = $twig;
     }
     return $this->_twigs[$loaderClass];
 }
 public function __construct(array $filters)
 {
     $this->twig = new Twig_Environment(new Twig_Loader_Filesystem(__DIR__ . '/../templates'));
     $this->twig->addExtension(new TwigBooleanStringExtension());
     $this->filters = $filters;
     return $this->generate();
 }
Ejemplo n.º 16
0
 /**
  * Twig constructor.
  *
  * @param AbsMenuPage $menuPage
  *
  * @since  1.0.0
  * @author Panagiotis Vagenas <*****@*****.**>
  */
 public function __construct(AbsMenuPage $menuPage)
 {
     $basePath = $menuPage->getWpMenuPages()->getBasePath();
     $this->defaultPaths[] = $basePath . '/' . IfcTemplateConstants::TEMPLATES_DIR;
     $sysTmpDir = sys_get_temp_dir();
     if (file_exists($sysTmpDir) && is_writable($sysTmpDir)) {
         $this->cachePath = trailingslashit($sysTmpDir) . 'twig/cache';
     }
     $twigOptions = [];
     if ($this->cachePath) {
         $twigOptions['cache'] = $this->cachePath;
     }
     if (IfcConstants::DEV) {
         $twigOptions['debug'] = true;
         $twigOptions['auto_reload'] = true;
         $twigOptions['strict_variables'] = true;
     }
     /**
      * Allows the ability to define extra locations when looking for templates.
      *
      * @param array $templatePaths The template paths
      *
      * @since 1.0.0
      */
     $templatePaths = apply_filters('MenuPages\\Templates\\Twig::templatePaths', $this->defaultPaths);
     $this->twigLoader = new \Twig_Loader_Filesystem($templatePaths);
     $this->twigEnvironment = new \Twig_Environment($this->twigLoader, $twigOptions);
     $this->twigEnvironment->addExtension(new WpTwigExtension($menuPage));
     if (IfcConstants::DEV) {
         $this->twigEnvironment->addExtension(new \Twig_Extension_Debug());
     }
 }
Ejemplo n.º 17
0
 /**
  * Sets up Twig ready for use and returns it
  * @return \Twig_Environment
  */
 protected function getTwigEnvironment()
 {
     /**
      * Get the config
      * @var \snb\config\ConfigInterface $config
      */
     $config = $this->container->get('config');
     $kernel = $this->container->get('kernel');
     // Find the cache path
     $cachePath = $config->get('twig.cache', ':/cache');
     // Use our loader the know how to map resource names to filenames
     $loader = new TwigFileLoader($this->container);
     // use the default environment. Should pass settings over from the config
     $twig = new \Twig_Environment($loader, array('cache' => $kernel->findPath($cachePath), 'debug' => $kernel->isDebug()));
     // Add the dump command (only works when debug is true)
     $twig->addExtension(new \Twig_Extension_Debug());
     // Add the app as a global...
     $twig->addGlobal('app', $kernel);
     // Add all the extensions that have been registered with the service provider
     $globals = $this->container->getMatching('twig.global.*');
     foreach ($globals as $global) {
         if ($global instanceof ViewGlobalInterface) {
             $twig->addGlobal($global->getGlobalName(), $global);
         }
     }
     // Add all the extensions that have been registered with the service provider
     $extensions = $this->container->getMatching('twig.extension.*');
     foreach ($extensions as $ext) {
         $twig->addExtension($ext);
     }
     return $twig;
 }
Ejemplo n.º 18
0
function Element($templateFile, array $options)
{
    global $config, $debug, $loader;
    if (function_exists('create_pm_header') && (isset($options['mod']) && $options['mod'] || isset($options['__mod']))) {
        $options['pm'] = create_pm_header();
    }
    if (isset($options['body']) && $config['debug']) {
        if (isset($debug['start'])) {
            $debug['time'] = '~' . round((microtime(true) - $debug['start']) * 1000, 2) . 'ms';
            unset($debug['start']);
        }
        $options['body'] .= '<h3>Debug</h3><pre style="white-space: pre-wrap;font-size: 10px;">' . str_replace("\n", '<br/>', utf8tohtml(print_r($debug, true))) . '</pre>';
    }
    $loader->setPaths($config['dir']['template']);
    $twig = new Twig_Environment($loader, array('autoescape' => false, 'cache' => "{$config['dir']['template']}/cache", 'debug' => $config['debug'] ? true : false));
    $twig->addExtension(new Twig_Extensions_Extension_Tinyboard());
    $twig->addExtension(new Twig_Extensions_Extension_I18n());
    // Read the template file
    if (@file_get_contents("{$config['dir']['template']}/{$templateFile}")) {
        $body = $twig->render($templateFile, $options);
        if ($config['minify_html'] && preg_match('/\\.html$/', $templateFile)) {
            $body = trim(preg_replace("/[\t\r\n]/", '', $body));
        }
        return $body;
    } else {
        throw new Exception("Template file '{$templateFile}' does not exist or is empty in '{$config['dir']['template']}'!");
    }
}
Ejemplo n.º 19
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->twig = new \Twig_Environment(new \Twig_Loader_Filesystem(array(__DIR__ . '/../../Resources/views/Form')));
     $this->twig->addExtension(new CKEditorExtension($this->helper));
     $this->template = $this->twig->loadTemplate('ckeditor_widget.html.twig');
 }
Ejemplo n.º 20
0
 private static function getInstance()
 {
     if (self::$instance) {
         return self::$instance;
     }
     $loader = new BitrixLoader($_SERVER['DOCUMENT_ROOT']);
     $c = Configuration::getInstance();
     $config = $c->get('maximaster');
     $twigConfig = (array) $config['tools']['twig'];
     $defaultConfig = array('debug' => false, 'charset' => SITE_CHARSET, 'cache' => $_SERVER['DOCUMENT_ROOT'] . '/bitrix/cache/maximaster/tools.twig', 'auto_reload' => isset($_GET['clear_cache']) && strtoupper($_GET['clear_cache']) == 'Y', 'autoescape' => false);
     $twigOptions = array_merge($defaultConfig, $twigConfig);
     $twig = new \Twig_Environment($loader, $twigOptions);
     if ($twig->isDebug()) {
         $twig->addExtension(new \Twig_Extension_Debug());
     }
     $twig->addExtension(new BitrixExtension());
     $twig->addExtension(new CustomFunctionsExtension());
     $event = new Event('', 'onAfterTwigTemplateEngineInited', array($twig));
     $event->send();
     if ($event->getResults()) {
         foreach ($event->getResults() as $evenResult) {
             if ($evenResult->getType() == \Bitrix\Main\EventResult::SUCCESS) {
                 $twig = current($evenResult->getParameters());
             }
         }
     }
     return self::$instance = $twig;
 }
Ejemplo n.º 21
0
 public function init()
 {
     $view_dir = [__DIR__ . '/../Views', __DIR__ . '/../Templates'];
     $twigConfig = [];
     if ($this->config['twig']['cache']) {
         $twigConfig["cache"] = $this->app['cache']['twig'];
     }
     $twigConfig["debug"] = $this->config['twig']['debug'];
     $loader = new \Twig_Loader_Filesystem($view_dir);
     foreach ($view_dir as $d) {
         $loader->addPath($d, 'Meister');
     }
     foreach ($this->config['modules'] as $app) {
         if (file_exists($this->app['Modules'] . $app . '/Views')) {
             $loader->addPath($this->app['Modules'] . $app . '/Views', $app);
         }
         if (file_exists($this->app['Modules'] . $app . '/Templates')) {
             $loader->addPath($this->app['Modules'] . $app . '/Templates', $app);
         }
     }
     $this->twig = new \Twig_Environment($loader, $twigConfig);
     $this->twig->addExtension(new \Twig_Extensions_Extension_I18n());
     /**
      * Verifica permissões para exibir determinada coisa
      */
     $function = new \Twig_SimpleFunction('permission', function ($rule) {
         return $this->app['auth']->checkRules($rule);
     });
     $this->twig->addFunction($function);
 }
 protected function setUp()
 {
     if (!class_exists('Symfony\\Component\\Locale\\Locale')) {
         $this->markTestSkipped('The "Locale" component is not available');
     }
     if (!class_exists('Symfony\\Component\\EventDispatcher\\EventDispatcher')) {
         $this->markTestSkipped('The "EventDispatcher" component is not available');
     }
     if (!class_exists('Symfony\\Component\\Form\\Form')) {
         $this->markTestSkipped('The "Form" component is not available');
     }
     if (!class_exists('Twig_Environment')) {
         $this->markTestSkipped('Twig is not available.');
     }
     parent::setUp();
     $rendererEngine = new TwigRendererEngine(array('form_table_layout.html.twig', 'custom_widgets.html.twig'));
     $renderer = new TwigRenderer($rendererEngine, $this->getMock('Symfony\\Component\\Form\\Extension\\Csrf\\CsrfProvider\\CsrfProviderInterface'));
     $this->extension = new FormExtension($renderer);
     $loader = new StubFilesystemLoader(array(__DIR__ . '/../../Resources/views/Form', __DIR__));
     $environment = new \Twig_Environment($loader, array('strict_variables' => true));
     $environment->addExtension(new TranslationExtension(new StubTranslator()));
     $environment->addGlobal('global', '');
     $environment->addExtension($this->extension);
     $this->extension->initRuntime($environment);
 }
 function __construct()
 {
     // This is how to call the template engine:
     // do_action('wunderground_render_template', $file_name, $data_array );
     add_action('wunderground_render_template', array(&$this, 'render'), 10, 2);
     // Set up Twig
     Twig_Autoloader::register();
     // This path should always be the last
     $base_path = trailingslashit(plugin_dir_path(Wunderground_Plugin::$file)) . 'templates';
     $this->loader = new Twig_Loader_Filesystem($base_path);
     // Tap in here to add additional template paths
     $additional_paths = apply_filters('wunderground_template_paths', array(trailingslashit(get_stylesheet_directory()) . 'wunderground'));
     foreach ($additional_paths as $path) {
         // If the directory exists
         if (is_dir($path)) {
             // Tell Twig to use it first
             $this->loader->prependPath($path);
         }
     }
     // You can force debug mode by adding `add_filter( 'wunderground_twig_debug' '__return_true' );`
     $debug = apply_filters('wunderground_twig_debug', current_user_can('manage_options') && isset($_GET['debug']));
     $this->twig = new Twig_Environment($this->loader, array('debug' => !empty($debug), 'auto_reload' => true));
     if (!empty($debug)) {
         $this->twig->addExtension(new Twig_Extension_Debug());
     }
 }
Ejemplo n.º 24
0
 public static function view($modules = NULL)
 {
     include_once __ROOT__ . 'vendor/autoload.php';
     $views = __VIEWS__;
     if (__ENV_MODE__ == "dev") {
         $cache = false;
     } else {
         $cache = true;
     }
     $loader = new \Twig_Loader_Filesystem($views);
     // Dossier contenant les templates
     if ($cache) {
         $twig = new \Twig_Environment($loader, array('debug' => false, 'cache' => $views . '/cache/', 'auto_reload' => true));
     } else {
         $twig = new \Twig_Environment($loader, array('debug' => true));
     }
     $twig->addExtension(new \Twig_Extensions_Extension_Text());
     $twig->addExtension(new \Twig_Extensions_Extension_I18n());
     $twig->addExtension(new \Twig_Extensions_Extension_Intl());
     $twig->addExtension(new \Twig_Extensions_Extension_Array());
     $twig->addExtension(new \Twig_Extensions_Extension_Date());
     $twig->addGlobal('app_name', __NAME_APPLICATION__);
     $path = array('views' => $views, 'url' => __URL_LOCAL__, 'bootstrap' => __BOOTSTRAP__);
     $twig->addGlobal('path', $path);
     $route = array('only' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
     $twig->addGlobal('route', $route);
     return $twig;
 }
Ejemplo n.º 25
0
 public function setUp()
 {
     $this->cmfHelper = $this->getMockBuilder('Symfony\\Cmf\\Bundle\\CoreBundle\\Templating\\Helper\\CmfHelper')->disableOriginalConstructor()->getMock();
     $this->cmfExtension = new CmfExtension($this->cmfHelper);
     $this->env = new \Twig_Environment(new \Twig_Loader_Array(array()));
     $this->env->addExtension($this->cmfExtension);
 }
Ejemplo n.º 26
0
 public function register(Application $app)
 {
     $app['twig'] = $app->share(function () use($app) {
         $twig = new \Twig_Environment($app['twig.loader'], isset($app['twig.options']) ? $app['twig.options'] : array());
         $twig->addGlobal('app', $app);
         if (isset($app['symfony_bridges'])) {
             if (isset($app['url_generator'])) {
                 $twig->addExtension(new TwigRoutingExtension($app['url_generator']));
             }
             if (isset($app['translator'])) {
                 $twig->addExtension(new TwigTranslationExtension($app['translator']));
             }
             if (isset($app['form.factory'])) {
                 $twig->addExtension(new TwigFormExtension(array('div_layout.html.twig')));
             }
         }
         if (isset($app['twig.configure'])) {
             $app['twig.configure']($twig);
         }
         return $twig;
     });
     $app['twig.loader'] = $app->share(function () use($app) {
         if (isset($app['twig.templates'])) {
             return new \Twig_Loader_Array($app['twig.templates']);
         } else {
             return new \Twig_Loader_Filesystem($app['twig.path']);
         }
     });
     if (isset($app['twig.class_path'])) {
         $app['autoloader']->registerPrefix('Twig_', $app['twig.class_path']);
     }
 }
Ejemplo n.º 27
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 . ')');
     }
 }
 public function setUp()
 {
     date_default_timezone_set('Europe/London');
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $this->pool = new Pool($container, '', '');
     $this->pool->setAdminServiceIds(array('sonata_admin_foo_service'));
     $this->pool->setAdminClasses(array('fooClass' => array('sonata_admin_foo_service')));
     $this->logger = $this->getMock('Psr\\Log\\LoggerInterface');
     $this->xEditableTypeMapping = array('choice' => 'select', 'boolean' => 'select', 'text' => 'text', 'textarea' => 'textarea', 'html' => 'textarea', 'email' => 'email', 'string' => 'text', 'smallint' => 'text', 'bigint' => 'text', 'integer' => 'number', 'decimal' => 'number', 'currency' => 'number', 'percent' => 'number', 'url' => 'url');
     $this->twigExtension = new SonataAdminExtension($this->pool, $this->logger);
     $this->twigExtension->setXEditableTypeMapping($this->xEditableTypeMapping);
     $loader = new StubFilesystemLoader(array(__DIR__ . '/../../../Resources/views/CRUD'));
     $this->environment = new \Twig_Environment($loader, array('strict_variables' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0));
     $this->environment->addExtension($this->twigExtension);
     // translation extension
     $translator = new Translator('en', new MessageSelector());
     $translator->addLoader('xlf', new XliffFileLoader());
     $translator->addResource('xlf', __DIR__ . '/../../../Resources/translations/SonataAdminBundle.en.xliff', 'en', 'SonataAdminBundle');
     $this->environment->addExtension(new TranslationExtension($translator));
     // routing extension
     $xmlFileLoader = new XmlFileLoader(new FileLocator(array(__DIR__ . '/../../../Resources/config/routing')));
     $routeCollection = $xmlFileLoader->load('sonata_admin.xml');
     $xmlFileLoader = new XmlFileLoader(new FileLocator(array(__DIR__ . '/../../Fixtures/Resources/config/routing')));
     $testRouteCollection = $xmlFileLoader->load('routing.xml');
     $routeCollection->addCollection($testRouteCollection);
     $requestContext = new RequestContext();
     $urlGenerator = new UrlGenerator($routeCollection, $requestContext);
     $this->environment->addExtension(new RoutingExtension($urlGenerator));
     $this->environment->addExtension(new \Twig_Extensions_Extension_Text());
     // initialize object
     $this->object = new \stdClass();
     // initialize admin
     $this->admin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $this->admin->expects($this->any())->method('getCode')->will($this->returnValue('xyz'));
     $this->admin->expects($this->any())->method('id')->with($this->equalTo($this->object))->will($this->returnValue(12345));
     $this->admin->expects($this->any())->method('getNormalizedIdentifier')->with($this->equalTo($this->object))->will($this->returnValue(12345));
     $this->admin->expects($this->any())->method('trans')->will($this->returnCallback(function ($id, $parameters = array(), $domain = null) use($translator) {
         return $translator->trans($id, $parameters, $domain);
     }));
     $this->adminBar = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $this->adminBar->expects($this->any())->method('isGranted')->will($this->returnValue(true));
     $this->adminBar->expects($this->any())->method('getNormalizedIdentifier')->with($this->equalTo($this->object))->will($this->returnValue(12345));
     // for php5.3 BC
     $admin = $this->admin;
     $adminBar = $this->adminBar;
     $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($admin, $adminBar) {
         if ($id == 'sonata_admin_foo_service') {
             return $admin;
         } elseif ($id == 'sonata_admin_bar_service') {
             return $adminBar;
         }
         return;
     }));
     // initialize field description
     $this->fieldDescription = $this->getMock('Sonata\\AdminBundle\\Admin\\FieldDescriptionInterface');
     $this->fieldDescription->expects($this->any())->method('getName')->will($this->returnValue('fd_name'));
     $this->fieldDescription->expects($this->any())->method('getAdmin')->will($this->returnValue($this->admin));
     $this->fieldDescription->expects($this->any())->method('getLabel')->will($this->returnValue('Data'));
 }
Ejemplo n.º 29
0
 /**
  * Инициализируется расширения, необходимые для работы
  */
 private function initExtensions()
 {
     if ($this->engine->isDebug()) {
         $this->engine->addExtension(new \Twig_Extension_Debug());
     }
     $this->engine->addExtension(new BitrixExtension());
     $this->engine->addExtension(new CustomFunctionsExtension());
 }
Ejemplo n.º 30
0
 public function loadTwig()
 {
     $this->twig = new \Twig_Environment(new \Twig_Loader_String(), ['debug' => true, 'autoescape' => false]);
     $this->twig->addExtension(new \Twig_Extension_Debug());
     $this->twig->addExtension(new \Foote\Ginny\Twig\InflectorExtension());
     $this->twig->addExtension(new \Foote\Ginny\Twig\GinnyExtension());
     $this->extendTwig();
 }