f0137c68425f07210664865e22425ae55d394a3e
[yaffs-website] / http-kernel / Kernel.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\HttpKernel;
13
14 use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator;
15 use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
16 use Symfony\Component\ClassLoader\ClassCollectionLoader;
17 use Symfony\Component\Config\ConfigCache;
18 use Symfony\Component\Config\Loader\DelegatingLoader;
19 use Symfony\Component\Config\Loader\LoaderResolver;
20 use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
21 use Symfony\Component\DependencyInjection\Compiler\PassConfig;
22 use Symfony\Component\DependencyInjection\ContainerBuilder;
23 use Symfony\Component\DependencyInjection\ContainerInterface;
24 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
25 use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
26 use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
27 use Symfony\Component\DependencyInjection\Loader\GlobFileLoader;
28 use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
29 use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
30 use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
31 use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
32 use Symfony\Component\Filesystem\Filesystem;
33 use Symfony\Component\HttpFoundation\Request;
34 use Symfony\Component\HttpFoundation\Response;
35 use Symfony\Component\HttpKernel\Bundle\BundleInterface;
36 use Symfony\Component\HttpKernel\Config\EnvParametersResource;
37 use Symfony\Component\HttpKernel\Config\FileLocator;
38 use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
39 use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
40
41 /**
42  * The Kernel is the heart of the Symfony system.
43  *
44  * It manages an environment made of bundles.
45  *
46  * @author Fabien Potencier <fabien@symfony.com>
47  */
48 abstract class Kernel implements KernelInterface, RebootableInterface, TerminableInterface
49 {
50     /**
51      * @var BundleInterface[]
52      */
53     protected $bundles = array();
54
55     protected $bundleMap;
56     protected $container;
57     protected $rootDir;
58     protected $environment;
59     protected $debug;
60     protected $booted = false;
61     protected $name;
62     protected $startTime;
63     protected $loadClassCache;
64
65     private $projectDir;
66     private $warmupDir;
67     private $requestStackSize = 0;
68     private $resetServices = false;
69
70     const VERSION = '3.4.18';
71     const VERSION_ID = 30418;
72     const MAJOR_VERSION = 3;
73     const MINOR_VERSION = 4;
74     const RELEASE_VERSION = 18;
75     const EXTRA_VERSION = '';
76
77     const END_OF_MAINTENANCE = '11/2020';
78     const END_OF_LIFE = '11/2021';
79
80     /**
81      * @param string $environment The environment
82      * @param bool   $debug       Whether to enable debugging or not
83      */
84     public function __construct($environment, $debug)
85     {
86         $this->environment = $environment;
87         $this->debug = (bool) $debug;
88         $this->rootDir = $this->getRootDir();
89         $this->name = $this->getName();
90     }
91
92     public function __clone()
93     {
94         $this->booted = false;
95         $this->container = null;
96         $this->requestStackSize = 0;
97         $this->resetServices = false;
98     }
99
100     /**
101      * {@inheritdoc}
102      */
103     public function boot()
104     {
105         if (true === $this->booted) {
106             if (!$this->requestStackSize && $this->resetServices) {
107                 if ($this->container->has('services_resetter')) {
108                     $this->container->get('services_resetter')->reset();
109                 }
110                 $this->resetServices = false;
111                 if ($this->debug) {
112                     $this->startTime = microtime(true);
113                 }
114             }
115
116             return;
117         }
118         if ($this->debug) {
119             $this->startTime = microtime(true);
120         }
121         if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
122             putenv('SHELL_VERBOSITY=3');
123             $_ENV['SHELL_VERBOSITY'] = 3;
124             $_SERVER['SHELL_VERBOSITY'] = 3;
125         }
126
127         if ($this->loadClassCache) {
128             $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]);
129         }
130
131         // init bundles
132         $this->initializeBundles();
133
134         // init container
135         $this->initializeContainer();
136
137         foreach ($this->getBundles() as $bundle) {
138             $bundle->setContainer($this->container);
139             $bundle->boot();
140         }
141
142         $this->booted = true;
143     }
144
145     /**
146      * {@inheritdoc}
147      */
148     public function reboot($warmupDir)
149     {
150         $this->shutdown();
151         $this->warmupDir = $warmupDir;
152         $this->boot();
153     }
154
155     /**
156      * {@inheritdoc}
157      */
158     public function terminate(Request $request, Response $response)
159     {
160         if (false === $this->booted) {
161             return;
162         }
163
164         if ($this->getHttpKernel() instanceof TerminableInterface) {
165             $this->getHttpKernel()->terminate($request, $response);
166         }
167     }
168
169     /**
170      * {@inheritdoc}
171      */
172     public function shutdown()
173     {
174         if (false === $this->booted) {
175             return;
176         }
177
178         $this->booted = false;
179
180         foreach ($this->getBundles() as $bundle) {
181             $bundle->shutdown();
182             $bundle->setContainer(null);
183         }
184
185         $this->container = null;
186         $this->requestStackSize = 0;
187         $this->resetServices = false;
188     }
189
190     /**
191      * {@inheritdoc}
192      */
193     public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
194     {
195         $this->boot();
196         ++$this->requestStackSize;
197         $this->resetServices = true;
198
199         try {
200             return $this->getHttpKernel()->handle($request, $type, $catch);
201         } finally {
202             --$this->requestStackSize;
203         }
204     }
205
206     /**
207      * Gets a HTTP kernel from the container.
208      *
209      * @return HttpKernel
210      */
211     protected function getHttpKernel()
212     {
213         return $this->container->get('http_kernel');
214     }
215
216     /**
217      * {@inheritdoc}
218      */
219     public function getBundles()
220     {
221         return $this->bundles;
222     }
223
224     /**
225      * {@inheritdoc}
226      */
227     public function getBundle($name, $first = true/*, $noDeprecation = false */)
228     {
229         $noDeprecation = false;
230         if (\func_num_args() >= 3) {
231             $noDeprecation = func_get_arg(2);
232         }
233
234         if (!$first && !$noDeprecation) {
235             @trigger_error(sprintf('Passing "false" as the second argument to "%s()" is deprecated as of 3.4 and will be removed in 4.0.', __METHOD__), E_USER_DEPRECATED);
236         }
237
238         if (!isset($this->bundleMap[$name])) {
239             throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled. Maybe you forgot to add it in the registerBundles() method of your %s.php file?', $name, \get_class($this)));
240         }
241
242         if (true === $first) {
243             return $this->bundleMap[$name][0];
244         }
245
246         return $this->bundleMap[$name];
247     }
248
249     /**
250      * {@inheritdoc}
251      *
252      * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
253      */
254     public function locateResource($name, $dir = null, $first = true)
255     {
256         if ('@' !== $name[0]) {
257             throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
258         }
259
260         if (false !== strpos($name, '..')) {
261             throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
262         }
263
264         $bundleName = substr($name, 1);
265         $path = '';
266         if (false !== strpos($bundleName, '/')) {
267             list($bundleName, $path) = explode('/', $bundleName, 2);
268         }
269
270         $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
271         $overridePath = substr($path, 9);
272         $resourceBundle = null;
273         $bundles = $this->getBundle($bundleName, false, true);
274         $files = array();
275
276         foreach ($bundles as $bundle) {
277             if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
278                 if (null !== $resourceBundle) {
279                     throw new \RuntimeException(sprintf('"%s" resource is hidden by a resource from the "%s" derived bundle. Create a "%s" file to override the bundle resource.', $file, $resourceBundle, $dir.'/'.$bundles[0]->getName().$overridePath));
280                 }
281
282                 if ($first) {
283                     return $file;
284                 }
285                 $files[] = $file;
286             }
287
288             if (file_exists($file = $bundle->getPath().'/'.$path)) {
289                 if ($first && !$isResource) {
290                     return $file;
291                 }
292                 $files[] = $file;
293                 $resourceBundle = $bundle->getName();
294             }
295         }
296
297         if (\count($files) > 0) {
298             return $first && $isResource ? $files[0] : $files;
299         }
300
301         throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
302     }
303
304     /**
305      * {@inheritdoc}
306      */
307     public function getName()
308     {
309         if (null === $this->name) {
310             $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
311             if (ctype_digit($this->name[0])) {
312                 $this->name = '_'.$this->name;
313             }
314         }
315
316         return $this->name;
317     }
318
319     /**
320      * {@inheritdoc}
321      */
322     public function getEnvironment()
323     {
324         return $this->environment;
325     }
326
327     /**
328      * {@inheritdoc}
329      */
330     public function isDebug()
331     {
332         return $this->debug;
333     }
334
335     /**
336      * {@inheritdoc}
337      */
338     public function getRootDir()
339     {
340         if (null === $this->rootDir) {
341             $r = new \ReflectionObject($this);
342             $this->rootDir = \dirname($r->getFileName());
343         }
344
345         return $this->rootDir;
346     }
347
348     /**
349      * Gets the application root dir (path of the project's composer file).
350      *
351      * @return string The project root dir
352      */
353     public function getProjectDir()
354     {
355         if (null === $this->projectDir) {
356             $r = new \ReflectionObject($this);
357             $dir = $rootDir = \dirname($r->getFileName());
358             while (!file_exists($dir.'/composer.json')) {
359                 if ($dir === \dirname($dir)) {
360                     return $this->projectDir = $rootDir;
361                 }
362                 $dir = \dirname($dir);
363             }
364             $this->projectDir = $dir;
365         }
366
367         return $this->projectDir;
368     }
369
370     /**
371      * {@inheritdoc}
372      */
373     public function getContainer()
374     {
375         return $this->container;
376     }
377
378     /**
379      * Loads the PHP class cache.
380      *
381      * This methods only registers the fact that you want to load the cache classes.
382      * The cache will actually only be loaded when the Kernel is booted.
383      *
384      * That optimization is mainly useful when using the HttpCache class in which
385      * case the class cache is not loaded if the Response is in the cache.
386      *
387      * @param string $name      The cache name prefix
388      * @param string $extension File extension of the resulting file
389      *
390      * @deprecated since version 3.3, to be removed in 4.0. The class cache is not needed anymore when using PHP 7.0.
391      */
392     public function loadClassCache($name = 'classes', $extension = '.php')
393     {
394         if (\PHP_VERSION_ID >= 70000) {
395             @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
396         }
397
398         $this->loadClassCache = array($name, $extension);
399     }
400
401     /**
402      * @internal
403      *
404      * @deprecated since version 3.3, to be removed in 4.0.
405      */
406     public function setClassCache(array $classes)
407     {
408         if (\PHP_VERSION_ID >= 70000) {
409             @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
410         }
411
412         file_put_contents(($this->warmupDir ?: $this->getCacheDir()).'/classes.map', sprintf('<?php return %s;', var_export($classes, true)));
413     }
414
415     /**
416      * @internal
417      */
418     public function setAnnotatedClassCache(array $annotatedClasses)
419     {
420         file_put_contents(($this->warmupDir ?: $this->getCacheDir()).'/annotations.map', sprintf('<?php return %s;', var_export($annotatedClasses, true)));
421     }
422
423     /**
424      * {@inheritdoc}
425      */
426     public function getStartTime()
427     {
428         return $this->debug ? $this->startTime : -INF;
429     }
430
431     /**
432      * {@inheritdoc}
433      */
434     public function getCacheDir()
435     {
436         return $this->rootDir.'/cache/'.$this->environment;
437     }
438
439     /**
440      * {@inheritdoc}
441      */
442     public function getLogDir()
443     {
444         return $this->rootDir.'/logs';
445     }
446
447     /**
448      * {@inheritdoc}
449      */
450     public function getCharset()
451     {
452         return 'UTF-8';
453     }
454
455     /**
456      * @deprecated since version 3.3, to be removed in 4.0.
457      */
458     protected function doLoadClassCache($name, $extension)
459     {
460         if (\PHP_VERSION_ID >= 70000) {
461             @trigger_error(__METHOD__.'() is deprecated since Symfony 3.3, to be removed in 4.0.', E_USER_DEPRECATED);
462         }
463         $cacheDir = $this->warmupDir ?: $this->getCacheDir();
464
465         if (!$this->booted && is_file($cacheDir.'/classes.map')) {
466             ClassCollectionLoader::load(include($cacheDir.'/classes.map'), $cacheDir, $name, $this->debug, false, $extension);
467         }
468     }
469
470     /**
471      * Initializes the data structures related to the bundle management.
472      *
473      *  - the bundles property maps a bundle name to the bundle instance,
474      *  - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
475      *
476      * @throws \LogicException if two bundles share a common name
477      * @throws \LogicException if a bundle tries to extend a non-registered bundle
478      * @throws \LogicException if a bundle tries to extend itself
479      * @throws \LogicException if two bundles extend the same ancestor
480      */
481     protected function initializeBundles()
482     {
483         // init bundles
484         $this->bundles = array();
485         $topMostBundles = array();
486         $directChildren = array();
487
488         foreach ($this->registerBundles() as $bundle) {
489             $name = $bundle->getName();
490             if (isset($this->bundles[$name])) {
491                 throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
492             }
493             $this->bundles[$name] = $bundle;
494
495             if ($parentName = $bundle->getParent()) {
496                 @trigger_error('Bundle inheritance is deprecated as of 3.4 and will be removed in 4.0.', E_USER_DEPRECATED);
497
498                 if (isset($directChildren[$parentName])) {
499                     throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
500                 }
501                 if ($parentName == $name) {
502                     throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
503                 }
504                 $directChildren[$parentName] = $name;
505             } else {
506                 $topMostBundles[$name] = $bundle;
507             }
508         }
509
510         // look for orphans
511         if (!empty($directChildren) && \count($diff = array_diff_key($directChildren, $this->bundles))) {
512             $diff = array_keys($diff);
513
514             throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
515         }
516
517         // inheritance
518         $this->bundleMap = array();
519         foreach ($topMostBundles as $name => $bundle) {
520             $bundleMap = array($bundle);
521             $hierarchy = array($name);
522
523             while (isset($directChildren[$name])) {
524                 $name = $directChildren[$name];
525                 array_unshift($bundleMap, $this->bundles[$name]);
526                 $hierarchy[] = $name;
527             }
528
529             foreach ($hierarchy as $hierarchyBundle) {
530                 $this->bundleMap[$hierarchyBundle] = $bundleMap;
531                 array_pop($bundleMap);
532             }
533         }
534     }
535
536     /**
537      * The extension point similar to the Bundle::build() method.
538      *
539      * Use this method to register compiler passes and manipulate the container during the building process.
540      */
541     protected function build(ContainerBuilder $container)
542     {
543     }
544
545     /**
546      * Gets the container class.
547      *
548      * @return string The container class
549      */
550     protected function getContainerClass()
551     {
552         return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
553     }
554
555     /**
556      * Gets the container's base class.
557      *
558      * All names except Container must be fully qualified.
559      *
560      * @return string
561      */
562     protected function getContainerBaseClass()
563     {
564         return 'Container';
565     }
566
567     /**
568      * Initializes the service container.
569      *
570      * The cached version of the service container is used when fresh, otherwise the
571      * container is built.
572      */
573     protected function initializeContainer()
574     {
575         $class = $this->getContainerClass();
576         $cacheDir = $this->warmupDir ?: $this->getCacheDir();
577         $cache = new ConfigCache($cacheDir.'/'.$class.'.php', $this->debug);
578         $oldContainer = null;
579         if ($fresh = $cache->isFresh()) {
580             // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
581             $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
582             $fresh = $oldContainer = false;
583             try {
584                 if (file_exists($cache->getPath()) && \is_object($this->container = include $cache->getPath())) {
585                     $this->container->set('kernel', $this);
586                     $oldContainer = $this->container;
587                     $fresh = true;
588                 }
589             } catch (\Throwable $e) {
590             } catch (\Exception $e) {
591             } finally {
592                 error_reporting($errorLevel);
593             }
594         }
595
596         if ($fresh) {
597             return;
598         }
599
600         if ($this->debug) {
601             $collectedLogs = array();
602             $previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL');
603             $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
604                 if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
605                     return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
606                 }
607
608                 if (isset($collectedLogs[$message])) {
609                     ++$collectedLogs[$message]['count'];
610
611                     return;
612                 }
613
614                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
615                 // Clean the trace by removing first frames added by the error handler itself.
616                 for ($i = 0; isset($backtrace[$i]); ++$i) {
617                     if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
618                         $backtrace = \array_slice($backtrace, 1 + $i);
619                         break;
620                     }
621                 }
622
623                 $collectedLogs[$message] = array(
624                     'type' => $type,
625                     'message' => $message,
626                     'file' => $file,
627                     'line' => $line,
628                     'trace' => $backtrace,
629                     'count' => 1,
630                 );
631             });
632         }
633
634         try {
635             $container = null;
636             $container = $this->buildContainer();
637             $container->compile();
638         } finally {
639             if ($this->debug && true !== $previousHandler) {
640                 restore_error_handler();
641
642                 file_put_contents($cacheDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
643                 file_put_contents($cacheDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
644             }
645         }
646
647         if (null === $oldContainer && file_exists($cache->getPath())) {
648             $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);
649             try {
650                 $oldContainer = include $cache->getPath();
651             } catch (\Throwable $e) {
652             } catch (\Exception $e) {
653             } finally {
654                 error_reporting($errorLevel);
655             }
656         }
657         $oldContainer = \is_object($oldContainer) ? new \ReflectionClass($oldContainer) : false;
658
659         $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
660         $this->container = require $cache->getPath();
661         $this->container->set('kernel', $this);
662
663         if ($oldContainer && \get_class($this->container) !== $oldContainer->name) {
664             // Because concurrent requests might still be using them,
665             // old container files are not removed immediately,
666             // but on a next dump of the container.
667             static $legacyContainers = array();
668             $oldContainerDir = \dirname($oldContainer->getFileName());
669             $legacyContainers[$oldContainerDir.'.legacy'] = true;
670             foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) {
671                 if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
672                     (new Filesystem())->remove(substr($legacyContainer, 0, -7));
673                 }
674             }
675
676             touch($oldContainerDir.'.legacy');
677         }
678
679         if ($this->container->has('cache_warmer')) {
680             $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
681         }
682     }
683
684     /**
685      * Returns the kernel parameters.
686      *
687      * @return array An array of kernel parameters
688      */
689     protected function getKernelParameters()
690     {
691         $bundles = array();
692         $bundlesMetadata = array();
693
694         foreach ($this->bundles as $name => $bundle) {
695             $bundles[$name] = \get_class($bundle);
696             $bundlesMetadata[$name] = array(
697                 'parent' => $bundle->getParent(),
698                 'path' => $bundle->getPath(),
699                 'namespace' => $bundle->getNamespace(),
700             );
701         }
702
703         return array_merge(
704             array(
705                 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
706                 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
707                 'kernel.environment' => $this->environment,
708                 'kernel.debug' => $this->debug,
709                 'kernel.name' => $this->name,
710                 'kernel.cache_dir' => realpath($cacheDir = $this->warmupDir ?: $this->getCacheDir()) ?: $cacheDir,
711                 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
712                 'kernel.bundles' => $bundles,
713                 'kernel.bundles_metadata' => $bundlesMetadata,
714                 'kernel.charset' => $this->getCharset(),
715                 'kernel.container_class' => $this->getContainerClass(),
716             ),
717             $this->getEnvParameters(false)
718         );
719     }
720
721     /**
722      * Gets the environment parameters.
723      *
724      * Only the parameters starting with "SYMFONY__" are considered.
725      *
726      * @return array An array of parameters
727      *
728      * @deprecated since version 3.3, to be removed in 4.0
729      */
730     protected function getEnvParameters()
731     {
732         if (0 === \func_num_args() || func_get_arg(0)) {
733             @trigger_error(sprintf('The "%s()" method is deprecated as of 3.3 and will be removed in 4.0. Use the %%env()%% syntax to get the value of any environment variable from configuration files instead.', __METHOD__), E_USER_DEPRECATED);
734         }
735
736         $parameters = array();
737         foreach ($_SERVER as $key => $value) {
738             if (0 === strpos($key, 'SYMFONY__')) {
739                 @trigger_error(sprintf('The support of special environment variables that start with SYMFONY__ (such as "%s") is deprecated as of 3.3 and will be removed in 4.0. Use the %%env()%% syntax instead to get the value of environment variables in configuration files.', $key), E_USER_DEPRECATED);
740                 $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
741             }
742         }
743
744         return $parameters;
745     }
746
747     /**
748      * Builds the service container.
749      *
750      * @return ContainerBuilder The compiled service container
751      *
752      * @throws \RuntimeException
753      */
754     protected function buildContainer()
755     {
756         foreach (array('cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
757             if (!is_dir($dir)) {
758                 if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
759                     throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
760                 }
761             } elseif (!is_writable($dir)) {
762                 throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
763             }
764         }
765
766         $container = $this->getContainerBuilder();
767         $container->addObjectResource($this);
768         $this->prepareContainer($container);
769
770         if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
771             $container->merge($cont);
772         }
773
774         $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
775         $container->addResource(new EnvParametersResource('SYMFONY__'));
776
777         return $container;
778     }
779
780     /**
781      * Prepares the ContainerBuilder before it is compiled.
782      */
783     protected function prepareContainer(ContainerBuilder $container)
784     {
785         $extensions = array();
786         foreach ($this->bundles as $bundle) {
787             if ($extension = $bundle->getContainerExtension()) {
788                 $container->registerExtension($extension);
789             }
790
791             if ($this->debug) {
792                 $container->addObjectResource($bundle);
793             }
794         }
795
796         foreach ($this->bundles as $bundle) {
797             $bundle->build($container);
798         }
799
800         $this->build($container);
801
802         foreach ($container->getExtensions() as $extension) {
803             $extensions[] = $extension->getAlias();
804         }
805
806         // ensure these extensions are implicitly loaded
807         $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
808     }
809
810     /**
811      * Gets a new ContainerBuilder instance used to build the service container.
812      *
813      * @return ContainerBuilder
814      */
815     protected function getContainerBuilder()
816     {
817         $container = new ContainerBuilder();
818         $container->getParameterBag()->add($this->getKernelParameters());
819
820         if ($this instanceof CompilerPassInterface) {
821             $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
822         }
823         if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
824             $container->setProxyInstantiator(new RuntimeInstantiator());
825         }
826
827         return $container;
828     }
829
830     /**
831      * Dumps the service container to PHP code in the cache.
832      *
833      * @param ConfigCache      $cache     The config cache
834      * @param ContainerBuilder $container The service container
835      * @param string           $class     The name of the class to generate
836      * @param string           $baseClass The name of the container's base class
837      */
838     protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
839     {
840         // cache the container
841         $dumper = new PhpDumper($container);
842
843         if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
844             $dumper->setProxyDumper(new ProxyDumper());
845         }
846
847         $content = $dumper->dump(array(
848             'class' => $class,
849             'base_class' => $baseClass,
850             'file' => $cache->getPath(),
851             'as_files' => true,
852             'debug' => $this->debug,
853             'inline_class_loader_parameter' => \PHP_VERSION_ID >= 70000 && !$this->loadClassCache && !class_exists(ClassCollectionLoader::class, false) ? 'container.dumper.inline_class_loader' : null,
854             'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
855         ));
856
857         $rootCode = array_pop($content);
858         $dir = \dirname($cache->getPath()).'/';
859         $fs = new Filesystem();
860
861         foreach ($content as $file => $code) {
862             $fs->dumpFile($dir.$file, $code);
863             @chmod($dir.$file, 0666 & ~umask());
864         }
865         @unlink(\dirname($dir.$file).'.legacy');
866
867         $cache->write($rootCode, $container->getResources());
868     }
869
870     /**
871      * Returns a loader for the container.
872      *
873      * @return DelegatingLoader The loader
874      */
875     protected function getContainerLoader(ContainerInterface $container)
876     {
877         $locator = new FileLocator($this);
878         $resolver = new LoaderResolver(array(
879             new XmlFileLoader($container, $locator),
880             new YamlFileLoader($container, $locator),
881             new IniFileLoader($container, $locator),
882             new PhpFileLoader($container, $locator),
883             new GlobFileLoader($container, $locator),
884             new DirectoryLoader($container, $locator),
885             new ClosureLoader($container),
886         ));
887
888         return new DelegatingLoader($resolver);
889     }
890
891     /**
892      * Removes comments from a PHP source string.
893      *
894      * We don't use the PHP php_strip_whitespace() function
895      * as we want the content to be readable and well-formatted.
896      *
897      * @param string $source A PHP string
898      *
899      * @return string The PHP string with the comments removed
900      */
901     public static function stripComments($source)
902     {
903         if (!\function_exists('token_get_all')) {
904             return $source;
905         }
906
907         $rawChunk = '';
908         $output = '';
909         $tokens = token_get_all($source);
910         $ignoreSpace = false;
911         for ($i = 0; isset($tokens[$i]); ++$i) {
912             $token = $tokens[$i];
913             if (!isset($token[1]) || 'b"' === $token) {
914                 $rawChunk .= $token;
915             } elseif (T_START_HEREDOC === $token[0]) {
916                 $output .= $rawChunk.$token[1];
917                 do {
918                     $token = $tokens[++$i];
919                     $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
920                 } while (T_END_HEREDOC !== $token[0]);
921                 $rawChunk = '';
922             } elseif (T_WHITESPACE === $token[0]) {
923                 if ($ignoreSpace) {
924                     $ignoreSpace = false;
925
926                     continue;
927                 }
928
929                 // replace multiple new lines with a single newline
930                 $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
931             } elseif (\in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
932                 $ignoreSpace = true;
933             } else {
934                 $rawChunk .= $token[1];
935
936                 // The PHP-open tag already has a new-line
937                 if (T_OPEN_TAG === $token[0]) {
938                     $ignoreSpace = true;
939                 }
940             }
941         }
942
943         $output .= $rawChunk;
944
945         if (\PHP_VERSION_ID >= 70000) {
946             // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
947             unset($tokens, $rawChunk);
948             gc_mem_caches();
949         }
950
951         return $output;
952     }
953
954     public function serialize()
955     {
956         return serialize(array($this->environment, $this->debug));
957     }
958
959     public function unserialize($data)
960     {
961         if (\PHP_VERSION_ID >= 70000) {
962             list($environment, $debug) = unserialize($data, array('allowed_classes' => false));
963         } else {
964             list($environment, $debug) = unserialize($data);
965         }
966
967         $this->__construct($environment, $debug);
968     }
969 }