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