protected function initialiseExtensions($config) { if (isset($config['built_in_extentions'])) { $built_in_ext = $config['built_in_extentions']; if (in_array('form', $built_in_ext)) { $formEngine = new TwigRendererEngine(array('form_div_layout.html.twig')); $formEngine->setEnvironment($this); $this->addExtension(new TranslationExtension($this->translator_service)); $this->addExtension(new FormExtension(new TwigRenderer($formEngine, $this->csrf_provider_service))); } } }
function initTwig(ContainerInterface $container, TranslatorInterface $translator) { $appVariableReflection = new \ReflectionClass('\\Symfony\\Bridge\\Twig\\AppVariable'); $twigLoader = new \Twig_Loader_Filesystem([VIEWS_PATH, dirname($appVariableReflection->getFileName()) . '/Resources/views/Form']); $twig = new \Twig_Environment($twigLoader); $formEngine = new TwigRendererEngine(['bootstrap_3_horizontal_layout.html.twig']); $formEngine->setEnvironment($twig); $twig->addExtension(new FormExtension(new TwigRenderer($formEngine, $container->get('csrf_token.manager')))); $twig->addExtension(new TranslationExtension($translator)); $container->set('twig', $twig); return $twig; }
private function __construct() { $csrfTokenManager = new CsrfTokenManager(); $validator = Validation::createValidator(); $localCode = substr(get_locale(), 0, 2); $translator = new Translator($localCode); $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource('xlf', VENDOR_FORM_DIR . '/Resources/translations/validators.en.xlf', $localCode, 'validators'); $translator->addResource('xlf', VENDOR_VALIDATOR_DIR . '/Resources/translations/validators.en.xlf', $localCode, 'validators'); $twig = herbert('Twig_Environment'); $formEngine = new TwigRendererEngine(array(DEFAULT_FORM_THEME)); $formEngine->setEnvironment($twig); $twig->addExtension(new TranslationExtension($translator)); $twig->addExtension(new FormExtension(new TwigRenderer($formEngine, $csrfTokenManager))); $this->formFactory = Forms::createFormFactoryBuilder()->addExtension(new CsrfExtension($csrfTokenManager))->addExtension(new ValidatorExtension($validator))->getFormFactory(); }
/** * Fetch the parsed content from this template. * * @param string $template The location of the template file, used to display this template. * * @return string The actual parsed content after executing this template. */ public function getContent($template) { $this->parseConstants(); $this->parseAuthentication(); $this->parseAuthenticatedUser(); $this->parseDebug(); $this->parseLabels(); $this->parseLocale(); $this->parseVars(); $template = str_replace(BACKEND_MODULES_PATH, '', $template); // path to TwigBridge library so we can locate the form theme files. $appVariableReflection = new ReflectionClass(AppVariable::class); $vendorTwigBridgeDir = dirname($appVariableReflection->getFileName()); // render the compiled File $loader = new Twig_Loader_Filesystem(array(BACKEND_MODULES_PATH, BACKEND_CORE_PATH, $vendorTwigBridgeDir . '/Resources/views/Form')); $twig = new Twig_Environment($loader, array('cache' => Model::getContainer()->getParameter('kernel.cache_dir') . '/twig', 'debug' => $this->debugMode)); // connect symphony forms $formEngine = new TwigRendererEngine(array('Layout/Templates/FormLayout.html.twig')); $formEngine->setEnvironment($twig); $twig->addExtension(new SymfonyFormExtension(new TwigRenderer($formEngine, Model::get('security.csrf.token_manager')))); $twigTranslationExtensionClass = Model::getContainer()->getParameter('twig.extension.trans.class'); $twig->addExtension(new $twigTranslationExtensionClass(Model::get('translator'))); // debug options if ($this->debugMode === true) { $twig->addExtension(new Twig_Extension_Debug()); } if (count($this->forms) > 0) { foreach ($this->forms as $form) { $twig->addGlobal('form_' . $form->getName(), $form); } } // should always be included, makes it possible to parse SpoonForm in twig new FormExtension($twig); // start the filters / globals TwigFilters::getFilters($twig, 'Backend'); $this->startGlobals($twig); return $twig->render($template, $this->variables); }
public function __construct() { if (DEV_MODE) { $options = array('cache' => false); } else { $options = array('cache' => ROOT_PATH . '/app/cache/twig'); } $loader = new \Twig_Loader_Filesystem(array(ROOT_PATH . '/src/Views', ROOT_PATH . '/app/views', ROOT_PATH . '/app/views/form')); parent::__construct($loader, $options); //form layout $formEngine = new TwigRendererEngine(array('form_div_layout.html.twig')); $formEngine->setEnvironment($this); //security $csrfSecret = md5(rand(0, 10000000000000000)); $session = new Session(); $csrfProvider = new SessionCsrfProvider($session, $csrfSecret); $this->addExtension(new FormExtension(new TwigRenderer($formEngine, $csrfProvider))); //translator $translator = new Translator('en'); $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource('xlf', ROOT_PATH . 'app/views/form/translation/messages.en.xlf', 'en'); $this->addExtension(new TranslationExtension($translator)); }
/** * The constructor will store the instance in the reference, preset some settings and map the custom modifiers. */ public function __construct() { parent::__construct(func_get_arg(0), func_get_arg(1), func_get_arg(2)); $this->debugMode = Model::getContainer()->getParameter('kernel.debug'); $this->forkSettings = Model::get('fork.settings'); // fork has been installed if ($this->forkSettings) { $this->themePath = FRONTEND_PATH . '/Themes/' . $this->forkSettings->get('Core', 'theme', 'default'); $loader = $this->environment->getLoader(); $loader = new \Twig_Loader_Chain(array($loader, new \Twig_Loader_Filesystem($this->getLoadingFolders()))); $this->environment->setLoader($loader); // connect symphony forms $formEngine = new TwigRendererEngine($this->getFormTemplates('FormLayout.html.twig')); $formEngine->setEnvironment($this->environment); $this->environment->addExtension(new SymfonyFormExtension(new TwigRenderer($formEngine, Model::get('security.csrf.token_manager')))); } $this->environment->disableStrictVariables(); // init Form extension new FormExtension($this->environment); // start the filters / globals TwigFilters::getFilters($this->environment, 'Frontend'); $this->startGlobals($this->environment); }
/** * @return mixed * * @throws BadExtensionException * @throws ClassNotExistsException */ public function build() { $twigLoader = new \Twig_Loader_Filesystem([APPLICATION_DIR, ROOT_DIR . '/vendor/inisire/framework/src', ROOT_DIR . '/vendor/symfony/twig-bridge/Resources/views/Form']); $twig = new \Twig_Environment($twigLoader, ['cache' => ROOT_DIR . '/cache/twig', 'debug' => true]); $translator = $this->container->get('translator'); $formEngine = new TwigRendererEngine(array('Framework/Module/Administration/View/form_theme.html.twig')); $formEngine->setEnvironment($twig); $twig->addExtension(new FormExtension(new TwigRenderer($formEngine))); $twig->addExtension(new TranslationExtension($translator)); // Register custom extensions $extensions = $this->container->configuration->get('extensions', []); foreach ($extensions as $class) { if (!class_exists($class)) { throw new ClassNotExistsException($class); } $instance = new $class(); if (!$instance instanceof Extension) { throw new BadExtensionException($class); } $instance->setContainer($this->container); $twig->addExtension($instance); } return $twig; }
/** * 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))); }
private function setFormEngine() { $formEngine = new TwigRendererEngine(array($this->defaultFormTheme)); $formEngine->setEnvironment($this->getTwig()->getEnvironment()); $this->getTwig()->getEnvironment()->addExtension(new FormExtension(new TwigRenderer($formEngine))); }
/** * {@inheritdoc} */ public function loadService() { $this->getContainer()->setShared('twig', function () { $loader = new \Twig_Loader_Filesystem([]); $loader->addPath(SRC_DIR . "/App/Resource/template"); foreach (Bundles::getLoaded() as $bundleName) { if (is_dir(SRC_DIR . "/{$bundleName}/Resource/template/")) { $loader->addPath(SRC_DIR . "/{$bundleName}/Resource/template", $bundleName); } } $loader->addPath(ROOT_DIR . '/vendor/symfony/twig-bridge/Resources', 'TwigBridgeTemplates'); if (Config::get('debug', false)) { $options = ['debug' => true, 'cache' => false]; } else { $options = ['debug' => false, 'cache' => CACHE_DIR . '/twig/']; } $twig = new \Twig_Environment($loader, $options); if (Config::get('debug', false)) { $twig->addExtension(new Twig_Extension_Debug()); } // add route generator function $twig->addFunction(new \Twig_SimpleFunction('generateUrl', function ($url = null, $withParams = true, $withLanguage = true, $incDomain = true) { $router = $this->getRouter(); return $router->generateUrl($url, [Router::GEN_OPT_LANGUAGE => $withLanguage, Router::GEN_OPT_WITH_PARAMS => $withParams, Router::GEN_OPT_INC_DOMAIN => $incDomain]); })); $twig->addFunction(new \Twig_SimpleFunction('getService', function ($name, array $args = []) { return $this->getContainer()->get($name, $args); })); /** @var Registry $registry */ $registry = $this->getContainer()->get('registry'); // return css tags $twig->addFunction(new \Twig_SimpleFunction('getCss', function ($css = null, $priority = 0) use($registry) { $result = $registry->get(TwigHelper::GLOBAL_CSS, TwigHelper::TWIG_REGISTRY_SCOPE); if (null !== $css) { $result = [['css' => $css, 'priority' => $priority]]; } if (is_array($result)) { foreach ($result as $row) { $order[] = $row['priority']; } array_multisort($order, $result); array_walk($result, function (&$item) { $item = $item['css']; // if it is direct link to file if (strpos($item, 'file://') === 0) { $item = substr($item, 7); $item = "<link rel=\"stylesheet\" href=\"{$item}\">"; } else { $item = "<style>\n{$item}\n</style>"; } }); $result = implode("\n", $result); } return strval($result); }, ['is_safe' => ['html']])); // return js tags $twig->addFunction(new \Twig_SimpleFunction('getJs', function ($js = null, $priority = 0) use($registry) { $result = $registry->get(TwigHelper::GLOBAL_JS, TwigHelper::TWIG_REGISTRY_SCOPE); if (null !== $js) { $result = [['js' => $js, 'priority' => $priority]]; } if (is_array($result)) { foreach ($result as $row) { $order[] = $row['priority']; } array_multisort($order, $result); array_walk($result, function (&$item) { $item = $item['js']; // if it is direct link to file if (strpos($item, 'file://') === 0) { $item = substr($item, 7); $item = "<script src=\"{$item}\"></script>"; } else { $item = "<script>\n{$item}\n</script>"; } }); $result = implode("\n", $result); } return strval($result); }, ['is_safe' => ['html']])); $twig->addFunction(new \Twig_SimpleFunction('addCss', function ($css, $priority = 0) { TwigHelper::addCss($css, $priority); })); $twig->addFunction(new \Twig_SimpleFunction('addJs', function ($js, $priority = 0) { TwigHelper::addJs($js, $priority); })); // return master twig $twig->addFunction(new \Twig_SimpleFunction('getMasterTwig', function () use($registry) { $result = $registry->get(TwigHelper::MASTER_TWIG, TwigHelper::TWIG_REGISTRY_SCOPE); $item = array_pop($result); $registry->set(TwigHelper::MASTER_TWIG, $result, TwigHelper::TWIG_REGISTRY_SCOPE); return strval($item); }, ['is_safe' => ['html']])); Library\Helper::addMasterTwig('@App/master.twig'); $renderer = new TwigRendererEngine(['@TwigBridgeTemplates/views/Form/form_div_layout.html.twig']); $renderer->setEnvironment($twig); $twig->addExtension(new FormExtension(new TwigRenderer($renderer))); $twig->addExtension(new TranslationExtension(new IdentityTranslator())); return $twig; }); $this->getContainer()->setShared('form_factory', function () { if (class_exists('Symfony\\Component\\Validator\\Mapping\\Factory\\LazyLoadingMetadataFactory')) { $metadataFactory = new LazyLoadingMetadataFactory(new StaticMethodLoader()); } else { $metadataFactory = new ClassMetadataFactory(new StaticMethodLoader()); } $builder = Validation::createValidatorBuilder()->setConstraintValidatorFactory(new ConstraintValidatorFactory())->setTranslationDomain('validators')->setMetadataFactory($metadataFactory); $extensions = [new HttpFoundationExtension(), new ValidatorExtension($builder->getValidator())]; return Forms::createFormFactoryBuilder()->addExtensions($extensions)->setResolvedTypeFactory(new ResolvedFormTypeFactory())->getFormFactory(); }); }
/** * Determines if the calling plugin is currently active (that is, it was requested). * If so, configure Orchestra for this plugin (e.g. setting namespace, directories etc.) * and construct a front controller to handle the current request. * * @param $pluginNamespace * @param $pluginDirectory * @param array $additionalNamespaces * @param array $additionalPrefixes * @param array $directories * @return mixed */ public static function setupPlugin($pluginNamespace, $pluginDirectory, $additionalNamespaces = array(), $additionalPrefixes = array(), $directories = array('src' => '/src', 'views' => '/resources/views', 'cache' => '/data/cache')) { global $orchestraConfig; global $orchestraClassLoader; // If there is no $request set yet, create one from globals // This needs to be done only once because the request is the // same, no matter which plugin called Framework::setupPlugin() // Also, make sure to undo WP addslasjes madness // Code is taken from Request::createFromGlobals() if (!self::$request) { $request = new Request(stripslashes_deep($_GET), stripslashes_deep($_POST), array(), stripslashes_deep($_COOKIE), stripslashes_deep($_FILES), stripslashes_deep($_SERVER)); if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))) { parse_str($request->getContent(), $data); $request->request = new ParameterBag($data); } self::$request = $request; } // Generate plugin identifier based on the namespace by stripping the backslashes $pluginIdentifier = str_replace('\\', '', $pluginNamespace); // Only proceed if the requested page is the calling plugin if (self::$request->query->get('page') == $pluginIdentifier) { // Register the namespace of the calling plugin // and any additional namespaces passed $additionalNamespaces[$pluginNamespace] = $pluginDirectory . $directories['src'] . '/'; $orchestraClassLoader->registerNamespaces($additionalNamespaces); // Register prefixes is passed if (count($additionalPrefixes) > 0) { $orchestraClassLoader->registerPrefixes($additionalPrefixes); } self::$pluginNamespace = $pluginNamespace; // Boot Doctrine and use the configuration of the active plugin if (!class_exists("Doctrine\\Common\\Version", false)) { include_once $pluginDirectory . '/doctrine-config.php'; include_once __DIR__ . '/../../includes/bootstrap-doctrine.php'; } // Setup Twig $translator = new Translator($orchestraConfig['language']); $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource('xlf', $orchestraConfig['vendorDir'] . '/symfony/form/Symfony/Component/Form/Resources/translations/validators.' . $orchestraConfig['language'] . '.xlf', $orchestraConfig['language'], 'validators'); $translator->addResource('xlf', $orchestraConfig['vendorDir'] . '/symfony/validator/Symfony/Component/Validator/Resources/translations/validators.' . $orchestraConfig['language'] . '.xlf', $orchestraConfig['language'], 'validators'); $loader = new \Twig_Loader_Filesystem(array(realpath($pluginDirectory . $directories['views']), $orchestraConfig['vendorDir'] . '/symfony/twig-bridge/Symfony/Bridge/Twig/Resources/views/Form')); $twigFormEngine = new TwigRendererEngine(array('form_div_layout.html.twig')); $twigEnvironmentOptions = array(); if ($orchestraConfig['env'] == 'prod') { $twigEnvironmentOptions['cache'] = realpath($pluginDirectory . $directories['cache']); } else { $twigEnvironmentOptions['cache'] = false; } $twig = new \Twig_Environment($loader, $twigEnvironmentOptions); $twig->addGlobal('wp', new WordpressProxy()); $twig->addExtension(new PluginBaseExtension(self::$request)); $twig->addExtension(new TranslationExtension($translator)); $twig->addExtension(new FormExtension(new TwigRenderer($twigFormEngine, null))); $twigFormEngine->setEnvironment($twig); // Setup the form factory with all CSRF and validator extensions $csrfProvider = new DefaultCsrfProvider($orchestraConfig['csrfSecret']); $validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator(); $formFactory = Forms::createFormFactoryBuilder()->addExtension(new CsrfExtension($csrfProvider))->addExtension(new ValidatorExtension($validator))->getFormFactory(); // Instantiate FrontController self::$frontController = new FrontController(self::$request, $em, $twig, $formFactory); } // Return the generated plugin identifier for use // inside the plugin, e.g. in add_menu_page() return $pluginIdentifier; }
private function addFormExtension(\Twig_environment $environment) { $engine = new TwigRendererEngine(array($this->form_theme)); $engine->setEnvironment($environment); $environment->addExtension(new FormExtension(new TwigRenderer($engine, $this->csrf_token_manager))); }
private function setUpTwig() { $cacheDir = $this->isDebug() ? null : $this->getCacheDir() . '/twig'; // Set up the twig templating environment to parse views $loader = new Twig_Loader_Filesystem(__DIR__ . '/../views'); $twig = new Twig_Environment($loader, array('cache' => $cacheDir, 'debug' => $this->isDebug())); // Load the routing extension to twig, which adds functions such as path() $formEngine = new TwigRendererEngine(array('form_layout.html.twig')); $formEngine->setEnvironment($twig); $twig->addExtension(new RoutingExtension(Service::getGenerator())); $twig->addExtension(new FormExtension(new TwigRenderer($formEngine))); $twig->addExtension(new ImagineExtension($this->container->get('liip_imagine.cache.manager'))); $twig->addExtension(new AssetExtension($this->container->get('assets.packages'))); $twig->addExtension(new StopwatchExtension($this->container->get('debug.stopwatch', null))); if ($this->getEnvironment() == 'profile') { $twig->addExtension(new DumpExtension($this->container->get('var_dumper.cloner'))); } $twig->addFunction(LinkToFunction::get()); $twig->addFilter(HumanDateFilter::get()); $twig->addFilter(TruncateFilter::get()); $twig->addFilter(MarkdownFilter::get()); $twig->addFilter(PluralFilter::get()); $twig->addFilter(YesNoFilter::get()); $twig->addTest(ValidTest::get()); $twig->addTest(InvalidTest::get()); if ($this->isDebug()) { $twig->addExtension(new Twig_Extension_Debug()); } Service::setTemplateEngine($twig); }
use Symfony\Component\Form\Forms; use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Form\Extension\Csrf\CsrfExtension; use Symfony\Component\Security\Csrf\CsrfTokenManager; use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\Loader\XliffFileLoader; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Extension\FormExtension; use Symfony\Bridge\Twig\Form\TwigRenderer; define('DEFAULT_FORM_THEME', 'form_div_layout.html.twig'); define('VENDOR_DIR', realpath(__DIR__ . '/../vendor')); define('VENDOR_FORM_DIR', VENDOR_DIR . '/symfony/form'); define('VENDOR_VALIDATOR_DIR', VENDOR_DIR . '/symfony/validator'); define('VENDOR_TWIG_BRIDGE_DIR', VENDOR_DIR . '/symfony/twig-bridge'); define('VIEWS_DIR', realpath(__DIR__ . '/../views')); // Set up the CSRF Token Manager $csrfTokenManager = new CsrfTokenManager(); // Set up the Validator component $validator = Validation::createValidator(); // Set up the Translation component $translator = new Translator('en'); $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource('xlf', VENDOR_FORM_DIR . '/Resources/translations/validators.en.xlf', 'en', 'validators'); $translator->addResource('xlf', VENDOR_VALIDATOR_DIR . '/Resources/translations/validators.en.xlf', 'en', 'validators'); $twig = new Twig_Environment(new Twig_Loader_Filesystem(array(VIEWS_DIR, VENDOR_TWIG_BRIDGE_DIR . '/Resources/views/Form'))); $formEngine = new TwigRendererEngine(array(DEFAULT_FORM_THEME)); $formEngine->setEnvironment($twig); $twig->addExtension(new TranslationExtension($translator)); $twig->addExtension(new FormExtension(new TwigRenderer($formEngine, $csrfTokenManager))); // Set up the Form component $formFactory = Forms::createFormFactoryBuilder()->addExtension(new CsrfExtension($csrfTokenManager))->addExtension(new ValidatorExtension($validator))->getFormFactory();
protected function setupForms() { // Set up the CSRF provider $csrfProvider = new DefaultCsrfProvider(CSRF_SECRET); // Set up the Translation component $translator = new Translator('en'); $translator->setFallbackLocale(array('en')); $translator->setLocale('en'); $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource('xlf', VENDOR_FORM_DIR . '/Resources/translations/validators.en.xlf', 'en', 'validators'); $translator->addResource('xlf', VENDOR_VALIDATOR_DIR . '/Resources/translations/validators.en.xlf', 'en', 'validators'); // Set up the Validator component $validator = Validation::createValidatorBuilder()->setTranslator($translator)->setTranslationDomain('validators')->getValidator(); $formEngine = new TwigRendererEngine(array(DEFAULT_FORM_THEME)); $twig = $this->view->getInstance(); $formEngine->setEnvironment($twig); $twig->addExtension(new TranslationExtension($translator)); $twig->addExtension(new FormExtension(new TwigRenderer($formEngine, $csrfProvider))); // Set up the Form component $this->form = Forms::createFormFactoryBuilder()->addExtension(new CsrfExtension($csrfProvider))->addExtension(new ValidatorExtension($validator))->getFormFactory(); }