Yaffs site version 1.1
[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\ContainerInterface;
17 use Symfony\Component\DependencyInjection\ContainerBuilder;
18 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
19 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
20 use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
21 use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
22 use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
23 use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
24 use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
25 use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
26 use Symfony\Component\HttpFoundation\Request;
27 use Symfony\Component\HttpFoundation\Response;
28 use Symfony\Component\HttpKernel\Bundle\BundleInterface;
29 use Symfony\Component\HttpKernel\Config\EnvParametersResource;
30 use Symfony\Component\HttpKernel\Config\FileLocator;
31 use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
32 use Symfony\Component\HttpKernel\DependencyInjection\AddClassesToCachePass;
33 use Symfony\Component\Config\Loader\LoaderResolver;
34 use Symfony\Component\Config\Loader\DelegatingLoader;
35 use Symfony\Component\Config\ConfigCache;
36 use Symfony\Component\ClassLoader\ClassCollectionLoader;
37
38 /**
39  * The Kernel is the heart of the Symfony system.
40  *
41  * It manages an environment made of bundles.
42  *
43  * @author Fabien Potencier <fabien@symfony.com>
44  */
45 abstract class Kernel implements KernelInterface, TerminableInterface
46 {
47     /**
48      * @var BundleInterface[]
49      */
50     protected $bundles = array();
51
52     protected $bundleMap;
53     protected $container;
54     protected $rootDir;
55     protected $environment;
56     protected $debug;
57     protected $booted = false;
58     protected $name;
59     protected $startTime;
60     protected $loadClassCache;
61
62     const VERSION = '2.8.22';
63     const VERSION_ID = 20822;
64     const MAJOR_VERSION = 2;
65     const MINOR_VERSION = 8;
66     const RELEASE_VERSION = 22;
67     const EXTRA_VERSION = '';
68
69     const END_OF_MAINTENANCE = '11/2018';
70     const END_OF_LIFE = '11/2019';
71
72     /**
73      * Constructor.
74      *
75      * @param string $environment The environment
76      * @param bool   $debug       Whether to enable debugging or not
77      */
78     public function __construct($environment, $debug)
79     {
80         $this->environment = $environment;
81         $this->debug = (bool) $debug;
82         $this->rootDir = $this->getRootDir();
83         $this->name = $this->getName();
84
85         if ($this->debug) {
86             $this->startTime = microtime(true);
87         }
88
89         $defClass = new \ReflectionMethod($this, 'init');
90         $defClass = $defClass->getDeclaringClass()->name;
91
92         if (__CLASS__ !== $defClass) {
93             @trigger_error(sprintf('Calling the %s::init() method is deprecated since version 2.3 and will be removed in 3.0. Move your logic to the constructor method instead.', $defClass), E_USER_DEPRECATED);
94             $this->init();
95         }
96     }
97
98     /**
99      * @deprecated since version 2.3, to be removed in 3.0. Move your logic in the constructor instead.
100      */
101     public function init()
102     {
103         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Move your logic to the constructor method instead.', E_USER_DEPRECATED);
104     }
105
106     public function __clone()
107     {
108         if ($this->debug) {
109             $this->startTime = microtime(true);
110         }
111
112         $this->booted = false;
113         $this->container = null;
114     }
115
116     /**
117      * Boots the current kernel.
118      */
119     public function boot()
120     {
121         if (true === $this->booted) {
122             return;
123         }
124
125         if ($this->loadClassCache) {
126             $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]);
127         }
128
129         // init bundles
130         $this->initializeBundles();
131
132         // init container
133         $this->initializeContainer();
134
135         foreach ($this->getBundles() as $bundle) {
136             $bundle->setContainer($this->container);
137             $bundle->boot();
138         }
139
140         $this->booted = true;
141     }
142
143     /**
144      * {@inheritdoc}
145      */
146     public function terminate(Request $request, Response $response)
147     {
148         if (false === $this->booted) {
149             return;
150         }
151
152         if ($this->getHttpKernel() instanceof TerminableInterface) {
153             $this->getHttpKernel()->terminate($request, $response);
154         }
155     }
156
157     /**
158      * {@inheritdoc}
159      */
160     public function shutdown()
161     {
162         if (false === $this->booted) {
163             return;
164         }
165
166         $this->booted = false;
167
168         foreach ($this->getBundles() as $bundle) {
169             $bundle->shutdown();
170             $bundle->setContainer(null);
171         }
172
173         $this->container = null;
174     }
175
176     /**
177      * {@inheritdoc}
178      */
179     public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
180     {
181         if (false === $this->booted) {
182             $this->boot();
183         }
184
185         return $this->getHttpKernel()->handle($request, $type, $catch);
186     }
187
188     /**
189      * Gets a HTTP kernel from the container.
190      *
191      * @return HttpKernel
192      */
193     protected function getHttpKernel()
194     {
195         return $this->container->get('http_kernel');
196     }
197
198     /**
199      * {@inheritdoc}
200      */
201     public function getBundles()
202     {
203         return $this->bundles;
204     }
205
206     /**
207      * {@inheritdoc}
208      *
209      * @deprecated since version 2.6, to be removed in 3.0.
210      */
211     public function isClassInActiveBundle($class)
212     {
213         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in version 3.0.', E_USER_DEPRECATED);
214
215         foreach ($this->getBundles() as $bundle) {
216             if (0 === strpos($class, $bundle->getNamespace())) {
217                 return true;
218             }
219         }
220
221         return false;
222     }
223
224     /**
225      * {@inheritdoc}
226      */
227     public function getBundle($name, $first = true)
228     {
229         if (!isset($this->bundleMap[$name])) {
230             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)));
231         }
232
233         if (true === $first) {
234             return $this->bundleMap[$name][0];
235         }
236
237         return $this->bundleMap[$name];
238     }
239
240     /**
241      * {@inheritdoc}
242      *
243      * @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle
244      */
245     public function locateResource($name, $dir = null, $first = true)
246     {
247         if ('@' !== $name[0]) {
248             throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name));
249         }
250
251         if (false !== strpos($name, '..')) {
252             throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name));
253         }
254
255         $bundleName = substr($name, 1);
256         $path = '';
257         if (false !== strpos($bundleName, '/')) {
258             list($bundleName, $path) = explode('/', $bundleName, 2);
259         }
260
261         $isResource = 0 === strpos($path, 'Resources') && null !== $dir;
262         $overridePath = substr($path, 9);
263         $resourceBundle = null;
264         $bundles = $this->getBundle($bundleName, false);
265         $files = array();
266
267         foreach ($bundles as $bundle) {
268             if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
269                 if (null !== $resourceBundle) {
270                     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.',
271                         $file,
272                         $resourceBundle,
273                         $dir.'/'.$bundles[0]->getName().$overridePath
274                     ));
275                 }
276
277                 if ($first) {
278                     return $file;
279                 }
280                 $files[] = $file;
281             }
282
283             if (file_exists($file = $bundle->getPath().'/'.$path)) {
284                 if ($first && !$isResource) {
285                     return $file;
286                 }
287                 $files[] = $file;
288                 $resourceBundle = $bundle->getName();
289             }
290         }
291
292         if (count($files) > 0) {
293             return $first && $isResource ? $files[0] : $files;
294         }
295
296         throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name));
297     }
298
299     /**
300      * {@inheritdoc}
301      */
302     public function getName()
303     {
304         if (null === $this->name) {
305             $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
306             if (ctype_digit($this->name[0])) {
307                 $this->name = '_'.$this->name;
308             }
309         }
310
311         return $this->name;
312     }
313
314     /**
315      * {@inheritdoc}
316      */
317     public function getEnvironment()
318     {
319         return $this->environment;
320     }
321
322     /**
323      * {@inheritdoc}
324      */
325     public function isDebug()
326     {
327         return $this->debug;
328     }
329
330     /**
331      * {@inheritdoc}
332      */
333     public function getRootDir()
334     {
335         if (null === $this->rootDir) {
336             $r = new \ReflectionObject($this);
337             $this->rootDir = dirname($r->getFileName());
338         }
339
340         return $this->rootDir;
341     }
342
343     /**
344      * {@inheritdoc}
345      */
346     public function getContainer()
347     {
348         return $this->container;
349     }
350
351     /**
352      * Loads the PHP class cache.
353      *
354      * This methods only registers the fact that you want to load the cache classes.
355      * The cache will actually only be loaded when the Kernel is booted.
356      *
357      * That optimization is mainly useful when using the HttpCache class in which
358      * case the class cache is not loaded if the Response is in the cache.
359      *
360      * @param string $name      The cache name prefix
361      * @param string $extension File extension of the resulting file
362      */
363     public function loadClassCache($name = 'classes', $extension = '.php')
364     {
365         $this->loadClassCache = array($name, $extension);
366     }
367
368     /**
369      * Used internally.
370      */
371     public function setClassCache(array $classes)
372     {
373         file_put_contents($this->getCacheDir().'/classes.map', sprintf('<?php return %s;', var_export($classes, true)));
374     }
375
376     /**
377      * {@inheritdoc}
378      */
379     public function getStartTime()
380     {
381         return $this->debug ? $this->startTime : -INF;
382     }
383
384     /**
385      * {@inheritdoc}
386      */
387     public function getCacheDir()
388     {
389         return $this->rootDir.'/cache/'.$this->environment;
390     }
391
392     /**
393      * {@inheritdoc}
394      */
395     public function getLogDir()
396     {
397         return $this->rootDir.'/logs';
398     }
399
400     /**
401      * {@inheritdoc}
402      */
403     public function getCharset()
404     {
405         return 'UTF-8';
406     }
407
408     protected function doLoadClassCache($name, $extension)
409     {
410         if (!$this->booted && is_file($this->getCacheDir().'/classes.map')) {
411             ClassCollectionLoader::load(include($this->getCacheDir().'/classes.map'), $this->getCacheDir(), $name, $this->debug, false, $extension);
412         }
413     }
414
415     /**
416      * Initializes the data structures related to the bundle management.
417      *
418      *  - the bundles property maps a bundle name to the bundle instance,
419      *  - the bundleMap property maps a bundle name to the bundle inheritance hierarchy (most derived bundle first).
420      *
421      * @throws \LogicException if two bundles share a common name
422      * @throws \LogicException if a bundle tries to extend a non-registered bundle
423      * @throws \LogicException if a bundle tries to extend itself
424      * @throws \LogicException if two bundles extend the same ancestor
425      */
426     protected function initializeBundles()
427     {
428         // init bundles
429         $this->bundles = array();
430         $topMostBundles = array();
431         $directChildren = array();
432
433         foreach ($this->registerBundles() as $bundle) {
434             $name = $bundle->getName();
435             if (isset($this->bundles[$name])) {
436                 throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
437             }
438             $this->bundles[$name] = $bundle;
439
440             if ($parentName = $bundle->getParent()) {
441                 if (isset($directChildren[$parentName])) {
442                     throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
443                 }
444                 if ($parentName == $name) {
445                     throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
446                 }
447                 $directChildren[$parentName] = $name;
448             } else {
449                 $topMostBundles[$name] = $bundle;
450             }
451         }
452
453         // look for orphans
454         if (!empty($directChildren) && count($diff = array_diff_key($directChildren, $this->bundles))) {
455             $diff = array_keys($diff);
456
457             throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
458         }
459
460         // inheritance
461         $this->bundleMap = array();
462         foreach ($topMostBundles as $name => $bundle) {
463             $bundleMap = array($bundle);
464             $hierarchy = array($name);
465
466             while (isset($directChildren[$name])) {
467                 $name = $directChildren[$name];
468                 array_unshift($bundleMap, $this->bundles[$name]);
469                 $hierarchy[] = $name;
470             }
471
472             foreach ($hierarchy as $hierarchyBundle) {
473                 $this->bundleMap[$hierarchyBundle] = $bundleMap;
474                 array_pop($bundleMap);
475             }
476         }
477     }
478
479     /**
480      * Gets the container class.
481      *
482      * @return string The container class
483      */
484     protected function getContainerClass()
485     {
486         return $this->name.ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
487     }
488
489     /**
490      * Gets the container's base class.
491      *
492      * All names except Container must be fully qualified.
493      *
494      * @return string
495      */
496     protected function getContainerBaseClass()
497     {
498         return 'Container';
499     }
500
501     /**
502      * Initializes the service container.
503      *
504      * The cached version of the service container is used when fresh, otherwise the
505      * container is built.
506      */
507     protected function initializeContainer()
508     {
509         $class = $this->getContainerClass();
510         $cache = new ConfigCache($this->getCacheDir().'/'.$class.'.php', $this->debug);
511         $fresh = true;
512         if (!$cache->isFresh()) {
513             $container = $this->buildContainer();
514             $container->compile();
515             $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
516
517             $fresh = false;
518         }
519
520         require_once $cache->getPath();
521
522         $this->container = new $class();
523         $this->container->set('kernel', $this);
524
525         if (!$fresh && $this->container->has('cache_warmer')) {
526             $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
527         }
528     }
529
530     /**
531      * Returns the kernel parameters.
532      *
533      * @return array An array of kernel parameters
534      */
535     protected function getKernelParameters()
536     {
537         $bundles = array();
538         $bundlesMetadata = array();
539
540         foreach ($this->bundles as $name => $bundle) {
541             $bundles[$name] = get_class($bundle);
542             $bundlesMetadata[$name] = array(
543                 'parent' => $bundle->getParent(),
544                 'path' => $bundle->getPath(),
545                 'namespace' => $bundle->getNamespace(),
546             );
547         }
548
549         return array_merge(
550             array(
551                 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
552                 'kernel.environment' => $this->environment,
553                 'kernel.debug' => $this->debug,
554                 'kernel.name' => $this->name,
555                 'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(),
556                 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
557                 'kernel.bundles' => $bundles,
558                 'kernel.bundles_metadata' => $bundlesMetadata,
559                 'kernel.charset' => $this->getCharset(),
560                 'kernel.container_class' => $this->getContainerClass(),
561             ),
562             $this->getEnvParameters()
563         );
564     }
565
566     /**
567      * Gets the environment parameters.
568      *
569      * Only the parameters starting with "SYMFONY__" are considered.
570      *
571      * @return array An array of parameters
572      */
573     protected function getEnvParameters()
574     {
575         $parameters = array();
576         foreach ($_SERVER as $key => $value) {
577             if (0 === strpos($key, 'SYMFONY__')) {
578                 $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
579             }
580         }
581
582         return $parameters;
583     }
584
585     /**
586      * Builds the service container.
587      *
588      * @return ContainerBuilder The compiled service container
589      *
590      * @throws \RuntimeException
591      */
592     protected function buildContainer()
593     {
594         foreach (array('cache' => $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
595             if (!is_dir($dir)) {
596                 if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
597                     throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
598                 }
599             } elseif (!is_writable($dir)) {
600                 throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
601             }
602         }
603
604         $container = $this->getContainerBuilder();
605         $container->addObjectResource($this);
606         $this->prepareContainer($container);
607
608         if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
609             $container->merge($cont);
610         }
611
612         $container->addCompilerPass(new AddClassesToCachePass($this));
613         $container->addResource(new EnvParametersResource('SYMFONY__'));
614
615         return $container;
616     }
617
618     /**
619      * Prepares the ContainerBuilder before it is compiled.
620      *
621      * @param ContainerBuilder $container A ContainerBuilder instance
622      */
623     protected function prepareContainer(ContainerBuilder $container)
624     {
625         $extensions = array();
626         foreach ($this->bundles as $bundle) {
627             if ($extension = $bundle->getContainerExtension()) {
628                 $container->registerExtension($extension);
629                 $extensions[] = $extension->getAlias();
630             }
631
632             if ($this->debug) {
633                 $container->addObjectResource($bundle);
634             }
635         }
636         foreach ($this->bundles as $bundle) {
637             $bundle->build($container);
638         }
639
640         // ensure these extensions are implicitly loaded
641         $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
642     }
643
644     /**
645      * Gets a new ContainerBuilder instance used to build the service container.
646      *
647      * @return ContainerBuilder
648      */
649     protected function getContainerBuilder()
650     {
651         $container = new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
652
653         if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
654             $container->setProxyInstantiator(new RuntimeInstantiator());
655         }
656
657         return $container;
658     }
659
660     /**
661      * Dumps the service container to PHP code in the cache.
662      *
663      * @param ConfigCache      $cache     The config cache
664      * @param ContainerBuilder $container The service container
665      * @param string           $class     The name of the class to generate
666      * @param string           $baseClass The name of the container's base class
667      */
668     protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
669     {
670         // cache the container
671         $dumper = new PhpDumper($container);
672
673         if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
674             $dumper->setProxyDumper(new ProxyDumper(md5($cache->getPath())));
675         }
676
677         $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass, 'file' => $cache->getPath(), 'debug' => $this->debug));
678
679         $cache->write($content, $container->getResources());
680     }
681
682     /**
683      * Returns a loader for the container.
684      *
685      * @param ContainerInterface $container The service container
686      *
687      * @return DelegatingLoader The loader
688      */
689     protected function getContainerLoader(ContainerInterface $container)
690     {
691         $locator = new FileLocator($this);
692         $resolver = new LoaderResolver(array(
693             new XmlFileLoader($container, $locator),
694             new YamlFileLoader($container, $locator),
695             new IniFileLoader($container, $locator),
696             new PhpFileLoader($container, $locator),
697             new DirectoryLoader($container, $locator),
698             new ClosureLoader($container),
699         ));
700
701         return new DelegatingLoader($resolver);
702     }
703
704     /**
705      * Removes comments from a PHP source string.
706      *
707      * We don't use the PHP php_strip_whitespace() function
708      * as we want the content to be readable and well-formatted.
709      *
710      * @param string $source A PHP string
711      *
712      * @return string The PHP string with the comments removed
713      */
714     public static function stripComments($source)
715     {
716         if (!function_exists('token_get_all')) {
717             return $source;
718         }
719
720         $rawChunk = '';
721         $output = '';
722         $tokens = token_get_all($source);
723         $ignoreSpace = false;
724         for ($i = 0; isset($tokens[$i]); ++$i) {
725             $token = $tokens[$i];
726             if (!isset($token[1]) || 'b"' === $token) {
727                 $rawChunk .= $token;
728             } elseif (T_START_HEREDOC === $token[0]) {
729                 $output .= $rawChunk.$token[1];
730                 do {
731                     $token = $tokens[++$i];
732                     $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
733                 } while ($token[0] !== T_END_HEREDOC);
734                 $rawChunk = '';
735             } elseif (T_WHITESPACE === $token[0]) {
736                 if ($ignoreSpace) {
737                     $ignoreSpace = false;
738
739                     continue;
740                 }
741
742                 // replace multiple new lines with a single newline
743                 $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
744             } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
745                 $ignoreSpace = true;
746             } else {
747                 $rawChunk .= $token[1];
748
749                 // The PHP-open tag already has a new-line
750                 if (T_OPEN_TAG === $token[0]) {
751                     $ignoreSpace = true;
752                 }
753             }
754         }
755
756         $output .= $rawChunk;
757
758         if (\PHP_VERSION_ID >= 70000) {
759             // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
760             unset($tokens, $rawChunk);
761             gc_mem_caches();
762         }
763
764         return $output;
765     }
766
767     public function serialize()
768     {
769         return serialize(array($this->environment, $this->debug));
770     }
771
772     public function unserialize($data)
773     {
774         list($environment, $debug) = unserialize($data);
775
776         $this->__construct($environment, $debug);
777     }
778 }