Ajout des vendor

This commit is contained in:
2022-04-07 13:06:23 +02:00
parent ea47c93aa7
commit 5c116e15b1
1348 changed files with 184572 additions and 1 deletions

View File

@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Attribute;
trigger_deprecation('symfony/http-kernel', '5.3', 'The "%s" interface is deprecated.', ArgumentInterface::class);
/**
* Marker interface for controller argument attributes.
*
* @deprecated since Symfony 5.3
*/
interface ArgumentInterface
{
}

View File

@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Attribute;
/**
* Service tag to autoconfigure controllers.
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
class AsController
{
public function __construct()
{
}
}

View File

@ -0,0 +1,163 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Bundle;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
/**
* An implementation of BundleInterface that adds a few conventions for DependencyInjection extensions.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class Bundle implements BundleInterface
{
use ContainerAwareTrait;
protected $name;
protected $extension;
protected $path;
private $namespace;
/**
* {@inheritdoc}
*/
public function boot()
{
}
/**
* {@inheritdoc}
*/
public function shutdown()
{
}
/**
* {@inheritdoc}
*
* This method can be overridden to register compilation passes,
* other extensions, ...
*/
public function build(ContainerBuilder $container)
{
}
/**
* Returns the bundle's container extension.
*
* @return ExtensionInterface|null
*
* @throws \LogicException
*/
public function getContainerExtension()
{
if (null === $this->extension) {
$extension = $this->createContainerExtension();
if (null !== $extension) {
if (!$extension instanceof ExtensionInterface) {
throw new \LogicException(sprintf('Extension "%s" must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface.', get_debug_type($extension)));
}
// check naming convention
$basename = preg_replace('/Bundle$/', '', $this->getName());
$expectedAlias = Container::underscore($basename);
if ($expectedAlias != $extension->getAlias()) {
throw new \LogicException(sprintf('Users will expect the alias of the default extension of a bundle to be the underscored version of the bundle name ("%s"). You can override "Bundle::getContainerExtension()" if you want to use "%s" or another alias.', $expectedAlias, $extension->getAlias()));
}
$this->extension = $extension;
} else {
$this->extension = false;
}
}
return $this->extension ?: null;
}
/**
* {@inheritdoc}
*/
public function getNamespace()
{
if (null === $this->namespace) {
$this->parseClassName();
}
return $this->namespace;
}
/**
* {@inheritdoc}
*/
public function getPath()
{
if (null === $this->path) {
$reflected = new \ReflectionObject($this);
$this->path = \dirname($reflected->getFileName());
}
return $this->path;
}
/**
* Returns the bundle name (the class short name).
*/
final public function getName(): string
{
if (null === $this->name) {
$this->parseClassName();
}
return $this->name;
}
public function registerCommands(Application $application)
{
}
/**
* Returns the bundle's container extension class.
*
* @return string
*/
protected function getContainerExtensionClass()
{
$basename = preg_replace('/Bundle$/', '', $this->getName());
return $this->getNamespace().'\\DependencyInjection\\'.$basename.'Extension';
}
/**
* Creates the bundle's container extension.
*
* @return ExtensionInterface|null
*/
protected function createContainerExtension()
{
return class_exists($class = $this->getContainerExtensionClass()) ? new $class() : null;
}
private function parseClassName()
{
$pos = strrpos(static::class, '\\');
$this->namespace = false === $pos ? '' : substr(static::class, 0, $pos);
if (null === $this->name) {
$this->name = false === $pos ? static::class : substr(static::class, $pos + 1);
}
}
}

View File

@ -0,0 +1,71 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Bundle;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
/**
* BundleInterface.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface BundleInterface extends ContainerAwareInterface
{
/**
* Boots the Bundle.
*/
public function boot();
/**
* Shutdowns the Bundle.
*/
public function shutdown();
/**
* Builds the bundle.
*
* It is only ever called once when the cache is empty.
*/
public function build(ContainerBuilder $container);
/**
* Returns the container extension that should be implicitly loaded.
*
* @return ExtensionInterface|null
*/
public function getContainerExtension();
/**
* Returns the bundle name (the class short name).
*
* @return string
*/
public function getName();
/**
* Gets the Bundle namespace.
*
* @return string
*/
public function getNamespace();
/**
* Gets the Bundle directory path.
*
* The path should always be returned as a Unix path (with /).
*
* @return string
*/
public function getPath();
}

317
vendor/symfony/http-kernel/CHANGELOG.md vendored Normal file
View File

@ -0,0 +1,317 @@
CHANGELOG
=========
5.4
---
* Add the ability to enable the profiler using a request query parameter, body parameter or attribute
* Deprecate `AbstractTestSessionListener` and `TestSessionListener`, use `AbstractSessionListener` and `SessionListener` instead
* Deprecate the `fileLinkFormat` parameter of `DebugHandlersListener`
* Add support for configuring log level, and status code by exception class
* Allow ignoring "kernel.reset" methods that don't exist with "on_invalid" attribute
5.3
---
* Deprecate `ArgumentInterface`
* Add `ArgumentMetadata::getAttributes()`
* Deprecate `ArgumentMetadata::getAttribute()`, use `getAttributes()` instead
* Mark the class `Symfony\Component\HttpKernel\EventListener\DebugHandlersListener` as internal
* Deprecate returning a `ContainerBuilder` from `KernelInterface::registerContainerConfiguration()`
* Deprecate `HttpKernelInterface::MASTER_REQUEST` and add `HttpKernelInterface::MAIN_REQUEST` as replacement
* Deprecate `KernelEvent::isMasterRequest()` and add `isMainRequest()` as replacement
* Add `#[AsController]` attribute for declaring standalone controllers on PHP 8
* Add `FragmentUriGeneratorInterface` and `FragmentUriGenerator` to generate the URI of a fragment
5.2.0
-----
* added session usage
* made the public `http_cache` service handle requests when available
* allowed enabling trusted hosts and proxies using new `kernel.trusted_hosts`,
`kernel.trusted_proxies` and `kernel.trusted_headers` parameters
* content of request parameter `_password` is now also hidden
in the request profiler raw content section
* Allowed adding attributes on controller arguments that will be passed to argument resolvers.
* kernels implementing the `ExtensionInterface` will now be auto-registered to the container
* added parameter `kernel.runtime_environment`, defined as `%env(default:kernel.environment:APP_RUNTIME_ENV)%`
* do not set a default `Accept` HTTP header when using `HttpKernelBrowser`
5.1.0
-----
* allowed to use a specific logger channel for deprecations
* made `WarmableInterface::warmUp()` return a list of classes or files to preload on PHP 7.4+;
not returning an array is deprecated
* made kernels implementing `WarmableInterface` be part of the cache warmup stage
* deprecated support for `service:action` syntax to reference controllers, use `serviceOrFqcn::method` instead
* allowed using public aliases to reference controllers
* added session usage reporting when the `_stateless` attribute of the request is set to `true`
* added `AbstractSessionListener::onSessionUsage()` to report when the session is used while a request is stateless
5.0.0
-----
* removed support for getting the container from a non-booted kernel
* removed the first and second constructor argument of `ConfigDataCollector`
* removed `ConfigDataCollector::getApplicationName()`
* removed `ConfigDataCollector::getApplicationVersion()`
* removed support for `Symfony\Component\Templating\EngineInterface` in `HIncludeFragmentRenderer`, use a `Twig\Environment` only
* removed `TranslatorListener` in favor of `LocaleAwareListener`
* removed `getRootDir()` and `getName()` from `Kernel` and `KernelInterface`
* removed `FilterControllerArgumentsEvent`, use `ControllerArgumentsEvent` instead
* removed `FilterControllerEvent`, use `ControllerEvent` instead
* removed `FilterResponseEvent`, use `ResponseEvent` instead
* removed `GetResponseEvent`, use `RequestEvent` instead
* removed `GetResponseForControllerResultEvent`, use `ViewEvent` instead
* removed `GetResponseForExceptionEvent`, use `ExceptionEvent` instead
* removed `PostResponseEvent`, use `TerminateEvent` instead
* removed `SaveSessionListener` in favor of `AbstractSessionListener`
* removed `Client`, use `HttpKernelBrowser` instead
* added method `getProjectDir()` to `KernelInterface`
* removed methods `serialize` and `unserialize` from `DataCollector`, store the serialized state in the data property instead
* made `ProfilerStorageInterface` internal
* removed the second and third argument of `KernelInterface::locateResource`
* removed the second and third argument of `FileLocator::__construct`
* removed loading resources from `%kernel.root_dir%/Resources` and `%kernel.root_dir%` as
fallback directories.
* removed class `ExceptionListener`, use `ErrorListener` instead
4.4.0
-----
* The `DebugHandlersListener` class has been marked as `final`
* Added new Bundle directory convention consistent with standard skeletons
* Deprecated the second and third argument of `KernelInterface::locateResource`
* Deprecated the second and third argument of `FileLocator::__construct`
* Deprecated loading resources from `%kernel.root_dir%/Resources` and `%kernel.root_dir%` as
fallback directories. Resources like service definitions are usually loaded relative to the
current directory or with a glob pattern. The fallback directories have never been advocated
so you likely do not use those in any app based on the SF Standard or Flex edition.
* Marked all dispatched event classes as `@final`
* Added `ErrorController` to enable the preview and error rendering mechanism
* Getting the container from a non-booted kernel is deprecated.
* Marked the `AjaxDataCollector`, `ConfigDataCollector`, `EventDataCollector`,
`ExceptionDataCollector`, `LoggerDataCollector`, `MemoryDataCollector`,
`RequestDataCollector` and `TimeDataCollector` classes as `@final`.
* Marked the `RouterDataCollector::collect()` method as `@final`.
* The `DataCollectorInterface::collect()` and `Profiler::collect()` methods third parameter signature
will be `\Throwable $exception = null` instead of `\Exception $exception = null` in Symfony 5.0.
* Deprecated methods `ExceptionEvent::get/setException()`, use `get/setThrowable()` instead
* Deprecated class `ExceptionListener`, use `ErrorListener` instead
4.3.0
-----
* renamed `Client` to `HttpKernelBrowser`
* `KernelInterface` doesn't extend `Serializable` anymore
* deprecated the `Kernel::serialize()` and `unserialize()` methods
* increased the priority of `Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener`
* made `Symfony\Component\HttpKernel\EventListener\LocaleListener` set the default locale early
* deprecated `TranslatorListener` in favor of `LocaleAwareListener`
* added the registration of all `LocaleAwareInterface` implementations into the `LocaleAwareListener`
* made `FileLinkFormatter` final and not implement `Serializable` anymore
* the base `DataCollector` doesn't implement `Serializable` anymore, you should
store all the serialized state in the data property instead
* `DumpDataCollector` has been marked as `final`
* added an event listener to prevent search engines from indexing applications in debug mode.
* renamed `FilterControllerArgumentsEvent` to `ControllerArgumentsEvent`
* renamed `FilterControllerEvent` to `ControllerEvent`
* renamed `FilterResponseEvent` to `ResponseEvent`
* renamed `GetResponseEvent` to `RequestEvent`
* renamed `GetResponseForControllerResultEvent` to `ViewEvent`
* renamed `GetResponseForExceptionEvent` to `ExceptionEvent`
* renamed `PostResponseEvent` to `TerminateEvent`
* added `HttpClientKernel` for handling requests with an `HttpClientInterface` instance
* added `trace_header` and `trace_level` configuration options to `HttpCache`
4.2.0
-----
* deprecated `KernelInterface::getRootDir()` and the `kernel.root_dir` parameter
* deprecated `KernelInterface::getName()` and the `kernel.name` parameter
* deprecated the first and second constructor argument of `ConfigDataCollector`
* deprecated `ConfigDataCollector::getApplicationName()`
* deprecated `ConfigDataCollector::getApplicationVersion()`
4.1.0
-----
* added orphaned events support to `EventDataCollector`
* `ExceptionListener` now logs exceptions at priority `0` (previously logged at `-128`)
* Added support for using `service::method` to reference controllers, making it consistent with other cases. It is recommended over the `service:action` syntax with a single colon, which will be deprecated in the future.
* Added the ability to profile individual argument value resolvers via the
`Symfony\Component\HttpKernel\Controller\ArgumentResolver\TraceableValueResolver`
4.0.0
-----
* removed the `DataCollector::varToString()` method, use `DataCollector::cloneVar()`
instead
* using the `DataCollector::cloneVar()` method requires the VarDumper component
* removed the `ValueExporter` class
* removed `ControllerResolverInterface::getArguments()`
* removed `TraceableControllerResolver::getArguments()`
* removed `ControllerResolver::getArguments()` and the ability to resolve arguments
* removed the `argument_resolver` service dependency from the `debug.controller_resolver`
* removed `LazyLoadingFragmentHandler::addRendererService()`
* removed `Psr6CacheClearer::addPool()`
* removed `Extension::addClassesToCompile()` and `Extension::getClassesToCompile()`
* removed `Kernel::loadClassCache()`, `Kernel::doLoadClassCache()`, `Kernel::setClassCache()`,
and `Kernel::getEnvParameters()`
* support for the `X-Status-Code` when handling exceptions in the `HttpKernel`
has been dropped, use the `HttpKernel::allowCustomResponseCode()` method
instead
* removed convention-based commands registration
* removed the `ChainCacheClearer::add()` method
* removed the `CacheaWarmerAggregate::add()` and `setWarmers()` methods
* made `CacheWarmerAggregate` and `ChainCacheClearer` classes final
3.4.0
-----
* added a minimalist PSR-3 `Logger` class that writes in `stderr`
* made kernels implementing `CompilerPassInterface` able to process the container
* deprecated bundle inheritance
* added `RebootableInterface` and implemented it in `Kernel`
* deprecated commands auto registration
* deprecated `EnvParametersResource`
* added `Symfony\Component\HttpKernel\Client::catchExceptions()`
* deprecated the `ChainCacheClearer::add()` method
* deprecated the `CacheaWarmerAggregate::add()` and `setWarmers()` methods
* made `CacheWarmerAggregate` and `ChainCacheClearer` classes final
* added the possibility to reset the profiler to its initial state
* deprecated data collectors without a `reset()` method
* deprecated implementing `DebugLoggerInterface` without a `clear()` method
3.3.0
-----
* added `kernel.project_dir` and `Kernel::getProjectDir()`
* deprecated `kernel.root_dir` and `Kernel::getRootDir()`
* deprecated `Kernel::getEnvParameters()`
* deprecated the special `SYMFONY__` environment variables
* added the possibility to change the query string parameter used by `UriSigner`
* deprecated `LazyLoadingFragmentHandler::addRendererService()`
* deprecated `Extension::addClassesToCompile()` and `Extension::getClassesToCompile()`
* deprecated `Psr6CacheClearer::addPool()`
3.2.0
-----
* deprecated `DataCollector::varToString()`, use `cloneVar()` instead
* changed surrogate capability name in `AbstractSurrogate::addSurrogateCapability` to 'symfony'
* Added `ControllerArgumentValueResolverPass`
3.1.0
-----
* deprecated passing objects as URI attributes to the ESI and SSI renderers
* deprecated `ControllerResolver::getArguments()`
* added `Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface`
* added `Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface` as argument to `HttpKernel`
* added `Symfony\Component\HttpKernel\Controller\ArgumentResolver`
* added `Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::getMethod()`
* added `Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::getRedirect()`
* added the `kernel.controller_arguments` event, triggered after controller arguments have been resolved
3.0.0
-----
* removed `Symfony\Component\HttpKernel\Kernel::init()`
* removed `Symfony\Component\HttpKernel\Kernel::isClassInActiveBundle()` and `Symfony\Component\HttpKernel\KernelInterface::isClassInActiveBundle()`
* removed `Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher::setProfiler()`
* removed `Symfony\Component\HttpKernel\EventListener\FragmentListener::getLocalIpAddresses()`
* removed `Symfony\Component\HttpKernel\EventListener\LocaleListener::setRequest()`
* removed `Symfony\Component\HttpKernel\EventListener\RouterListener::setRequest()`
* removed `Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest()`
* removed `Symfony\Component\HttpKernel\Fragment\FragmentHandler::setRequest()`
* removed `Symfony\Component\HttpKernel\HttpCache\Esi::hasSurrogateEsiCapability()`
* removed `Symfony\Component\HttpKernel\HttpCache\Esi::addSurrogateEsiCapability()`
* removed `Symfony\Component\HttpKernel\HttpCache\Esi::needsEsiParsing()`
* removed `Symfony\Component\HttpKernel\HttpCache\HttpCache::getEsi()`
* removed `Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel`
* removed `Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass`
* removed `Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener`
* removed `Symfony\Component\HttpKernel\EventListener\EsiListener`
* removed `Symfony\Component\HttpKernel\HttpCache\EsiResponseCacheStrategy`
* removed `Symfony\Component\HttpKernel\HttpCache\EsiResponseCacheStrategyInterface`
* removed `Symfony\Component\HttpKernel\Log\LoggerInterface`
* removed `Symfony\Component\HttpKernel\Log\NullLogger`
* removed `Symfony\Component\HttpKernel\Profiler::import()`
* removed `Symfony\Component\HttpKernel\Profiler::export()`
2.8.0
-----
* deprecated `Profiler::import` and `Profiler::export`
2.7.0
-----
* added the HTTP status code to profiles
2.6.0
-----
* deprecated `Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener`, use `Symfony\Component\HttpKernel\EventListener\DebugHandlersListener` instead
* deprecated unused method `Symfony\Component\HttpKernel\Kernel::isClassInActiveBundle` and `Symfony\Component\HttpKernel\KernelInterface::isClassInActiveBundle`
2.5.0
-----
* deprecated `Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass`, use `Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass` instead
2.4.0
-----
* added event listeners for the session
* added the KernelEvents::FINISH_REQUEST event
2.3.0
-----
* [BC BREAK] renamed `Symfony\Component\HttpKernel\EventListener\DeprecationLoggerListener` to `Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener` and changed its constructor
* deprecated `Symfony\Component\HttpKernel\Debug\ErrorHandler`, `Symfony\Component\HttpKernel\Debug\ExceptionHandler`,
`Symfony\Component\HttpKernel\Exception\FatalErrorException` and `Symfony\Component\HttpKernel\Exception\FlattenException`
* deprecated `Symfony\Component\HttpKernel\Kernel::init()`
* added the possibility to specify an id an extra attributes to hinclude tags
* added the collect of data if a controller is a Closure in the Request collector
* pass exceptions from the ExceptionListener to the logger using the logging context to allow for more
detailed messages
2.2.0
-----
* [BC BREAK] the path info for sub-request is now always _fragment (or whatever you configured instead of the default)
* added Symfony\Component\HttpKernel\EventListener\FragmentListener
* added Symfony\Component\HttpKernel\UriSigner
* added Symfony\Component\HttpKernel\FragmentRenderer and rendering strategies (in Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface)
* added Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel
* added ControllerReference to create reference of Controllers (used in the FragmentRenderer class)
* [BC BREAK] renamed TimeDataCollector::getTotalTime() to
TimeDataCollector::getDuration()
* updated the MemoryDataCollector to include the memory used in the
kernel.terminate event listeners
* moved the Stopwatch classes to a new component
* added TraceableControllerResolver
* added TraceableEventDispatcher (removed ContainerAwareTraceableEventDispatcher)
* added support for WinCache opcode cache in ConfigDataCollector
2.1.0
-----
* [BC BREAK] the charset is now configured via the Kernel::getCharset() method
* [BC BREAK] the current locale for the user is not stored anymore in the session
* added the HTTP method to the profiler storage
* updated all listeners to implement EventSubscriberInterface
* added TimeDataCollector
* added ContainerAwareTraceableEventDispatcher
* moved TraceableEventDispatcherInterface to the EventDispatcher component
* added RouterListener, LocaleListener, and StreamedResponseListener
* added CacheClearerInterface (and ChainCacheClearer)
* added a kernel.terminate event (via TerminableInterface and PostResponseEvent)
* added a Stopwatch class
* added WarmableInterface
* improved extensibility between bundles
* added profiler storages for Memcache(d), File-based, MongoDB, Redis
* moved Filesystem class to its own component

View File

@ -0,0 +1,25 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheClearer;
/**
* CacheClearerInterface.
*
* @author Dustin Dobervich <ddobervich@gmail.com>
*/
interface CacheClearerInterface
{
/**
* Clears any caches necessary.
*/
public function clear(string $cacheDir);
}

View File

@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheClearer;
/**
* ChainCacheClearer.
*
* @author Dustin Dobervich <ddobervich@gmail.com>
*
* @final
*/
class ChainCacheClearer implements CacheClearerInterface
{
private $clearers;
/**
* @param iterable<mixed, CacheClearerInterface> $clearers
*/
public function __construct(iterable $clearers = [])
{
$this->clearers = $clearers;
}
/**
* {@inheritdoc}
*/
public function clear(string $cacheDir)
{
foreach ($this->clearers as $clearer) {
$clearer->clear($cacheDir);
}
}
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheClearer;
use Psr\Cache\CacheItemPoolInterface;
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class Psr6CacheClearer implements CacheClearerInterface
{
private $pools = [];
/**
* @param array<string, CacheItemPoolInterface> $pools
*/
public function __construct(array $pools = [])
{
$this->pools = $pools;
}
/**
* @return bool
*/
public function hasPool(string $name)
{
return isset($this->pools[$name]);
}
/**
* @return CacheItemPoolInterface
*
* @throws \InvalidArgumentException If the cache pool with the given name does not exist
*/
public function getPool(string $name)
{
if (!$this->hasPool($name)) {
throw new \InvalidArgumentException(sprintf('Cache pool not found: "%s".', $name));
}
return $this->pools[$name];
}
/**
* @return bool
*
* @throws \InvalidArgumentException If the cache pool with the given name does not exist
*/
public function clearPool(string $name)
{
if (!isset($this->pools[$name])) {
throw new \InvalidArgumentException(sprintf('Cache pool not found: "%s".', $name));
}
return $this->pools[$name]->clear();
}
/**
* {@inheritdoc}
*/
public function clear(string $cacheDir)
{
foreach ($this->pools as $pool) {
$pool->clear();
}
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheWarmer;
/**
* Abstract cache warmer that knows how to write a file to the cache.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class CacheWarmer implements CacheWarmerInterface
{
protected function writeCacheFile(string $file, $content)
{
$tmpFile = @tempnam(\dirname($file), basename($file));
if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
@chmod($file, 0666 & ~umask());
return;
}
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
}
}

View File

@ -0,0 +1,126 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheWarmer;
/**
* Aggregates several cache warmers into a single one.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class CacheWarmerAggregate implements CacheWarmerInterface
{
private $warmers;
private $debug;
private $deprecationLogsFilepath;
private $optionalsEnabled = false;
private $onlyOptionalsEnabled = false;
/**
* @param iterable<mixed, CacheWarmerInterface> $warmers
*/
public function __construct(iterable $warmers = [], bool $debug = false, string $deprecationLogsFilepath = null)
{
$this->warmers = $warmers;
$this->debug = $debug;
$this->deprecationLogsFilepath = $deprecationLogsFilepath;
}
public function enableOptionalWarmers()
{
$this->optionalsEnabled = true;
}
public function enableOnlyOptionalWarmers()
{
$this->onlyOptionalsEnabled = $this->optionalsEnabled = true;
}
/**
* {@inheritdoc}
*/
public function warmUp(string $cacheDir): array
{
if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) {
$collectedLogs = [];
$previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) {
return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
}
if (isset($collectedLogs[$message])) {
++$collectedLogs[$message]['count'];
return null;
}
$backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3);
// Clean the trace by removing first frames added by the error handler itself.
for ($i = 0; isset($backtrace[$i]); ++$i) {
if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
$backtrace = \array_slice($backtrace, 1 + $i);
break;
}
}
$collectedLogs[$message] = [
'type' => $type,
'message' => $message,
'file' => $file,
'line' => $line,
'trace' => $backtrace,
'count' => 1,
];
return null;
});
}
$preload = [];
try {
foreach ($this->warmers as $warmer) {
if (!$this->optionalsEnabled && $warmer->isOptional()) {
continue;
}
if ($this->onlyOptionalsEnabled && !$warmer->isOptional()) {
continue;
}
$preload[] = array_values((array) $warmer->warmUp($cacheDir));
}
} finally {
if ($collectDeprecations) {
restore_error_handler();
if (is_file($this->deprecationLogsFilepath)) {
$previousLogs = unserialize(file_get_contents($this->deprecationLogsFilepath));
if (\is_array($previousLogs)) {
$collectedLogs = array_merge($previousLogs, $collectedLogs);
}
}
file_put_contents($this->deprecationLogsFilepath, serialize(array_values($collectedLogs)));
}
}
return array_values(array_unique(array_merge([], ...$preload)));
}
/**
* {@inheritdoc}
*/
public function isOptional(): bool
{
return false;
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheWarmer;
/**
* Interface for classes able to warm up the cache.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface CacheWarmerInterface extends WarmableInterface
{
/**
* Checks whether this warmer is optional or not.
*
* Optional warmers can be ignored on certain conditions.
*
* A warmer should return true if the cache can be
* generated incrementally and on-demand.
*
* @return bool
*/
public function isOptional();
}

View File

@ -0,0 +1,27 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheWarmer;
/**
* Interface for classes that support warming their cache.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface WarmableInterface
{
/**
* Warms up the cache.
*
* @return string[] A list of classes or files to preload on PHP 7.4+
*/
public function warmUp(string $cacheDir);
}

View File

@ -0,0 +1,46 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Config;
use Symfony\Component\Config\FileLocator as BaseFileLocator;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* FileLocator uses the KernelInterface to locate resources in bundles.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FileLocator extends BaseFileLocator
{
private $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
parent::__construct();
}
/**
* {@inheritdoc}
*/
public function locate(string $file, string $currentPath = null, bool $first = true)
{
if (isset($file[0]) && '@' === $file[0]) {
$resource = $this->kernel->locateResource($file);
return $first ? $resource : [$resource];
}
return parent::locate($file, $currentPath, $first);
}
}

View File

@ -0,0 +1,98 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\DefaultValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestAttributeValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\SessionValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\VariadicValueResolver;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface;
/**
* Responsible for resolving the arguments passed to an action.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class ArgumentResolver implements ArgumentResolverInterface
{
private $argumentMetadataFactory;
private $argumentValueResolvers;
/**
* @param iterable<mixed, ArgumentValueResolverInterface> $argumentValueResolvers
*/
public function __construct(ArgumentMetadataFactoryInterface $argumentMetadataFactory = null, iterable $argumentValueResolvers = [])
{
$this->argumentMetadataFactory = $argumentMetadataFactory ?? new ArgumentMetadataFactory();
$this->argumentValueResolvers = $argumentValueResolvers ?: self::getDefaultArgumentValueResolvers();
}
/**
* {@inheritdoc}
*/
public function getArguments(Request $request, callable $controller): array
{
$arguments = [];
foreach ($this->argumentMetadataFactory->createArgumentMetadata($controller) as $metadata) {
foreach ($this->argumentValueResolvers as $resolver) {
if (!$resolver->supports($request, $metadata)) {
continue;
}
$resolved = $resolver->resolve($request, $metadata);
$atLeastOne = false;
foreach ($resolved as $append) {
$atLeastOne = true;
$arguments[] = $append;
}
if (!$atLeastOne) {
throw new \InvalidArgumentException(sprintf('"%s::resolve()" must yield at least one value.', get_debug_type($resolver)));
}
// continue to the next controller argument
continue 2;
}
$representative = $controller;
if (\is_array($representative)) {
$representative = sprintf('%s::%s()', \get_class($representative[0]), $representative[1]);
} elseif (\is_object($representative)) {
$representative = \get_class($representative);
}
throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.', $representative, $metadata->getName()));
}
return $arguments;
}
/**
* @return iterable<int, ArgumentValueResolverInterface>
*/
public static function getDefaultArgumentValueResolvers(): iterable
{
return [
new RequestAttributeValueResolver(),
new RequestValueResolver(),
new SessionValueResolver(),
new DefaultValueResolver(),
new VariadicValueResolver(),
];
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Yields the default value defined in the action signature when no value has been given.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class DefaultValueResolver implements ArgumentValueResolverInterface
{
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return $argument->hasDefaultValue() || (null !== $argument->getType() && $argument->isNullable() && !$argument->isVariadic());
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
yield $argument->hasDefaultValue() ? $argument->getDefaultValue() : null;
}
}

View File

@ -0,0 +1,81 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Provides an intuitive error message when controller fails because it is not registered as a service.
*
* @author Simeon Kolev <simeon.kolev9@gmail.com>
*/
final class NotTaggedControllerValueResolver implements ArgumentValueResolverInterface
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
$controller = $request->attributes->get('_controller');
if (\is_array($controller) && \is_callable($controller, true) && \is_string($controller[0])) {
$controller = $controller[0].'::'.$controller[1];
} elseif (!\is_string($controller) || '' === $controller) {
return false;
}
if ('\\' === $controller[0]) {
$controller = ltrim($controller, '\\');
}
if (!$this->container->has($controller) && false !== $i = strrpos($controller, ':')) {
$controller = substr($controller, 0, $i).strtolower(substr($controller, $i));
}
return false === $this->container->has($controller);
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
if (\is_array($controller = $request->attributes->get('_controller'))) {
$controller = $controller[0].'::'.$controller[1];
}
if ('\\' === $controller[0]) {
$controller = ltrim($controller, '\\');
}
if (!$this->container->has($controller)) {
$i = strrpos($controller, ':');
$controller = substr($controller, 0, $i).strtolower(substr($controller, $i));
}
$what = sprintf('argument $%s of "%s()"', $argument->getName(), $controller);
$message = sprintf('Could not resolve %s, maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?', $what);
throw new RuntimeException($message);
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Yields a non-variadic argument's value from the request attributes.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class RequestAttributeValueResolver implements ArgumentValueResolverInterface
{
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return !$argument->isVariadic() && $request->attributes->has($argument->getName());
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
yield $request->attributes->get($argument->getName());
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Yields the same instance as the request object passed along.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class RequestValueResolver implements ArgumentValueResolverInterface
{
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return Request::class === $argument->getType() || is_subclass_of($argument->getType(), Request::class);
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
yield $request;
}
}

View File

@ -0,0 +1,93 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Yields a service keyed by _controller and argument name.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class ServiceValueResolver implements ArgumentValueResolverInterface
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
$controller = $request->attributes->get('_controller');
if (\is_array($controller) && \is_callable($controller, true) && \is_string($controller[0])) {
$controller = $controller[0].'::'.$controller[1];
} elseif (!\is_string($controller) || '' === $controller) {
return false;
}
if ('\\' === $controller[0]) {
$controller = ltrim($controller, '\\');
}
if (!$this->container->has($controller) && false !== $i = strrpos($controller, ':')) {
$controller = substr($controller, 0, $i).strtolower(substr($controller, $i));
}
return $this->container->has($controller) && $this->container->get($controller)->has($argument->getName());
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
if (\is_array($controller = $request->attributes->get('_controller'))) {
$controller = $controller[0].'::'.$controller[1];
}
if ('\\' === $controller[0]) {
$controller = ltrim($controller, '\\');
}
if (!$this->container->has($controller)) {
$i = strrpos($controller, ':');
$controller = substr($controller, 0, $i).strtolower(substr($controller, $i));
}
try {
yield $this->container->get($controller)->get($argument->getName());
} catch (RuntimeException $e) {
$what = sprintf('argument $%s of "%s()"', $argument->getName(), $controller);
$message = preg_replace('/service "\.service_locator\.[^"]++"/', $what, $e->getMessage());
if ($e->getMessage() === $message) {
$message = sprintf('Cannot resolve %s: %s', $what, $message);
}
$r = new \ReflectionProperty($e, 'message');
$r->setAccessible(true);
$r->setValue($e, $message);
throw $e;
}
}
}

View File

@ -0,0 +1,50 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Yields the Session.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class SessionValueResolver implements ArgumentValueResolverInterface
{
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
if (!$request->hasSession()) {
return false;
}
$type = $argument->getType();
if (SessionInterface::class !== $type && !is_subclass_of($type, SessionInterface::class)) {
return false;
}
return $request->getSession() instanceof $type;
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
yield $request->getSession();
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\Stopwatch\Stopwatch;
/**
* Provides timing information via the stopwatch.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class TraceableValueResolver implements ArgumentValueResolverInterface
{
private $inner;
private $stopwatch;
public function __construct(ArgumentValueResolverInterface $inner, Stopwatch $stopwatch)
{
$this->inner = $inner;
$this->stopwatch = $stopwatch;
}
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
$method = \get_class($this->inner).'::'.__FUNCTION__;
$this->stopwatch->start($method, 'controller.argument_value_resolver');
$return = $this->inner->supports($request, $argument);
$this->stopwatch->stop($method);
return $return;
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
$method = \get_class($this->inner).'::'.__FUNCTION__;
$this->stopwatch->start($method, 'controller.argument_value_resolver');
yield from $this->inner->resolve($request, $argument);
$this->stopwatch->stop($method);
}
}

View File

@ -0,0 +1,46 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Yields a variadic argument's values from the request attributes.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class VariadicValueResolver implements ArgumentValueResolverInterface
{
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return $argument->isVariadic() && $request->attributes->has($argument->getName());
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
$values = $request->attributes->get($argument->getName());
if (!\is_array($values)) {
throw new \InvalidArgumentException(sprintf('The action argument "...$%1$s" is required to be an array, the request attribute "%1$s" contains a type of "%2$s" instead.', $argument->getName(), get_debug_type($values)));
}
yield from $values;
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* An ArgumentResolverInterface instance knows how to determine the
* arguments for a specific action.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface ArgumentResolverInterface
{
/**
* Returns the arguments to pass to the controller.
*
* @return array
*
* @throws \RuntimeException When no value could be provided for a required argument
*/
public function getArguments(Request $request, callable $controller);
}

View File

@ -0,0 +1,37 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
/**
* Responsible for resolving the value of an argument based on its metadata.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
interface ArgumentValueResolverInterface
{
/**
* Whether this resolver can resolve the value for the given ArgumentMetadata.
*
* @return bool
*/
public function supports(Request $request, ArgumentMetadata $argument);
/**
* Returns the possible value(s).
*
* @return iterable
*/
public function resolve(Request $request, ArgumentMetadata $argument);
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Container;
/**
* A controller resolver searching for a controller in a psr-11 container when using the "service::method" notation.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
class ContainerControllerResolver extends ControllerResolver
{
protected $container;
public function __construct(ContainerInterface $container, LoggerInterface $logger = null)
{
$this->container = $container;
parent::__construct($logger);
}
protected function createController(string $controller)
{
if (1 === substr_count($controller, ':')) {
$controller = str_replace(':', '::', $controller);
trigger_deprecation('symfony/http-kernel', '5.1', 'Referencing controllers with a single colon is deprecated. Use "%s" instead.', $controller);
}
return parent::createController($controller);
}
/**
* {@inheritdoc}
*/
protected function instantiateController(string $class)
{
$class = ltrim($class, '\\');
if ($this->container->has($class)) {
return $this->container->get($class);
}
try {
return parent::instantiateController($class);
} catch (\Error $e) {
}
$this->throwExceptionIfControllerWasRemoved($class, $e);
if ($e instanceof \ArgumentCountError) {
throw new \InvalidArgumentException(sprintf('Controller "%s" has required constructor arguments and does not exist in the container. Did you forget to define the controller as a service?', $class), 0, $e);
}
throw new \InvalidArgumentException(sprintf('Controller "%s" does neither exist as service nor as class.', $class), 0, $e);
}
private function throwExceptionIfControllerWasRemoved(string $controller, \Throwable $previous)
{
if ($this->container instanceof Container && isset($this->container->getRemovedIds()[$controller])) {
throw new \InvalidArgumentException(sprintf('Controller "%s" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?', $controller), 0, $previous);
}
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
/**
* Acts as a marker and a data holder for a Controller.
*
* Some methods in Symfony accept both a URI (as a string) or a controller as
* an argument. In the latter case, instead of passing an array representing
* the controller, you can use an instance of this class.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @see FragmentRendererInterface
*/
class ControllerReference
{
public $controller;
public $attributes = [];
public $query = [];
/**
* @param string $controller The controller name
* @param array $attributes An array of parameters to add to the Request attributes
* @param array $query An array of parameters to add to the Request query string
*/
public function __construct(string $controller, array $attributes = [], array $query = [])
{
$this->controller = $controller;
$this->attributes = $attributes;
$this->query = $query;
}
}

View File

@ -0,0 +1,220 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* This implementation uses the '_controller' request attribute to determine
* the controller to execute.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Tobias Schultze <http://tobion.de>
*/
class ControllerResolver implements ControllerResolverInterface
{
private $logger;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function getController(Request $request)
{
if (!$controller = $request->attributes->get('_controller')) {
if (null !== $this->logger) {
$this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
}
return false;
}
if (\is_array($controller)) {
if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) {
try {
$controller[0] = $this->instantiateController($controller[0]);
} catch (\Error|\LogicException $e) {
try {
// We cannot just check is_callable but have to use reflection because a non-static method
// can still be called statically in PHP but we don't want that. This is deprecated in PHP 7, so we
// could simplify this with PHP 8.
if ((new \ReflectionMethod($controller[0], $controller[1]))->isStatic()) {
return $controller;
}
} catch (\ReflectionException $reflectionException) {
throw $e;
}
throw $e;
}
}
if (!\is_callable($controller)) {
throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
}
return $controller;
}
if (\is_object($controller)) {
if (!\is_callable($controller)) {
throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
}
return $controller;
}
if (\function_exists($controller)) {
return $controller;
}
try {
$callable = $this->createController($controller);
} catch (\InvalidArgumentException $e) {
throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e);
}
if (!\is_callable($callable)) {
throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable));
}
return $callable;
}
/**
* Returns a callable for the given controller.
*
* @return callable
*
* @throws \InvalidArgumentException When the controller cannot be created
*/
protected function createController(string $controller)
{
if (!str_contains($controller, '::')) {
$controller = $this->instantiateController($controller);
if (!\is_callable($controller)) {
throw new \InvalidArgumentException($this->getControllerError($controller));
}
return $controller;
}
[$class, $method] = explode('::', $controller, 2);
try {
$controller = [$this->instantiateController($class), $method];
} catch (\Error|\LogicException $e) {
try {
if ((new \ReflectionMethod($class, $method))->isStatic()) {
return $class.'::'.$method;
}
} catch (\ReflectionException $reflectionException) {
throw $e;
}
throw $e;
}
if (!\is_callable($controller)) {
throw new \InvalidArgumentException($this->getControllerError($controller));
}
return $controller;
}
/**
* Returns an instantiated controller.
*
* @return object
*/
protected function instantiateController(string $class)
{
return new $class();
}
private function getControllerError($callable): string
{
if (\is_string($callable)) {
if (str_contains($callable, '::')) {
$callable = explode('::', $callable, 2);
} else {
return sprintf('Function "%s" does not exist.', $callable);
}
}
if (\is_object($callable)) {
$availableMethods = $this->getClassMethodsWithoutMagicMethods($callable);
$alternativeMsg = $availableMethods ? sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : '';
return sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', get_debug_type($callable), $alternativeMsg);
}
if (!\is_array($callable)) {
return sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($callable));
}
if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
return 'Invalid array callable, expected [controller, method].';
}
[$controller, $method] = $callable;
if (\is_string($controller) && !class_exists($controller)) {
return sprintf('Class "%s" does not exist.', $controller);
}
$className = \is_object($controller) ? get_debug_type($controller) : $controller;
if (method_exists($controller, $method)) {
return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
}
$collection = $this->getClassMethodsWithoutMagicMethods($controller);
$alternatives = [];
foreach ($collection as $item) {
$lev = levenshtein($method, $item);
if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
$alternatives[] = $item;
}
}
asort($alternatives);
$message = sprintf('Expected method "%s" on class "%s"', $method, $className);
if (\count($alternatives) > 0) {
$message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
} else {
$message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
}
return $message;
}
private function getClassMethodsWithoutMagicMethods($classOrObject): array
{
$methods = get_class_methods($classOrObject);
return array_filter($methods, function (string $method) {
return 0 !== strncmp($method, '__', 2);
});
}
}

View File

@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* A ControllerResolverInterface implementation knows how to determine the
* controller to execute based on a Request object.
*
* A Controller can be any valid PHP callable.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface ControllerResolverInterface
{
/**
* Returns the Controller instance associated with a Request.
*
* As several resolvers can exist for a single application, a resolver must
* return false when it is not able to determine the controller.
*
* The resolver must only throw an exception when it should be able to load a
* controller but cannot because of some errors made by the developer.
*
* @return callable|false A PHP callable representing the Controller,
* or false if this resolver is not able to determine the controller
*
* @throws \LogicException If a controller was found based on the request but it is not callable
*/
public function getController(Request $request);
}

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Renders error or exception pages from a given FlattenException.
*
* @author Yonel Ceruto <yonelceruto@gmail.com>
* @author Matthias Pigulla <mp@webfactory.de>
*/
class ErrorController
{
private $kernel;
private $controller;
private $errorRenderer;
public function __construct(HttpKernelInterface $kernel, $controller, ErrorRendererInterface $errorRenderer)
{
$this->kernel = $kernel;
$this->controller = $controller;
$this->errorRenderer = $errorRenderer;
}
public function __invoke(\Throwable $exception): Response
{
$exception = $this->errorRenderer->render($exception);
return new Response($exception->getAsString(), $exception->getStatusCode(), $exception->getHeaders());
}
public function preview(Request $request, int $code): Response
{
/*
* This Request mimics the parameters set by
* \Symfony\Component\HttpKernel\EventListener\ErrorListener::duplicateRequest, with
* the additional "showException" flag.
*/
$subRequest = $request->duplicate(null, null, [
'_controller' => $this->controller,
'exception' => new HttpException($code, 'This is a sample exception.'),
'logger' => null,
'showException' => false,
]);
return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Stopwatch\Stopwatch;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class TraceableArgumentResolver implements ArgumentResolverInterface
{
private $resolver;
private $stopwatch;
public function __construct(ArgumentResolverInterface $resolver, Stopwatch $stopwatch)
{
$this->resolver = $resolver;
$this->stopwatch = $stopwatch;
}
/**
* {@inheritdoc}
*/
public function getArguments(Request $request, callable $controller)
{
$e = $this->stopwatch->start('controller.get_arguments');
$ret = $this->resolver->getArguments($request, $controller);
$e->stop();
return $ret;
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Stopwatch\Stopwatch;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class TraceableControllerResolver implements ControllerResolverInterface
{
private $resolver;
private $stopwatch;
public function __construct(ControllerResolverInterface $resolver, Stopwatch $stopwatch)
{
$this->resolver = $resolver;
$this->stopwatch = $stopwatch;
}
/**
* {@inheritdoc}
*/
public function getController(Request $request)
{
$e = $this->stopwatch->start('controller.get_callable');
$ret = $this->resolver->getController($request);
$e->stop();
return $ret;
}
}

View File

@ -0,0 +1,163 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\ControllerMetadata;
use Symfony\Component\HttpKernel\Attribute\ArgumentInterface;
/**
* Responsible for storing metadata of an argument.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
class ArgumentMetadata
{
public const IS_INSTANCEOF = 2;
private $name;
private $type;
private $isVariadic;
private $hasDefaultValue;
private $defaultValue;
private $isNullable;
private $attributes;
/**
* @param object[] $attributes
*/
public function __construct(string $name, ?string $type, bool $isVariadic, bool $hasDefaultValue, $defaultValue, bool $isNullable = false, $attributes = [])
{
$this->name = $name;
$this->type = $type;
$this->isVariadic = $isVariadic;
$this->hasDefaultValue = $hasDefaultValue;
$this->defaultValue = $defaultValue;
$this->isNullable = $isNullable || null === $type || ($hasDefaultValue && null === $defaultValue);
if (null === $attributes || $attributes instanceof ArgumentInterface) {
trigger_deprecation('symfony/http-kernel', '5.3', 'The "%s" constructor expects an array of PHP attributes as last argument, %s given.', __CLASS__, get_debug_type($attributes));
$attributes = $attributes ? [$attributes] : [];
}
$this->attributes = $attributes;
}
/**
* Returns the name as given in PHP, $foo would yield "foo".
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns the type of the argument.
*
* The type is the PHP class in 5.5+ and additionally the basic type in PHP 7.0+.
*
* @return string|null
*/
public function getType()
{
return $this->type;
}
/**
* Returns whether the argument is defined as "...$variadic".
*
* @return bool
*/
public function isVariadic()
{
return $this->isVariadic;
}
/**
* Returns whether the argument has a default value.
*
* Implies whether an argument is optional.
*
* @return bool
*/
public function hasDefaultValue()
{
return $this->hasDefaultValue;
}
/**
* Returns whether the argument accepts null values.
*
* @return bool
*/
public function isNullable()
{
return $this->isNullable;
}
/**
* Returns the default value of the argument.
*
* @throws \LogicException if no default value is present; {@see self::hasDefaultValue()}
*
* @return mixed
*/
public function getDefaultValue()
{
if (!$this->hasDefaultValue) {
throw new \LogicException(sprintf('Argument $%s does not have a default value. Use "%s::hasDefaultValue()" to avoid this exception.', $this->name, __CLASS__));
}
return $this->defaultValue;
}
/**
* Returns the attribute (if any) that was set on the argument.
*/
public function getAttribute(): ?ArgumentInterface
{
trigger_deprecation('symfony/http-kernel', '5.3', 'Method "%s()" is deprecated, use "getAttributes()" instead.', __METHOD__);
if (!$this->attributes) {
return null;
}
return $this->attributes[0] instanceof ArgumentInterface ? $this->attributes[0] : null;
}
/**
* @return object[]
*/
public function getAttributes(string $name = null, int $flags = 0): array
{
if (!$name) {
return $this->attributes;
}
$attributes = [];
if ($flags & self::IS_INSTANCEOF) {
foreach ($this->attributes as $attribute) {
if ($attribute instanceof $name) {
$attributes[] = $attribute;
}
}
} else {
foreach ($this->attributes as $attribute) {
if (\get_class($attribute) === $name) {
$attributes[] = $attribute;
}
}
}
return $attributes;
}
}

View File

@ -0,0 +1,78 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\ControllerMetadata;
/**
* Builds {@see ArgumentMetadata} objects based on the given Controller.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface
{
/**
* {@inheritdoc}
*/
public function createArgumentMetadata($controller): array
{
$arguments = [];
if (\is_array($controller)) {
$reflection = new \ReflectionMethod($controller[0], $controller[1]);
$class = $reflection->class;
} elseif (\is_object($controller) && !$controller instanceof \Closure) {
$reflection = new \ReflectionMethod($controller, '__invoke');
$class = $reflection->class;
} else {
$reflection = new \ReflectionFunction($controller);
if ($class = str_contains($reflection->name, '{closure}') ? null : $reflection->getClosureScopeClass()) {
$class = $class->name;
}
}
foreach ($reflection->getParameters() as $param) {
$attributes = [];
if (\PHP_VERSION_ID >= 80000) {
foreach ($param->getAttributes() as $reflectionAttribute) {
if (class_exists($reflectionAttribute->getName())) {
$attributes[] = $reflectionAttribute->newInstance();
}
}
}
$arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param, $class), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull(), $attributes);
}
return $arguments;
}
/**
* Returns an associated type to the given parameter if available.
*/
private function getType(\ReflectionParameter $parameter, ?string $class): ?string
{
if (!$type = $parameter->getType()) {
return null;
}
$name = $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
if (null !== $class) {
switch (strtolower($name)) {
case 'self':
return $class;
case 'parent':
return get_parent_class($class) ?: null;
}
}
return $name;
}
}

View File

@ -0,0 +1,27 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\ControllerMetadata;
/**
* Builds method argument data.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
interface ArgumentMetadataFactoryInterface
{
/**
* @param string|object|array $controller The controller to resolve the arguments for
*
* @return ArgumentMetadata[]
*/
public function createArgumentMetadata($controller);
}

View File

@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @author Bart van den Burg <bart@burgov.nl>
*
* @final
*/
class AjaxDataCollector extends DataCollector
{
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
// all collecting is done client side
}
public function reset()
{
// all collecting is done client side
}
public function getName(): string
{
return 'ajax';
}
}

View File

@ -0,0 +1,275 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\VarDumper\Caster\ClassStub;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class ConfigDataCollector extends DataCollector implements LateDataCollectorInterface
{
/**
* @var KernelInterface
*/
private $kernel;
/**
* Sets the Kernel associated with this Request.
*/
public function setKernel(KernelInterface $kernel = null)
{
$this->kernel = $kernel;
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
$eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE);
$eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE);
$this->data = [
'token' => $response->headers->get('X-Debug-Token'),
'symfony_version' => Kernel::VERSION,
'symfony_minor_version' => sprintf('%s.%s', Kernel::MAJOR_VERSION, Kernel::MINOR_VERSION),
'symfony_lts' => 4 === Kernel::MINOR_VERSION,
'symfony_state' => $this->determineSymfonyState(),
'symfony_eom' => $eom->format('F Y'),
'symfony_eol' => $eol->format('F Y'),
'env' => isset($this->kernel) ? $this->kernel->getEnvironment() : 'n/a',
'debug' => isset($this->kernel) ? $this->kernel->isDebug() : 'n/a',
'php_version' => \PHP_VERSION,
'php_architecture' => \PHP_INT_SIZE * 8,
'php_intl_locale' => class_exists(\Locale::class, false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a',
'php_timezone' => date_default_timezone_get(),
'xdebug_enabled' => \extension_loaded('xdebug'),
'apcu_enabled' => \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), \FILTER_VALIDATE_BOOLEAN),
'zend_opcache_enabled' => \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN),
'bundles' => [],
'sapi_name' => \PHP_SAPI,
];
if (isset($this->kernel)) {
foreach ($this->kernel->getBundles() as $name => $bundle) {
$this->data['bundles'][$name] = new ClassStub(\get_class($bundle));
}
}
if (preg_match('~^(\d+(?:\.\d+)*)(.+)?$~', $this->data['php_version'], $matches) && isset($matches[2])) {
$this->data['php_version'] = $matches[1];
$this->data['php_version_extra'] = $matches[2];
}
}
/**
* {@inheritdoc}
*/
public function reset()
{
$this->data = [];
}
public function lateCollect()
{
$this->data = $this->cloneVar($this->data);
}
/**
* Gets the token.
*/
public function getToken(): ?string
{
return $this->data['token'];
}
/**
* Gets the Symfony version.
*/
public function getSymfonyVersion(): string
{
return $this->data['symfony_version'];
}
/**
* Returns the state of the current Symfony release.
*
* @return string One of: unknown, dev, stable, eom, eol
*/
public function getSymfonyState(): string
{
return $this->data['symfony_state'];
}
/**
* Returns the minor Symfony version used (without patch numbers of extra
* suffix like "RC", "beta", etc.).
*/
public function getSymfonyMinorVersion(): string
{
return $this->data['symfony_minor_version'];
}
/**
* Returns if the current Symfony version is a Long-Term Support one.
*/
public function isSymfonyLts(): bool
{
return $this->data['symfony_lts'];
}
/**
* Returns the human readable date when this Symfony version ends its
* maintenance period.
*/
public function getSymfonyEom(): string
{
return $this->data['symfony_eom'];
}
/**
* Returns the human readable date when this Symfony version reaches its
* "end of life" and won't receive bugs or security fixes.
*/
public function getSymfonyEol(): string
{
return $this->data['symfony_eol'];
}
/**
* Gets the PHP version.
*/
public function getPhpVersion(): string
{
return $this->data['php_version'];
}
/**
* Gets the PHP version extra part.
*/
public function getPhpVersionExtra(): ?string
{
return $this->data['php_version_extra'] ?? null;
}
/**
* @return int The PHP architecture as number of bits (e.g. 32 or 64)
*/
public function getPhpArchitecture(): int
{
return $this->data['php_architecture'];
}
public function getPhpIntlLocale(): string
{
return $this->data['php_intl_locale'];
}
public function getPhpTimezone(): string
{
return $this->data['php_timezone'];
}
/**
* Gets the environment.
*/
public function getEnv(): string
{
return $this->data['env'];
}
/**
* Returns true if the debug is enabled.
*
* @return bool|string true if debug is enabled, false otherwise or a string if no kernel was set
*/
public function isDebug()
{
return $this->data['debug'];
}
/**
* Returns true if the XDebug is enabled.
*/
public function hasXDebug(): bool
{
return $this->data['xdebug_enabled'];
}
/**
* Returns true if APCu is enabled.
*/
public function hasApcu(): bool
{
return $this->data['apcu_enabled'];
}
/**
* Returns true if Zend OPcache is enabled.
*/
public function hasZendOpcache(): bool
{
return $this->data['zend_opcache_enabled'];
}
public function getBundles()
{
return $this->data['bundles'];
}
/**
* Gets the PHP SAPI name.
*/
public function getSapiName(): string
{
return $this->data['sapi_name'];
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'config';
}
/**
* Tries to retrieve information about the current Symfony version.
*
* @return string One of: dev, stable, eom, eol
*/
private function determineSymfonyState(): string
{
$now = new \DateTime();
$eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->modify('last day of this month');
$eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->modify('last day of this month');
if ($now > $eol) {
$versionState = 'eol';
} elseif ($now > $eom) {
$versionState = 'eom';
} elseif ('' !== Kernel::EXTRA_VERSION) {
$versionState = 'dev';
} else {
$versionState = 'stable';
}
return $versionState;
}
}

View File

@ -0,0 +1,112 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\VarDumper\Caster\CutStub;
use Symfony\Component\VarDumper\Caster\ReflectionCaster;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Cloner\Stub;
use Symfony\Component\VarDumper\Cloner\VarCloner;
/**
* DataCollector.
*
* Children of this class must store the collected data in the data property.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Bernhard Schussek <bschussek@symfony.com>
*/
abstract class DataCollector implements DataCollectorInterface
{
/**
* @var array|Data
*/
protected $data = [];
/**
* @var ClonerInterface
*/
private $cloner;
/**
* Converts the variable into a serializable Data instance.
*
* This array can be displayed in the template using
* the VarDumper component.
*
* @param mixed $var
*
* @return Data
*/
protected function cloneVar($var)
{
if ($var instanceof Data) {
return $var;
}
if (null === $this->cloner) {
$this->cloner = new VarCloner();
$this->cloner->setMaxItems(-1);
$this->cloner->addCasters($this->getCasters());
}
return $this->cloner->cloneVar($var);
}
/**
* @return callable[] The casters to add to the cloner
*/
protected function getCasters()
{
$casters = [
'*' => function ($v, array $a, Stub $s, $isNested) {
if (!$v instanceof Stub) {
foreach ($a as $k => $v) {
if (\is_object($v) && !$v instanceof \DateTimeInterface && !$v instanceof Stub) {
$a[$k] = new CutStub($v);
}
}
}
return $a;
},
] + ReflectionCaster::UNSET_CLOSURE_FILE_INFO;
return $casters;
}
/**
* @return array
*/
public function __sleep()
{
return ['data'];
}
public function __wakeup()
{
}
/**
* @internal to prevent implementing \Serializable
*/
final protected function serialize()
{
}
/**
* @internal to prevent implementing \Serializable
*/
final protected function unserialize($data)
{
}
}

View File

@ -0,0 +1,36 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Service\ResetInterface;
/**
* DataCollectorInterface.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface DataCollectorInterface extends ResetInterface
{
/**
* Collects data for the given Request and Response.
*/
public function collect(Request $request, Response $response, \Throwable $exception = null);
/**
* Returns the name of the collector.
*
* @return string
*/
public function getName();
}

View File

@ -0,0 +1,291 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Symfony\Component\VarDumper\Server\Connection;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @final
*/
class DumpDataCollector extends DataCollector implements DataDumperInterface
{
private $stopwatch;
private $fileLinkFormat;
private $dataCount = 0;
private $isCollected = true;
private $clonesCount = 0;
private $clonesIndex = 0;
private $rootRefs;
private $charset;
private $requestStack;
private $dumper;
private $sourceContextProvider;
/**
* @param string|FileLinkFormatter|null $fileLinkFormat
* @param DataDumperInterface|Connection|null $dumper
*/
public function __construct(Stopwatch $stopwatch = null, $fileLinkFormat = null, string $charset = null, RequestStack $requestStack = null, $dumper = null)
{
$this->stopwatch = $stopwatch;
$this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
$this->charset = $charset ?: ini_get('php.output_encoding') ?: ini_get('default_charset') ?: 'UTF-8';
$this->requestStack = $requestStack;
$this->dumper = $dumper;
// All clones share these properties by reference:
$this->rootRefs = [
&$this->data,
&$this->dataCount,
&$this->isCollected,
&$this->clonesCount,
];
$this->sourceContextProvider = $dumper instanceof Connection && isset($dumper->getContextProviders()['source']) ? $dumper->getContextProviders()['source'] : new SourceContextProvider($this->charset);
}
public function __clone()
{
$this->clonesIndex = ++$this->clonesCount;
}
public function dump(Data $data)
{
if ($this->stopwatch) {
$this->stopwatch->start('dump');
}
['name' => $name, 'file' => $file, 'line' => $line, 'file_excerpt' => $fileExcerpt] = $this->sourceContextProvider->getContext();
if ($this->dumper instanceof Connection) {
if (!$this->dumper->write($data)) {
$this->isCollected = false;
}
} elseif ($this->dumper) {
$this->doDump($this->dumper, $data, $name, $file, $line);
} else {
$this->isCollected = false;
}
if (!$this->dataCount) {
$this->data = [];
}
$this->data[] = compact('data', 'name', 'file', 'line', 'fileExcerpt');
++$this->dataCount;
if ($this->stopwatch) {
$this->stopwatch->stop('dump');
}
}
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
if (!$this->dataCount) {
$this->data = [];
}
// Sub-requests and programmatic calls stay in the collected profile.
if ($this->dumper || ($this->requestStack && $this->requestStack->getMainRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) {
return;
}
// In all other conditions that remove the web debug toolbar, dumps are written on the output.
if (!$this->requestStack
|| !$response->headers->has('X-Debug-Token')
|| $response->isRedirection()
|| ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type'), 'html'))
|| 'html' !== $request->getRequestFormat()
|| false === strripos($response->getContent(), '</body>')
) {
if ($response->headers->has('Content-Type') && str_contains($response->headers->get('Content-Type'), 'html')) {
$dumper = new HtmlDumper('php://output', $this->charset);
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
} else {
$dumper = new CliDumper('php://output', $this->charset);
if (method_exists($dumper, 'setDisplayOptions')) {
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
}
}
foreach ($this->data as $dump) {
$this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line']);
}
}
}
public function reset()
{
if ($this->stopwatch) {
$this->stopwatch->reset();
}
$this->data = [];
$this->dataCount = 0;
$this->isCollected = true;
$this->clonesCount = 0;
$this->clonesIndex = 0;
}
/**
* @internal
*/
public function __sleep(): array
{
if (!$this->dataCount) {
$this->data = [];
}
if ($this->clonesCount !== $this->clonesIndex) {
return [];
}
$this->data[] = $this->fileLinkFormat;
$this->data[] = $this->charset;
$this->dataCount = 0;
$this->isCollected = true;
return parent::__sleep();
}
/**
* @internal
*/
public function __wakeup()
{
parent::__wakeup();
$charset = array_pop($this->data);
$fileLinkFormat = array_pop($this->data);
$this->dataCount = \count($this->data);
foreach ($this->data as $dump) {
if (!\is_string($dump['name']) || !\is_string($dump['file']) || !\is_int($dump['line'])) {
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
}
self::__construct($this->stopwatch, \is_string($fileLinkFormat) || $fileLinkFormat instanceof FileLinkFormatter ? $fileLinkFormat : null, \is_string($charset) ? $charset : null);
}
public function getDumpsCount(): int
{
return $this->dataCount;
}
public function getDumps(string $format, int $maxDepthLimit = -1, int $maxItemsPerDepth = -1): array
{
$data = fopen('php://memory', 'r+');
if ('html' === $format) {
$dumper = new HtmlDumper($data, $this->charset);
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
} else {
throw new \InvalidArgumentException(sprintf('Invalid dump format: "%s".', $format));
}
$dumps = [];
if (!$this->dataCount) {
return $this->data = [];
}
foreach ($this->data as $dump) {
$dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
$dump['data'] = stream_get_contents($data, -1, 0);
ftruncate($data, 0);
rewind($data);
$dumps[] = $dump;
}
return $dumps;
}
public function getName(): string
{
return 'dump';
}
public function __destruct()
{
if (0 === $this->clonesCount-- && !$this->isCollected && $this->dataCount) {
$this->clonesCount = 0;
$this->isCollected = true;
$h = headers_list();
$i = \count($h);
array_unshift($h, 'Content-Type: '.ini_get('default_mimetype'));
while (0 !== stripos($h[$i], 'Content-Type:')) {
--$i;
}
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && stripos($h[$i], 'html')) {
$dumper = new HtmlDumper('php://output', $this->charset);
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
} else {
$dumper = new CliDumper('php://output', $this->charset);
if (method_exists($dumper, 'setDisplayOptions')) {
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
}
}
foreach ($this->data as $i => $dump) {
$this->data[$i] = null;
$this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line']);
}
$this->data = [];
$this->dataCount = 0;
}
}
private function doDump(DataDumperInterface $dumper, Data $data, string $name, string $file, int $line)
{
if ($dumper instanceof CliDumper) {
$contextDumper = function ($name, $file, $line, $fmt) {
if ($this instanceof HtmlDumper) {
if ($file) {
$s = $this->style('meta', '%s');
$f = strip_tags($this->style('', $file));
$name = strip_tags($this->style('', $name));
if ($fmt && $link = \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line)) {
$name = sprintf('<a href="%s" title="%s">'.$s.'</a>', strip_tags($this->style('', $link)), $f, $name);
} else {
$name = sprintf('<abbr title="%s">'.$s.'</abbr>', $f, $name);
}
} else {
$name = $this->style('meta', $name);
}
$this->line = $name.' on line '.$this->style('meta', $line).':';
} else {
$this->line = $this->style('meta', $name).' on line '.$this->style('meta', $line).':';
}
$this->dumpLine(0);
};
$contextDumper = $contextDumper->bindTo($dumper, $dumper);
$contextDumper($name, $file, $line, $this->fileLinkFormat);
} else {
$cloner = new VarCloner();
$dumper->dump($cloner->cloneVar($name.' on line '.$line.':'));
}
$dumper->dump($data);
}
}

View File

@ -0,0 +1,137 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\Service\ResetInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class EventDataCollector extends DataCollector implements LateDataCollectorInterface
{
protected $dispatcher;
private $requestStack;
private $currentRequest;
public function __construct(EventDispatcherInterface $dispatcher = null, RequestStack $requestStack = null)
{
$this->dispatcher = $dispatcher;
$this->requestStack = $requestStack;
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
$this->currentRequest = $this->requestStack && $this->requestStack->getMainRequest() !== $request ? $request : null;
$this->data = [
'called_listeners' => [],
'not_called_listeners' => [],
'orphaned_events' => [],
];
}
public function reset()
{
$this->data = [];
if ($this->dispatcher instanceof ResetInterface) {
$this->dispatcher->reset();
}
}
public function lateCollect()
{
if ($this->dispatcher instanceof TraceableEventDispatcher) {
$this->setCalledListeners($this->dispatcher->getCalledListeners($this->currentRequest));
$this->setNotCalledListeners($this->dispatcher->getNotCalledListeners($this->currentRequest));
$this->setOrphanedEvents($this->dispatcher->getOrphanedEvents($this->currentRequest));
}
$this->data = $this->cloneVar($this->data);
}
/**
* @param array $listeners An array of called listeners
*
* @see TraceableEventDispatcher
*/
public function setCalledListeners(array $listeners)
{
$this->data['called_listeners'] = $listeners;
}
/**
* @see TraceableEventDispatcher
*
* @return array|Data
*/
public function getCalledListeners()
{
return $this->data['called_listeners'];
}
/**
* @see TraceableEventDispatcher
*/
public function setNotCalledListeners(array $listeners)
{
$this->data['not_called_listeners'] = $listeners;
}
/**
* @see TraceableEventDispatcher
*
* @return array|Data
*/
public function getNotCalledListeners()
{
return $this->data['not_called_listeners'];
}
/**
* @param array $events An array of orphaned events
*
* @see TraceableEventDispatcher
*/
public function setOrphanedEvents(array $events)
{
$this->data['orphaned_events'] = $events;
}
/**
* @see TraceableEventDispatcher
*
* @return array|Data
*/
public function getOrphanedEvents()
{
return $this->data['orphaned_events'];
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'events';
}
}

View File

@ -0,0 +1,85 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class ExceptionDataCollector extends DataCollector
{
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
if (null !== $exception) {
$this->data = [
'exception' => FlattenException::createFromThrowable($exception),
];
}
}
/**
* {@inheritdoc}
*/
public function reset()
{
$this->data = [];
}
public function hasException(): bool
{
return isset($this->data['exception']);
}
/**
* @return \Exception|FlattenException
*/
public function getException()
{
return $this->data['exception'];
}
public function getMessage(): string
{
return $this->data['exception']->getMessage();
}
public function getCode(): int
{
return $this->data['exception']->getCode();
}
public function getStatusCode(): int
{
return $this->data['exception']->getStatusCode();
}
public function getTrace(): array
{
return $this->data['exception']->getTrace();
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'exception';
}
}

View File

@ -0,0 +1,25 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
/**
* LateDataCollectorInterface.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface LateDataCollectorInterface
{
/**
* Collects data as late as possible.
*/
public function lateCollect();
}

View File

@ -0,0 +1,358 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class LoggerDataCollector extends DataCollector implements LateDataCollectorInterface
{
private $logger;
private $containerPathPrefix;
private $currentRequest;
private $requestStack;
private $processedLogs;
public function __construct(object $logger = null, string $containerPathPrefix = null, RequestStack $requestStack = null)
{
if (null !== $logger && $logger instanceof DebugLoggerInterface) {
$this->logger = $logger;
}
$this->containerPathPrefix = $containerPathPrefix;
$this->requestStack = $requestStack;
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
$this->currentRequest = $this->requestStack && $this->requestStack->getMainRequest() !== $request ? $request : null;
}
/**
* {@inheritdoc}
*/
public function reset()
{
if ($this->logger instanceof DebugLoggerInterface) {
$this->logger->clear();
}
$this->data = [];
}
/**
* {@inheritdoc}
*/
public function lateCollect()
{
if (null !== $this->logger) {
$containerDeprecationLogs = $this->getContainerDeprecationLogs();
$this->data = $this->computeErrorsCount($containerDeprecationLogs);
// get compiler logs later (only when they are needed) to improve performance
$this->data['compiler_logs'] = [];
$this->data['compiler_logs_filepath'] = $this->containerPathPrefix.'Compiler.log';
$this->data['logs'] = $this->sanitizeLogs(array_merge($this->logger->getLogs($this->currentRequest), $containerDeprecationLogs));
$this->data = $this->cloneVar($this->data);
}
$this->currentRequest = null;
}
public function getLogs()
{
return $this->data['logs'] ?? [];
}
public function getProcessedLogs()
{
if (null !== $this->processedLogs) {
return $this->processedLogs;
}
$rawLogs = $this->getLogs();
if ([] === $rawLogs) {
return $this->processedLogs = $rawLogs;
}
$logs = [];
foreach ($this->getLogs()->getValue() as $rawLog) {
$rawLogData = $rawLog->getValue();
if ($rawLogData['priority']->getValue() > 300) {
$logType = 'error';
} elseif (isset($rawLogData['scream']) && false === $rawLogData['scream']->getValue()) {
$logType = 'deprecation';
} elseif (isset($rawLogData['scream']) && true === $rawLogData['scream']->getValue()) {
$logType = 'silenced';
} else {
$logType = 'regular';
}
$logs[] = [
'type' => $logType,
'errorCount' => $rawLog['errorCount'] ?? 1,
'timestamp' => $rawLogData['timestamp_rfc3339']->getValue(),
'priority' => $rawLogData['priority']->getValue(),
'priorityName' => $rawLogData['priorityName']->getValue(),
'channel' => $rawLogData['channel']->getValue(),
'message' => $rawLogData['message'],
'context' => $rawLogData['context'],
];
}
// sort logs from oldest to newest
usort($logs, static function ($logA, $logB) {
return $logA['timestamp'] <=> $logB['timestamp'];
});
return $this->processedLogs = $logs;
}
public function getFilters()
{
$filters = [
'channel' => [],
'priority' => [
'Debug' => 100,
'Info' => 200,
'Notice' => 250,
'Warning' => 300,
'Error' => 400,
'Critical' => 500,
'Alert' => 550,
'Emergency' => 600,
],
];
$allChannels = [];
foreach ($this->getProcessedLogs() as $log) {
if ('' === trim($log['channel'])) {
continue;
}
$allChannels[] = $log['channel'];
}
$channels = array_unique($allChannels);
sort($channels);
$filters['channel'] = $channels;
return $filters;
}
public function getPriorities()
{
return $this->data['priorities'] ?? [];
}
public function countErrors()
{
return $this->data['error_count'] ?? 0;
}
public function countDeprecations()
{
return $this->data['deprecation_count'] ?? 0;
}
public function countWarnings()
{
return $this->data['warning_count'] ?? 0;
}
public function countScreams()
{
return $this->data['scream_count'] ?? 0;
}
public function getCompilerLogs()
{
return $this->cloneVar($this->getContainerCompilerLogs($this->data['compiler_logs_filepath'] ?? null));
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'logger';
}
private function getContainerDeprecationLogs(): array
{
if (null === $this->containerPathPrefix || !is_file($file = $this->containerPathPrefix.'Deprecations.log')) {
return [];
}
if ('' === $logContent = trim(file_get_contents($file))) {
return [];
}
$bootTime = filemtime($file);
$logs = [];
foreach (unserialize($logContent) as $log) {
$log['context'] = ['exception' => new SilencedErrorContext($log['type'], $log['file'], $log['line'], $log['trace'], $log['count'])];
$log['timestamp'] = $bootTime;
$log['timestamp_rfc3339'] = (new \DateTimeImmutable())->setTimestamp($bootTime)->format(\DateTimeInterface::RFC3339_EXTENDED);
$log['priority'] = 100;
$log['priorityName'] = 'DEBUG';
$log['channel'] = null;
$log['scream'] = false;
unset($log['type'], $log['file'], $log['line'], $log['trace'], $log['trace'], $log['count']);
$logs[] = $log;
}
return $logs;
}
private function getContainerCompilerLogs(string $compilerLogsFilepath = null): array
{
if (!is_file($compilerLogsFilepath)) {
return [];
}
$logs = [];
foreach (file($compilerLogsFilepath, \FILE_IGNORE_NEW_LINES) as $log) {
$log = explode(': ', $log, 2);
if (!isset($log[1]) || !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)++$/', $log[0])) {
$log = ['Unknown Compiler Pass', implode(': ', $log)];
}
$logs[$log[0]][] = ['message' => $log[1]];
}
return $logs;
}
private function sanitizeLogs(array $logs)
{
$sanitizedLogs = [];
$silencedLogs = [];
foreach ($logs as $log) {
if (!$this->isSilencedOrDeprecationErrorLog($log)) {
$sanitizedLogs[] = $log;
continue;
}
$message = '_'.$log['message'];
$exception = $log['context']['exception'];
if ($exception instanceof SilencedErrorContext) {
if (isset($silencedLogs[$h = spl_object_hash($exception)])) {
continue;
}
$silencedLogs[$h] = true;
if (!isset($sanitizedLogs[$message])) {
$sanitizedLogs[$message] = $log + [
'errorCount' => 0,
'scream' => true,
];
}
$sanitizedLogs[$message]['errorCount'] += $exception->count;
continue;
}
$errorId = md5("{$exception->getSeverity()}/{$exception->getLine()}/{$exception->getFile()}\0{$message}", true);
if (isset($sanitizedLogs[$errorId])) {
++$sanitizedLogs[$errorId]['errorCount'];
} else {
$log += [
'errorCount' => 1,
'scream' => false,
];
$sanitizedLogs[$errorId] = $log;
}
}
return array_values($sanitizedLogs);
}
private function isSilencedOrDeprecationErrorLog(array $log): bool
{
if (!isset($log['context']['exception'])) {
return false;
}
$exception = $log['context']['exception'];
if ($exception instanceof SilencedErrorContext) {
return true;
}
if ($exception instanceof \ErrorException && \in_array($exception->getSeverity(), [\E_DEPRECATED, \E_USER_DEPRECATED], true)) {
return true;
}
return false;
}
private function computeErrorsCount(array $containerDeprecationLogs): array
{
$silencedLogs = [];
$count = [
'error_count' => $this->logger->countErrors($this->currentRequest),
'deprecation_count' => 0,
'warning_count' => 0,
'scream_count' => 0,
'priorities' => [],
];
foreach ($this->logger->getLogs($this->currentRequest) as $log) {
if (isset($count['priorities'][$log['priority']])) {
++$count['priorities'][$log['priority']]['count'];
} else {
$count['priorities'][$log['priority']] = [
'count' => 1,
'name' => $log['priorityName'],
];
}
if ('WARNING' === $log['priorityName']) {
++$count['warning_count'];
}
if ($this->isSilencedOrDeprecationErrorLog($log)) {
$exception = $log['context']['exception'];
if ($exception instanceof SilencedErrorContext) {
if (isset($silencedLogs[$h = spl_object_hash($exception)])) {
continue;
}
$silencedLogs[$h] = true;
$count['scream_count'] += $exception->count;
} else {
++$count['deprecation_count'];
}
}
}
foreach ($containerDeprecationLogs as $deprecationLog) {
$count['deprecation_count'] += $deprecationLog['context']['exception']->count;
}
ksort($count['priorities']);
return $count;
}
}

View File

@ -0,0 +1,113 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class MemoryDataCollector extends DataCollector implements LateDataCollectorInterface
{
public function __construct()
{
$this->reset();
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
$this->updateMemoryUsage();
}
/**
* {@inheritdoc}
*/
public function reset()
{
$this->data = [
'memory' => 0,
'memory_limit' => $this->convertToBytes(ini_get('memory_limit')),
];
}
/**
* {@inheritdoc}
*/
public function lateCollect()
{
$this->updateMemoryUsage();
}
public function getMemory(): int
{
return $this->data['memory'];
}
/**
* @return int|float
*/
public function getMemoryLimit()
{
return $this->data['memory_limit'];
}
public function updateMemoryUsage()
{
$this->data['memory'] = memory_get_peak_usage(true);
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'memory';
}
/**
* @return int|float
*/
private function convertToBytes(string $memoryLimit)
{
if ('-1' === $memoryLimit) {
return -1;
}
$memoryLimit = strtolower($memoryLimit);
$max = strtolower(ltrim($memoryLimit, '+'));
if (str_starts_with($max, '0x')) {
$max = \intval($max, 16);
} elseif (str_starts_with($max, '0')) {
$max = \intval($max, 8);
} else {
$max = (int) $max;
}
switch (substr($memoryLimit, -1)) {
case 't': $max *= 1024;
// no break
case 'g': $max *= 1024;
// no break
case 'm': $max *= 1024;
// no break
case 'k': $max *= 1024;
}
return $max;
}
}

View File

@ -0,0 +1,504 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\VarDumper\Cloner\Data;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class RequestDataCollector extends DataCollector implements EventSubscriberInterface, LateDataCollectorInterface
{
/**
* @var \SplObjectStorage<Request, callable>
*/
private $controllers;
private $sessionUsages = [];
private $requestStack;
public function __construct(RequestStack $requestStack = null)
{
$this->controllers = new \SplObjectStorage();
$this->requestStack = $requestStack;
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
// attributes are serialized and as they can be anything, they need to be converted to strings.
$attributes = [];
$route = '';
foreach ($request->attributes->all() as $key => $value) {
if ('_route' === $key) {
$route = \is_object($value) ? $value->getPath() : $value;
$attributes[$key] = $route;
} else {
$attributes[$key] = $value;
}
}
$content = $request->getContent();
$sessionMetadata = [];
$sessionAttributes = [];
$flashes = [];
if ($request->hasSession()) {
$session = $request->getSession();
if ($session->isStarted()) {
$sessionMetadata['Created'] = date(\DATE_RFC822, $session->getMetadataBag()->getCreated());
$sessionMetadata['Last used'] = date(\DATE_RFC822, $session->getMetadataBag()->getLastUsed());
$sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime();
$sessionAttributes = $session->all();
$flashes = $session->getFlashBag()->peekAll();
}
}
$statusCode = $response->getStatusCode();
$responseCookies = [];
foreach ($response->headers->getCookies() as $cookie) {
$responseCookies[$cookie->getName()] = $cookie;
}
$dotenvVars = [];
foreach (explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? $_ENV['SYMFONY_DOTENV_VARS'] ?? '') as $name) {
if ('' !== $name && isset($_ENV[$name])) {
$dotenvVars[$name] = $_ENV[$name];
}
}
$this->data = [
'method' => $request->getMethod(),
'format' => $request->getRequestFormat(),
'content_type' => $response->headers->get('Content-Type', 'text/html'),
'status_text' => Response::$statusTexts[$statusCode] ?? '',
'status_code' => $statusCode,
'request_query' => $request->query->all(),
'request_request' => $request->request->all(),
'request_files' => $request->files->all(),
'request_headers' => $request->headers->all(),
'request_server' => $request->server->all(),
'request_cookies' => $request->cookies->all(),
'request_attributes' => $attributes,
'route' => $route,
'response_headers' => $response->headers->all(),
'response_cookies' => $responseCookies,
'session_metadata' => $sessionMetadata,
'session_attributes' => $sessionAttributes,
'session_usages' => array_values($this->sessionUsages),
'stateless_check' => $this->requestStack && $this->requestStack->getMainRequest()->attributes->get('_stateless', false),
'flashes' => $flashes,
'path_info' => $request->getPathInfo(),
'controller' => 'n/a',
'locale' => $request->getLocale(),
'dotenv_vars' => $dotenvVars,
];
if (isset($this->data['request_headers']['php-auth-pw'])) {
$this->data['request_headers']['php-auth-pw'] = '******';
}
if (isset($this->data['request_server']['PHP_AUTH_PW'])) {
$this->data['request_server']['PHP_AUTH_PW'] = '******';
}
if (isset($this->data['request_request']['_password'])) {
$encodedPassword = rawurlencode($this->data['request_request']['_password']);
$content = str_replace('_password='.$encodedPassword, '_password=******', $content);
$this->data['request_request']['_password'] = '******';
}
$this->data['content'] = $content;
foreach ($this->data as $key => $value) {
if (!\is_array($value)) {
continue;
}
if ('request_headers' === $key || 'response_headers' === $key) {
$this->data[$key] = array_map(function ($v) { return isset($v[0]) && !isset($v[1]) ? $v[0] : $v; }, $value);
}
}
if (isset($this->controllers[$request])) {
$this->data['controller'] = $this->parseController($this->controllers[$request]);
unset($this->controllers[$request]);
}
if ($request->attributes->has('_redirected') && $redirectCookie = $request->cookies->get('sf_redirect')) {
$this->data['redirect'] = json_decode($redirectCookie, true);
$response->headers->clearCookie('sf_redirect');
}
if ($response->isRedirect()) {
$response->headers->setCookie(new Cookie(
'sf_redirect',
json_encode([
'token' => $response->headers->get('x-debug-token'),
'route' => $request->attributes->get('_route', 'n/a'),
'method' => $request->getMethod(),
'controller' => $this->parseController($request->attributes->get('_controller')),
'status_code' => $statusCode,
'status_text' => Response::$statusTexts[$statusCode],
]),
0, '/', null, $request->isSecure(), true, false, 'lax'
));
}
$this->data['identifier'] = $this->data['route'] ?: (\is_array($this->data['controller']) ? $this->data['controller']['class'].'::'.$this->data['controller']['method'].'()' : $this->data['controller']);
if ($response->headers->has('x-previous-debug-token')) {
$this->data['forward_token'] = $response->headers->get('x-previous-debug-token');
}
}
public function lateCollect()
{
$this->data = $this->cloneVar($this->data);
}
public function reset()
{
$this->data = [];
$this->controllers = new \SplObjectStorage();
$this->sessionUsages = [];
}
public function getMethod()
{
return $this->data['method'];
}
public function getPathInfo()
{
return $this->data['path_info'];
}
public function getRequestRequest()
{
return new ParameterBag($this->data['request_request']->getValue());
}
public function getRequestQuery()
{
return new ParameterBag($this->data['request_query']->getValue());
}
public function getRequestFiles()
{
return new ParameterBag($this->data['request_files']->getValue());
}
public function getRequestHeaders()
{
return new ParameterBag($this->data['request_headers']->getValue());
}
public function getRequestServer(bool $raw = false)
{
return new ParameterBag($this->data['request_server']->getValue($raw));
}
public function getRequestCookies(bool $raw = false)
{
return new ParameterBag($this->data['request_cookies']->getValue($raw));
}
public function getRequestAttributes()
{
return new ParameterBag($this->data['request_attributes']->getValue());
}
public function getResponseHeaders()
{
return new ParameterBag($this->data['response_headers']->getValue());
}
public function getResponseCookies()
{
return new ParameterBag($this->data['response_cookies']->getValue());
}
public function getSessionMetadata()
{
return $this->data['session_metadata']->getValue();
}
public function getSessionAttributes()
{
return $this->data['session_attributes']->getValue();
}
public function getStatelessCheck()
{
return $this->data['stateless_check'];
}
public function getSessionUsages()
{
return $this->data['session_usages'];
}
public function getFlashes()
{
return $this->data['flashes']->getValue();
}
public function getContent()
{
return $this->data['content'];
}
public function isJsonRequest()
{
return 1 === preg_match('{^application/(?:\w+\++)*json$}i', $this->data['request_headers']['content-type']);
}
public function getPrettyJson()
{
$decoded = json_decode($this->getContent());
return \JSON_ERROR_NONE === json_last_error() ? json_encode($decoded, \JSON_PRETTY_PRINT) : null;
}
public function getContentType()
{
return $this->data['content_type'];
}
public function getStatusText()
{
return $this->data['status_text'];
}
public function getStatusCode()
{
return $this->data['status_code'];
}
public function getFormat()
{
return $this->data['format'];
}
public function getLocale()
{
return $this->data['locale'];
}
public function getDotenvVars()
{
return new ParameterBag($this->data['dotenv_vars']->getValue());
}
/**
* Gets the route name.
*
* The _route request attributes is automatically set by the Router Matcher.
*/
public function getRoute(): string
{
return $this->data['route'];
}
public function getIdentifier()
{
return $this->data['identifier'];
}
/**
* Gets the route parameters.
*
* The _route_params request attributes is automatically set by the RouterListener.
*/
public function getRouteParams(): array
{
return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : [];
}
/**
* Gets the parsed controller.
*
* @return array|string|Data The controller as a string or array of data
* with keys 'class', 'method', 'file' and 'line'
*/
public function getController()
{
return $this->data['controller'];
}
/**
* Gets the previous request attributes.
*
* @return array|Data|false A legacy array of data from the previous redirection response
* or false otherwise
*/
public function getRedirect()
{
return $this->data['redirect'] ?? false;
}
public function getForwardToken()
{
return $this->data['forward_token'] ?? null;
}
public function onKernelController(ControllerEvent $event)
{
$this->controllers[$event->getRequest()] = $event->getController();
}
public function onKernelResponse(ResponseEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
if ($event->getRequest()->cookies->has('sf_redirect')) {
$event->getRequest()->attributes->set('_redirected', true);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'request';
}
public function collectSessionUsage(): void
{
$trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
$traceEndIndex = \count($trace) - 1;
for ($i = $traceEndIndex; $i > 0; --$i) {
if (null !== ($class = $trace[$i]['class'] ?? null) && (is_subclass_of($class, SessionInterface::class) || is_subclass_of($class, SessionBagInterface::class))) {
$traceEndIndex = $i;
break;
}
}
if ((\count($trace) - 1) === $traceEndIndex) {
return;
}
// Remove part of the backtrace that belongs to session only
array_splice($trace, 0, $traceEndIndex);
// Merge identical backtraces generated by internal call reports
$name = sprintf('%s:%s', $trace[1]['class'] ?? $trace[0]['file'], $trace[0]['line']);
if (!\array_key_exists($name, $this->sessionUsages)) {
$this->sessionUsages[$name] = [
'name' => $name,
'file' => $trace[0]['file'],
'line' => $trace[0]['line'],
'trace' => $trace,
];
}
}
/**
* @param string|object|array|null $controller The controller to parse
*
* @return array|string An array of controller data or a simple string
*/
private function parseController($controller)
{
if (\is_string($controller) && str_contains($controller, '::')) {
$controller = explode('::', $controller);
}
if (\is_array($controller)) {
try {
$r = new \ReflectionMethod($controller[0], $controller[1]);
return [
'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
'method' => $controller[1],
'file' => $r->getFileName(),
'line' => $r->getStartLine(),
];
} catch (\ReflectionException $e) {
if (\is_callable($controller)) {
// using __call or __callStatic
return [
'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
'method' => $controller[1],
'file' => 'n/a',
'line' => 'n/a',
];
}
}
}
if ($controller instanceof \Closure) {
$r = new \ReflectionFunction($controller);
$controller = [
'class' => $r->getName(),
'method' => null,
'file' => $r->getFileName(),
'line' => $r->getStartLine(),
];
if (str_contains($r->name, '{closure}')) {
return $controller;
}
$controller['method'] = $r->name;
if ($class = $r->getClosureScopeClass()) {
$controller['class'] = $class->name;
} else {
return $r->name;
}
return $controller;
}
if (\is_object($controller)) {
$r = new \ReflectionClass($controller);
return [
'class' => $r->getName(),
'method' => null,
'file' => $r->getFileName(),
'line' => $r->getStartLine(),
];
}
return \is_string($controller) ? $controller : 'n/a';
}
}

View File

@ -0,0 +1,108 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class RouterDataCollector extends DataCollector
{
/**
* @var \SplObjectStorage<Request, callable>
*/
protected $controllers;
public function __construct()
{
$this->reset();
}
/**
* {@inheritdoc}
*
* @final
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
if ($response instanceof RedirectResponse) {
$this->data['redirect'] = true;
$this->data['url'] = $response->getTargetUrl();
if ($this->controllers->contains($request)) {
$this->data['route'] = $this->guessRoute($request, $this->controllers[$request]);
}
}
unset($this->controllers[$request]);
}
public function reset()
{
$this->controllers = new \SplObjectStorage();
$this->data = [
'redirect' => false,
'url' => null,
'route' => null,
];
}
protected function guessRoute(Request $request, $controller)
{
return 'n/a';
}
/**
* Remembers the controller associated to each request.
*/
public function onKernelController(ControllerEvent $event)
{
$this->controllers[$event->getRequest()] = $event->getController();
}
/**
* @return bool Whether this request will result in a redirect
*/
public function getRedirect()
{
return $this->data['redirect'];
}
/**
* @return string|null
*/
public function getTargetUrl()
{
return $this->data['url'];
}
/**
* @return string|null
*/
public function getTargetRoute()
{
return $this->data['route'];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'router';
}
}

View File

@ -0,0 +1,143 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\Stopwatch\StopwatchEvent;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class TimeDataCollector extends DataCollector implements LateDataCollectorInterface
{
private $kernel;
private $stopwatch;
public function __construct(KernelInterface $kernel = null, Stopwatch $stopwatch = null)
{
$this->kernel = $kernel;
$this->stopwatch = $stopwatch;
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Throwable $exception = null)
{
if (null !== $this->kernel) {
$startTime = $this->kernel->getStartTime();
} else {
$startTime = $request->server->get('REQUEST_TIME_FLOAT');
}
$this->data = [
'token' => $request->attributes->get('_stopwatch_token'),
'start_time' => $startTime * 1000,
'events' => [],
'stopwatch_installed' => class_exists(Stopwatch::class, false),
];
}
/**
* {@inheritdoc}
*/
public function reset()
{
$this->data = [];
if (null !== $this->stopwatch) {
$this->stopwatch->reset();
}
}
/**
* {@inheritdoc}
*/
public function lateCollect()
{
if (null !== $this->stopwatch && isset($this->data['token'])) {
$this->setEvents($this->stopwatch->getSectionEvents($this->data['token']));
}
unset($this->data['token']);
}
/**
* @param StopwatchEvent[] $events The request events
*/
public function setEvents(array $events)
{
foreach ($events as $event) {
$event->ensureStopped();
}
$this->data['events'] = $events;
}
/**
* @return StopwatchEvent[]
*/
public function getEvents(): array
{
return $this->data['events'];
}
/**
* Gets the request elapsed time.
*/
public function getDuration(): float
{
if (!isset($this->data['events']['__section__'])) {
return 0;
}
$lastEvent = $this->data['events']['__section__'];
return $lastEvent->getOrigin() + $lastEvent->getDuration() - $this->getStartTime();
}
/**
* Gets the initialization time.
*
* This is the time spent until the beginning of the request handling.
*/
public function getInitTime(): float
{
if (!isset($this->data['events']['__section__'])) {
return 0;
}
return $this->data['events']['__section__']->getOrigin() - $this->getStartTime();
}
public function getStartTime(): float
{
return $this->data['start_time'];
}
public function isStopwatchInstalled(): bool
{
return $this->data['stopwatch_installed'];
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'time';
}
}

View File

@ -0,0 +1,116 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Debug;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Formats debug file links.
*
* @author Jérémy Romey <jeremy@free-agent.fr>
*
* @final
*/
class FileLinkFormatter
{
private const FORMATS = [
'textmate' => 'txmt://open?url=file://%f&line=%l',
'macvim' => 'mvim://open?url=file://%f&line=%l',
'emacs' => 'emacs://open?url=file://%f&line=%l',
'sublime' => 'subl://open?url=file://%f&line=%l',
'phpstorm' => 'phpstorm://open?file=%f&line=%l',
'atom' => 'atom://core/open/file?filename=%f&line=%l',
'vscode' => 'vscode://file/%f:%l',
];
private $fileLinkFormat;
private $requestStack;
private $baseDir;
private $urlFormat;
/**
* @param string|\Closure $urlFormat the URL format, or a closure that returns it on-demand
*/
public function __construct(string $fileLinkFormat = null, RequestStack $requestStack = null, string $baseDir = null, $urlFormat = null)
{
$fileLinkFormat = (self::FORMATS[$fileLinkFormat] ?? $fileLinkFormat) ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
if ($fileLinkFormat && !\is_array($fileLinkFormat)) {
$i = strpos($f = $fileLinkFormat, '&', max(strrpos($f, '%f'), strrpos($f, '%l'))) ?: \strlen($f);
$fileLinkFormat = [substr($f, 0, $i)] + preg_split('/&([^>]++)>/', substr($f, $i), -1, \PREG_SPLIT_DELIM_CAPTURE);
}
$this->fileLinkFormat = $fileLinkFormat;
$this->requestStack = $requestStack;
$this->baseDir = $baseDir;
$this->urlFormat = $urlFormat;
}
public function format(string $file, int $line)
{
if ($fmt = $this->getFileLinkFormat()) {
for ($i = 1; isset($fmt[$i]); ++$i) {
if (str_starts_with($file, $k = $fmt[$i++])) {
$file = substr_replace($file, $fmt[$i], 0, \strlen($k));
break;
}
}
return strtr($fmt[0], ['%f' => $file, '%l' => $line]);
}
return false;
}
/**
* @internal
*/
public function __sleep(): array
{
$this->fileLinkFormat = $this->getFileLinkFormat();
return ['fileLinkFormat'];
}
/**
* @internal
*/
public static function generateUrlFormat(UrlGeneratorInterface $router, string $routeName, string $queryString): ?string
{
try {
return $router->generate($routeName).$queryString;
} catch (\Throwable $e) {
return null;
}
}
private function getFileLinkFormat()
{
if ($this->fileLinkFormat) {
return $this->fileLinkFormat;
}
if ($this->requestStack && $this->baseDir && $this->urlFormat) {
$request = $this->requestStack->getMainRequest();
if ($request instanceof Request && (!$this->urlFormat instanceof \Closure || $this->urlFormat = ($this->urlFormat)())) {
return [
$request->getSchemeAndHttpHost().$this->urlFormat,
$this->baseDir.\DIRECTORY_SEPARATOR, '',
];
}
}
return null;
}
}

View File

@ -0,0 +1,91 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Debug;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher as BaseTraceableEventDispatcher;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Collects some data about event listeners.
*
* This event dispatcher delegates the dispatching to another one.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TraceableEventDispatcher extends BaseTraceableEventDispatcher
{
/**
* {@inheritdoc}
*/
protected function beforeDispatch(string $eventName, object $event)
{
switch ($eventName) {
case KernelEvents::REQUEST:
$event->getRequest()->attributes->set('_stopwatch_token', substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6));
$this->stopwatch->openSection();
break;
case KernelEvents::VIEW:
case KernelEvents::RESPONSE:
// stop only if a controller has been executed
if ($this->stopwatch->isStarted('controller')) {
$this->stopwatch->stop('controller');
}
break;
case KernelEvents::TERMINATE:
$sectionId = $event->getRequest()->attributes->get('_stopwatch_token');
if (null === $sectionId) {
break;
}
// There is a very special case when using built-in AppCache class as kernel wrapper, in the case
// of an ESI request leading to a `stale` response [B] inside a `fresh` cached response [A].
// In this case, `$token` contains the [B] debug token, but the open `stopwatch` section ID
// is equal to the [A] debug token. Trying to reopen section with the [B] token throws an exception
// which must be caught.
try {
$this->stopwatch->openSection($sectionId);
} catch (\LogicException $e) {
}
break;
}
}
/**
* {@inheritdoc}
*/
protected function afterDispatch(string $eventName, object $event)
{
switch ($eventName) {
case KernelEvents::CONTROLLER_ARGUMENTS:
$this->stopwatch->start('controller', 'section');
break;
case KernelEvents::RESPONSE:
$sectionId = $event->getRequest()->attributes->get('_stopwatch_token');
if (null === $sectionId) {
break;
}
$this->stopwatch->stopSection($sectionId);
break;
case KernelEvents::TERMINATE:
// In the special case described in the `preDispatch` method above, the `$token` section
// does not exist, then closing it throws an exception which must be caught.
$sectionId = $event->getRequest()->attributes->get('_stopwatch_token');
if (null === $sectionId) {
break;
}
try {
$this->stopwatch->stopSection($sectionId);
} catch (\LogicException $e) {
}
break;
}
}
}

View File

@ -0,0 +1,146 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Composer\Autoload\ClassLoader;
use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\ErrorHandler\DebugClassLoader;
use Symfony\Component\HttpKernel\Kernel;
/**
* Sets the classes to compile in the cache for the container.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AddAnnotatedClassesToCachePass implements CompilerPassInterface
{
private $kernel;
public function __construct(Kernel $kernel)
{
$this->kernel = $kernel;
}
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$annotatedClasses = [];
foreach ($container->getExtensions() as $extension) {
if ($extension instanceof Extension) {
$annotatedClasses[] = $extension->getAnnotatedClassesToCompile();
}
}
$annotatedClasses = array_merge($this->kernel->getAnnotatedClassesToCompile(), ...$annotatedClasses);
$existingClasses = $this->getClassesInComposerClassMaps();
$annotatedClasses = $container->getParameterBag()->resolveValue($annotatedClasses);
$this->kernel->setAnnotatedClassCache($this->expandClasses($annotatedClasses, $existingClasses));
}
/**
* Expands the given class patterns using a list of existing classes.
*
* @param array $patterns The class patterns to expand
* @param array $classes The existing classes to match against the patterns
*/
private function expandClasses(array $patterns, array $classes): array
{
$expanded = [];
// Explicit classes declared in the patterns are returned directly
foreach ($patterns as $key => $pattern) {
if (!str_ends_with($pattern, '\\') && !str_contains($pattern, '*')) {
unset($patterns[$key]);
$expanded[] = ltrim($pattern, '\\');
}
}
// Match patterns with the classes list
$regexps = $this->patternsToRegexps($patterns);
foreach ($classes as $class) {
$class = ltrim($class, '\\');
if ($this->matchAnyRegexps($class, $regexps)) {
$expanded[] = $class;
}
}
return array_unique($expanded);
}
private function getClassesInComposerClassMaps(): array
{
$classes = [];
foreach (spl_autoload_functions() as $function) {
if (!\is_array($function)) {
continue;
}
if ($function[0] instanceof DebugClassLoader || $function[0] instanceof LegacyDebugClassLoader) {
$function = $function[0]->getClassLoader();
}
if (\is_array($function) && $function[0] instanceof ClassLoader) {
$classes += array_filter($function[0]->getClassMap());
}
}
return array_keys($classes);
}
private function patternsToRegexps(array $patterns): array
{
$regexps = [];
foreach ($patterns as $pattern) {
// Escape user input
$regex = preg_quote(ltrim($pattern, '\\'));
// Wildcards * and **
$regex = strtr($regex, ['\\*\\*' => '.*?', '\\*' => '[^\\\\]*?']);
// If this class does not end by a slash, anchor the end
if ('\\' !== substr($regex, -1)) {
$regex .= '$';
}
$regexps[] = '{^\\\\'.$regex.'}';
}
return $regexps;
}
private function matchAnyRegexps(string $class, array $regexps): bool
{
$isTest = str_contains($class, 'Test');
foreach ($regexps as $regex) {
if ($isTest && !str_contains($regex, 'Test')) {
continue;
}
if (preg_match($regex, '\\'.$class)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* This extension sub-class provides first-class integration with the
* Config/Definition Component.
*
* You can use this as base class if
*
* a) you use the Config/Definition component for configuration,
* b) your configuration class is named "Configuration", and
* c) the configuration class resides in the DependencyInjection sub-folder.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
abstract class ConfigurableExtension extends Extension
{
/**
* {@inheritdoc}
*/
final public function load(array $configs, ContainerBuilder $container)
{
$this->loadInternal($this->processConfiguration($this->getConfiguration($configs, $container), $configs), $container);
}
/**
* Configures the passed container according to the merged configuration.
*/
abstract protected function loadInternal(array $mergedConfig, ContainerBuilder $container);
}

View File

@ -0,0 +1,68 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\TraceableValueResolver;
use Symfony\Component\Stopwatch\Stopwatch;
/**
* Gathers and configures the argument value resolvers.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
class ControllerArgumentValueResolverPass implements CompilerPassInterface
{
use PriorityTaggedServiceTrait;
private $argumentResolverService;
private $argumentValueResolverTag;
private $traceableResolverStopwatch;
public function __construct(string $argumentResolverService = 'argument_resolver', string $argumentValueResolverTag = 'controller.argument_value_resolver', string $traceableResolverStopwatch = 'debug.stopwatch')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->argumentResolverService = $argumentResolverService;
$this->argumentValueResolverTag = $argumentValueResolverTag;
$this->traceableResolverStopwatch = $traceableResolverStopwatch;
}
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition($this->argumentResolverService)) {
return;
}
$resolvers = $this->findAndSortTaggedServices($this->argumentValueResolverTag, $container);
if ($container->getParameter('kernel.debug') && class_exists(Stopwatch::class) && $container->has($this->traceableResolverStopwatch)) {
foreach ($resolvers as $resolverReference) {
$id = (string) $resolverReference;
$container->register("debug.$id", TraceableValueResolver::class)
->setDecoratedService($id)
->setArguments([new Reference("debug.$id.inner"), new Reference($this->traceableResolverStopwatch)]);
}
}
$container
->getDefinition($this->argumentResolverService)
->replaceArgument(1, new IteratorArgument($resolvers))
;
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\Extension\Extension as BaseExtension;
/**
* Allow adding classes to the class cache.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class Extension extends BaseExtension
{
private $annotatedClasses = [];
/**
* Gets the annotated classes to cache.
*
* @return array
*/
public function getAnnotatedClassesToCompile()
{
return $this->annotatedClasses;
}
/**
* Adds annotated classes to the class cache.
*
* @param array $annotatedClasses An array of class patterns
*/
public function addAnnotatedClassesToCompile(array $annotatedClasses)
{
$this->annotatedClasses = array_merge($this->annotatedClasses, $annotatedClasses);
}
}

View File

@ -0,0 +1,67 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
/**
* Adds services tagged kernel.fragment_renderer as HTTP content rendering strategies.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FragmentRendererPass implements CompilerPassInterface
{
private $handlerService;
private $rendererTag;
public function __construct(string $handlerService = 'fragment.handler', string $rendererTag = 'kernel.fragment_renderer')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->handlerService = $handlerService;
$this->rendererTag = $rendererTag;
}
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition($this->handlerService)) {
return;
}
$definition = $container->getDefinition($this->handlerService);
$renderers = [];
foreach ($container->findTaggedServiceIds($this->rendererTag, true) as $id => $tags) {
$def = $container->getDefinition($id);
$class = $container->getParameterBag()->resolveValue($def->getClass());
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if (!$r->isSubclassOf(FragmentRendererInterface::class)) {
throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, FragmentRendererInterface::class));
}
foreach ($tags as $tag) {
$renderers[$tag['alias']] = new Reference($id);
}
}
$definition->replaceArgument(0, ServiceLocatorTagPass::register($container, $renderers));
}
}

View File

@ -0,0 +1,51 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
/**
* Lazily loads fragment renderers from the dependency injection container.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class LazyLoadingFragmentHandler extends FragmentHandler
{
private $container;
/**
* @var array<string, bool>
*/
private $initialized = [];
public function __construct(ContainerInterface $container, RequestStack $requestStack, bool $debug = false)
{
$this->container = $container;
parent::__construct($requestStack, [], $debug);
}
/**
* {@inheritdoc}
*/
public function render($uri, string $renderer = 'inline', array $options = [])
{
if (!isset($this->initialized[$renderer]) && $this->container->has($renderer)) {
$this->addRenderer($this->container->get($renderer));
$this->initialized[$renderer] = true;
}
return parent::render($uri, $renderer, $options);
}
}

View File

@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Log\Logger;
/**
* Registers the default logger if necessary.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class LoggerPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$container->setAlias(LoggerInterface::class, 'logger')
->setPublic(false);
if ($container->has('logger')) {
return;
}
$container->register('logger', Logger::class)
->setPublic(false);
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass as BaseMergeExtensionConfigurationPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Ensures certain extensions are always loaded.
*
* @author Kris Wallsmith <kris@symfony.com>
*/
class MergeExtensionConfigurationPass extends BaseMergeExtensionConfigurationPass
{
private $extensions;
/**
* @param string[] $extensions
*/
public function __construct(array $extensions)
{
$this->extensions = $extensions;
}
public function process(ContainerBuilder $container)
{
foreach ($this->extensions as $extension) {
if (!\count($container->getExtensionConfig($extension))) {
$container->loadFromExtension($extension, []);
}
}
parent::process($container);
}
}

View File

@ -0,0 +1,223 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Creates the service-locators required by ServiceValueResolver.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
{
private $resolverServiceId;
private $controllerTag;
private $controllerLocator;
private $notTaggedControllerResolverServiceId;
public function __construct(string $resolverServiceId = 'argument_resolver.service', string $controllerTag = 'controller.service_arguments', string $controllerLocator = 'argument_resolver.controller_locator', string $notTaggedControllerResolverServiceId = 'argument_resolver.not_tagged_controller')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->resolverServiceId = $resolverServiceId;
$this->controllerTag = $controllerTag;
$this->controllerLocator = $controllerLocator;
$this->notTaggedControllerResolverServiceId = $notTaggedControllerResolverServiceId;
}
public function process(ContainerBuilder $container)
{
if (false === $container->hasDefinition($this->resolverServiceId) && false === $container->hasDefinition($this->notTaggedControllerResolverServiceId)) {
return;
}
$parameterBag = $container->getParameterBag();
$controllers = [];
$publicAliases = [];
foreach ($container->getAliases() as $id => $alias) {
if ($alias->isPublic() && !$alias->isPrivate()) {
$publicAliases[(string) $alias][] = $id;
}
}
foreach ($container->findTaggedServiceIds($this->controllerTag, true) as $id => $tags) {
$def = $container->getDefinition($id);
$def->setPublic(true);
$class = $def->getClass();
$autowire = $def->isAutowired();
$bindings = $def->getBindings();
// resolve service class, taking parent definitions into account
while ($def instanceof ChildDefinition) {
$def = $container->findDefinition($def->getParent());
$class = $class ?: $def->getClass();
$bindings += $def->getBindings();
}
$class = $parameterBag->resolveValue($class);
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
$isContainerAware = $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($class, AbstractController::class);
// get regular public methods
$methods = [];
$arguments = [];
foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
if ('setContainer' === $r->name && $isContainerAware) {
continue;
}
if (!$r->isConstructor() && !$r->isDestructor() && !$r->isAbstract()) {
$methods[strtolower($r->name)] = [$r, $r->getParameters()];
}
}
// validate and collect explicit per-actions and per-arguments service references
foreach ($tags as $attributes) {
if (!isset($attributes['action']) && !isset($attributes['argument']) && !isset($attributes['id'])) {
$autowire = true;
continue;
}
foreach (['action', 'argument', 'id'] as $k) {
if (!isset($attributes[$k][0])) {
throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "%s" %s for service "%s".', $k, $this->controllerTag, json_encode($attributes, \JSON_UNESCAPED_UNICODE), $id));
}
}
if (!isset($methods[$action = strtolower($attributes['action'])])) {
throw new InvalidArgumentException(sprintf('Invalid "action" attribute on tag "%s" for service "%s": no public "%s()" method found on class "%s".', $this->controllerTag, $id, $attributes['action'], $class));
}
[$r, $parameters] = $methods[$action];
$found = false;
foreach ($parameters as $p) {
if ($attributes['argument'] === $p->name) {
if (!isset($arguments[$r->name][$p->name])) {
$arguments[$r->name][$p->name] = $attributes['id'];
}
$found = true;
break;
}
}
if (!$found) {
throw new InvalidArgumentException(sprintf('Invalid "%s" tag for service "%s": method "%s()" has no "%s" argument on class "%s".', $this->controllerTag, $id, $r->name, $attributes['argument'], $class));
}
}
foreach ($methods as [$r, $parameters]) {
/** @var \ReflectionMethod $r */
// create a per-method map of argument-names to service/type-references
$args = [];
foreach ($parameters as $p) {
/** @var \ReflectionParameter $p */
$type = ltrim($target = (string) ProxyHelper::getTypeHint($r, $p), '\\');
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
if (isset($arguments[$r->name][$p->name])) {
$target = $arguments[$r->name][$p->name];
if ('?' !== $target[0]) {
$invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
} elseif ('' === $target = (string) substr($target, 1)) {
throw new InvalidArgumentException(sprintf('A "%s" tag must have non-empty "id" attributes for service "%s".', $this->controllerTag, $id));
} elseif ($p->allowsNull() && !$p->isOptional()) {
$invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
}
} elseif (isset($bindings[$bindingName = $type.' $'.$name = Target::parseName($p)]) || isset($bindings[$bindingName = '$'.$name]) || isset($bindings[$bindingName = $type])) {
$binding = $bindings[$bindingName];
[$bindingValue, $bindingId, , $bindingType, $bindingFile] = $binding->getValues();
$binding->setValues([$bindingValue, $bindingId, true, $bindingType, $bindingFile]);
if (!$bindingValue instanceof Reference) {
$args[$p->name] = new Reference('.value.'.$container->hash($bindingValue));
$container->register((string) $args[$p->name], 'mixed')
->setFactory('current')
->addArgument([$bindingValue]);
} else {
$args[$p->name] = $bindingValue;
}
continue;
} elseif (!$type || !$autowire || '\\' !== $target[0]) {
continue;
} elseif (is_subclass_of($type, \UnitEnum::class)) {
// do not attempt to register enum typed arguments if not already present in bindings
continue;
} elseif (!$p->allowsNull()) {
$invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
}
if (Request::class === $type || SessionInterface::class === $type) {
continue;
}
if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
$message = sprintf('Cannot determine controller argument for "%s::%s()": the $%s argument is type-hinted with the non-existent class or interface: "%s".', $class, $r->name, $p->name, $type);
// see if the type-hint lives in the same namespace as the controller
if (0 === strncmp($type, $class, strrpos($class, '\\'))) {
$message .= ' Did you forget to add a use statement?';
}
$container->register($erroredId = '.errored.'.$container->hash($message), $type)
->addError($message);
$args[$p->name] = new Reference($erroredId, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE);
} else {
$target = ltrim($target, '\\');
$args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, Target::parseName($p)) : new Reference($target, $invalidBehavior);
}
}
// register the maps as a per-method service-locators
if ($args) {
$controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container, $args);
foreach ($publicAliases[$id] ?? [] as $alias) {
$controllers[$alias.'::'.$r->name] = clone $controllers[$id.'::'.$r->name];
}
}
}
}
$controllerLocatorRef = ServiceLocatorTagPass::register($container, $controllers);
if ($container->hasDefinition($this->resolverServiceId)) {
$container->getDefinition($this->resolverServiceId)
->replaceArgument(0, $controllerLocatorRef);
}
if ($container->hasDefinition($this->notTaggedControllerResolverServiceId)) {
$container->getDefinition($this->notTaggedControllerResolverServiceId)
->replaceArgument(0, $controllerLocatorRef);
}
$container->setAlias($this->controllerLocator, (string) $controllerLocatorRef);
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Register all services that have the "kernel.locale_aware" tag into the listener.
*
* @author Pierre Bobiet <pierrebobiet@gmail.com>
*/
class RegisterLocaleAwareServicesPass implements CompilerPassInterface
{
private $listenerServiceId;
private $localeAwareTag;
public function __construct(string $listenerServiceId = 'locale_aware_listener', string $localeAwareTag = 'kernel.locale_aware')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->listenerServiceId = $listenerServiceId;
$this->localeAwareTag = $localeAwareTag;
}
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition($this->listenerServiceId)) {
return;
}
$services = [];
foreach ($container->findTaggedServiceIds($this->localeAwareTag) as $id => $tags) {
$services[] = new Reference($id);
}
if (!$services) {
$container->removeDefinition($this->listenerServiceId);
return;
}
$container
->getDefinition($this->listenerServiceId)
->setArgument(0, new IteratorArgument($services))
;
}
}

View File

@ -0,0 +1,79 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Removes empty service-locators registered for ServiceValueResolver.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class RemoveEmptyControllerArgumentLocatorsPass implements CompilerPassInterface
{
private $controllerLocator;
public function __construct(string $controllerLocator = 'argument_resolver.controller_locator')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->controllerLocator = $controllerLocator;
}
public function process(ContainerBuilder $container)
{
$controllerLocator = $container->findDefinition($this->controllerLocator);
$controllers = $controllerLocator->getArgument(0);
foreach ($controllers as $controller => $argumentRef) {
$argumentLocator = $container->getDefinition((string) $argumentRef->getValues()[0]);
if (!$argumentLocator->getArgument(0)) {
// remove empty argument locators
$reason = sprintf('Removing service-argument resolver for controller "%s": no corresponding services exist for the referenced types.', $controller);
} else {
// any methods listed for call-at-instantiation cannot be actions
$reason = false;
[$id, $action] = explode('::', $controller);
if ($container->hasAlias($id)) {
continue;
}
$controllerDef = $container->getDefinition($id);
foreach ($controllerDef->getMethodCalls() as [$method]) {
if (0 === strcasecmp($action, $method)) {
$reason = sprintf('Removing method "%s" of service "%s" from controller candidates: the method is called at instantiation, thus cannot be an action.', $action, $id);
break;
}
}
if (!$reason) {
// see Symfony\Component\HttpKernel\Controller\ContainerControllerResolver
$controllers[$id.':'.$action] = $argumentRef;
if ('__invoke' === $action) {
$controllers[$id] = $argumentRef;
}
continue;
}
}
unset($controllers[$controller]);
$container->log($this, $reason);
}
$controllerLocator->replaceArgument(0, $controllers);
}
}

View File

@ -0,0 +1,79 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
/**
* @author Alexander M. Turek <me@derrabus.de>
*/
class ResettableServicePass implements CompilerPassInterface
{
private $tagName;
public function __construct(string $tagName = 'kernel.reset')
{
if (0 < \func_num_args()) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
}
$this->tagName = $tagName;
}
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->has('services_resetter')) {
return;
}
$services = $methods = [];
foreach ($container->findTaggedServiceIds($this->tagName, true) as $id => $tags) {
$services[$id] = new Reference($id, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE);
foreach ($tags as $attributes) {
if (!isset($attributes['method'])) {
throw new RuntimeException(sprintf('Tag "%s" requires the "method" attribute to be set.', $this->tagName));
}
if (!isset($methods[$id])) {
$methods[$id] = [];
}
if ('ignore' === ($attributes['on_invalid'] ?? null)) {
$attributes['method'] = '?'.$attributes['method'];
}
$methods[$id][] = $attributes['method'];
}
}
if (!$services) {
$container->removeAlias('services_resetter');
$container->removeDefinition('services_resetter');
return;
}
$container->findDefinition('services_resetter')
->setArgument(0, new IteratorArgument($services))
->setArgument(1, $methods);
}
}

View File

@ -0,0 +1,51 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DependencyInjection;
use Symfony\Contracts\Service\ResetInterface;
/**
* Resets provided services.
*
* @author Alexander M. Turek <me@derrabus.de>
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class ServicesResetter implements ResetInterface
{
private $resettableServices;
private $resetMethods;
/**
* @param \Traversable<string, object> $resettableServices
* @param array<string, string|string[]> $resetMethods
*/
public function __construct(\Traversable $resettableServices, array $resetMethods)
{
$this->resettableServices = $resettableServices;
$this->resetMethods = $resetMethods;
}
public function reset()
{
foreach ($this->resettableServices as $id => $service) {
foreach ((array) $this->resetMethods[$id] as $resetMethod) {
if ('?' === $resetMethod[0] && !method_exists($service, $resetMethod = substr($resetMethod, 1))) {
continue;
}
$service->$resetMethod();
}
}
}
}

View File

@ -0,0 +1,61 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Allows filtering of controller arguments.
*
* You can call getController() to retrieve the controller and getArguments
* to retrieve the current arguments. With setArguments() you can replace
* arguments that are used to call the controller.
*
* Arguments set in the event must be compatible with the signature of the
* controller.
*
* @author Christophe Coevoet <stof@notk.org>
*/
final class ControllerArgumentsEvent extends KernelEvent
{
private $controller;
private $arguments;
public function __construct(HttpKernelInterface $kernel, callable $controller, array $arguments, Request $request, ?int $requestType)
{
parent::__construct($kernel, $request, $requestType);
$this->controller = $controller;
$this->arguments = $arguments;
}
public function getController(): callable
{
return $this->controller;
}
public function setController(callable $controller)
{
$this->controller = $controller;
}
public function getArguments(): array
{
return $this->arguments;
}
public function setArguments(array $arguments)
{
$this->arguments = $arguments;
}
}

View File

@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Allows filtering of a controller callable.
*
* You can call getController() to retrieve the current controller. With
* setController() you can set a new controller that is used in the processing
* of the request.
*
* Controllers should be callables.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
final class ControllerEvent extends KernelEvent
{
private $controller;
public function __construct(HttpKernelInterface $kernel, callable $controller, Request $request, ?int $requestType)
{
parent::__construct($kernel, $request, $requestType);
$this->setController($controller);
}
public function getController(): callable
{
return $this->controller;
}
public function setController(callable $controller): void
{
$this->controller = $controller;
}
}

View File

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Allows to create a response for a thrown exception.
*
* Call setResponse() to set the response that will be returned for the
* current request. The propagation of this event is stopped as soon as a
* response is set.
*
* You can also call setThrowable() to replace the thrown exception. This
* exception will be thrown if no response is set during processing of this
* event.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
final class ExceptionEvent extends RequestEvent
{
private $throwable;
/**
* @var bool
*/
private $allowCustomResponseCode = false;
public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, \Throwable $e)
{
parent::__construct($kernel, $request, $requestType);
$this->setThrowable($e);
}
public function getThrowable(): \Throwable
{
return $this->throwable;
}
/**
* Replaces the thrown exception.
*
* This exception will be thrown if no response is set in the event.
*/
public function setThrowable(\Throwable $exception): void
{
$this->throwable = $exception;
}
/**
* Mark the event as allowing a custom response code.
*/
public function allowCustomResponseCode(): void
{
$this->allowCustomResponseCode = true;
}
/**
* Returns true if the event allows a custom response code.
*/
public function isAllowingCustomResponseCode(): bool
{
return $this->allowCustomResponseCode;
}
}

View File

@ -0,0 +1,21 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
/**
* Triggered whenever a request is fully processed.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
final class FinishRequestEvent extends KernelEvent
{
}

View File

@ -0,0 +1,92 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* Base class for events thrown in the HttpKernel component.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class KernelEvent extends Event
{
private $kernel;
private $request;
private $requestType;
/**
* @param int $requestType The request type the kernel is currently processing; one of
* HttpKernelInterface::MAIN_REQUEST or HttpKernelInterface::SUB_REQUEST
*/
public function __construct(HttpKernelInterface $kernel, Request $request, ?int $requestType)
{
$this->kernel = $kernel;
$this->request = $request;
$this->requestType = $requestType;
}
/**
* Returns the kernel in which this event was thrown.
*
* @return HttpKernelInterface
*/
public function getKernel()
{
return $this->kernel;
}
/**
* Returns the request the kernel is currently processing.
*
* @return Request
*/
public function getRequest()
{
return $this->request;
}
/**
* Returns the request type the kernel is currently processing.
*
* @return int One of HttpKernelInterface::MAIN_REQUEST and
* HttpKernelInterface::SUB_REQUEST
*/
public function getRequestType()
{
return $this->requestType;
}
/**
* Checks if this is the main request.
*/
public function isMainRequest(): bool
{
return HttpKernelInterface::MAIN_REQUEST === $this->requestType;
}
/**
* Checks if this is a master request.
*
* @return bool
*
* @deprecated since symfony/http-kernel 5.3, use isMainRequest() instead
*/
public function isMasterRequest()
{
trigger_deprecation('symfony/http-kernel', '5.3', '"%s()" is deprecated, use "isMainRequest()" instead.', __METHOD__);
return $this->isMainRequest();
}
}

View File

@ -0,0 +1,58 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Response;
/**
* Allows to create a response for a request.
*
* Call setResponse() to set the response that will be returned for the
* current request. The propagation of this event is stopped as soon as a
* response is set.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class RequestEvent extends KernelEvent
{
private $response;
/**
* Returns the response object.
*
* @return Response|null
*/
public function getResponse()
{
return $this->response;
}
/**
* Sets a response and stops event propagation.
*/
public function setResponse(Response $response)
{
$this->response = $response;
$this->stopPropagation();
}
/**
* Returns whether a response was set.
*
* @return bool
*/
public function hasResponse()
{
return null !== $this->response;
}
}

View File

@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Allows to filter a Response object.
*
* You can call getResponse() to retrieve the current response. With
* setResponse() you can set a new response that will be returned to the
* browser.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
final class ResponseEvent extends KernelEvent
{
private $response;
public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, Response $response)
{
parent::__construct($kernel, $request, $requestType);
$this->setResponse($response);
}
public function getResponse(): Response
{
return $this->response;
}
public function setResponse(Response $response): void
{
$this->response = $response;
}
}

View File

@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Allows to execute logic after a response was sent.
*
* Since it's only triggered on main requests, the `getRequestType()` method
* will always return the value of `HttpKernelInterface::MAIN_REQUEST`.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
final class TerminateEvent extends KernelEvent
{
private $response;
public function __construct(HttpKernelInterface $kernel, Request $request, Response $response)
{
parent::__construct($kernel, $request, HttpKernelInterface::MAIN_REQUEST);
$this->response = $response;
}
public function getResponse(): Response
{
return $this->response;
}
}

View File

@ -0,0 +1,61 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Allows to create a response for the return value of a controller.
*
* Call setResponse() to set the response that will be returned for the
* current request. The propagation of this event is stopped as soon as a
* response is set.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
final class ViewEvent extends RequestEvent
{
/**
* The return value of the controller.
*
* @var mixed
*/
private $controllerResult;
public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, $controllerResult)
{
parent::__construct($kernel, $request, $requestType);
$this->controllerResult = $controllerResult;
}
/**
* Returns the return value of the controller.
*
* @return mixed
*/
public function getControllerResult()
{
return $this->controllerResult;
}
/**
* Assigns the return value of the controller.
*
* @param mixed $controllerResult The controller return value
*/
public function setControllerResult($controllerResult): void
{
$this->controllerResult = $controllerResult;
}
}

View File

@ -0,0 +1,306 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\SessionUtils;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Exception\UnexpectedSessionUsageException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Service\ResetInterface;
/**
* Sets the session onto the request on the "kernel.request" event and saves
* it on the "kernel.response" event.
*
* In addition, if the session has been started it overrides the Cache-Control
* header in such a way that all caching is disabled in that case.
* If you have a scenario where caching responses with session information in
* them makes sense, you can disable this behaviour by setting the header
* AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER on the response.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Tobias Schultze <http://tobion.de>
*
* @internal
*/
abstract class AbstractSessionListener implements EventSubscriberInterface, ResetInterface
{
public const NO_AUTO_CACHE_CONTROL_HEADER = 'Symfony-Session-NoAutoCacheControl';
protected $container;
private $sessionUsageStack = [];
private $debug;
/**
* @var array<string, mixed>
*/
private $sessionOptions;
public function __construct(ContainerInterface $container = null, bool $debug = false, array $sessionOptions = [])
{
$this->container = $container;
$this->debug = $debug;
$this->sessionOptions = $sessionOptions;
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if (!$request->hasSession()) {
// This variable prevents calling `$this->getSession()` twice in case the Request (and the below factory) is cloned
$sess = null;
$request->setSessionFactory(function () use (&$sess, $request) {
if (!$sess) {
$sess = $this->getSession();
}
/*
* For supporting sessions in php runtime with runners like roadrunner or swoole, the session
* cookie needs to be read from the cookie bag and set on the session storage.
*
* Do not set it when a native php session is active.
*/
if ($sess && !$sess->isStarted() && \PHP_SESSION_ACTIVE !== session_status()) {
$sessionId = $request->cookies->get($sess->getName(), '');
$sess->setId($sessionId);
}
return $sess;
});
}
$session = $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : null;
$this->sessionUsageStack[] = $session instanceof Session ? $session->getUsageIndex() : 0;
}
public function onKernelResponse(ResponseEvent $event)
{
if (!$event->isMainRequest() || (!$this->container->has('initialized_session') && !$event->getRequest()->hasSession())) {
return;
}
$response = $event->getResponse();
$autoCacheControl = !$response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER);
// Always remove the internal header if present
$response->headers->remove(self::NO_AUTO_CACHE_CONTROL_HEADER);
if (!$session = $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : $event->getRequest()->getSession()) {
return;
}
if ($session->isStarted()) {
/*
* Saves the session, in case it is still open, before sending the response/headers.
*
* This ensures several things in case the developer did not save the session explicitly:
*
* * If a session save handler without locking is used, it ensures the data is available
* on the next request, e.g. after a redirect. PHPs auto-save at script end via
* session_register_shutdown is executed after fastcgi_finish_request. So in this case
* the data could be missing the next request because it might not be saved the moment
* the new request is processed.
* * A locking save handler (e.g. the native 'files') circumvents concurrency problems like
* the one above. But by saving the session before long-running things in the terminate event,
* we ensure the session is not blocked longer than needed.
* * When regenerating the session ID no locking is involved in PHPs session design. See
* https://bugs.php.net/61470 for a discussion. So in this case, the session must
* be saved anyway before sending the headers with the new session ID. Otherwise session
* data could get lost again for concurrent requests with the new ID. One result could be
* that you get logged out after just logging in.
*
* This listener should be executed as one of the last listeners, so that previous listeners
* can still operate on the open session. This prevents the overhead of restarting it.
* Listeners after closing the session can still work with the session as usual because
* Symfonys session implementation starts the session on demand. So writing to it after
* it is saved will just restart it.
*/
$session->save();
/*
* For supporting sessions in php runtime with runners like roadrunner or swoole the session
* cookie need to be written on the response object and should not be written by PHP itself.
*/
$sessionName = $session->getName();
$sessionId = $session->getId();
$sessionOptions = $this->getSessionOptions($this->sessionOptions);
$sessionCookiePath = $sessionOptions['cookie_path'] ?? '/';
$sessionCookieDomain = $sessionOptions['cookie_domain'] ?? null;
$sessionCookieSecure = $sessionOptions['cookie_secure'] ?? false;
$sessionCookieHttpOnly = $sessionOptions['cookie_httponly'] ?? true;
$sessionCookieSameSite = $sessionOptions['cookie_samesite'] ?? Cookie::SAMESITE_LAX;
SessionUtils::popSessionCookie($sessionName, $sessionId);
$request = $event->getRequest();
$requestSessionCookieId = $request->cookies->get($sessionName);
$isSessionEmpty = $session->isEmpty() && empty($_SESSION); // checking $_SESSION to keep compatibility with native sessions
if ($requestSessionCookieId && $isSessionEmpty) {
$response->headers->clearCookie(
$sessionName,
$sessionCookiePath,
$sessionCookieDomain,
$sessionCookieSecure,
$sessionCookieHttpOnly,
$sessionCookieSameSite
);
} elseif ($sessionId !== $requestSessionCookieId && !$isSessionEmpty) {
$expire = 0;
$lifetime = $sessionOptions['cookie_lifetime'] ?? null;
if ($lifetime) {
$expire = time() + $lifetime;
}
$response->headers->setCookie(
Cookie::create(
$sessionName,
$sessionId,
$expire,
$sessionCookiePath,
$sessionCookieDomain,
$sessionCookieSecure,
$sessionCookieHttpOnly,
false,
$sessionCookieSameSite
)
);
}
}
if ($session instanceof Session ? $session->getUsageIndex() === end($this->sessionUsageStack) : !$session->isStarted()) {
return;
}
if ($autoCacheControl) {
$response
->setExpires(new \DateTime())
->setPrivate()
->setMaxAge(0)
->headers->addCacheControlDirective('must-revalidate');
}
if (!$event->getRequest()->attributes->get('_stateless', false)) {
return;
}
if ($this->debug) {
throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.');
}
if ($this->container->has('logger')) {
$this->container->get('logger')->warning('Session was used while the request was declared stateless.');
}
}
public function onFinishRequest(FinishRequestEvent $event)
{
if ($event->isMainRequest()) {
array_pop($this->sessionUsageStack);
}
}
public function onSessionUsage(): void
{
if (!$this->debug) {
return;
}
if ($this->container && $this->container->has('session_collector')) {
$this->container->get('session_collector')();
}
if (!$requestStack = $this->container && $this->container->has('request_stack') ? $this->container->get('request_stack') : null) {
return;
}
$stateless = false;
$clonedRequestStack = clone $requestStack;
while (null !== ($request = $clonedRequestStack->pop()) && !$stateless) {
$stateless = $request->attributes->get('_stateless');
}
if (!$stateless) {
return;
}
if (!$session = $this->container && $this->container->has('initialized_session') ? $this->container->get('initialized_session') : $requestStack->getCurrentRequest()->getSession()) {
return;
}
if ($session->isStarted()) {
$session->save();
}
throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.');
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 128],
// low priority to come after regular response listeners, but higher than StreamedResponseListener
KernelEvents::RESPONSE => ['onKernelResponse', -1000],
KernelEvents::FINISH_REQUEST => ['onFinishRequest'],
];
}
public function reset(): void
{
if (\PHP_SESSION_ACTIVE === session_status()) {
session_abort();
}
session_unset();
$_SESSION = [];
if (!headers_sent()) { // session id can only be reset when no headers were so we check for headers_sent first
session_id('');
}
}
/**
* Gets the session object.
*
* @return SessionInterface|null
*/
abstract protected function getSession();
private function getSessionOptions(array $sessionOptions): array
{
$mergedSessionOptions = [];
foreach (session_get_cookie_params() as $key => $value) {
$mergedSessionOptions['cookie_'.$key] = $value;
}
foreach ($sessionOptions as $key => $value) {
// do the same logic as in the NativeSessionStorage
if ('cookie_secure' === $key && 'auto' === $value) {
continue;
}
$mergedSessionOptions[$key] = $value;
}
return $mergedSessionOptions;
}
}

View File

@ -0,0 +1,120 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
trigger_deprecation('symfony/http-kernel', '5.4', '"%s" is deprecated use "%s" instead.', AbstractTestSessionListener::class, AbstractSessionListener::class);
/**
* TestSessionListener.
*
* Saves session in test environment.
*
* @author Bulat Shakirzyanov <mallluhuct@gmail.com>
* @author Fabien Potencier <fabien@symfony.com>
*
* @internal
*
* @deprecated since Symfony 5.4, use AbstractSessionListener instead
*/
abstract class AbstractTestSessionListener implements EventSubscriberInterface
{
private $sessionId;
private $sessionOptions;
public function __construct(array $sessionOptions = [])
{
$this->sessionOptions = $sessionOptions;
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
// bootstrap the session
if ($event->getRequest()->hasSession()) {
$session = $event->getRequest()->getSession();
} elseif (!$session = $this->getSession()) {
return;
}
$cookies = $event->getRequest()->cookies;
if ($cookies->has($session->getName())) {
$this->sessionId = $cookies->get($session->getName());
$session->setId($this->sessionId);
}
}
/**
* Checks if session was initialized and saves if current request is the main request
* Runs on 'kernel.response' in test environment.
*/
public function onKernelResponse(ResponseEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if (!$request->hasSession()) {
return;
}
$session = $request->getSession();
if ($wasStarted = $session->isStarted()) {
$session->save();
}
if ($session instanceof Session ? !$session->isEmpty() || (null !== $this->sessionId && $session->getId() !== $this->sessionId) : $wasStarted) {
$params = session_get_cookie_params() + ['samesite' => null];
foreach ($this->sessionOptions as $k => $v) {
if (str_starts_with($k, 'cookie_')) {
$params[substr($k, 7)] = $v;
}
}
foreach ($event->getResponse()->headers->getCookies() as $cookie) {
if ($session->getName() === $cookie->getName() && $params['path'] === $cookie->getPath() && $params['domain'] == $cookie->getDomain()) {
return;
}
}
$event->getResponse()->headers->setCookie(new Cookie($session->getName(), $session->getId(), 0 === $params['lifetime'] ? 0 : time() + $params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly'], false, $params['samesite'] ?: null));
$this->sessionId = $session->getId();
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 127], // AFTER SessionListener
KernelEvents::RESPONSE => ['onKernelResponse', -128],
];
}
/**
* Gets the session object.
*
* @return SessionInterface|null
*/
abstract protected function getSession();
}

View File

@ -0,0 +1,52 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Adds configured formats to each request.
*
* @author Gildas Quemener <gildas.quemener@gmail.com>
*
* @final
*/
class AddRequestFormatsListener implements EventSubscriberInterface
{
protected $formats;
public function __construct(array $formats)
{
$this->formats = $formats;
}
/**
* Adds request formats.
*/
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
foreach ($this->formats as $format => $mimeTypes) {
$request->setFormat($format, $mimeTypes);
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => ['onKernelRequest', 100]];
}
}

View File

@ -0,0 +1,190 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleEvent;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\ErrorHandler\ErrorHandler;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Configures errors and exceptions handlers.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @final
*
* @internal since Symfony 5.3
*/
class DebugHandlersListener implements EventSubscriberInterface
{
private $earlyHandler;
private $exceptionHandler;
private $logger;
private $deprecationLogger;
private $levels;
private $throwAt;
private $scream;
private $scope;
private $firstCall = true;
private $hasTerminatedWithException;
/**
* @param callable|null $exceptionHandler A handler that must support \Throwable instances that will be called on Exception
* @param array|int|null $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
* @param int|null $throwAt Thrown errors in a bit field of E_* constants, or null to keep the current value
* @param bool $scream Enables/disables screaming mode, where even silenced errors are logged
* @param bool $scope Enables/disables scoping mode
*/
public function __construct(callable $exceptionHandler = null, LoggerInterface $logger = null, $levels = \E_ALL, ?int $throwAt = \E_ALL, bool $scream = true, $scope = true, $deprecationLogger = null, $fileLinkFormat = null)
{
if (!\is_bool($scope)) {
trigger_deprecation('symfony/http-kernel', '5.4', 'Passing a $fileLinkFormat is deprecated.');
$scope = $deprecationLogger;
$deprecationLogger = $fileLinkFormat;
}
$handler = set_exception_handler('var_dump');
$this->earlyHandler = \is_array($handler) ? $handler[0] : null;
restore_exception_handler();
$this->exceptionHandler = $exceptionHandler;
$this->logger = $logger;
$this->levels = $levels ?? \E_ALL;
$this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? \E_ALL : null));
$this->scream = $scream;
$this->scope = $scope;
$this->deprecationLogger = $deprecationLogger;
}
/**
* Configures the error handler.
*/
public function configure(object $event = null)
{
if ($event instanceof ConsoleEvent && !\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
return;
}
if (!$event instanceof KernelEvent ? !$this->firstCall : !$event->isMainRequest()) {
return;
}
$this->firstCall = $this->hasTerminatedWithException = false;
$handler = set_exception_handler('var_dump');
$handler = \is_array($handler) ? $handler[0] : null;
restore_exception_handler();
if (!$handler instanceof ErrorHandler) {
$handler = $this->earlyHandler;
}
if ($handler instanceof ErrorHandler) {
if ($this->logger || $this->deprecationLogger) {
$this->setDefaultLoggers($handler);
if (\is_array($this->levels)) {
$levels = 0;
foreach ($this->levels as $type => $log) {
$levels |= $type;
}
} else {
$levels = $this->levels;
}
if ($this->scream) {
$handler->screamAt($levels);
}
if ($this->scope) {
$handler->scopeAt($levels & ~\E_USER_DEPRECATED & ~\E_DEPRECATED);
} else {
$handler->scopeAt(0, true);
}
$this->logger = $this->deprecationLogger = $this->levels = null;
}
if (null !== $this->throwAt) {
$handler->throwAt($this->throwAt, true);
}
}
if (!$this->exceptionHandler) {
if ($event instanceof KernelEvent) {
if (method_exists($kernel = $event->getKernel(), 'terminateWithException')) {
$request = $event->getRequest();
$hasRun = &$this->hasTerminatedWithException;
$this->exceptionHandler = static function (\Throwable $e) use ($kernel, $request, &$hasRun) {
if ($hasRun) {
throw $e;
}
$hasRun = true;
$kernel->terminateWithException($e, $request);
};
}
} elseif ($event instanceof ConsoleEvent && $app = $event->getCommand()->getApplication()) {
$output = $event->getOutput();
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$this->exceptionHandler = static function (\Throwable $e) use ($app, $output) {
$app->renderThrowable($e, $output);
};
}
}
if ($this->exceptionHandler) {
if ($handler instanceof ErrorHandler) {
$handler->setExceptionHandler($this->exceptionHandler);
}
$this->exceptionHandler = null;
}
}
private function setDefaultLoggers(ErrorHandler $handler): void
{
if (\is_array($this->levels)) {
$levelsDeprecatedOnly = [];
$levelsWithoutDeprecated = [];
foreach ($this->levels as $type => $log) {
if (\E_DEPRECATED == $type || \E_USER_DEPRECATED == $type) {
$levelsDeprecatedOnly[$type] = $log;
} else {
$levelsWithoutDeprecated[$type] = $log;
}
}
} else {
$levelsDeprecatedOnly = $this->levels & (\E_DEPRECATED | \E_USER_DEPRECATED);
$levelsWithoutDeprecated = $this->levels & ~\E_DEPRECATED & ~\E_USER_DEPRECATED;
}
$defaultLoggerLevels = $this->levels;
if ($this->deprecationLogger && $levelsDeprecatedOnly) {
$handler->setDefaultLogger($this->deprecationLogger, $levelsDeprecatedOnly);
$defaultLoggerLevels = $levelsWithoutDeprecated;
}
if ($this->logger && $defaultLoggerLevels) {
$handler->setDefaultLogger($this->logger, $defaultLoggerLevels);
}
}
public static function getSubscribedEvents(): array
{
$events = [KernelEvents::REQUEST => ['configure', 2048]];
if (\defined('Symfony\Component\Console\ConsoleEvents::COMMAND')) {
$events[ConsoleEvents::COMMAND] = ['configure', 2048];
}
return $events;
}
}

View File

@ -0,0 +1,43 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Ensures that the application is not indexed by search engines.
*
* @author Gary PEGEOT <garypegeot@gmail.com>
*/
class DisallowRobotsIndexingListener implements EventSubscriberInterface
{
private const HEADER_NAME = 'X-Robots-Tag';
public function onResponse(ResponseEvent $event): void
{
if (!$event->getResponse()->headers->has(static::HEADER_NAME)) {
$event->getResponse()->headers->set(static::HEADER_NAME, 'noindex');
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => ['onResponse', -255],
];
}
}

View File

@ -0,0 +1,63 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
use Symfony\Component\VarDumper\Server\Connection;
use Symfony\Component\VarDumper\VarDumper;
/**
* Configures dump() handler.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class DumpListener implements EventSubscriberInterface
{
private $cloner;
private $dumper;
private $connection;
public function __construct(ClonerInterface $cloner, DataDumperInterface $dumper, Connection $connection = null)
{
$this->cloner = $cloner;
$this->dumper = $dumper;
$this->connection = $connection;
}
public function configure()
{
$cloner = $this->cloner;
$dumper = $this->dumper;
$connection = $this->connection;
VarDumper::setHandler(static function ($var) use ($cloner, $dumper, $connection) {
$data = $cloner->cloneVar($var);
if (!$connection || !$connection->write($data)) {
$dumper->dump($data);
}
});
}
public static function getSubscribedEvents()
{
if (!class_exists(ConsoleEvents::class)) {
return [];
}
// Register early to have a working dump() as early as possible
return [ConsoleEvents::COMMAND => ['configure', 1024]];
}
}

View File

@ -0,0 +1,180 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\Debug\Exception\FlattenException as LegacyFlattenException;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class ErrorListener implements EventSubscriberInterface
{
protected $controller;
protected $logger;
protected $debug;
protected $exceptionsMapping;
public function __construct($controller, LoggerInterface $logger = null, bool $debug = false, array $exceptionsMapping = [])
{
$this->controller = $controller;
$this->logger = $logger;
$this->debug = $debug;
$this->exceptionsMapping = $exceptionsMapping;
}
public function logKernelException(ExceptionEvent $event)
{
$throwable = $event->getThrowable();
$logLevel = null;
foreach ($this->exceptionsMapping as $class => $config) {
if ($throwable instanceof $class && $config['log_level']) {
$logLevel = $config['log_level'];
break;
}
}
foreach ($this->exceptionsMapping as $class => $config) {
if (!$throwable instanceof $class || !$config['status_code']) {
continue;
}
if (!$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() !== $config['status_code']) {
$headers = $throwable instanceof HttpExceptionInterface ? $throwable->getHeaders() : [];
$throwable = new HttpException($config['status_code'], $throwable->getMessage(), $throwable, $headers);
$event->setThrowable($throwable);
}
break;
}
$e = FlattenException::createFromThrowable($throwable);
$this->logException($throwable, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass(), $e->getMessage(), $e->getFile(), $e->getLine()), $logLevel);
}
public function onKernelException(ExceptionEvent $event)
{
if (null === $this->controller) {
return;
}
$throwable = $event->getThrowable();
$request = $this->duplicateRequest($throwable, $event->getRequest());
try {
$response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false);
} catch (\Exception $e) {
$f = FlattenException::createFromThrowable($e);
$this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', $f->getClass(), $f->getMessage(), $e->getFile(), $e->getLine()));
$prev = $e;
do {
if ($throwable === $wrapper = $prev) {
throw $e;
}
} while ($prev = $wrapper->getPrevious());
$prev = new \ReflectionProperty($wrapper instanceof \Exception ? \Exception::class : \Error::class, 'previous');
$prev->setAccessible(true);
$prev->setValue($wrapper, $throwable);
throw $e;
}
$event->setResponse($response);
if ($this->debug) {
$event->getRequest()->attributes->set('_remove_csp_headers', true);
}
}
public function removeCspHeader(ResponseEvent $event): void
{
if ($this->debug && $event->getRequest()->attributes->get('_remove_csp_headers', false)) {
$event->getResponse()->headers->remove('Content-Security-Policy');
}
}
public function onControllerArguments(ControllerArgumentsEvent $event)
{
$e = $event->getRequest()->attributes->get('exception');
if (!$e instanceof \Throwable || false === $k = array_search($e, $event->getArguments(), true)) {
return;
}
$r = new \ReflectionFunction(\Closure::fromCallable($event->getController()));
$r = $r->getParameters()[$k] ?? null;
if ($r && (!($r = $r->getType()) instanceof \ReflectionNamedType || \in_array($r->getName(), [FlattenException::class, LegacyFlattenException::class], true))) {
$arguments = $event->getArguments();
$arguments[$k] = FlattenException::createFromThrowable($e);
$event->setArguments($arguments);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER_ARGUMENTS => 'onControllerArguments',
KernelEvents::EXCEPTION => [
['logKernelException', 0],
['onKernelException', -128],
],
KernelEvents::RESPONSE => ['removeCspHeader', -128],
];
}
/**
* Logs an exception.
*/
protected function logException(\Throwable $exception, string $message, string $logLevel = null): void
{
if (null !== $this->logger) {
if (null !== $logLevel) {
$this->logger->log($logLevel, $message, ['exception' => $exception]);
} elseif (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
$this->logger->critical($message, ['exception' => $exception]);
} else {
$this->logger->error($message, ['exception' => $exception]);
}
}
}
/**
* Clones the request for the exception.
*/
protected function duplicateRequest(\Throwable $exception, Request $request): Request
{
$attributes = [
'_controller' => $this->controller,
'exception' => $exception,
'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null,
];
$request = $request->duplicate(null, null, $attributes);
$request->setMethod('GET');
return $request;
}
}

View File

@ -0,0 +1,99 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\UriSigner;
/**
* Handles content fragments represented by special URIs.
*
* All URL paths starting with /_fragment are handled as
* content fragments by this listener.
*
* Throws an AccessDeniedHttpException exception if the request
* is not signed or if it is not an internal sub-request.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class FragmentListener implements EventSubscriberInterface
{
private $signer;
private $fragmentPath;
/**
* @param string $fragmentPath The path that triggers this listener
*/
public function __construct(UriSigner $signer, string $fragmentPath = '/_fragment')
{
$this->signer = $signer;
$this->fragmentPath = $fragmentPath;
}
/**
* Fixes request attributes when the path is '/_fragment'.
*
* @throws AccessDeniedHttpException if the request does not come from a trusted IP
*/
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if ($this->fragmentPath !== rawurldecode($request->getPathInfo())) {
return;
}
if ($request->attributes->has('_controller')) {
// Is a sub-request: no need to parse _path but it should still be removed from query parameters as below.
$request->query->remove('_path');
return;
}
if ($event->isMainRequest()) {
$this->validateRequest($request);
}
parse_str($request->query->get('_path', ''), $attributes);
$request->attributes->add($attributes);
$request->attributes->set('_route_params', array_replace($request->attributes->get('_route_params', []), $attributes));
$request->query->remove('_path');
}
protected function validateRequest(Request $request)
{
// is the Request safe?
if (!$request->isMethodSafe()) {
throw new AccessDeniedHttpException();
}
// is the Request signed?
if ($this->signer->checkRequest($request)) {
return;
}
throw new AccessDeniedHttpException();
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 48]],
];
}
}

View File

@ -0,0 +1,77 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Translation\LocaleAwareInterface;
/**
* Pass the current locale to the provided services.
*
* @author Pierre Bobiet <pierrebobiet@gmail.com>
*/
class LocaleAwareListener implements EventSubscriberInterface
{
private $localeAwareServices;
private $requestStack;
/**
* @param iterable<mixed, LocaleAwareInterface> $localeAwareServices
*/
public function __construct(iterable $localeAwareServices, RequestStack $requestStack)
{
$this->localeAwareServices = $localeAwareServices;
$this->requestStack = $requestStack;
}
public function onKernelRequest(RequestEvent $event): void
{
$this->setLocale($event->getRequest()->getLocale(), $event->getRequest()->getDefaultLocale());
}
public function onKernelFinishRequest(FinishRequestEvent $event): void
{
if (null === $parentRequest = $this->requestStack->getParentRequest()) {
foreach ($this->localeAwareServices as $service) {
$service->setLocale($event->getRequest()->getDefaultLocale());
}
return;
}
$this->setLocale($parentRequest->getLocale(), $parentRequest->getDefaultLocale());
}
public static function getSubscribedEvents()
{
return [
// must be registered after the Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 15]],
KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', -15]],
];
}
private function setLocale(string $locale, string $defaultLocale): void
{
foreach ($this->localeAwareServices as $service) {
try {
$service->setLocale($locale);
} catch (\InvalidArgumentException $e) {
$service->setLocale($defaultLocale);
}
}
}
}

View File

@ -0,0 +1,95 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RequestContextAwareInterface;
/**
* Initializes the locale based on the current request.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class LocaleListener implements EventSubscriberInterface
{
private $router;
private $defaultLocale;
private $requestStack;
private $useAcceptLanguageHeader;
private $enabledLocales;
public function __construct(RequestStack $requestStack, string $defaultLocale = 'en', RequestContextAwareInterface $router = null, bool $useAcceptLanguageHeader = false, array $enabledLocales = [])
{
$this->defaultLocale = $defaultLocale;
$this->requestStack = $requestStack;
$this->router = $router;
$this->useAcceptLanguageHeader = $useAcceptLanguageHeader;
$this->enabledLocales = $enabledLocales;
}
public function setDefaultLocale(KernelEvent $event)
{
$event->getRequest()->setDefaultLocale($this->defaultLocale);
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$this->setLocale($request);
$this->setRouterContext($request);
}
public function onKernelFinishRequest(FinishRequestEvent $event)
{
if (null !== $parentRequest = $this->requestStack->getParentRequest()) {
$this->setRouterContext($parentRequest);
}
}
private function setLocale(Request $request)
{
if ($locale = $request->attributes->get('_locale')) {
$request->setLocale($locale);
} elseif ($this->useAcceptLanguageHeader && $this->enabledLocales && ($preferredLanguage = $request->getPreferredLanguage($this->enabledLocales))) {
$request->setLocale($preferredLanguage);
$request->attributes->set('_vary_by_language', true);
}
}
private function setRouterContext(Request $request)
{
if (null !== $this->router) {
$this->router->getContext()->setParameter('_locale', $request->getLocale());
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['setDefaultLocale', 100],
// must be registered after the Router to have access to the _locale
['onKernelRequest', 16],
],
KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]],
];
}
}

View File

@ -0,0 +1,136 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Profiler\Profile;
use Symfony\Component\HttpKernel\Profiler\Profiler;
/**
* ProfilerListener collects data for the current request by listening to the kernel events.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class ProfilerListener implements EventSubscriberInterface
{
protected $profiler;
protected $matcher;
protected $onlyException;
protected $onlyMainRequests;
protected $exception;
/** @var \SplObjectStorage<Request, Profile> */
protected $profiles;
protected $requestStack;
protected $collectParameter;
/** @var \SplObjectStorage<Request, Request|null> */
protected $parents;
/**
* @param bool $onlyException True if the profiler only collects data when an exception occurs, false otherwise
* @param bool $onlyMainRequests True if the profiler only collects data when the request is the main request, false otherwise
*/
public function __construct(Profiler $profiler, RequestStack $requestStack, RequestMatcherInterface $matcher = null, bool $onlyException = false, bool $onlyMainRequests = false, string $collectParameter = null)
{
$this->profiler = $profiler;
$this->matcher = $matcher;
$this->onlyException = $onlyException;
$this->onlyMainRequests = $onlyMainRequests;
$this->profiles = new \SplObjectStorage();
$this->parents = new \SplObjectStorage();
$this->requestStack = $requestStack;
$this->collectParameter = $collectParameter;
}
/**
* Handles the onKernelException event.
*/
public function onKernelException(ExceptionEvent $event)
{
if ($this->onlyMainRequests && !$event->isMainRequest()) {
return;
}
$this->exception = $event->getThrowable();
}
/**
* Handles the onKernelResponse event.
*/
public function onKernelResponse(ResponseEvent $event)
{
if ($this->onlyMainRequests && !$event->isMainRequest()) {
return;
}
if ($this->onlyException && null === $this->exception) {
return;
}
$request = $event->getRequest();
if (null !== $this->collectParameter && null !== $collectParameterValue = $request->get($this->collectParameter)) {
true === $collectParameterValue || filter_var($collectParameterValue, \FILTER_VALIDATE_BOOLEAN) ? $this->profiler->enable() : $this->profiler->disable();
}
$exception = $this->exception;
$this->exception = null;
if (null !== $this->matcher && !$this->matcher->matches($request)) {
return;
}
if (!$profile = $this->profiler->collect($request, $event->getResponse(), $exception)) {
return;
}
$this->profiles[$request] = $profile;
$this->parents[$request] = $this->requestStack->getParentRequest();
}
public function onKernelTerminate(TerminateEvent $event)
{
// attach children to parents
foreach ($this->profiles as $request) {
if (null !== $parentRequest = $this->parents[$request]) {
if (isset($this->profiles[$parentRequest])) {
$this->profiles[$parentRequest]->addChild($this->profiles[$request]);
}
}
}
// save profiles
foreach ($this->profiles as $request) {
$this->profiler->saveProfile($this->profiles[$request]);
}
$this->profiles = new \SplObjectStorage();
$this->parents = new \SplObjectStorage();
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', -100],
KernelEvents::EXCEPTION => ['onKernelException', 0],
KernelEvents::TERMINATE => ['onKernelTerminate', -1024],
];
}
}

View File

@ -0,0 +1,68 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* ResponseListener fixes the Response headers based on the Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class ResponseListener implements EventSubscriberInterface
{
private $charset;
private $addContentLanguageHeader;
public function __construct(string $charset, bool $addContentLanguageHeader = false)
{
$this->charset = $charset;
$this->addContentLanguageHeader = $addContentLanguageHeader;
}
/**
* Filters the Response.
*/
public function onKernelResponse(ResponseEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$response = $event->getResponse();
if (null === $response->getCharset()) {
$response->setCharset($this->charset);
}
if ($this->addContentLanguageHeader && !$response->isInformational() && !$response->isEmpty() && !$response->headers->has('Content-Language')) {
$response->headers->set('Content-Language', $event->getRequest()->getLocale());
}
if ($event->getRequest()->attributes->get('_vary_by_language')) {
$response->setVary('Accept-Language', false);
}
$response->prepare($event->getRequest());
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
}

View File

@ -0,0 +1,174 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\NoConfigurationException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RequestContextAwareInterface;
/**
* Initializes the context from the request and sets request attributes based on a matching route.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Yonel Ceruto <yonelceruto@gmail.com>
*
* @final
*/
class RouterListener implements EventSubscriberInterface
{
private $matcher;
private $context;
private $logger;
private $requestStack;
private $projectDir;
private $debug;
/**
* @param UrlMatcherInterface|RequestMatcherInterface $matcher The Url or Request matcher
* @param RequestContext|null $context The RequestContext (can be null when $matcher implements RequestContextAwareInterface)
*
* @throws \InvalidArgumentException
*/
public function __construct($matcher, RequestStack $requestStack, RequestContext $context = null, LoggerInterface $logger = null, string $projectDir = null, bool $debug = true)
{
if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
}
if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
}
$this->matcher = $matcher;
$this->context = $context ?? $matcher->getContext();
$this->requestStack = $requestStack;
$this->logger = $logger;
$this->projectDir = $projectDir;
$this->debug = $debug;
}
private function setCurrentRequest(Request $request = null)
{
if (null !== $request) {
try {
$this->context->fromRequest($request);
} catch (\UnexpectedValueException $e) {
throw new BadRequestHttpException($e->getMessage(), $e, $e->getCode());
}
}
}
/**
* After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator
* operates on the correct context again.
*/
public function onKernelFinishRequest(FinishRequestEvent $event)
{
$this->setCurrentRequest($this->requestStack->getParentRequest());
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$this->setCurrentRequest($request);
if ($request->attributes->has('_controller')) {
// routing is already done
return;
}
// add attributes based on the request (routing)
try {
// matching a request is more powerful than matching a URL path + context, so try that first
if ($this->matcher instanceof RequestMatcherInterface) {
$parameters = $this->matcher->matchRequest($request);
} else {
$parameters = $this->matcher->match($request->getPathInfo());
}
if (null !== $this->logger) {
$this->logger->info('Matched route "{route}".', [
'route' => $parameters['_route'] ?? 'n/a',
'route_parameters' => $parameters,
'request_uri' => $request->getUri(),
'method' => $request->getMethod(),
]);
}
$request->attributes->add($parameters);
unset($parameters['_route'], $parameters['_controller']);
$request->attributes->set('_route_params', $parameters);
} catch (ResourceNotFoundException $e) {
$message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getUriForPath($request->getPathInfo()));
if ($referer = $request->headers->get('referer')) {
$message .= sprintf(' (from "%s")', $referer);
}
throw new NotFoundHttpException($message, $e);
} catch (MethodNotAllowedException $e) {
$message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getUriForPath($request->getPathInfo()), implode(', ', $e->getAllowedMethods()));
throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
}
}
public function onKernelException(ExceptionEvent $event)
{
if (!$this->debug || !($e = $event->getThrowable()) instanceof NotFoundHttpException) {
return;
}
if ($e->getPrevious() instanceof NoConfigurationException) {
$event->setResponse($this->createWelcomeResponse());
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 32]],
KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]],
KernelEvents::EXCEPTION => ['onKernelException', -64],
];
}
private function createWelcomeResponse(): Response
{
$version = Kernel::VERSION;
$projectDir = realpath((string) $this->projectDir).\DIRECTORY_SEPARATOR;
$docVersion = substr(Kernel::VERSION, 0, 3);
ob_start();
include \dirname(__DIR__).'/Resources/welcome.html.php';
return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND);
}
}

View File

@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpKernel\Event\RequestEvent;
/**
* Sets the session in the request.
*
* When the passed container contains a "session_storage" entry which
* holds a NativeSessionStorage instance, the "cookie_secure" option
* will be set to true whenever the current main request is secure.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class SessionListener extends AbstractSessionListener
{
public function onKernelRequest(RequestEvent $event)
{
parent::onKernelRequest($event);
if (!$event->isMainRequest() || (!$this->container->has('session') && !$this->container->has('session_factory'))) {
return;
}
if ($this->container->has('session_storage')
&& ($storage = $this->container->get('session_storage')) instanceof NativeSessionStorage
&& ($mainRequest = $this->container->get('request_stack')->getMainRequest())
&& $mainRequest->isSecure()
) {
$storage->setOptions(['cookie_secure' => true]);
}
}
protected function getSession(): ?SessionInterface
{
if ($this->container->has('session')) {
return $this->container->get('session');
}
if ($this->container->has('session_factory')) {
return $this->container->get('session_factory')->createSession();
}
return null;
}
}

View File

@ -0,0 +1,51 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* StreamedResponseListener is responsible for sending the Response
* to the client.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class StreamedResponseListener implements EventSubscriberInterface
{
/**
* Filters the Response.
*/
public function onKernelResponse(ResponseEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$response = $event->getResponse();
if ($response instanceof StreamedResponse) {
$response->send();
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', -1024],
];
}
}

View File

@ -0,0 +1,67 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\SurrogateInterface;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* SurrogateListener adds a Surrogate-Control HTTP header when the Response needs to be parsed for Surrogates.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class SurrogateListener implements EventSubscriberInterface
{
private $surrogate;
public function __construct(SurrogateInterface $surrogate = null)
{
$this->surrogate = $surrogate;
}
/**
* Filters the Response.
*/
public function onKernelResponse(ResponseEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$kernel = $event->getKernel();
$surrogate = $this->surrogate;
if ($kernel instanceof HttpCache) {
$surrogate = $kernel->getSurrogate();
if (null !== $this->surrogate && $this->surrogate->getName() !== $surrogate->getName()) {
$surrogate = $this->surrogate;
}
}
if (null === $surrogate) {
return;
}
$surrogate->addSurrogateControl($event->getResponse());
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
}

View File

@ -0,0 +1,46 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
trigger_deprecation('symfony/http-kernel', '5.4', '"%s" is deprecated, use "%s" instead.', TestSessionListener::class, SessionListener::class);
/**
* Sets the session in the request.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*
* @deprecated since Symfony 5.4, use SessionListener instead
*/
class TestSessionListener extends AbstractTestSessionListener
{
private $container;
public function __construct(ContainerInterface $container, array $sessionOptions = [])
{
$this->container = $container;
parent::__construct($sessionOptions);
}
protected function getSession(): ?SessionInterface
{
if ($this->container->has('session')) {
return $this->container->get('session');
}
return null;
}
}

View File

@ -0,0 +1,55 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Validates Requests.
*
* @author Magnus Nordlander <magnus@fervo.se>
*
* @final
*/
class ValidateRequestListener implements EventSubscriberInterface
{
/**
* Performs the validation.
*/
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if ($request::getTrustedProxies()) {
$request->getClientIps();
}
$request->getHost();
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onKernelRequest', 256],
],
];
}
}

View File

@ -0,0 +1,35 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Fabien Potencier <fabien@symfony.com>
* @author Christophe Coevoet <stof@notk.org>
*/
class AccessDeniedHttpException extends HttpException
{
/**
* @param string|null $message The internal exception message
* @param \Throwable|null $previous The previous exception
* @param int $code The internal exception code
*/
public function __construct(?string $message = '', \Throwable $previous = null, int $code = 0, array $headers = [])
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
parent::__construct(403, $message, $previous, $headers, $code);
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Ben Ramsey <ben@benramsey.com>
*/
class BadRequestHttpException extends HttpException
{
/**
* @param string|null $message The internal exception message
* @param \Throwable|null $previous The previous exception
* @param int $code The internal exception code
*/
public function __construct(?string $message = '', \Throwable $previous = null, int $code = 0, array $headers = [])
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
parent::__construct(400, $message, $previous, $headers, $code);
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Ben Ramsey <ben@benramsey.com>
*/
class ConflictHttpException extends HttpException
{
/**
* @param string|null $message The internal exception message
* @param \Throwable|null $previous The previous exception
* @param int $code The internal exception code
*/
public function __construct(?string $message = '', \Throwable $previous = null, int $code = 0, array $headers = [])
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
parent::__construct(409, $message, $previous, $headers, $code);
}
}

View File

@ -0,0 +1,84 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class ControllerDoesNotReturnResponseException extends \LogicException
{
public function __construct(string $message, callable $controller, string $file, int $line)
{
parent::__construct($message);
if (!$controllerDefinition = $this->parseControllerDefinition($controller)) {
return;
}
$this->file = $controllerDefinition['file'];
$this->line = $controllerDefinition['line'];
$r = new \ReflectionProperty(\Exception::class, 'trace');
$r->setAccessible(true);
$r->setValue($this, array_merge([
[
'line' => $line,
'file' => $file,
],
], $this->getTrace()));
}
private function parseControllerDefinition(callable $controller): ?array
{
if (\is_string($controller) && str_contains($controller, '::')) {
$controller = explode('::', $controller);
}
if (\is_array($controller)) {
try {
$r = new \ReflectionMethod($controller[0], $controller[1]);
return [
'file' => $r->getFileName(),
'line' => $r->getEndLine(),
];
} catch (\ReflectionException $e) {
return null;
}
}
if ($controller instanceof \Closure) {
$r = new \ReflectionFunction($controller);
return [
'file' => $r->getFileName(),
'line' => $r->getEndLine(),
];
}
if (\is_object($controller)) {
$r = new \ReflectionClass($controller);
try {
$line = $r->getMethod('__invoke')->getEndLine();
} catch (\ReflectionException $e) {
$line = $r->getEndLine();
}
return [
'file' => $r->getFileName(),
'line' => $line,
];
}
return null;
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Ben Ramsey <ben@benramsey.com>
*/
class GoneHttpException extends HttpException
{
/**
* @param string|null $message The internal exception message
* @param \Throwable|null $previous The previous exception
* @param int $code The internal exception code
*/
public function __construct(?string $message = '', \Throwable $previous = null, int $code = 0, array $headers = [])
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
parent::__construct(410, $message, $previous, $headers, $code);
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* HttpException.
*
* @author Kris Wallsmith <kris@symfony.com>
*/
class HttpException extends \RuntimeException implements HttpExceptionInterface
{
private $statusCode;
private $headers;
public function __construct(int $statusCode, ?string $message = '', \Throwable $previous = null, array $headers = [], ?int $code = 0)
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
if (null === $code) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $code to "%s()" is deprecated, pass 0 instead.', __METHOD__);
$code = 0;
}
$this->statusCode = $statusCode;
$this->headers = $headers;
parent::__construct($message, $code, $previous);
}
public function getStatusCode()
{
return $this->statusCode;
}
public function getHeaders()
{
return $this->headers;
}
/**
* Set response headers.
*
* @param array $headers Response headers
*/
public function setHeaders(array $headers)
{
$this->headers = $headers;
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* Interface for HTTP error exceptions.
*
* @author Kris Wallsmith <kris@symfony.com>
*/
interface HttpExceptionInterface extends \Throwable
{
/**
* Returns the status code.
*
* @return int
*/
public function getStatusCode();
/**
* Returns response headers.
*
* @return array
*/
public function getHeaders();
}

View File

@ -0,0 +1,16 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
class InvalidMetadataException extends \LogicException
{
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Ben Ramsey <ben@benramsey.com>
*/
class LengthRequiredHttpException extends HttpException
{
/**
* @param string|null $message The internal exception message
* @param \Throwable|null $previous The previous exception
* @param int $code The internal exception code
*/
public function __construct(?string $message = '', \Throwable $previous = null, int $code = 0, array $headers = [])
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
parent::__construct(411, $message, $previous, $headers, $code);
}
}

View File

@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Kris Wallsmith <kris@symfony.com>
*/
class MethodNotAllowedHttpException extends HttpException
{
/**
* @param string[] $allow An array of allowed methods
* @param string|null $message The internal exception message
* @param \Throwable|null $previous The previous exception
* @param int|null $code The internal exception code
*/
public function __construct(array $allow, ?string $message = '', \Throwable $previous = null, ?int $code = 0, array $headers = [])
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
if (null === $code) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $code to "%s()" is deprecated, pass 0 instead.', __METHOD__);
$code = 0;
}
$headers['Allow'] = strtoupper(implode(', ', $allow));
parent::__construct(405, $message, $previous, $headers, $code);
}
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* @author Ben Ramsey <ben@benramsey.com>
*/
class NotAcceptableHttpException extends HttpException
{
/**
* @param string|null $message The internal exception message
* @param \Throwable|null $previous The previous exception
* @param int $code The internal exception code
*/
public function __construct(?string $message = '', \Throwable $previous = null, int $code = 0, array $headers = [])
{
if (null === $message) {
trigger_deprecation('symfony/http-kernel', '5.3', 'Passing null as $message to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
$message = '';
}
parent::__construct(406, $message, $previous, $headers, $code);
}
}

Some files were not shown because too many files have changed in this diff Show More