/** * @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']]); } } }
public function configure(\Twig_Environment $environment) { $environment->getExtension('core')->setDateFormat($this->dateFormat, $this->intervalFormat); if (null !== $this->timezone) { $environment->getExtension('core')->setTimezone($this->timezone); } $environment->getExtension('core')->setNumberFormat($this->decimals, $this->decimalPoint, $this->thousandsSeparator); }
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(); }
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(); }
/** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) { return; } $securityContext = $this->securityContext; if ($securityContext && $securityContext->getToken() instanceof TokenInterface && $securityContext->getToken()->getUser() instanceof TimeZoneInterface) { $timeZone = $securityContext->getToken()->getUser()->getTimezone(); if ($timeZone) { $this->twigEnvironment->getExtension('core')->setTimezone($timeZone); } } }
/** * Echoes the <script> tag. * */ public function includeAceEditor() { if (!$this->environment->hasExtension('asset') || $this->editorIncluded) { return; } if (!$this->editorIncluded) { foreach (array('ace', 'ext-language_tools') as $file) { $jsPath = $this->environment->getExtension('asset')->getAssetUrl($this->basePath . '/' . $this->mode . '/' . $file . '.js'); echo sprintf('<script src="%s" charset="utf-8" type="text/javascript"></script>', $jsPath); } $this->editorIncluded = true; } }
public function includeAceEditor() { if (!$this->environment->hasExtension('assets')) { return; } if (!$this->editorIncluded) { $this->editorIncluded = true; } if (!$this->ckeditorIncluded) { $jsPath = $this->environment->getExtension('assets')->getAssetUrl($this->basePath . '/' . $this->mode); echo sprintf('<script src="%s" charset="utf-8"></script>', $jsPath); $this->ckeditorIncluded = true; } }
/** * Get Twig-instance * * @return Twig_Environment */ protected static function getTwig() { if (!static::$twig) { $loader = new \Twig_Loader_Filesystem(PATH_APP . '/views'); static::$twig = new \Twig_Environment($loader, array('cache' => MAIN_SERVER ? PATH_DATA . '/twig-cache' : null, 'strict_variables' => true, 'autoescape' => false)); static::$twig->getExtension('core')->setNumberFormat(2, ',', ' '); static::$twig->addExtension(new \Kofradia\Twig\Date()); static::$twig->addExtension(new \Kofradia\Twig\Counter()); static::$twig->addExtension(new \Kofradia\Twig\Render()); static::$twig->addExtension(new \Kofradia\Twig\Helpers()); static::$twig->addGlobal("page", \ess::$b->page); static::$twig->addGlobal("helper", new \Kofradia\Twig\TemplateHelper()); } return static::$twig; }
protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) { if ($node instanceof \Twig_Node_Block) { $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needCollapsing(); } elseif ($node instanceof WhitespaceCollapse) { $this->statusStack[] = $node->getAttribute('value'); } elseif ($env->hasExtension('whitespace_collapser')) { /** @var \MatTheCat\Twig\Extension\WhitespaceCollapser $extension */ $extension = $env->getExtension('whitespace_collapser'); $extensionDefault = $extension->getDefault(); if ($node instanceof \Twig_Node_Module) { if (is_array($extensionDefault)) { $filename = $node->getAttribute('filename'); if (substr($filename, -5) === '.twig') { $filename = substr($filename, 0, -5); } $this->enabledByDefault = in_array(pathinfo($filename, PATHINFO_EXTENSION), $extensionDefault, true); } else { $this->enabledByDefault = $extensionDefault; } } elseif ($node instanceof \Twig_Node_AutoEscape) { $this->statusStack[] = is_array($extensionDefault) ? in_array($node->getAttribute('value'), $extensionDefault) : $extensionDefault; } } return $node; }
/** * Extracts formulae from filter function nodes. * * @return array|null The formula */ private function checkNode(\Twig_NodeInterface $node, \Twig_Environment $env) { if ($node instanceof \Twig_Node_Expression_Function) { $name = $node->getNode('name')->getAttribute('name'); if ($env->getFunction($name) instanceof AsseticFilterFunction) { $arguments = array(); foreach ($node->getNode('arguments') as $argument) { $arguments[] = eval('return '.$env->compile($argument).';'); } $invoker = $env->getExtension('assetic')->getFilterInvoker($name); $factory = $invoker->getFactory(); $inputs = isset($arguments[0]) ? (array) $arguments[0] : array(); $filters = $invoker->getFilters(); $options = array_replace($invoker->getOptions(), isset($arguments[1]) ? $arguments[1] : array()); if (!isset($options['name'])) { $options['name'] = $factory->generateAssetName($inputs, $filters); } return array($inputs, $filters, $options); } } }
public function __construct(\Twig_Environment $twig, LoggerInterface $logger = null) { $this->twig = $twig; $this->logger = $logger; $globals = $twig->getExtension('assetic')->getGlobals(); $this->debug = $globals['assetic']['debug']; }
/** * Renders fragment by window state. * * @param \Twig_Environment $environment * @param AbstractWindowsState $windowState * * @return string */ public function renderFragment(\Twig_Environment $environment, AbstractWindowsState $windowState) { $result = ''; $scheduleDelete = false; $windowState->setRenderedSuccessfully(false); try { $uri = $this->windowsStateRequestManager->getUri($windowState->getData()); /** @var HttpKernelExtension $httpKernelExtension */ $httpKernelExtension = $environment->getExtension('http_kernel'); $result = $httpKernelExtension->renderFragment($uri); $windowState->setRenderedSuccessfully(true); return $result; } catch (NotFoundHttpException $e) { $scheduleDelete = true; } catch (\InvalidArgumentException $e) { $scheduleDelete = true; } if ($scheduleDelete) { try { $this->windowsStateManagerRegistry->getManager()->deleteWindowsState($windowState->getId()); } catch (AccessDeniedException $e) { return $result; } } return $result; }
function let(\Twig_Environment $environment, AssetsExtension $assets, FSiFilePathResolver $filePathResolver) { $this->beConstructedWith($filePathResolver); $environment->hasExtension('assets')->shouldBeCalled()->willReturn(true); $environment->getExtension('assets')->shouldBeCalled()->willReturn($assets); $environment->getGlobals()->shouldBeCalled()->willReturn(array()); $this->initRuntime($environment); }
public function testCustomEscaper() { $twig = new Twig_Environment($this->getMock('Twig_LoaderInterface')); $twig->getExtension('core')->setEscaper('foo', 'foo_escaper_for_test'); $this->assertEquals('fooUTF-8', twig_escape_filter($twig, 'foo', 'foo')); $this->assertEquals('UTF-8', twig_escape_filter($twig, null, 'foo')); $this->assertEquals('42UTF-8', twig_escape_filter($twig, 42, 'foo')); }
/** * 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; }
protected function needEscaping(Twig_Environment $env) { if (count($this->statusStack)) { return $this->statusStack[count($this->statusStack) - 1]; } else { return $env->hasExtension('escaper') ? $env->getExtension('escaper')->isGlobal() : false; } }
public function initTypeaheadFunction(\Twig_Environment $env) { if (!TypeaheadType::$initialized) { TypeaheadType::$initialized = true; $url = $env->getExtension('assets')->getAssetUrl('bundles/lifotypeahead/js/typeaheadbundle.js'); return "<script type=\"text/javascript\" src=\"{$url}\"></script>"; } return ''; }
/** * Create the new twig contao environment */ protected function __construct() { $arrTemplatePaths = array(); $blnDebug = $GLOBALS['TL_CONFIG']['debugMode'] || $GLOBALS['TL_CONFIG']['twigDebugMode']; // Make sure the cache directory exists if (version_compare(VERSION, '2', '<=') && !is_dir(TL_ROOT . '/system/cache')) { Files::getInstance()->mkdir('system/cache'); } if (!is_dir(TL_ROOT . '/system/cache/twig')) { Files::getInstance()->mkdir('system/cache/twig'); } // Add the layout templates directory if (TL_MODE == 'FE') { global $objPage; $strTemplateGroup = str_replace(array('../', 'templates/'), '', $objPage->templateGroup); if ($strTemplateGroup != '') { $arrTemplatePaths[] = TL_ROOT . '/templates/' . $strTemplateGroup; } } // Add the global templates directory $arrTemplatePaths[] = TL_ROOT . '/templates'; // Add all modules templates directories foreach (Config::getInstance()->getActiveModules() as $strModule) { $strPath = TL_ROOT . '/system/modules/' . $strModule . '/templates'; if (is_dir($strPath)) { $arrTemplatePaths[] = $strPath; } } // Create the default array loader $this->loaderArray = new Twig_Loader_Array(array()); // Create the default filesystem loader $this->loaderFilesystem = new Twig_Loader_Filesystem($arrTemplatePaths); // Create the effective chain loader $this->loader = new Twig_Loader_Chain(); // Register the default filesystem loaders $this->loader->addLoader($this->loaderArray); $this->loader->addLoader($this->loaderFilesystem); // Create the environment $this->environment = new Twig_Environment($this->loader, array('cache' => TL_ROOT . '/system/cache/twig', 'debug' => $blnDebug, 'autoescape' => false)); // set default formats $this->environment->getExtension('core')->setNumberFormat(2, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']); // set default date format and timezone $this->environment->getExtension('core')->setDateFormat($GLOBALS['TL_CONFIG']['datimFormat']); $this->environment->getExtension('core')->setTimezone('Europe/Paris'); // Add debug extension if ($blnDebug || $GLOBALS['TL_CONFIG']['twigDebugExtension']) { $this->environment->addExtension(new Twig_Extension_Debug()); } $this->environment->addExtension(new ContaoTwigExtension()); // HOOK: custom twig initialisation if (isset($GLOBALS['TL_HOOKS']['initializeTwig']) && is_array($GLOBALS['TL_HOOKS']['initializeTwig'])) { foreach ($GLOBALS['TL_HOOKS']['initializeTwig'] as $callback) { $this->import($callback[0]); $this->{$callback}[0]->{$callback}[1]($this); } } }
/** * Twig initialization that sets the twig loader chain, then the environment, then extensions * and also the base set of twig vars */ public function init() { if (!isset($this->twig)) { /** @var Config $config */ $config = $this->grav['config']; /** @var UniformResourceLocator $locator */ $locator = $this->grav['locator']; $debugger = $this->grav['debugger']; $this->twig_paths = $locator->findResources('theme://templates'); $this->grav->fireEvent('onTwigTemplatePaths'); $this->loader = new \Twig_Loader_Filesystem($this->twig_paths); $this->loaderArray = new \Twig_Loader_Array(array()); $loader_chain = new \Twig_Loader_Chain(array($this->loaderArray, $this->loader)); $params = $config->get('system.twig'); if (!empty($params['cache'])) { $params['cache'] = $locator->findResource('cache://twig', true, true); } $this->twig = new \Twig_Environment($loader_chain, $params); if ($debugger->enabled() && $config->get('system.debugger.twig')) { $this->twig = new \DebugBar\Bridge\Twig\TraceableTwigEnvironment($this->twig); $collector = new \DebugBar\Bridge\Twig\TwigCollector($this->twig); $debugger->addCollector($collector); } if ($config->get('system.twig.undefined_functions')) { $this->twig->registerUndefinedFunctionCallback(function ($name) { if (function_exists($name)) { return new \Twig_Function_Function($name); } return new \Twig_Function_Function(function () { }); }); } if ($config->get('system.twig.undefined_filters')) { $this->twig->registerUndefinedFilterCallback(function ($name) { if (function_exists($name)) { return new \Twig_Filter_Function($name); } return new \Twig_Filter_Function(function () { }); }); } $this->grav->fireEvent('onTwigInitialized'); // set default date format if set in config if ($config->get('system.pages.dateformat.long')) { $this->twig->getExtension('core')->setDateFormat($config->get('system.pages.dateformat.long')); } // enable the debug extension if required if ($config->get('system.twig.debug')) { $this->twig->addExtension(new \Twig_Extension_Debug()); } $this->twig->addExtension(new TwigExtension()); $this->grav->fireEvent('onTwigExtensions'); // Set some standard variables for twig $this->twig_vars = array('grav' => $this->grav, 'config' => $config, 'uri' => $this->grav['uri'], 'base_dir' => rtrim(ROOT_DIR, '/'), 'base_url' => $this->grav['base_url'], 'base_url_absolute' => $this->grav['base_url_absolute'], 'base_url_relative' => $this->grav['base_url_relative'], 'theme_dir' => $locator->findResource('theme://'), 'theme_url' => $this->grav['base_url'] . '/' . $locator->findResource('theme://', false), 'site' => $config->get('site'), 'assets' => $this->grav['assets'], 'taxonomy' => $this->grav['taxonomy'], 'browser' => $this->grav['browser']); } }
/** * Constructor * * @param string $name * @param Language $language */ public function __construct() { \Twig_Autoloader::register(); $chain_loader = new \Twig_Loader_Chain([new \Twig_Loader_Filesystem(), new \Twig_Loader_String()]); $this->twig = new \Twig_Environment($chain_loader, ['cache' => Config::$cache_directory, 'auto_reload' => true, 'debug' => Config::$debug, 'autoescape' => Config::$autoescape]); if (class_exists('\\Skeleton\\I18n\\Translation')) { $this->i18n_available = true; $this->twig->addExtension(new \Skeleton\I18n\Template\Twig\Extension\Tigron()); } if (Config::$debug === true) { $this->twig->addExtension(new \Twig_Extension_Debug()); } $this->twig->addExtension(new \Skeleton\Template\Twig\Extension\Common()); $this->twig->addExtension(new \Twig_Extension_StringLoader()); $this->twig->addExtension(new \Twig_Extensions_Extension_Text()); $parser = new \Skeleton\Template\Twig\Extension\Markdown\Engine(); $parser->single_linebreak = true; $this->twig->addExtension(new MarkdownExtension($parser)); $this->twig->getExtension('core')->setNumberFormat(2, '.', ''); }
/** * Render html element attributes. * This function is only for internal use. * * @param array $attributes * @param null $translationDomain * @return string */ public function datagridAttributes(array $attributes, $translationDomain = null) { $attrs = array(); foreach ($attributes as $attributeName => $attributeValue) { if ($attributeName == 'title') { $attrs[] = $attributeName . '="' . $this->environment->getExtension('translator')->trans($attributeValue, array(), $translationDomain) . '"'; continue; } $attrs[] = $attributeName . '="' . $attributeValue . '"'; } return ' ' . implode(' ', $attrs); }
public function contentCollection($key, $type, array $arguments = array(), $default = null, $noedit = false) { $debugmessage = ''; if ($this->env->isDebug()) { $debugmessage .= "<!--debug IbrowsSimpleCMS Collection\n"; $debugmessage .= "type={$type} \n"; $debugmessage .= "key={$key} \n"; $debugmessage .= "default={$default} \n"; $debugmessage .= "arguments=" . print_r($arguments, true) . " \n"; $debugmessage .= '-->'; if ($default == null) { $default = "{$key}-{$type}"; } } $objs = $this->manager->findAll($type, $key); $out = ''; $grant = $this->handler->isGranted('ibrows_simple_cms_content'); if ($noedit) { $grant = false; } $addkey = $this->manager->getNewGroupKey($key, $objs); if ($objs) { foreach ($objs as $objkey => $content) { /* @var $content \Ibrows\SimpleCMSBundle\Entity\ContentInterface */ $outobj = $debugmessage . $content->toHTML($this, $arguments); if ($grant && $this->handler->isGranted('ibrows_simple_cms_content_edit_key', array('key' => $content->getKeyword(), 'type' => $type))) { $outobj = $this->wrapOutputForEdit($outobj, $content->getKeyword(), $type, $arguments, $default); } $out .= $outobj; } } else { if (!$grant) { $out = $default; } } if (!$grant) { return $out; } $class = ''; if (isset($arguments['inline']) && $arguments['inline'] == true) { $class = 'inline'; } //addlink if ($this->handler->isGranted('ibrows_simple_cms_content_create', array('type' => $type))) { $editpath = $this->env->getExtension('routing')->getPath('ibrows_simple_cms_content_edit_key', array('key' => $addkey, 'type' => $type)); $editpath .= "?args=" . urlencode(serialize($arguments)); $editpath .= "&default=" . $default; $outadd = '<a href="' . $editpath . '" class="simplecms-editlink simplecms-addlink" > </a> ADD ' . $default . ''; $outadd = "<div class=\"simplcms-{$addkey}-{$type} simplecms-edit simplecms-add {$class}\" id=\"simplcms-{$addkey}-{$type}\" >{$outadd}</div>"; } return "<div class=\"simplcms-collection-{$key}-{$type} simplecms-edit-collection {$class}\" id=\"simplcms-collection-{$key}-{$type}\" >{$out}{$outadd}</div>"; }
/** * Called before child nodes are visited. * * @param Twig_NodeInterface $node The node to visit * @param Twig_Environment $env The Twig environment instance * * @return Twig_NodeInterface The modified node */ public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { if ($env->hasExtension('escaper') && ($defaultStrategy = $env->getExtension('escaper')->getDefaultStrategy($node->getAttribute('filename')))) { $this->defaultStrategy = $defaultStrategy; } } elseif ($node instanceof Twig_Node_AutoEscape) { $this->statusStack[] = $node->getAttribute('value'); } elseif ($node instanceof Twig_Node_Block) { $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env); } return $node; }
/** * * @param ContaoTwigConfig $config * * @return void * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ private function addDefaultFormats(ContaoTwigConfig $config) { if ($config->isSetNumberFormat()) { $this->environment->getExtension('core')->setNumberFormat(2, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']); } // set default date format and timezone if ($config->isSetDateFormat()) { $this->environment->getExtension('core')->setDateFormat($GLOBALS['TL_CONFIG']['datimFormat']); } if ($config->isSetTimeZone()) { $this->environment->getExtension('core')->setTimezone($GLOBALS['TL_CONFIG']['timeZone']); } }
/** * {@inheritdoc} */ public function __construct($templatesPath, $config) { $loaderFS = new \Twig_Loader_Filesystem($templatesPath); $loaderArray = new \Twig_Loader_Array(['redirect.html.twig' => '<!DOCTYPE html> <html> <head lang="en"> <link rel="canonical" href="{{ url(page.destination) }}"/> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="refresh" content="0;url={{ url(page.destination) }}" /> </head> </html>']); $loader = new \Twig_Loader_Chain([$loaderArray, $loaderFS]); $this->twig = new \Twig_Environment($loader, ['autoescape' => false, 'strict_variables' => $this->twigStrict, 'debug' => $this->twigDebug, 'cache' => $this->twigCache]); $this->twig->addExtension(new \Twig_Extension_Debug()); $this->twig->addExtension(new TwigExtension($config->getOutputPath())); $this->twig->getExtension('core')->setDateFormat($config->get('site.date.format')); $this->twig->getExtension('core')->setTimezone($config->get('site.date.timezone')); // excerpt filter $excerptFilter = new \Twig_SimpleFilter('excerpt', function ($string, $length = 450, $suffix = '…') { $str = trim(strip_tags($string)); if (mb_strlen($str) > $length) { $string = mb_substr($string, 0, $length) . $suffix; } return $string; }); $this->twig->addFilter($excerptFilter); // read time function $readtimeFunction = new \Twig_SimpleFunction('readtime', function ($text) { $words = str_word_count(strip_tags($text)); $min = floor($words / 200); if ($min === 0) { return '1'; } return $min; }); $this->twig->addFunction($readtimeFunction); $this->fs = new Filesystem(); }
private function wrapOutputForEdit($out,$key, $type, array $arguments = array(), $default=''){ $class = ''; if(isset($arguments['inline']) && $arguments['inline'] == true ){ $class = 'inline'; } $editpath = $this->env->getExtension('routing')->getPath('ibrows_simple_cms_content_edit_key', array('key' => $key, 'type' => $type)); $editpath .="?args=" . urlencode(serialize($arguments)); $editpath .="&default=" . $default; $out = '<a href="' . $editpath . '" class="simplecms-editlink" ></a>' . $out; $out = '<a href="' . $this->env->getExtension('routing')->getPath('ibrows_simple_cms_content_delete_key', array('key' => $key, 'type' => $type)) . '" class="simplecms-deletelink" > </a>' . $out; $out = "<div class=\"simplecms-edit $class\" id=\"simplcms-$key-$type\" >$out</div>"; return $out; }
/** * {@inheritdoc} */ protected function doEnterNode(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { if ($env->hasExtension('escaper') && ($defaultStrategy = $env->getExtension('escaper')->getDefaultStrategy($node->getAttribute('filename')))) { $this->defaultStrategy = $defaultStrategy; } $this->safeVars = array(); } elseif ($node instanceof Twig_Node_AutoEscape) { $this->statusStack[] = $node->getAttribute('value'); } elseif ($node instanceof Twig_Node_Block) { $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env); } elseif ($node instanceof Twig_Node_Import) { $this->safeVars[] = $node->getNode('var')->getAttribute('name'); } return $node; }
public function render($file, array $context = array()) { $gantry = \Gantry\Framework\Gantry::instance(); /** @var UniformResourceLocator $locator */ $locator = $gantry['locator']; $loader = new \Twig_Loader_Filesystem($locator->findResources('gantry-engine://twig')); $params = array('cache' => $locator('gantry-cache://twig', true, true), 'debug' => true, 'auto_reload' => true, 'autoescape' => 'html'); // FIXME: Get timezone from WP. $timezone = 'UTC'; $twig = new \Twig_Environment($loader, $params); $twig->getExtension('core')->setTimezone(new \DateTimeZone($timezone)); $this->add_to_twig($twig); // Include Gantry specific things to the context. $context = $this->add_to_context($context); return $twig->render($file, $context); }
/** * Initializer. * * @param Application $app */ public function __construct(Application $app) { $this->app = $app; $this->site = new Site($app); // Set asset manifest $this->manifest = new AssetManifest($this->app->getEnvironment()); // Set system paths $this->target = $this->app->getTarget(); $this->source = $this->app->getSource(); // Check paths $fs = new Filesystem(); if (!$fs->exists($this->source)) { throw new \Exception("Source folder not found at \"{$this->source}\"."); } // Ensure we have a target if (!$fs->exists($this->target)) { $fs->mkdir($this->target); } // Setup a twig loader $loader = new Twig_Loader_Chain(); $loader->addLoader(new Twig\Loader($this->site)); // If a template directory exists, add a filesystem loader to resolve // templates residing within it $templateDir = $this->source . DIRECTORY_SEPARATOR . "_templates"; if (is_dir($templateDir)) { $loader->addLoader(new Twig_Loader_Filesystem($templateDir)); } $includesDir = $this->source . DIRECTORY_SEPARATOR . "_includes"; if (is_dir($includesDir)) { $loader->addLoader(new Twig_Loader_Filesystem($includesDir)); } // Full template rendering $this->twig = new Twig_Environment($loader, ['debug' => true]); // Make the site variable global $this->twig->addGlobal('site', $this->site); // Add an escaper for XML $this->twig->getExtension('core')->setEscaper('xml', function ($env, $content) { return htmlentities($content, ENT_COMPAT | ENT_XML1); }); // Add build in extensions $this->twig->addExtension(new Twig\Extension($this)); $this->registerTwigExtensions(); // Fire booted event Event::fire('builder.booted', [$this]); }
/** * @param \Symfony\Component\HttpFoundation\Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function setObjectFieldValueAction(Request $request) { $field = $request->get('field'); $code = $request->get('code'); $objectId = $request->get('objectId'); $value = $request->get('value'); $context = $request->get('context'); $admin = $this->pool->getInstance($code); // alter should be done by using a post method if ($request->getMethod() != 'POST') { return new Response(json_encode(array('status' => 'KO', 'message' => 'Expected a POST Request')), 200, array('Content-Type' => 'application/json')); } $object = $admin->getObject($objectId); if (!$object) { return new Response(json_encode(array('status' => 'KO', 'message' => 'Object does not exist')), 200, array('Content-Type' => 'application/json')); } // check user permission if (false === $admin->isGranted('EDIT', $object)) { return new Response(json_encode(array('status' => 'KO', 'message' => 'Invalid permissions')), 200, array('Content-Type' => 'application/json')); } if ($context == 'list') { $fieldDescription = $admin->getListFieldDescription($field); } else { return new Response(json_encode(array('status' => 'KO', 'message' => 'Invalid context')), 200, array('Content-Type' => 'application/json')); } if (!$fieldDescription) { return new Response(json_encode(array('status' => 'KO', 'message' => 'The field does not exist')), 200, array('Content-Type' => 'application/json')); } if (!$fieldDescription->getOption('editable')) { return new Response(json_encode(array('status' => 'KO', 'message' => 'The field cannot be edit, editable option must be set to true')), 200, array('Content-Type' => 'application/json')); } // TODO : call the validator component ... $propertyPath = new PropertyPath($field); $propertyPath->setValue($object, $value); $admin->update($object); // render the widget // todo : fix this, the twig environment variable is not set inside the extension ... $extension = $this->twig->getExtension('sonata_admin'); $extension->initRuntime($this->twig); $content = $extension->renderListElement($object, $fieldDescription); return new Response(json_encode(array('status' => 'OK', 'content' => $content)), 200, array('Content-Type' => 'application/json')); }