annotate vendor/symfony/http-kernel/Kernel.php @ 16:c2387f117808

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