public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); $routes = $this->router->getRouteCollection(); $route = $routes->get($request->attributes->get('_route')); if (!$route->getOption('requires_license')) { return; } if ('active' != $request->get('lic') && $this->kernel->getEnvironment() == 'prod') { // Checking for whitelisted users try { $user = $this->tokenStorage->getToken()->getUser(); $today = date('Y-m-d'); if ($user instanceof UserInterface) { $whitelist = $this->kernel->getContainer()->getParameter('license_whitelist'); foreach ($whitelist as $allowed) { if ($allowed['client_key'] == $user->getClientKey() && $today <= $allowed['valid_till']) { return; } } } } catch (\Exception $e) { // Do nothing } $url = $this->router->generate('atlassian_connect_unlicensed'); $response = new RedirectResponse($url); $event->setResponse($response); } }
/** * {@inheritDoc} */ public function process(ContainerBuilder $container) { if ('test' === $this->kernel->getEnvironment()) { $definition = $container->getDefinition('translator.default'); $definition->setClass('Braincrafted\\Bundle\\TestingBundle\\Translator\\NoTranslator'); } }
/** * Constructor. * * @param KernelInterface $kernel A KernelInterface instance */ public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; parent::__construct('Symfony', Kernel::VERSION . ' - ' . $kernel->getName() . '/' . $kernel->getEnvironment() . ($kernel->isDebug() ? '/debug' : '')); $this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment())); $this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.')); }
/** * @param ConsoleTerminateEvent $event */ public function onConsoleTerminate(ConsoleTerminateEvent $event) { $command = $event->getCommand(); $environment = $this->kernel->getEnvironment(); if ($environment == 'test' && $command instanceof LoadMigrationsCommand && $event->getInput()->getOption('force')) { $executor = new CommandExecutor($environment, $event->getOutput(), $command->getApplication()); $executor->runCommand('oro:test:schema:update', ['--process-isolation' => true]); } }
/** * @return array */ protected function getCoreBundlesClasses() { $bundles = [\Symfony\Bundle\FrameworkBundle\FrameworkBundle::class, \Symfony\Bundle\SecurityBundle\SecurityBundle::class, \Symfony\Bundle\TwigBundle\TwigBundle::class, \Symfony\Bundle\MonologBundle\MonologBundle::class, \Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class, \Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class, \Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle::class, \Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class, \Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class, \Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class, \FOS\JsRoutingBundle\FOSJsRoutingBundle::class, \Bazinga\Bundle\JsTranslationBundle\BazingaJsTranslationBundle::class, \Liip\ImagineBundle\LiipImagineBundle::class, \Knp\DoctrineBehaviors\Bundle\DoctrineBehaviorsBundle::class, \Cache\AdapterBundle\CacheAdapterBundle::class, \WellCommerce\Bundle\AppBundle\WellCommerceAppBundle::class]; if (in_array($this->kernel->getEnvironment(), ['dev', 'test'])) { $bundles[] = \Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class; $bundles[] = \Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle::class; } return $bundles; }
/** * Constructor. * * @param KernelInterface $kernel A KernelInterface instance */ public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; parent::__construct('Symfony', Kernel::VERSION . ' - ' . $kernel->getName() . '/' . $kernel->getEnvironment() . ($kernel->isDebug() ? '/debug' : '')); $this->getDefinition()->addOption(new InputOption('--shell', '-s', InputOption::VALUE_NONE, 'Launch the shell.')); $this->getDefinition()->addOption(new InputOption('--process-isolation', null, InputOption::VALUE_NONE, 'Launch commands from shell as a separate processes.')); $this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment())); $this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.')); }
public function onKernelResponse(FilterResponseEvent $event) { if (!in_array($this->kernel->getEnvironment(), array('test', 'dev'))) { $response = $event->getResponse(); $compressedContent = new HtmlCompressor($response->getContent()); $response->setContent($compressedContent->compress()); return $response; } }
/** * @return KernelInterface */ private function getKernel(InputInterface $input) { $env = $input->getParameterOption(['--env', '-e'], $this->baseKernel->getEnvironment()); $debug = !$input->hasParameterOption(['--no-debug', '']); if ($env === $this->baseKernel->getEnvironment() && $debug === $this->baseKernel->isDebug()) { return $this->baseKernel; } $kernelClass = new ReflectionClass($this->baseKernel); return $kernelClass->newInstance([$env, $debug]); }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = array('app_name' => $this->name, 'app_version' => $this->version, 'token' => $response->headers->get('X-Debug-Token'), 'symfony_version' => Kernel::VERSION, 'symfony_state' => 'unknown', 'name' => isset($this->kernel) ? $this->kernel->getName() : 'n/a', 'env' => isset($this->kernel) ? $this->kernel->getEnvironment() : 'n/a', 'debug' => isset($this->kernel) ? $this->kernel->isDebug() : 'n/a', 'php_version' => PHP_VERSION, 'xdebug_enabled' => extension_loaded('xdebug'), 'eaccel_enabled' => extension_loaded('eaccelerator') && ini_get('eaccelerator.enable'), 'apc_enabled' => extension_loaded('apc') && ini_get('apc.enabled'), 'xcache_enabled' => extension_loaded('xcache') && ini_get('xcache.cacher'), 'wincache_enabled' => extension_loaded('wincache') && ini_get('wincache.ocenabled'), 'zend_opcache_enabled' => extension_loaded('Zend OPcache') && ini_get('opcache.enable'), 'bundles' => array(), 'sapi_name' => PHP_SAPI); if (isset($this->kernel)) { foreach ($this->kernel->getBundles() as $name => $bundle) { $this->data['bundles'][$name] = $bundle->getPath(); } $this->data['symfony_state'] = $this->determineSymfonyState(); } }
/** * {@inheritdoc} */ public function populate(EntityManager $em = null) { $process = new Process(sprintf("%s/console fos:elastica:populate --env=%s", $this->kernel->getRootDir(), $this->kernel->getEnvironment())); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } $this->output = $process->getOutput(); return $this; }
private function getCoreBundlesClasses() : array { $bundles = [FrameworkBundle::class, SecurityBundle::class, TwigBundle::class, MonologBundle::class, SwiftmailerBundle::class, DoctrineBundle::class, DoctrineCacheBundle::class, DoctrineMigrationsBundle::class, DoctrineFixturesBundle::class, SensioFrameworkExtraBundle::class, FOSJsRoutingBundle::class, BazingaJsTranslationBundle::class, LiipImagineBundle::class, DoctrineBehaviorsBundle::class, CacheAdapterBundle::class, TwigCacheBundle::class]; if (in_array($this->kernel->getEnvironment(), ['dev', 'test'])) { $bundles[] = WebProfilerBundle::class; $bundles[] = SensioGeneratorBundle::class; } if (in_array($this->kernel->getEnvironment(), ['prod'])) { $bundles[] = WebProfilerBundle::class; } return $bundles; }
public function onKernelException(GetResponseForExceptionEvent $event) { if ($this->kernel->getEnvironment() === 'prod') { $exception = $event->getException(); if ($exception instanceof HttpExceptionInterface) { $status_code = $exception->getStatusCode(); } else { $status_code = 500; } $response = new Response($this->getTwig()->render('rootiovmailmeBundle::error.html.twig', array('status_code' => $status_code))); $event->setResponse($response); } }
/** * {@inheritdoc} */ public function populate(EntityManager $em = null) { $command = new PopulateCommand(); $command->setContainer($this->kernel->getContainer()); $output = new BufferedOutput(); $input = new ArgvInput(['env' => $this->kernel->getEnvironment()]); if ($command->run($input, $output)) { //return code is not zero throw new \RuntimeException($output->fetch()); } $this->output = $output->fetch(); return $this; }
public function onKernelException(GetResponseForExceptionEvent $event) { if ('prod' !== $this->kernel->getEnvironment()) { return; } $exception = $event->getException(); $response = new Response(); $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); if ($exception instanceof HttpExceptionInterface) { if (400 < $exception->getStatusCode() && 500 > $exception->getStatusCode()) { $response->setStatusCode(Response::HTTP_NOT_FOUND); $response->headers->replace($exception->getHeaders()); } } $event->setResponse($response); }
public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; parent::__construct("Thelia", Thelia::THELIA_VERSION); $this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment())); $this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.')); }
public function createToken(Request $request, $providerKey) { $jwt = $request->query->get('jwt'); if (!$jwt && $this->kernel->getEnvironment() == 'dev') { $tenant = $this->em->getRepository('AtlassianConnectBundle:Tenant')->find(1); $clientKey = $tenant->getClientKey(); $sharedSecret = $tenant->getSharedSecret(); $qshHelper = new QSH(); $qsh = $qshHelper->create('GET', $request->getRequestUri()); $payload = ['iss' => $clientKey, 'iat' => time(), 'exp' => time() + 86400, 'qsh' => $qsh, 'sub' => 'admin']; $jwt = JWT::encode($payload, $sharedSecret); } if (!$jwt) { throw new BadCredentialsException('No JWT token found'); } return new PreAuthenticatedToken('anon.', $jwt, $providerKey); }
/** * Constructor. * * @param KernelInterface $kernel A KernelInterface instance * @param EmbeddedComposer $embeddedComposer Composer Class Loader */ public function __construct(KernelInterface $kernel, EmbeddedComposer $embeddedComposer) { $this->kernel = $kernel; $this->embeddedComposer = $embeddedComposer; if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { date_default_timezone_set(@date_default_timezone_get()); } $version = $embeddedComposer->findPackage('sculpin/sculpin')->getPrettyVersion(); if ($version !== Sculpin::GIT_VERSION && Sculpin::GIT_VERSION !== '@' . 'git_version' . '@') { $version .= ' (' . Sculpin::GIT_VERSION . ')'; } parent::__construct('Sculpin', $version . ' - ' . $kernel->getName() . '/' . $kernel->getEnvironment() . ($kernel->isDebug() ? '/debug' : '')); $this->getDefinition()->addOption(new InputOption('--project-dir', null, InputOption::VALUE_REQUIRED, 'The project directory.', '.')); $this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment())); $this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.')); $this->getDefinition()->addOption(new InputOption('--safe', null, InputOption::VALUE_NONE, 'Enable safe mode (no bundles loaded, no kernel booted)')); $this->getDefinition()->addOption(new InputOption('--git-version', null, InputOption::VALUE_NONE, 'See Git version')); }
/** * Constructor. */ public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; parent::__construct('Symfony', Kernel::VERSION . ' - ' . $kernel->getName() . '/' . $kernel->getEnvironment() . ($kernel->isDebug() ? '/debug' : '')); $this->definition->addOption(new InputOption('--shell', '-s', InputOption::VALUE_NONE, 'Launch the shell.')); $this->definition->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', 'dev')); $this->definition->addOption(new InputOption('--debug', '-d', InputOption::VALUE_NONE, 'Whether to run in debug mode.')); $this->kernel->boot(); $this->registerCommands(); }
/** * Compiles translations and clears cache for a current environment, newly compiled translations * will be detected by Symfony on a next request. * * @throws \Exception * * @return CompilationResult */ public function compile() { $app = $this->createApplication(); $input = new ArrayInput(array('command' => 'modera:translations:compile', '--no-ansi' => true, '-v' => true)); $input->setInteractive(false); $compileOutput = new BufferedOutput(); $compileTranslationsExitCode = $app->run($input, $compileOutput); if (0 == $compileTranslationsExitCode) { $cacheClearOutput = new BufferedOutput(); $input = new ArrayInput(array('command' => 'cache:clear', '--env' => $this->kernel->getEnvironment(), '--no-ansi' => true)); $input->setInteractive(false); $cacheClearExitCode = $app->run($input, $cacheClearOutput); if (0 == $cacheClearExitCode) { return new CompilationResult($compileTranslationsExitCode, $compileOutput->fetch()); } else { return new CompilationResult($cacheClearExitCode, $cacheClearOutput->fetch()); } } return new CompilationResult($compileTranslationsExitCode, $compileOutput->fetch()); }
/** * Constructor. * * @DI\InjectParams({ * "em" = @DI\Inject("claroline.persistence.object_manager"), * "im" = @DI\Inject("claroline.manager.icon_manager"), * "mm" = @DI\Inject("claroline.manager.mask_manager"), * "fileSystem" = @DI\Inject("filesystem"), * "kernel" = @DI\Inject("kernel"), * "toolManager" = @DI\Inject("claroline.manager.tool_manager"), * "toolMaskManager" = @DI\Inject("claroline.manager.tool_mask_decoder_manager") * }) */ public function __construct(ObjectManager $em, IconManager $im, Filesystem $fileSystem, KernelInterface $kernel, MaskManager $mm, ToolManager $toolManager, ToolMaskDecoderManager $toolMaskManager) { $this->em = $em; $this->im = $im; $this->mm = $mm; $this->fileSystem = $fileSystem; $this->kernelRootDir = $kernel->getRootDir(); $this->modifyTemplate = $kernel->getEnvironment() !== 'test'; $this->toolManager = $toolManager; $this->toolMaskManager = $toolMaskManager; }
/** * @return string * @throws \Bigfoot\Bundle\ContextBundle\Exception\NotFoundException */ public function getDefaultFrontLocale() { if (!in_array($this->kernel->getEnvironment(), array('admin', 'admin_dev'))) { return $this->get('language'); } $config = $this->get('language_back', true); if (isset($config['parameters']['default_front_locale'])) { return $config['parameters']['default_front_locale']; } $config = $this->getConfig('language'); return $config['default_value']; }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = array( 'app_name' => $this->name, 'app_version' => $this->version, 'token' => $response->headers->get('X-Debug-Token'), 'symfony_version' => Kernel::VERSION, 'symfony_state' => 'unknown', 'name' => isset($this->kernel) ? $this->kernel->getName() : 'n/a', 'env' => isset($this->kernel) ? $this->kernel->getEnvironment() : 'n/a', 'debug' => isset($this->kernel) ? $this->kernel->isDebug() : 'n/a', 'php_version' => PHP_VERSION, 'php_architecture' => PHP_INT_SIZE * 8, 'php_intl_locale' => class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a', 'php_timezone' => date_default_timezone_get(), 'xdebug_enabled' => extension_loaded('xdebug'), 'apcu_enabled' => extension_loaded('apcu') && ini_get('apc.enabled'), 'zend_opcache_enabled' => extension_loaded('Zend OPcache') && ini_get('opcache.enable'), 'bundles' => array(), 'sapi_name' => PHP_SAPI, ); if (isset($this->kernel)) { foreach ($this->kernel->getBundles() as $name => $bundle) { $this->data['bundles'][$name] = $bundle->getPath(); } $this->data['symfony_state'] = $this->determineSymfonyState(); $this->data['symfony_minor_version'] = sprintf('%s.%s', Kernel::MAJOR_VERSION, Kernel::MINOR_VERSION); $eom = \DateTime::createFromFormat('m/Y', Kernel::END_OF_MAINTENANCE); $eol = \DateTime::createFromFormat('m/Y', Kernel::END_OF_LIFE); $this->data['symfony_eom'] = $eom->format('F Y'); $this->data['symfony_eol'] = $eol->format('F Y'); } if (preg_match('~^(\d+(?:\.\d+)*)(.+)?$~', $this->data['php_version'], $matches) && isset($matches[2])) { $this->data['php_version'] = $matches[1]; $this->data['php_version_extra'] = $matches[2]; } }
private function initializeCache() { // We have to warm up the extend entities cache in separate process // to allow this process continue executing. // The problem is we need initialized DI contained for warming up this cache, // but in this moment we are exactly doing this for the current process. $pb = ProcessBuilder::create()->setTimeout(self::CACHE_GENERATION_TIMEOUT)->add(CommandExecutor::getPhpExecutable())->add($this->kernel->getRootDir() . '/console')->add('oro:entity-extend:cache:warmup')->add('--env')->add($this->kernel->getEnvironment())->add('--cache-dir')->add($this->cacheDir); $attempts = 0; do { if (!CommandExecutor::isCommandRunning('oro:entity-extend:cache:warmup')) { // if cache was generated there is no need to generate it again if ($attempts > 0) { return; } $pb->getProcess()->run(); return; } else { $attempts++; sleep(self::CACHE_CHECKOUT_INTERVAL); } } while ($attempts < self::CACHE_CHECKOUT_ATTEMPTS); }
/** * Manages the queue. Dispatches processes, kills timed out processes, etc. */ public function manageQueue() { //Checks if there is a SIGTERM present. if ($this->checkSigterm()) { return true; } $this->clearIdleWorkers(); foreach ($this->workers as $index => $worker) { if (!$worker && count($this->queue) > 0) { $processName = $this->queue->extract(); $this->workers[$index] = new Process($this->phpPath . ' app/console foreman:dispatch ' . $processName . ' --env=' . $this->kernel->getEnvironment()); $this->workers[$index]->setTimeout($this->timeout); $this->workers[$index]->start(); $this->eventDispatcher->dispatch('foreman.process.started', new ProcessStartedEvent($processName)); } } }
/** * Handle form entry of permission changes. * * @param Request $request * * @return bool */ public function bindRequest(Request $request) { $changes = $request->request->get('permission-hidden-fields'); if (empty($changes)) { return true; } // Just apply the changes to the current node (non recursively) $this->applyAclChangeset($this->resource, $changes, false); // Apply recursively (on request) $applyRecursive = $request->request->get('applyRecursive'); if ($applyRecursive) { // Serialize changes & store them in DB $user = $this->tokenStorage->getToken()->getUser(); $this->createAclChangeSet($this->resource, $changes, $user); $cmd = 'php ' . $this->kernel->getRootDir() . '/console kuma:acl:apply'; $cmd .= ' --env=' . $this->kernel->getEnvironment(); $this->shellHelper->runInBackground($cmd); } return true; }
/** * Register bundles * * @param array Exclude bundles * @params Kernel $kernel * * @return array Array of bundles */ public function registerBundles($excludeBundles, KernelInterface $kernel = null) { $bundles = array(); $env = $kernel !== null ? $kernel->getEnvironment() : null; $excludeClasses = array(); foreach ($excludeBundles as $bundle) { $excludeClasses[] = get_class($bundle); } foreach ($this->getDependencyBundleList($env) as $bundleClass) { if (!in_array($bundleClass, $excludeClasses)) { $excludeBundles[] = $bundles[] = $bdl = new $bundleClass(); if (method_exists($bdl, 'registerBundles')) { $subBdls = $bdl->registerBundles($excludeBundles, $kernel); foreach ($subBdls as $subBdl) { $excludeBundles[] = $bundles[] = $subBdl; } } } } return $bundles; }
/** * @param KernelInterface $parent * @param string $namespace * @param string $parentClass * @param string $warmupDir * * @return KernelInterface */ protected function getTempKernel(KernelInterface $parent, $namespace, $parentClass, $warmupDir) { $rootDir = $parent->getRootDir(); // the temp kernel class name must have the same length than the real one // to avoid the many problems in serialized resources files $class = substr($parentClass, 0, -1) . '_'; // the temp kernel name must be changed too $name = substr($parent->getName(), 0, -1) . '_'; $code = <<<EOF <?php namespace {$namespace} { class {$class} extends {$parentClass} { public function getCacheDir() { return '{$warmupDir}'; } public function getName() { return '{$name}'; } public function getRootDir() { return '{$rootDir}'; } } } EOF; $this->getContainer()->get('filesystem')->mkdir($warmupDir); file_put_contents($file = $warmupDir . '/kernel.tmp', $code); require_once $file; @unlink($file); $class = "{$namespace}\\{$class}"; return new $class($parent->getEnvironment(), $parent->isDebug()); }
/** * @param KernelInterface $parent * @param string $namespace * @param string $parentClass * @param string $warmupDir * * @return KernelInterface */ protected function getTempKernel(KernelInterface $parent, $namespace, $parentClass, $warmupDir) { $cacheDir = var_export($warmupDir, true); $rootDir = var_export(realpath($parent->getRootDir()), true); $logDir = var_export(realpath($parent->getLogDir()), true); // the temp kernel class name must have the same length than the real one // to avoid the many problems in serialized resources files $class = substr($parentClass, 0, -1) . '_'; // the temp kernel name must be changed too $name = var_export(substr($parent->getName(), 0, -1) . '_', true); $code = <<<EOF <?php namespace {$namespace} { class {$class} extends {$parentClass} { public function getCacheDir() { return {$cacheDir}; } public function getName() { return {$name}; } public function getRootDir() { return {$rootDir}; } public function getLogDir() { return {$logDir}; } protected function buildContainer() { \$container = parent::buildContainer(); // filter container's resources, removing reference to temp kernel file \$resources = \$container->getResources(); \$filteredResources = array(); foreach (\$resources as \$resource) { if ((string) \$resource !== __FILE__) { \$filteredResources[] = \$resource; } } \$container->setResources(\$filteredResources); return \$container; } } } EOF; $this->getContainer()->get('filesystem')->mkdir($warmupDir); file_put_contents($file = $warmupDir . '/kernel.tmp', $code); require_once $file; $class = "{$namespace}\\{$class}"; return new $class($parent->getEnvironment(), $parent->isDebug()); }
protected function getTempKernel(KernelInterface $parent, $namespace, $class, $warmupDir) { $suffix = $this->getTempKernelSuffix(); $rootDir = $parent->getRootDir(); $code = <<<EOF <?php namespace {$namespace} { class {$class}{$suffix} extends {$class} { public function getCacheDir() { return '{$warmupDir}'; } public function getRootDir() { return '{$rootDir}'; } protected function getContainerClass() { return parent::getContainerClass().'{$suffix}'; } } } EOF; $this->getContainer()->get('filesystem')->mkdir($warmupDir); file_put_contents($file = $warmupDir . '/kernel.tmp', $code); require_once $file; @unlink($file); $class = "{$namespace}\\{$class}{$suffix}"; return new $class($parent->getEnvironment(), $parent->isDebug()); }
/** * Returns the container object. * * @param KernelInterface $kernel * @param Request $request * * @return ContainerBuilder */ public static function create(KernelInterface $kernel, Request $request) { $rootDir = $kernel->getRootDir(); $cacheDir = dirname($rootDir) . '/var/cache/' . $kernel->getEnvironment(); $logsDir = dirname($rootDir) . '/var/logs'; $container = new ContainerBuilder(); $container->setParameter('kernel.root_dir', $rootDir); $container->setParameter('kernel.cache_dir', $cacheDir); $container->setParameter('kernel.logs_dir', $logsDir); $container->setParameter('kernel.debug', false); $parameters = []; // Load the parameters.yml file if (file_exists($rootDir . '/config/parameters.yml')) { $parameters = Yaml::parse(file_get_contents($rootDir . '/config/parameters.yml')); } elseif (file_exists($rootDir . '/config/parameters.yml.dist')) { $parameters = Yaml::parse(file_get_contents($rootDir . '/config/parameters.yml.dist')); } // Add the parameters to the container if (!empty($parameters['parameters'])) { foreach ($parameters['parameters'] as $name => $value) { $container->setParameter($name, $value); } } // Add the Contao parameters $container->setParameter('contao.upload_path', 'files'); $container->setParameter('contao.image.target_path', 'assets/images'); // Set up the request stack $requestStack = new RequestStack(); $requestStack->push($request); $container->set('request_stack', $requestStack); // Create the session bag $bag = new ArrayAttributeBag('_contao_be_attributes'); $bag->setName('contao_backend'); // Start the session $session = new Session(); $session->registerBag($bag); $session->start(); $container->set('session', $session); // Set up the database connection $container->set('database_connection', ConnectionFactory::create($parameters)); // Resolve the locale $translationsDir = __DIR__ . '/../Resources/translations'; $resolver = new LanguageResolver($requestStack, $translationsDir); $locale = $resolver->getLocale(); // Update the request locale $request->setLocale($locale); // Set up the translator $translator = new Translator($locale); $translator->setFallbackLocales(['en']); $translator->addLoader('xlf', new XliffFileLoader()); $translator->addResource('xlf', $translationsDir . '/messages.en.xlf', 'en'); if ('en' !== $locale) { $translator->addResource('xlf', $translationsDir . '/messages.' . $locale . '.xlf', 'en'); } $container->set('translator', $translator); // Set up Twig $twigLoader = new \Twig_Loader_Filesystem(); $twigLoader->addPath(__DIR__ . '/../Resources/views', 'ContaoInstallation'); $twig = new \Twig_Environment($twigLoader); $twig->addExtension(new AnsiExtension()); $twig->addFunction(new \Twig_SimpleFunction('asset', function ($path) use($request) { return '/' . ltrim($request->getBasePath() . '/' . $path, '/'); })); $twig->addFilter(new \Twig_SimpleFilter('trans', function ($message, $params = []) use($translator) { return $translator->trans($message, $params); })); $container->set('twig', $twig); $kernelBundles = []; foreach ($kernel->getBundles() as $bundle) { $kernelBundles[$bundle->getName()] = get_class($bundle); } $container->set('kernel', $kernel); $container->setParameter('kernel.bundles', $kernelBundles); // Add the file system $container->set('filesystem', new Filesystem()); // Add the Contao resources paths $pass = new AddResourcesPathsPass(); $pass->process($container); // Add the Contao resource finder $container->set('contao.resource_finder', new ResourceFinder($container->getParameter('contao.resources_paths'))); // Add the Contao resource locator $container->set('contao.resource_locator', new FileLocator($container->getParameter('contao.resources_paths'))); // Add the Contao cache $container->set('contao.cache', new FilesystemCache($cacheDir . '/contao/cache', '', 022)); // Add the installer services $container->set('contao.installer', new Installer($container->get('database_connection'), $container->get('contao.resource_finder'), $container->get('translator'))); $container->set('contao.install_tool', new InstallTool($container->get('database_connection'), $rootDir)); $container->set('contao.install_tool_user', new InstallToolUser($container->get('session'))); return $container; }