annotate vendor/symfony/http-kernel/Kernel.php @ 19:fa3358dc1485 tip

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