commit 7897adbfeba38e7404b13efe1745bb3fbb8217b2 Author: Fabien Potencier Date: Thu Jun 12 09:04:27 2014 +0200 - diff --git a/core/authorize.php b/core/authorize.php index f938f39..1c5a9f8 100644 --- a/core/authorize.php +++ b/core/authorize.php @@ -47,7 +47,7 @@ * TRUE if the current user can run authorize.php, and FALSE if not. */ function authorize_access_allowed() { - \Drupal::service('session_manager')->initialize(); + \Drupal::service('session_manager')->startLazy(); return Settings::get('allow_authorize_operations', TRUE) && user_access('administer software updates'); } diff --git a/core/core.services.yml b/core/core.services.yml index 9466f95..b726e0a 100644 --- a/core/core.services.yml +++ b/core/core.services.yml @@ -267,10 +267,6 @@ services: arguments: ['@controller_resolver', '@module_handler', '@cache.discovery', '@language_manager', '@access_manager', '@current_user', '@request_stack'] plugin.cache_clearer: class: Drupal\Core\Plugin\CachedDiscoveryClearer - request: - class: Symfony\Component\HttpFoundation\Request - synthetic: true - synchronized: true request_stack: class: Symfony\Component\HttpFoundation\RequestStack tags: @@ -289,9 +285,8 @@ services: class: Drupal\Core\Controller\TitleResolver arguments: ['@controller_resolver', '@string_translation'] http_kernel: - class: Drupal\Core\HttpKernel + class: Symfony\Component\HttpKernel\HttpKernel arguments: ['@event_dispatcher', '@controller_resolver', '@request_stack'] - parent: container.trait language_manager: class: Drupal\Core\Language\LanguageManager arguments: ['@language.default'] @@ -356,9 +351,8 @@ services: - { name: service_collector, tag: route_filter, call: addRouteFilter } url_generator: class: Drupal\Core\Routing\UrlGenerator - arguments: ['@router.route_provider', '@path_processor_manager', '@route_processor_manager', '@config.factory', '@settings', '@logger.channel.default'] + arguments: ['@router.route_provider', '@path_processor_manager', '@route_processor_manager', '@config.factory', '@settings', '@logger.channel.default', '@request_stack'] calls: - - [setRequest, ['@?request']] - [setContext, ['@?router.request_context']] link_generator: class: Drupal\Core\Utility\LinkGenerator @@ -548,10 +542,9 @@ services: class: Drupal\Core\Access\AccessArgumentsResolver access_manager: class: Drupal\Core\Access\AccessManager - arguments: ['@router.route_provider', '@url_generator', '@paramconverter_manager', '@access_arguments_resolver'] + arguments: ['@router.route_provider', '@url_generator', '@paramconverter_manager', '@access_arguments_resolver', '@request_stack'] calls: - [setContainer, ['@service_container']] - - [setRequest, ['@?request']] access_subscriber: class: Drupal\Core\EventSubscriber\AccessSubscriber arguments: ['@access_manager', '@current_user'] @@ -610,13 +603,11 @@ services: tags: - { name: event_subscriber } arguments: ['@language_manager', '@config.factory'] - scope: request redirect_response_subscriber: class: Drupal\Core\EventSubscriber\RedirectResponseSubscriber arguments: ['@url_generator'] tags: - { name: event_subscriber } - scope: request request_close_subscriber: class: Drupal\Core\EventSubscriber\RequestCloseSubscriber tags: @@ -787,12 +778,10 @@ services: arguments: ['@authentication'] current_user: class: Drupal\Core\Session\AccountProxy - arguments: ['@authentication', '@request'] + arguments: ['@authentication', '@request_stack'] session_manager: class: Drupal\Core\Session\SessionManager arguments: ['@request_stack', '@database', '@session_manager.metadata_bag', '@settings'] - tags: - - { name: persist } session_manager.metadata_bag: class: Drupal\Core\Session\MetadataBag arguments: ['@settings'] diff --git a/core/includes/bootstrap.inc b/core/includes/bootstrap.inc index a9ea984..b05c890 100644 --- a/core/includes/bootstrap.inc +++ b/core/includes/bootstrap.inc @@ -1367,7 +1367,6 @@ function drupal_handle_request($test_only = FALSE) { // Create a request object from the HttpFoundation. $request = Request::createFromGlobals(); $container = \Drupal::getContainer(); - $container->set('request', $request); $container->get('request_stack')->push($request); drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE); @@ -1516,7 +1515,6 @@ function _drupal_bootstrap_kernel() { $kernel->boot(); $request = Request::createFromGlobals(); $container = \Drupal::getContainer(); - $container->set('request', $request); $container->get('request_stack')->push($request); } } diff --git a/core/includes/common.inc b/core/includes/common.inc index 3f0fd1d..2ccd31b 100644 --- a/core/includes/common.inc +++ b/core/includes/common.inc @@ -1758,7 +1758,7 @@ function _drupal_add_js($data = NULL, $options = NULL) { // @todo Make this less hacky: http://drupal.org/node/1547376. $scriptPath = $GLOBALS['script_path']; $pathPrefix = ''; - $current_query = \Drupal::service('request')->query->all(); + $current_query = \Drupal::service('request_stack')->getCurrentRequest()->query->all(); url('', array('script' => &$scriptPath, 'prefix' => &$pathPrefix)); $current_path = current_path(); $current_path_is_admin = FALSE; diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc index f7550b1..4ff4122 100644 --- a/core/includes/install.core.inc +++ b/core/includes/install.core.inc @@ -365,8 +365,6 @@ function install_begin_request(&$install_state) { // Enter the request scope and add the Request. // @todo Remove this after converting all installer screens into controllers. $container = $kernel->getContainer(); - $container->enterScope('request'); - $container->set('request', $request, 'request'); $container->get('request_stack')->push($request); // Register the file translation service. @@ -1459,7 +1457,7 @@ function install_load_profile(&$install_state) { */ function install_bootstrap_full() { drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); - \Drupal::service('session_manager')->initialize(); + \Drupal::service('session_manager')->startLazy(); } /** diff --git a/core/includes/install.inc b/core/includes/install.inc index 67e41f6..def35ed 100644 --- a/core/includes/install.inc +++ b/core/includes/install.inc @@ -642,8 +642,6 @@ function drupal_install_system($install_state) { $kernel->boot(); if ($request) { - $kernel->getContainer()->enterScope('request'); - $kernel->getContainer()->set('request', $request, 'request'); $kernel->getContainer()->get('request_stack')->push($request); } diff --git a/core/includes/path.inc b/core/includes/path.inc index 02ab498..9b177c9 100644 --- a/core/includes/path.inc +++ b/core/includes/path.inc @@ -70,8 +70,8 @@ function current_path() { // @todo Remove the check for whether the request service exists and the // fallback code below, once the path alias logic has been figured out in // http://drupal.org/node/1269742. - if (\Drupal::getContainer()->isScopeActive('request')) { - $path = \Drupal::request()->attributes->get('_system_path'); + if ($request = \Drupal::request()) { + $path = $request->attributes->get('_system_path'); if ($path !== NULL) { return $path; } diff --git a/core/lib/Drupal.php b/core/lib/Drupal.php index 57cf2ef..c83d6db 100644 --- a/core/lib/Drupal.php +++ b/core/lib/Drupal.php @@ -158,7 +158,7 @@ public static function hasService($id) { * TRUE if there is a currently active request object, FALSE otherwise. */ public static function hasRequest() { - return static::$container && static::$container->has('request') && static::$container->initialized('request') && static::$container->isScopeActive('request'); + return static::$container && static::$container->has('request_stack') && static::$container->get('request_stack')->getMasterRequest() !== NULL; } /** @@ -184,7 +184,7 @@ public static function hasRequest() { * The currently active request object. */ public static function request() { - return static::$container->get('request'); + return static::$container->get('request_stack')->getCurrentRequest(); } /** diff --git a/core/lib/Drupal/Core/Access/AccessManager.php b/core/lib/Drupal/Core/Access/AccessManager.php index b40905f..21185c1 100644 --- a/core/lib/Drupal/Core/Access/AccessManager.php +++ b/core/lib/Drupal/Core/Access/AccessManager.php @@ -18,6 +18,7 @@ use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Cmf\Component\Routing\RouteObjectInterface; @@ -94,11 +95,11 @@ class AccessManager implements ContainerAwareInterface { protected $argumentsResolver; /** - * A request object. + * A request stack object. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * Constructs a AccessManager instance. @@ -111,25 +112,15 @@ class AccessManager implements ContainerAwareInterface { * The param converter manager. * @param \Drupal\Core\Access\AccessArgumentsResolverInterface $arguments_resolver * The access arguments resolver. + * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack + * The request stack object. */ - public function __construct(RouteProviderInterface $route_provider, UrlGeneratorInterface $url_generator, ParamConverterManagerInterface $paramconverter_manager, AccessArgumentsResolverInterface $arguments_resolver) { + public function __construct(RouteProviderInterface $route_provider, UrlGeneratorInterface $url_generator, ParamConverterManagerInterface $paramconverter_manager, AccessArgumentsResolverInterface $arguments_resolver, RequestStack $requestStack) { $this->routeProvider = $route_provider; $this->urlGenerator = $url_generator; $this->paramConverterManager = $paramconverter_manager; $this->argumentsResolver = $arguments_resolver; - } - - /** - * Sets the request object to use. - * - * This is used by the RouterListener to make additional request attributes - * available. - * - * @param \Symfony\Component\HttpFoundation\Request $request - * The request object. - */ - public function setRequest(Request $request) { - $this->request = $request; + $this->requestStack = $requestStack; } /** @@ -222,7 +213,7 @@ public function checkNamedRoute($route_name, array $parameters = array(), Accoun if (empty($route_request)) { // Create a request and copy the account from the current request. $defaults = $parameters + $route->getDefaults(); - $route_request = RequestHelper::duplicate($this->request, $this->urlGenerator->generate($route_name, $defaults)); + $route_request = RequestHelper::duplicate($this->requestStack->getCurrentRequest(), $this->urlGenerator->generate($route_name, $defaults)); $defaults[RouteObjectInterface::ROUTE_OBJECT] = $route; $route_request->attributes->add($this->paramConverterManager->convert($defaults, $route_request)); } diff --git a/core/lib/Drupal/Core/Authentication/AuthenticationProviderInterface.php b/core/lib/Drupal/Core/Authentication/AuthenticationProviderInterface.php index 374de78..bc8e10c 100644 --- a/core/lib/Drupal/Core/Authentication/AuthenticationProviderInterface.php +++ b/core/lib/Drupal/Core/Authentication/AuthenticationProviderInterface.php @@ -29,7 +29,7 @@ public function applies(Request $request); /** * Authenticates the user. * - * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Symfony\Component\HttpFoundation\Request|null $request * The request object. * * @return \Drupal\Core\Session\AccountInterface|null diff --git a/core/lib/Drupal/Core/Authentication/Provider/Cookie.php b/core/lib/Drupal/Core/Authentication/Provider/Cookie.php index 167a0b0..c5f23c8 100644 --- a/core/lib/Drupal/Core/Authentication/Provider/Cookie.php +++ b/core/lib/Drupal/Core/Authentication/Provider/Cookie.php @@ -47,7 +47,8 @@ public function applies(Request $request) { public function authenticate(Request $request) { // Global $user is deprecated, but the session system is still based on it. global $user; - if ($this->sessionManager->initialize()->isStarted()) { + $this->sessionManager->startLazy(); + if ($this->sessionManager->isStarted()) { return $user; } return NULL; diff --git a/core/lib/Drupal/Core/CoreServiceProvider.php b/core/lib/Drupal/Core/CoreServiceProvider.php index c72cafc..02a5625 100644 --- a/core/lib/Drupal/Core/CoreServiceProvider.php +++ b/core/lib/Drupal/Core/CoreServiceProvider.php @@ -22,7 +22,6 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\DependencyInjection\Compiler\PassConfig; /** @@ -41,10 +40,6 @@ class CoreServiceProvider implements ServiceProviderInterface { * {@inheritdoc} */ public function register(ContainerBuilder $container) { - // The 'request' scope and service enable services to depend on the Request - // object and get reconstructed when the request object changes (e.g., - // during a subrequest). - $container->addScope(new Scope('request')); $this->registerTwig($container); $this->registerUuid($container); $this->registerTest($container); diff --git a/core/lib/Drupal/Core/DependencyInjection/ContainerBuilder.php b/core/lib/Drupal/Core/DependencyInjection/ContainerBuilder.php index 56f1627..4c32cd8 100644 --- a/core/lib/Drupal/Core/DependencyInjection/ContainerBuilder.php +++ b/core/lib/Drupal/Core/DependencyInjection/ContainerBuilder.php @@ -10,6 +10,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder as SymfonyContainerBuilder; use Symfony\Component\DependencyInjection\Container as SymfonyContainer; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; /** * Drupal's dependency injection container builder. @@ -18,14 +19,11 @@ */ class ContainerBuilder extends SymfonyContainerBuilder { - /** - * Overrides Symfony\Component\DependencyInjection\ContainerBuilder::addObjectResource(). - * - * Drupal does not use Symfony's Config component, so we override - * addObjectResource() with an empty implementation to prevent errors during - * container compilation. - */ - public function addObjectResource($object) { + public function __construct(ParameterBagInterface $parameterBag = null) + { + $this->setResourceTracking(false); + + parent::__construct($parameterBag); } /** @@ -54,52 +52,6 @@ public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE */ public function set($id, $service, $scope = self::SCOPE_CONTAINER) { SymfonyContainer::set($id, $service, $scope); - - if ($this->hasDefinition($id) && ($definition = $this->getDefinition($id)) && $definition->isSynchronized()) { - $this->synchronize($id); - } - } - - /** - * Synchronizes a service change. - * - * This method is a copy of the ContainerBuilder of symfony. - * - * This method updates all services that depend on the given - * service by calling all methods referencing it. - * - * @param string $id A service id - */ - private function synchronize($id) { - foreach ($this->getDefinitions() as $definitionId => $definition) { - // only check initialized services - if (!$this->initialized($definitionId)) { - continue; - } - - foreach ($definition->getMethodCalls() as $call) { - foreach ($call[1] as $argument) { - if ($argument instanceof Reference && $id == (string) $argument) { - $this->callMethod($this->get($definitionId), $call); - } - } - } - } - } - - /** - * A 1to1 copy of parent::callMethod. - */ - protected function callMethod($service, $call) { - $services = self::getServiceConditionals($call[1]); - - foreach ($services as $s) { - if (!$this->has($s)) { - return; - } - } - - call_user_func_array(array($service, $call[0]), $this->resolveServices($this->getParameterBag()->resolveValue($call[1]))); } /** diff --git a/core/lib/Drupal/Core/DrupalKernel.php b/core/lib/Drupal/Core/DrupalKernel.php index d3b7b1b..ff7970c 100644 --- a/core/lib/Drupal/Core/DrupalKernel.php +++ b/core/lib/Drupal/Core/DrupalKernel.php @@ -390,17 +390,22 @@ protected function getKernelParameters() { protected function initializeContainer() { $this->containerNeedsDumping = FALSE; $persist = $this->getServicesToPersist(); - // The request service requires custom persisting logic, since it is also - // potentially scoped. - $request_scope = FALSE; + $session_manager_state = 0; if (isset($this->container)) { - if ($this->container->isScopeActive('request')) { - $request_scope = TRUE; - } - if ($this->container->initialized('request')) { - $request = $this->container->get('request'); + // If there is a session manager, close and save the session. + if ($this->container->initialized('session_manager')) { + $session_manager = $this->container->get('session_manager'); + if ($session_manager->isStartedLazy()) { + $session_manager_state |= 0x1; + } + if ($session_manager->isStarted()) { + $session_manager_state |= 0x2; + } + $session_manager->save(); + unset($session_manager); } } + $this->container = NULL; $class = $this->getClassName(); $cache_file = $class . '.php'; @@ -442,12 +447,11 @@ protected function initializeContainer() { // Set the class loader which was registered as a synthetic service. $this->container->set('class_loader', $this->classLoader); - // If we have a request set it back to the new container. - if ($request_scope) { - $this->container->enterScope('request'); + if ($session_manager_state & 0x1) { + $this->container->get('session_manager')->startLazy(); } - if (isset($request)) { - $this->container->set('request', $request); + if ($session_manager_state & 0x2) { + $this->container->get('session_manager')->start(); } \Drupal::setContainer($this->container); } diff --git a/core/lib/Drupal/Core/Entity/ContentEntityDatabaseStorage.php b/core/lib/Drupal/Core/Entity/ContentEntityDatabaseStorage.php index b51272c..d61b170 100644 --- a/core/lib/Drupal/Core/Entity/ContentEntityDatabaseStorage.php +++ b/core/lib/Drupal/Core/Entity/ContentEntityDatabaseStorage.php @@ -40,13 +40,6 @@ class ContentEntityDatabaseStorage extends ContentEntityStorageBase implements SqlEntityStorageInterface { /** - * The storage field definitions for this entity type. - * - * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[] - */ - protected $fieldStorageDefinitions; - - /** * The mapping of field columns to SQL tables. * * @var \Drupal\Core\Entity\Sql\TableMappingInterface @@ -130,6 +123,17 @@ public static function createInstance(ContainerInterface $container, EntityTypeI } /** + * Gets the base field definitions for a content entity type. + * + * @return \Drupal\Core\Field\FieldDefinitionInterface[] + * The array of base field definitions for the entity type, keyed by field + * name. + */ + public function getFieldStorageDefinitions() { + return $this->entityManager->getBaseFieldDefinitions($this->entityTypeId); + } + + /** * Constructs a ContentEntityDatabaseStorage object. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type @@ -144,7 +148,6 @@ public function __construct(EntityTypeInterface $entity_type, Connection $databa $this->database = $database; $this->entityManager = $entity_manager; - $this->fieldStorageDefinitions = $entity_manager->getBaseFieldDefinitions($entity_type->id()); // @todo Remove table names from the entity type definition in // https://drupal.org/node/2232465 @@ -236,7 +239,7 @@ protected function schemaHandler() { public function getTableMapping() { if (!isset($this->tableMapping)) { - $definitions = array_filter($this->fieldStorageDefinitions, function (FieldDefinitionInterface $definition) { + $definitions = array_filter($this->getFieldStorageDefinitions(), function (FieldDefinitionInterface $definition) { // @todo Remove the check for FieldDefinitionInterface::isMultiple() when // multiple-value base fields are supported in // https://drupal.org/node/2248977. @@ -834,10 +837,10 @@ protected function mapToStorageRecord(ContentEntityInterface $entity, $table_nam $table_mapping = $this->getTableMapping(); foreach ($table_mapping->getFieldNames($table_name) as $field_name) { - if (empty($this->fieldStorageDefinitions[$field_name])) { + if (empty($this->getFieldStorageDefinitions()[$field_name])) { throw new EntityStorageException(String::format('Table mapping contains invalid field %field.', array('%field' => $field_name))); } - $definition = $this->fieldStorageDefinitions[$field_name]; + $definition = $this->getFieldStorageDefinitions()[$field_name]; $columns = $table_mapping->getColumnNames($field_name); foreach ($columns as $column_name => $schema_name) { diff --git a/core/lib/Drupal/Core/Form/FormBase.php b/core/lib/Drupal/Core/Form/FormBase.php index 5dedf6c..94cfdb4 100644 --- a/core/lib/Drupal/Core/Form/FormBase.php +++ b/core/lib/Drupal/Core/Form/FormBase.php @@ -144,7 +144,7 @@ public function resetConfigFactory() { */ protected function getRequest() { if (!$this->request) { - $this->request = $this->container()->get('request'); + $this->request = \Drupal::request(); } return $this->request; } diff --git a/core/lib/Drupal/Core/Form/FormBuilder.php b/core/lib/Drupal/Core/Form/FormBuilder.php index d3bedc1..32a21af 100644 --- a/core/lib/Drupal/Core/Form/FormBuilder.php +++ b/core/lib/Drupal/Core/Form/FormBuilder.php @@ -13,7 +13,6 @@ use Drupal\Core\Access\CsrfTokenGenerator; use Drupal\Core\DependencyInjection\ClassResolverInterface; use Drupal\Core\Extension\ModuleHandlerInterface; -use Drupal\Core\HttpKernel; use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface; use Drupal\Core\Render\Element; use Drupal\Core\Site\Settings; @@ -21,6 +20,7 @@ use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; +use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; @@ -67,7 +67,7 @@ class FormBuilder implements FormBuilderInterface, FormValidatorInterface, FormS /** * The HTTP kernel to handle forms returning response objects. * - * @var \Drupal\Core\HttpKernel + * @var \Symfony\Component\HttpKernel\HttpKernel */ protected $httpKernel; diff --git a/core/lib/Drupal/Core/HttpKernel.php b/core/lib/Drupal/Core/HttpKernel.php deleted file mode 100644 index dba6032..0000000 --- a/core/lib/Drupal/Core/HttpKernel.php +++ /dev/null @@ -1,263 +0,0 @@ - - * @author Johannes M. Schmitt - */ -class HttpKernel extends BaseHttpKernel implements ContainerAwareInterface { - - use ContainerAwareTrait; - - private $esiSupport; - - public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) - { - $request->headers->set('X-Php-Ob-Level', ob_get_level()); - - $this->container->enterScope('request'); - $this->container->set('request', $request, 'request'); - - try { - $response = parent::handle($request, $type, $catch); - } catch (\Exception $e) { - $this->container->leaveScope('request'); - - throw $e; - } - - $this->container->leaveScope('request'); - - return $response; - } - - /** - * Forwards the request to another controller. - * - * @param string|null $controller - * The controller name (a string like BlogBundle:Post:index). - * @param array $attributes - * An array of request attributes. - * @param array $query - * An array of request query parameters. - * - * @return Response - * A Response instance - */ - public function forward($controller, array $attributes = array(), array $query = array()) - { - $subrequest = $this->setupSubrequest($controller, $attributes, $query); - - return $this->handle($subrequest, HttpKernelInterface::SUB_REQUEST); - } - - /** - * Renders a Controller and returns the Response content. - * - * Note that this method generates an esi:include tag only when both the standalone - * option is set to true and the request has ESI capability (@see Symfony\Component\HttpKernel\HttpCache\ESI). - * - * Available options: - * - * * attributes: An array of request attributes (only when the first argument is a controller) - * * query: An array of request query parameters (only when the first argument is a controller) - * * ignore_errors: true to return an empty string in case of an error - * * alt: an alternative controller to execute in case of an error (can be a controller, a URI, or an array with the controller, the attributes, and the query arguments) - * * standalone: whether to generate an esi:include tag or not when ESI is supported - * * comment: a comment to add when returning an esi:include tag - * - * @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI - * @param array $options An array of options - * - * @return string The Response content - */ - public function render($controller, array $options = array()) - { - $options = array_merge(array( - 'attributes' => array(), - 'query' => array(), - 'ignore_errors' => !$this->container->getParameter('kernel.debug'), - 'alt' => array(), - 'standalone' => false, - 'comment' => '', - ), $options); - - if (!is_array($options['alt'])) { - $options['alt'] = array($options['alt']); - } - - if (null === $this->esiSupport) { - $this->esiSupport = $this->container->has('esi') && $this->container->get('esi')->hasSurrogateEsiCapability($this->container->get('request')); - } - - if ($this->esiSupport && (true === $options['standalone'] || 'esi' === $options['standalone'])) { - $uri = $this->generateInternalUri($controller, $options['attributes'], $options['query']); - - $alt = ''; - if ($options['alt']) { - $alt = $this->generateInternalUri($options['alt'][0], isset($options['alt'][1]) ? $options['alt'][1] : array(), isset($options['alt'][2]) ? $options['alt'][2] : array()); - } - - return $this->container->get('esi')->renderIncludeTag($uri, $alt, $options['ignore_errors'], $options['comment']); - } - - if ('js' === $options['standalone']) { - $uri = $this->generateInternalUri($controller, $options['attributes'], $options['query'], false); - $defaultContent = null; - - if ($template = $this->container->getParameter('templating.hinclude.default_template')) { - $defaultContent = $this->container->get('templating')->render($template); - } - - return $this->renderHIncludeTag($uri, $defaultContent); - } - - $request = $this->container->get('request'); - - // controller or URI? - if (0 === strpos($controller, '/')) { - $subRequest = Request::create($request->getUriForPath($controller), 'get', array(), $request->cookies->all(), array(), $request->server->all()); - if ($session = $request->getSession()) { - $subRequest->setSession($session); - } - } else { - $options['attributes']['_controller'] = $controller; - - if (!isset($options['attributes']['_format'])) { - $options['attributes']['_format'] = $request->getRequestFormat(); - } - - $options['attributes'][RouteObjectInterface::ROUTE_OBJECT] = '_internal'; - $subRequest = $request->duplicate($options['query'], null, $options['attributes']); - $subRequest->setMethod('GET'); - } - - $level = ob_get_level(); - try { - $response = $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false); - - if (!$response->isSuccessful()) { - throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $request->getUri(), $response->getStatusCode())); - } - - if (!$response instanceof StreamedResponse) { - return $response->getContent(); - } - - $response->sendContent(); - } catch (\Exception $e) { - if ($options['alt']) { - $alt = $options['alt']; - unset($options['alt']); - $options['attributes'] = isset($alt[1]) ? $alt[1] : array(); - $options['query'] = isset($alt[2]) ? $alt[2] : array(); - - return $this->render($alt[0], $options); - } - - if (!$options['ignore_errors']) { - throw $e; - } - - // let's clean up the output buffers that were created by the sub-request - while (ob_get_level() > $level) { - ob_get_clean(); - } - } - } - - /** - * Generates an internal URI for a given controller. - * - * This method uses the "_internal" route, which should be available. - * - * @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI - * @param array $attributes An array of request attributes - * @param array $query An array of request query parameters - * @param boolean $secure - * - * @return string An internal URI - */ - public function generateInternalUri($controller, array $attributes = array(), array $query = array(), $secure = true) - { - if (0 === strpos($controller, '/')) { - return $controller; - } - - $path = http_build_query($attributes, '', '&'); - $uri = $this->container->get('router')->generate($secure ? '_internal' : '_internal_public', array( - 'controller' => $controller, - 'path' => $path ?: 'none', - '_format' => $this->container->get('request')->getRequestFormat(), - )); - - if ($queryString = http_build_query($query, '', '&')) { - $uri .= '?'.$queryString; - } - - return $uri; - } - - /** - * Renders an HInclude tag. - * - * @param string $uri A URI - * @param string $defaultContent Default content - */ - public function renderHIncludeTag($uri, $defaultContent = null) - { - return sprintf('%s', $uri, $defaultContent); - } - - public function hasEsiSupport() - { - return $this->esiSupport; - } - - /** - * Creates a request object for a subrequest. - * - * @param string $controller - * The controller name (a string like BlogBundle:Post:index) - * @param array $attributes - * An array of request attributes. - * @param array $query - * An array of request query parameters. - * - * @return \Symfony\Component\HttpFoundation\Request - * Returns the new request. - */ - public function setupSubrequest($controller, array $attributes, array $query) { - // Don't override the controller if it's NULL. - if (isset($controller)) { - $attributes['_controller'] = $controller; - } - else { - unset($attributes['_controller']); - } - return $this->container->get('request')->duplicate($query, NULL, $attributes); - } - -} diff --git a/core/lib/Drupal/Core/Logger/LoggerChannel.php b/core/lib/Drupal/Core/Logger/LoggerChannel.php index 074cd23..9f16a61 100644 --- a/core/lib/Drupal/Core/Logger/LoggerChannel.php +++ b/core/lib/Drupal/Core/Logger/LoggerChannel.php @@ -11,7 +11,7 @@ use Psr\Log\LoggerInterface; use Psr\Log\LoggerTrait; use Psr\Log\LogLevel; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * Defines a logger channel that most implementations will use. @@ -52,11 +52,11 @@ class LoggerChannel implements LoggerChannelInterface { protected $loggers = array(); /** - * The request object. + * The request stack object. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * The current user object. @@ -95,10 +95,10 @@ public function log($level, $message, array $context = array()) { $context['uid'] = $this->currentUser->id(); } // Some context values are only available when in a request context. - if ($this->request) { - $context['request_uri'] = $this->request->getUri(); - $context['referer'] = $this->request->headers->get('Referer', ''); - $context['ip'] = $this->request->getClientIP(); + if ($this->requestStack && $request = $this->requestStack->getCurrentRequest()) { + $context['request_uri'] = $request->getUri(); + $context['referer'] = $request->headers->get('Referer', ''); + $context['ip'] = $request->getClientIP(); } if (is_string($level)) { @@ -114,8 +114,8 @@ public function log($level, $message, array $context = array()) { /** * {@inheritdoc} */ - public function setRequest(Request $request = NULL) { - $this->request = $request; + public function setRequestStack(RequestStack $requestStack = NULL) { + $this->requestStack = $requestStack; } /** diff --git a/core/lib/Drupal/Core/Logger/LoggerChannelFactory.php b/core/lib/Drupal/Core/Logger/LoggerChannelFactory.php index 1ec1710..328828e 100644 --- a/core/lib/Drupal/Core/Logger/LoggerChannelFactory.php +++ b/core/lib/Drupal/Core/Logger/LoggerChannelFactory.php @@ -43,7 +43,7 @@ public function get($channel) { // the current user to the channel. if ($this->container) { try { - $instance->setRequest($this->container->get('request')); + $instance->setRequestStack($this->container->get('request_stack')); $instance->setCurrentUser($this->container->get('current_user')); } catch (RuntimeException $e) { diff --git a/core/lib/Drupal/Core/Logger/LoggerChannelInterface.php b/core/lib/Drupal/Core/Logger/LoggerChannelInterface.php index 15d9741..20afd7e 100644 --- a/core/lib/Drupal/Core/Logger/LoggerChannelInterface.php +++ b/core/lib/Drupal/Core/Logger/LoggerChannelInterface.php @@ -9,7 +9,7 @@ use Drupal\Core\Session\AccountInterface; use Psr\Log\LoggerInterface; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * Logger channel interface. @@ -17,12 +17,12 @@ interface LoggerChannelInterface extends LoggerInterface { /** - * Sets the request. + * Sets the request stack. * - * @param \Symfony\Component\HttpFoundation\Request|null $request + * @param \Symfony\Component\HttpFoundation\RequestStack|null $requestStack * The current request object. */ - public function setRequest(Request $request = NULL); + public function setRequestStack(RequestStack $requestStack = NULL); /** * Sets the current user. diff --git a/core/lib/Drupal/Core/Routing/UrlGenerator.php b/core/lib/Drupal/Core/Routing/UrlGenerator.php index 7028101..6f5dd45 100644 --- a/core/lib/Drupal/Core/Routing/UrlGenerator.php +++ b/core/lib/Drupal/Core/Routing/UrlGenerator.php @@ -9,6 +9,7 @@ use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Route as SymfonyRoute; use Symfony\Component\Routing\Exception\RouteNotFoundException; @@ -27,11 +28,11 @@ class UrlGenerator extends ProviderBasedGenerator implements UrlGeneratorInterface { /** - * A request object. + * A request stack object. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * The path processor to convert the system path to one suitable for urls. @@ -91,7 +92,7 @@ class UrlGenerator extends ProviderBasedGenerator implements UrlGeneratorInterfa * @param \Psr\Log\LoggerInterface $logger * An optional logger for recording errors. */ - public function __construct(RouteProviderInterface $provider, OutboundPathProcessorInterface $path_processor, OutboundRouteProcessorInterface $route_processor, ConfigFactoryInterface $config, Settings $settings, LoggerInterface $logger = NULL) { + public function __construct(RouteProviderInterface $provider, OutboundPathProcessorInterface $path_processor, OutboundRouteProcessorInterface $route_processor, ConfigFactoryInterface $config, Settings $settings, LoggerInterface $logger = NULL, RequestStack $requestStack) { parent::__construct($provider, $logger); $this->pathProcessor = $path_processor; @@ -99,24 +100,26 @@ public function __construct(RouteProviderInterface $provider, OutboundPathProces $this->mixedModeSessions = $settings->get('mixed_mode_sessions', FALSE); $allowed_protocols = $config->get('system.filter')->get('protocols') ?: array('http', 'https'); UrlHelper::setAllowedProtocols($allowed_protocols); + $this->requestStack = $requestStack; + $this->updateRequest(); } - /** - * {@inheritdoc} - */ - public function setRequest(Request $request) { - $this->request = $request; - // Set some properties, based on the request, that are used during path-based - // url generation. - $this->basePath = $request->getBasePath() . '/'; - $this->baseUrl = $request->getSchemeAndHttpHost() . $this->basePath; - $this->scriptPath = ''; - $base_path_with_script = $request->getBaseUrl(); - $script_name = $request->getScriptName(); - if (!empty($base_path_with_script) && strpos($base_path_with_script, $script_name) !== FALSE) { - $length = strlen($this->basePath); - $this->scriptPath = ltrim(substr($script_name, $length), '/') . '/'; - } + // @todo this should probably be inline in the constructor as this is only + // useful to get some current tests pass + public function updateRequest() + { + $request = $this->requestStack->getCurrentRequest(); + // Set some properties, based on the request, that are used during path-based + // url generation. + $this->basePath = $request->getBasePath() . '/'; + $this->baseUrl = $request->getSchemeAndHttpHost() . $this->basePath; + $this->scriptPath = ''; + $base_path_with_script = $request->getBaseUrl(); + $script_name = $request->getScriptName(); + if (!empty($base_path_with_script) && strpos($base_path_with_script, $script_name) !== FALSE) { + $length = strlen($this->basePath); + $this->scriptPath = ltrim(substr($script_name, $length), '/') . '/'; + } } /** @@ -351,7 +354,7 @@ protected function processPath($path, &$options = array()) { $actual_path = $path; $query_string = ''; } - $path = '/' . $this->pathProcessor->processOutbound(trim($actual_path, '/'), $options, $this->request); + $path = '/' . $this->pathProcessor->processOutbound(trim($actual_path, '/'), $options, $this->requestStack->getCurrentRequest()); $path .= $query_string; return $path; } diff --git a/core/lib/Drupal/Core/Routing/UrlGeneratorInterface.php b/core/lib/Drupal/Core/Routing/UrlGeneratorInterface.php index 3a64ecd..a3535ad 100644 --- a/core/lib/Drupal/Core/Routing/UrlGeneratorInterface.php +++ b/core/lib/Drupal/Core/Routing/UrlGeneratorInterface.php @@ -7,7 +7,6 @@ namespace Drupal\Core\Routing; -use Symfony\Component\HttpFoundation\Request; use Symfony\Cmf\Component\Routing\VersatileGeneratorInterface; /** @@ -143,14 +142,6 @@ public function getPathFromRoute($name, $parameters = array()); public function generateFromRoute($name, $parameters = array(), $options = array()); /** - * Sets the $request property. - * - * @param \Symfony\Component\HttpFoundation\Request $request - * The HttpRequest object representing the current request. - */ - public function setRequest(Request $request); - - /** * Sets the baseUrl property. * * This property is made up of scheme, host and base_path, e.g. diff --git a/core/lib/Drupal/Core/Session/AccountProxy.php b/core/lib/Drupal/Core/Session/AccountProxy.php index 9f00218..d74a66d 100644 --- a/core/lib/Drupal/Core/Session/AccountProxy.php +++ b/core/lib/Drupal/Core/Session/AccountProxy.php @@ -8,7 +8,7 @@ namespace Drupal\Core\Session; use Drupal\Core\Authentication\AuthenticationManagerInterface; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * A proxied implementation of AccountInterface. @@ -26,9 +26,9 @@ class AccountProxy implements AccountProxyInterface { /** * The current request. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * The authentication manager. @@ -52,9 +52,9 @@ class AccountProxy implements AccountProxyInterface { * @param \Symfony\Component\HttpFoundation\Request $request * The request object used for authenticating. */ - public function __construct(AuthenticationManagerInterface $authentication_manager, Request $request) { + public function __construct(AuthenticationManagerInterface $authentication_manager, RequestStack $requestStack) { $this->authenticationManager = $authentication_manager; - $this->request = $request; + $this->requestStack = $requestStack; } /** @@ -74,7 +74,7 @@ public function setAccount(AccountInterface $account) { */ public function getAccount() { if (!isset($this->account)) { - $this->setAccount($this->authenticationManager->authenticate($this->request)); + $this->setAccount($this->authenticationManager->authenticate($this->requestStack->getMasterRequest())); } return $this->account; } diff --git a/core/lib/Drupal/Core/Session/SessionManager.php b/core/lib/Drupal/Core/Session/SessionManager.php index f656b2d..e8dc572 100644 --- a/core/lib/Drupal/Core/Session/SessionManager.php +++ b/core/lib/Drupal/Core/Session/SessionManager.php @@ -63,7 +63,7 @@ class SessionManager extends NativeSessionStorage implements SessionManagerInter * * @var bool */ - protected $lazySession; + protected $startedLazy; /** * Whether session management is enabled or temporarily disabled. @@ -89,10 +89,18 @@ class SessionManager extends NativeSessionStorage implements SessionManagerInter * The settings instance. */ public function __construct(RequestStack $request_stack, Connection $connection, SymfonyMetadataBag $metadata_bag, Settings $settings) { - parent::__construct(); + $options = array(); + $this->requestStack = $request_stack; $this->connection = $connection; - $this->setMetadataBag($metadata_bag); + + // Register the default session handler. + // @todo Extract session storage from session handler into a service. + $save_handler = new SessionHandler($this, $this->requestStack, $this->connection); + $write_check_handler = new WriteCheckSessionHandler($save_handler); + $this->setSaveHandler($write_check_handler); + + parent::__construct($options, $write_check_handler, $metadata_bag); $this->setMixedMode($settings->get('mixed_mode_sessions', FALSE)); @@ -108,14 +116,12 @@ public function __construct(RequestStack $request_stack, Connection $connection, /** * {@inheritdoc} */ - public function initialize() { + public function startLazy() { global $user; - // Register the default session handler. - // @todo Extract session storage from session handler into a service. - $save_handler = new SessionHandler($this, $this->requestStack, $this->connection); - $write_check_handler = new WriteCheckSessionHandler($save_handler); - $this->setSaveHandler($write_check_handler); + if (($this->started || $this->startedLazy) && !$this->closed) { + return $this->started; + } $is_https = $this->requestStack->getCurrentRequest()->isSecure(); $cookies = $this->requestStack->getCurrentRequest()->cookies; @@ -125,7 +131,7 @@ public function initialize() { // session is only started on demand in save(), making // anonymous users not use a session cookie unless something is stored in // $_SESSION. This allows HTTP proxies to cache anonymous pageviews. - $this->start(); + $result = $this->start(); if ($user->isAuthenticated() || !$this->isSessionObsolete()) { drupal_page_is_cacheable(FALSE); } @@ -135,17 +141,26 @@ public function initialize() { // we lazily start sessions at the end of this request, and some // processes (like drupal_get_token()) needs to know the future // session ID in advance. - $this->lazySession = TRUE; $user = new AnonymousUserSession(); $this->setId(Crypt::randomBytesBase64()); if ($is_https && $this->isMixedMode()) { $session_id = Crypt::randomBytesBase64(); $cookies->set($insecure_session_name, $session_id); } + $result = FALSE; } date_default_timezone_set(drupal_get_user_timezone()); - return $this; + $this->startedLazy = TRUE; + + return $result; + } + + /** + * {@inheritdoc} + */ + public function isStartedLazy() { + return $this->startedLazy; } /** @@ -174,7 +189,7 @@ public function start() { public function save() { global $user; - if (!$this->isEnabled()) { + if (!$this->isEnabled() || $this->isCli()) { // We don't have anything to do if we are not allowed to save the session. return; } @@ -189,7 +204,7 @@ public function save() { else { // There is session data to store. Start the session if it is not already // started. - if (!$this->isStarted()) { + if (!$this->getSaveHandler()->isActive()) { $this->start(); if ($this->requestStack->getCurrentRequest()->isSecure() && $this->isMixedMode()) { $insecure_session_name = $this->getInsecureName(); @@ -202,6 +217,8 @@ public function save() { // Write the session data. parent::save(); } + + $this->startedLazy = FALSE; } /** @@ -211,7 +228,7 @@ public function regenerate($destroy = FALSE, $lifetime = NULL) { global $user; // Nothing to do if we are not allowed to change the session. - if (!$this->isEnabled()) { + if (!$this->isEnabled() || $this->isCli()) { return; } @@ -226,7 +243,7 @@ public function regenerate($destroy = FALSE, $lifetime = NULL) { if ($is_https && $this->isMixedMode()) { $insecure_session_name = $this->getInsecureName(); - if (!isset($this->lazySession) && $cookies->has($insecure_session_name)) { + if ($this->isStarted() && $cookies->has($insecure_session_name)) { $old_insecure_session_id = $cookies->get($insecure_session_name); } $params = session_get_cookie_params(); @@ -294,7 +311,7 @@ public function regenerate($destroy = FALSE, $lifetime = NULL) { */ public function delete($uid) { // Nothing to do if we are not allowed to change the session. - if (!$this->isEnabled()) { + if (!$this->isEnabled() || $this->isCli()) { return; } $this->connection->delete('sessions') diff --git a/core/lib/Drupal/Core/Session/SessionManagerInterface.php b/core/lib/Drupal/Core/Session/SessionManagerInterface.php index dc9aa40..e7ea14d 100644 --- a/core/lib/Drupal/Core/Session/SessionManagerInterface.php +++ b/core/lib/Drupal/Core/Session/SessionManagerInterface.php @@ -15,11 +15,20 @@ interface SessionManagerInterface extends SessionStorageInterface { /** - * Initializes the session handler, starting a session if needed. + * Starts a session if appropriate cookies are on the request. * - * @return $this + * @return bool + * TRUE if the session was started. + */ + public function startLazy(); + + /** + * Determines whether the session was started lazily. + * + * @return bool + * TRUE if the session was started lazily. */ - public function initialize(); + public function isStartedLazy(); /** * Ends a specific user's session(s). diff --git a/core/modules/block/src/Tests/BlockViewBuilderTest.php b/core/modules/block/src/Tests/BlockViewBuilderTest.php index a6571cb..c215f50 100644 --- a/core/modules/block/src/Tests/BlockViewBuilderTest.php +++ b/core/modules/block/src/Tests/BlockViewBuilderTest.php @@ -158,8 +158,9 @@ public function testBlockViewBuilderCache() { */ protected function verifyRenderCacheHandling() { // Force a request via GET so we can get drupal_render() cache working. - $request_method = \Drupal::request()->server->get('REQUEST_METHOD'); - $this->container->get('request')->setMethod('GET'); + $request = \Drupal::request(); + $request_method = $request->server->get('REQUEST_METHOD'); + $request->setMethod('GET'); // Test that entities with caching disabled do not generate a cache entry. $build = $this->getBlockRenderArray(); @@ -189,7 +190,7 @@ protected function verifyRenderCacheHandling() { $this->assertFalse($this->container->get('cache.render')->get($cid), 'The block render cache entry has been cleared when the block was deleted.'); // Restore the previous request method. - $this->container->get('request')->setMethod($request_method); + $request->setMethod($request_method); } /** @@ -218,8 +219,9 @@ public function testBlockViewBuilderAlter() { \Drupal::state()->set('block_test_view_alter_suffix', FALSE); // Force a request via GET so we can get drupal_render() cache working. - $request_method = \Drupal::request()->server->get('REQUEST_METHOD'); - $this->container->get('request')->setMethod('GET'); + $request = \Drupal::request(); + $request_method = $request->server->get('REQUEST_METHOD'); + $request->setMethod('GET'); $default_keys = array('entity_view', 'block', 'test_block', 'en', 'cache_context.theme'); $default_tags = array('content' => TRUE, 'block_view' => TRUE, 'block' => array('test_block'), 'theme' => 'stark', 'block_plugin' => array('test_cache')); @@ -264,7 +266,7 @@ public function testBlockViewBuilderAlter() { $this->assertTrue(isset($build['#prefix']) && $build['#prefix'] === 'Hiya!
', 'A cached block without content is altered.'); // Restore the previous request method. - $this->container->get('request')->setMethod($request_method); + $request->setMethod($request_method); } /** @@ -277,8 +279,9 @@ public function testBlockViewBuilderAlter() { */ public function testBlockViewBuilderCacheContexts() { // Force a request via GET so we can get drupal_render() cache working. - $request_method = \Drupal::request()->server->get('REQUEST_METHOD'); - $this->container->get('request')->setMethod('GET'); + $request = \Drupal::request(); + $request_method = $request->server->get('REQUEST_METHOD'); + $request->setMethod('GET'); // First: no cache context. $this->setBlockCacheConfig(array( @@ -316,7 +319,7 @@ public function testBlockViewBuilderCacheContexts() { $this->container->set('cache_context.url', $original_url_cache_context); // Restore the previous request method. - $this->container->get('request')->setMethod($request_method); + $request->setMethod($request_method); } /** diff --git a/core/modules/book/src/Plugin/Block/BookNavigationBlock.php b/core/modules/book/src/Plugin/Block/BookNavigationBlock.php index b36beff..36b61d6 100644 --- a/core/modules/book/src/Plugin/Block/BookNavigationBlock.php +++ b/core/modules/book/src/Plugin/Block/BookNavigationBlock.php @@ -67,7 +67,7 @@ public static function create(ContainerInterface $container, array $configuratio $configuration, $plugin_id, $plugin_definition, - $container->get('request'), + $container->get('request_stack')->getCurrentRequest(), $container->get('book.manager') ); } diff --git a/core/modules/comment/tests/src/Entity/CommentLockTest.php b/core/modules/comment/tests/src/Entity/CommentLockTest.php index 887d3ca..8fbc40b 100644 --- a/core/modules/comment/tests/src/Entity/CommentLockTest.php +++ b/core/modules/comment/tests/src/Entity/CommentLockTest.php @@ -9,6 +9,8 @@ use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\Entity\EntityType; use Drupal\Tests\UnitTestCase; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * Unit tests for the comment entity lock behavior. @@ -37,8 +39,10 @@ public function testLocks() { $container->set('module_handler', $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface')); $container->set('current_user', $this->getMock('Drupal\Core\Session\AccountInterface')); $container->set('cache.test', $this->getMock('Drupal\Core\Cache\CacheBackendInterface')); + $requestStack = new RequestStack(); + $requestStack->push(Request::create('/')); + $container->set('request_stack', $requestStack); $container->setParameter('cache_bins', array('cache.test' => 'test')); - $container->register('request', 'Symfony\Component\HttpFoundation\Request'); $lock = $this->getMock('Drupal\Core\Lock\LockBackendInterface'); $cid = 2; $lock_name = "comment:$cid:.00/"; diff --git a/core/modules/config_translation/src/Controller/ConfigTranslationListController.php b/core/modules/config_translation/src/Controller/ConfigTranslationListController.php index 5ca474d..3167aca 100644 --- a/core/modules/config_translation/src/Controller/ConfigTranslationListController.php +++ b/core/modules/config_translation/src/Controller/ConfigTranslationListController.php @@ -50,7 +50,7 @@ public function __construct(ConfigMapperManagerInterface $mapper_manager, $confi public static function create(ContainerInterface $container) { return new static( $container->get('plugin.manager.config_translation.mapper'), - $container->get('request')->attributes->get('_raw_variables')->get('config_translation_mapper') + $container->get('request_stack')->getCurrentRequest()->attributes->get('_raw_variables')->get('config_translation_mapper') ); } diff --git a/core/modules/content_translation/src/Tests/ContentTranslationSyncImageTest.php b/core/modules/content_translation/src/Tests/ContentTranslationSyncImageTest.php index 5749baf..a70ed6b 100644 --- a/core/modules/content_translation/src/Tests/ContentTranslationSyncImageTest.php +++ b/core/modules/content_translation/src/Tests/ContentTranslationSyncImageTest.php @@ -122,7 +122,7 @@ function testImageFieldSync() { $langcode = $this->langcodes[1]; // Populate the required contextual values. - $attributes = $this->container->get('request')->attributes; + $attributes = \Drupal::request()->attributes; $attributes->set('source_langcode', $default_langcode); // Populate the test entity with some random initial values. diff --git a/core/modules/filter/src/Tests/FilterHtmlImageSecureTest.php b/core/modules/filter/src/Tests/FilterHtmlImageSecureTest.php index c5b5e0d..03e7bee 100644 --- a/core/modules/filter/src/Tests/FilterHtmlImageSecureTest.php +++ b/core/modules/filter/src/Tests/FilterHtmlImageSecureTest.php @@ -102,7 +102,7 @@ function testImageSource() { // Create a list of test image sources. // The keys become the value of the IMG 'src' attribute, the values are the // expected filter conversions. - $host = $this->container->get('request')->getHost(); + $host = \Drupal::request()->getHost(); $host_pattern = '|^http\://' . $host . '(\:[0-9]{0,5})|'; $images = array( $http_base_url . '/' . $druplicon => base_path() . $druplicon, diff --git a/core/modules/language/language.services.yml b/core/modules/language/language.services.yml index e183e6d..9b5b2f4 100644 --- a/core/modules/language/language.services.yml +++ b/core/modules/language/language.services.yml @@ -4,7 +4,7 @@ services: arguments: ['@container.namespaces', '@cache.discovery', '@module_handler'] language_negotiator: class: Drupal\language\LanguageNegotiator - arguments: ['@language_manager', '@plugin.manager.language_negotiation_method', '@config.factory', '@settings'] + arguments: ['@language_manager', '@plugin.manager.language_negotiation_method', '@config.factory', '@settings', '@request_stack'] calls: - [initLanguageManager] language.config_subscriber: diff --git a/core/modules/language/src/ConfigurableLanguageManager.php b/core/modules/language/src/ConfigurableLanguageManager.php index 0d9c7c6..cb96a8e 100644 --- a/core/modules/language/src/ConfigurableLanguageManager.php +++ b/core/modules/language/src/ConfigurableLanguageManager.php @@ -16,6 +16,7 @@ use Drupal\Core\Language\LanguageManager; use Drupal\language\Config\LanguageConfigFactoryOverrideInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * Overrides default LanguageManager to provide configured languages. @@ -46,9 +47,9 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl /** * The request object. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * The language negotiator. @@ -113,11 +114,12 @@ public static function rebuildServices() { * @param \Drupal\Core\Config\StorageInterface $config_storage * The configuration storage engine. */ - public function __construct(LanguageDefault $default_language, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, LanguageConfigFactoryOverrideInterface $config_override) { + public function __construct(LanguageDefault $default_language, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, LanguageConfigFactoryOverrideInterface $config_override, RequestStack $requestStack) { $this->defaultLanguage = $default_language; $this->configFactory = $config_factory; $this->moduleHandler = $module_handler; $this->configFactoryOverride = $config_override; + $this->requestStack = $requestStack; } /** @@ -247,13 +249,6 @@ public function reset($type = NULL) { /** * {@inheritdoc} */ - public function setRequest(Request $request) { - $this->request = $request; - } - - /** - * {@inheritdoc} - */ public function getNegotiator() { return $this->negotiator; } @@ -371,7 +366,7 @@ public function getLanguageSwitchLinks($type, $path) { $reflector = new \ReflectionClass($method['class']); if ($reflector->implementsInterface('\Drupal\language\LanguageSwitcherInterface')) { - $result = $this->negotiator->getNegotiationMethodInstance($method_id)->getLanguageSwitchLinks($this->request, $type, $path); + $result = $this->negotiator->getNegotiationMethodInstance($method_id)->getLanguageSwitchLinks($this->requestStack->getCurrentRequest(), $type, $path); if (!empty($result)) { // Allow modules to provide translations for specific links. diff --git a/core/modules/language/src/ConfigurableLanguageManagerInterface.php b/core/modules/language/src/ConfigurableLanguageManagerInterface.php index 2edf0bb..0d15e2f 100644 --- a/core/modules/language/src/ConfigurableLanguageManagerInterface.php +++ b/core/modules/language/src/ConfigurableLanguageManagerInterface.php @@ -21,14 +21,6 @@ public static function rebuildServices(); /** - * Injects the request object. - * - * @param \Symfony\Component\HttpFoundation\Request - * The request object. - */ - public function setRequest(Request $request); - - /** * Returns the language negotiator. * * @retun \Drupal\language\LanguageNegotiatorInterface diff --git a/core/modules/language/src/EventSubscriber/LanguageRequestSubscriber.php b/core/modules/language/src/EventSubscriber/LanguageRequestSubscriber.php index fcc1ddf..c543fc7 100644 --- a/core/modules/language/src/EventSubscriber/LanguageRequestSubscriber.php +++ b/core/modules/language/src/EventSubscriber/LanguageRequestSubscriber.php @@ -78,10 +78,9 @@ public function onKernelRequestLanguage(GetResponseEvent $event) { if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) { $request = $event->getRequest(); $this->negotiator->setCurrentUser($this->currentUser); - $this->negotiator->setRequest($request); + $this->negotiator->reset(); if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) { $this->languageManager->setNegotiator($this->negotiator); - $this->languageManager->setRequest($request); $this->languageManager->setConfigOverrideLanguage($this->languageManager->getCurrentLanguage()); } // After the language manager has initialized, set the default langcode diff --git a/core/modules/language/src/HttpKernel/PathProcessorLanguage.php b/core/modules/language/src/HttpKernel/PathProcessorLanguage.php index b2eb841..c3a6a9f 100644 --- a/core/modules/language/src/HttpKernel/PathProcessorLanguage.php +++ b/core/modules/language/src/HttpKernel/PathProcessorLanguage.php @@ -110,7 +110,7 @@ public function processOutbound($path, &$options = array(), Request $request = N $this->multilingual = $this->languageManager->isMultilingual(); } if ($this->multilingual) { - $this->negotiator->setRequest($request); + $this->negotiator->reset(); $scope = 'outbound'; if (!isset($this->processors[$scope])) { $this->initProcessors($scope); diff --git a/core/modules/language/src/LanguageNegotiator.php b/core/modules/language/src/LanguageNegotiator.php index cdeb8cf..eb1df93 100644 --- a/core/modules/language/src/LanguageNegotiator.php +++ b/core/modules/language/src/LanguageNegotiator.php @@ -12,7 +12,7 @@ use Drupal\Core\Language\LanguageManagerInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\Site\Settings; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * Class responsible for performing language negotiation. @@ -48,11 +48,11 @@ class LanguageNegotiator implements LanguageNegotiatorInterface { protected $settings; /** - * The request object. + * The request stack object. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * The current active user. @@ -87,11 +87,12 @@ class LanguageNegotiator implements LanguageNegotiatorInterface { * @param \Drupal\Core\Site\Settings $settings * The settings instance. */ - public function __construct(ConfigurableLanguageManagerInterface $language_manager, PluginManagerInterface $negotiator_manager, ConfigFactoryInterface $config_factory, Settings $settings) { + public function __construct(ConfigurableLanguageManagerInterface $language_manager, PluginManagerInterface $negotiator_manager, ConfigFactoryInterface $config_factory, Settings $settings, RequestStack $requestStack) { $this->languageManager = $language_manager; $this->negotiatorManager = $negotiator_manager; $this->configFactory = $config_factory; $this->settings = $settings; + $this->requestStack = $requestStack; } /** @@ -124,18 +125,10 @@ public function setCurrentUser(AccountInterface $current_user) { /** * {@inheritdoc} */ - public function setRequest(Request $request) { - $this->request = $request; - $this->reset(); - } - - /** - * {@inheritdoc} - */ public function initializeType($type) { $language = NULL; - if ($this->currentUser && $this->request) { + if ($this->currentUser) { // Execute the language negotiation methods in the order they were set up // and return the first valid language found. foreach ($this->getEnabledNegotiators($type) as $method_id => $info) { @@ -207,7 +200,7 @@ protected function negotiateLanguage($type, $method_id) { // If the language negotiation method has no cache preference or this is // satisfied we can execute the callback. if ($cache = !isset($method['cache']) || $this->currentUser->isAuthenticated() || $method['cache'] == $cache_enabled) { - $langcode = $this->getNegotiationMethodInstance($method_id)->getLangcode($this->request); + $langcode = $this->getNegotiationMethodInstance($method_id)->getLangcode($this->requestStack->getCurrentRequest()); } } diff --git a/core/modules/language/src/LanguageNegotiatorInterface.php b/core/modules/language/src/LanguageNegotiatorInterface.php index 13d7068..309d84a 100644 --- a/core/modules/language/src/LanguageNegotiatorInterface.php +++ b/core/modules/language/src/LanguageNegotiatorInterface.php @@ -8,7 +8,6 @@ namespace Drupal\language; use Drupal\Core\Session\AccountInterface; -use Symfony\Component\HttpFoundation\Request; /** * Common interface for language negotiation services. @@ -124,14 +123,6 @@ public function reset(); public function setCurrentUser(AccountInterface $current_user); /** - * Sets the active request and resets all language types. - * - * @param \Symfony\Component\HttpFoundation\Request $request - * The HttpRequest object representing the current request. - */ - public function setRequest(Request $request); - - /** * Initializes the specified language type. * * @param string $type diff --git a/core/modules/language/src/LanguageServiceProvider.php b/core/modules/language/src/LanguageServiceProvider.php index a565c1c..523e383 100644 --- a/core/modules/language/src/LanguageServiceProvider.php +++ b/core/modules/language/src/LanguageServiceProvider.php @@ -52,7 +52,8 @@ public function alter(ContainerBuilder $container) { $definition->setClass('Drupal\language\ConfigurableLanguageManager') ->addArgument(new Reference('config.factory')) ->addArgument(new Reference('module_handler')) - ->addArgument(new Reference('language.config_factory_override')); + ->addArgument(new Reference('language.config_factory_override')) + ->addArgument(new Reference('request_stack')); if ($default_language_values = $this->getDefaultLanguageValues()) { $container->setParameter('language.default_values', $default_language_values); } diff --git a/core/modules/language/src/Tests/LanguageUILanguageNegotiationTest.php b/core/modules/language/src/Tests/LanguageUILanguageNegotiationTest.php index a3fe8e8..5412ae9 100644 --- a/core/modules/language/src/Tests/LanguageUILanguageNegotiationTest.php +++ b/core/modules/language/src/Tests/LanguageUILanguageNegotiationTest.php @@ -16,6 +16,7 @@ use Drupal\Core\Language\Language; use Drupal\Core\Language\LanguageInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Drupal\language\LanguageNegotiatorInterface; /** @@ -69,7 +70,9 @@ function setUp() { parent::setUp(); $this->request = Request::createFromGlobals(); - $this->container->set('request', $this->request); + $requestStack = new RequestStack(); + $requestStack->push($this->request); + $this->container->set('request_stack', $requestStack); $admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages', 'administer blocks')); $this->drupalLogin($admin_user); @@ -452,9 +455,9 @@ function testLanguageDomain() { $this->settingsSet('mixed_mode_sessions', FALSE); // Test HTTPS via current URL scheme. - $generator = $this->container->get('url_generator'); $request = Request::create('', 'GET', array(), array(), array(), array('HTTPS' => 'on')); - $generator->setRequest($request); + $this->container->get('request_stack')->push($request); + $generator = $this->container->get('url_generator'); $italian_url = url('admin', array('language' => $languages['it'], 'script' => '')); $correct_link = 'https://' . $link; $this->assertTrue($italian_url == $correct_link, format_string('The url() function returns the right URL (via current URL scheme) (@url) in accordance with the chosen language', array('@url' => $italian_url))); diff --git a/core/modules/rest/tests/src/CollectRoutesTest.php b/core/modules/rest/tests/src/CollectRoutesTest.php index f511192..1352929 100644 --- a/core/modules/rest/tests/src/CollectRoutesTest.php +++ b/core/modules/rest/tests/src/CollectRoutesTest.php @@ -55,7 +55,6 @@ protected function setUp() { ->getMock(); $container->set('content_negotiation', $content_negotiation); - $container->set('request', $request); $this->view = $this->getMock('\Drupal\views\Entity\View', array('initHandlers'), array( array('id' => 'test_view'), diff --git a/core/modules/simpletest/src/KernelTestBase.php b/core/modules/simpletest/src/KernelTestBase.php index 5f0183a..ddf8fc5 100644 --- a/core/modules/simpletest/src/KernelTestBase.php +++ b/core/modules/simpletest/src/KernelTestBase.php @@ -152,7 +152,6 @@ protected function setUp() { $this->kernel->boot(); $request = Request::create('/'); - $this->container->set('request', $request); $this->container->get('request_stack')->push($request); // Create a minimal core.extension configuration object so that the list of @@ -284,7 +283,7 @@ public function containerBuild(ContainerBuilder $container) { } $request = Request::create('/'); - $this->container->set('request', $request); + $container->get('request_stack')->push($request); } /** diff --git a/core/modules/simpletest/src/TestBase.php b/core/modules/simpletest/src/TestBase.php index 0987d3d..d54f918 100644 --- a/core/modules/simpletest/src/TestBase.php +++ b/core/modules/simpletest/src/TestBase.php @@ -7,6 +7,7 @@ namespace Drupal\simpletest; +use Drupal\Component\Utility\Crypt; use Drupal\Component\Utility\Random; use Drupal\Core\Database\Database; use Drupal\Component\Utility\String; @@ -23,6 +24,7 @@ use Drupal\Core\StreamWrapper\PublicStream; use Drupal\Core\Utility\Error; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\DependencyInjection\Reference; /** @@ -197,6 +199,11 @@ protected $randomGenerator; /** + * The name of the session cookie. + */ + protected $originalSessionName; + + /** * Constructor for Test. * * @param $test_id @@ -1036,8 +1043,17 @@ private function prepareEnvironment() { $this->originalProfile = drupal_get_profile(); $this->originalUser = isset($user) ? clone $user : NULL; - // Ensure that the current session is not changed by the new environment. - \Drupal::service('session_manager')->disable(); + // Prevent that session data is leaked into the UI test runner by closing + // the session and then setting the session-name (i.e. the name of the + // session cookie) to a random value. If a test starts a new session, then + // it will be associated with a different session-name. After the test-run + // it can be safely destroyed. + // @see TestBase::restoreEnvironment() + if (PHP_SAPI != 'cli' && session_status() == PHP_SESSION_ACTIVE) { + session_write_close(); + } + $this->originalSessionName = session_name(); + session_name('SIMPLETEST' . Crypt::randomBytesBase64()); // Save and clean the shutdown callbacks array because it is static cached // and will be changed by the test run. Otherwise it will contain callbacks @@ -1094,7 +1110,10 @@ private function prepareEnvironment() { $this->container->register('info_parser', 'Drupal\Core\Extension\InfoParser'); $request = Request::create('/'); - $this->container->set('request', $request); + + $requestStack = new RequestStack(); + $requestStack->push($request); + $this->container->set('request_stack', $requestStack); // Run all tests as a anonymous user by default, web tests will replace that // during the test set up. @@ -1152,6 +1171,14 @@ protected function tearDown() { * @see TestBase::prepareEnvironment() */ private function restoreEnvironment() { + // Destroy the session if one was started during the test-run. + $_SESSION = array(); + if (PHP_SAPI != 'cli' && session_status() == PHP_SESSION_ACTIVE) { + session_destroy(); + $params = session_get_cookie_params(); + setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']); + } + session_name($this->originalSessionName); // Reset all static variables. // Unsetting static variables will potentially invoke destruct methods, // which might call into functions that prime statics and caches again. @@ -1237,7 +1264,6 @@ private function restoreEnvironment() { // Restore original user session. $this->container->set('current_user', $this->originalUser); - \Drupal::service('session_manager')->enable(); } /** diff --git a/core/modules/simpletest/src/WebTestBase.php b/core/modules/simpletest/src/WebTestBase.php index 3bd1d86..1d08fb9 100644 --- a/core/modules/simpletest/src/WebTestBase.php +++ b/core/modules/simpletest/src/WebTestBase.php @@ -778,6 +778,16 @@ protected function drupalLogout() { } /** + * Return the session name in use on the child site. + * + * @return string + * The name of the session cookie. + */ + public function getSessionName() { + return $this->session_name; + } + + /** * Sets up a Drupal site for running functional and integration tests. * * Installs Drupal with the installation profile specified in @@ -808,6 +818,12 @@ protected function setUp() { 'pass_raw' => $this->randomName(), )); + // The simpletest child site currently uses the same session name as the + // execution environment. + // @todo: Introduce a setting such that the session name can be customized + // for the child site. + $this->session_name = $this->originalSessionName; + // Reset the static batch to remove Simpletest's batch operations. $batch = &batch_get(); $batch = array(); @@ -1104,27 +1120,32 @@ protected function writeCustomTranslations() { protected function rebuildContainer($environment = 'prod') { // Preserve the request object after the container rebuild. $request = \Drupal::request(); - // When called from InstallerTestBase, the current container is the minimal - // container from TestBase::prepareEnvironment(), which does not contain a - // request stack. - if (\Drupal::getContainer()->initialized('request_stack')) { - $request_stack = \Drupal::service('request_stack'); + // If there is a session manager, close and save the session. + $session_manager_state = 0; + if (\Drupal::getContainer()->initialized('session_manager')) { + $session_manager = \Drupal::getContainer()->get('session_manager'); + if ($session_manager->isStartedLazy()) { + $session_manager_state |= 0x1; + } + if ($session_manager->isStarted()) { + $session_manager_state |= 0x2; + } + $session_manager->save(); + unset($session_manager); } - $this->kernel = new DrupalKernel($environment, drupal_classloader(), TRUE, FALSE); $this->kernel->boot(); // DrupalKernel replaces the container in \Drupal::getContainer() with a // different object, so we need to replace the instance on this test class. $this->container = \Drupal::getContainer(); // The current user is set in TestBase::prepareEnvironment(). - $this->container->set('request', $request); - if (isset($request_stack)) { - $this->container->set('request_stack', $request_stack); + $this->container->get('request_stack')->push($request); + if ($session_manager_state & 0x1) { + $this->container->get('session_manager')->startLazy(); } - else { - $this->container->get('request_stack')->push($request); + if ($session_manager_state & 0x2) { + $this->container->get('session_manager')->start(); } - $this->container->get('current_user')->setAccount(\Drupal::currentUser()); // The request context is normally set by the router_listener from within // its KernelEvents::REQUEST listener. In the simpletest parent site this @@ -1241,9 +1262,6 @@ protected function curlInitialize() { if (!$result) { throw new \UnexpectedValueException('One or more cURL options could not be set.'); } - - // By default, the child session name should be the same as the parent. - $this->session_name = session_name(); } // We set the user agent header on each request so as to use the current // time and a new uniqid. @@ -1649,6 +1667,7 @@ protected function drupalPostForm($path, $edit, $submit, array $options = array( if (isset($path)) { $this->drupalGet($path, $options); } + if ($this->parse()) { $edit_save = $edit; // Let's iterate over all the forms. @@ -3819,7 +3838,8 @@ protected function prepareRequestForGenerator($clean_urls = TRUE, $override_serv $server = array_merge($server, $override_server_vars); $request = Request::create($request_path, 'GET', array(), array(), array(), $server); - $generator->setRequest($request); + $this->container->get('request_stack')->push($request); + $generator->updateRequest(); return $request; } } diff --git a/core/modules/system/src/Plugin/Block/SystemBreadcrumbBlock.php b/core/modules/system/src/Plugin/Block/SystemBreadcrumbBlock.php index 814fce5..9680a88 100644 --- a/core/modules/system/src/Plugin/Block/SystemBreadcrumbBlock.php +++ b/core/modules/system/src/Plugin/Block/SystemBreadcrumbBlock.php @@ -24,8 +24,7 @@ class SystemBreadcrumbBlock extends BlockBase { */ public function build() { $breadcrumb_manager = \Drupal::service('breadcrumb'); - $request = \Drupal::service('request'); - $breadcrumb = $breadcrumb_manager->build($request->attributes->all()); + $breadcrumb = $breadcrumb_manager->build(\Drupal::request()->attributes->all()); if (!empty($breadcrumb)) { // $breadcrumb is expected to be an array of rendered breadcrumb links. return array( diff --git a/core/modules/system/src/Plugin/Block/SystemHelpBlock.php b/core/modules/system/src/Plugin/Block/SystemHelpBlock.php index d15cfc6..05a7dd0 100644 --- a/core/modules/system/src/Plugin/Block/SystemHelpBlock.php +++ b/core/modules/system/src/Plugin/Block/SystemHelpBlock.php @@ -72,7 +72,7 @@ public function __construct(array $configuration, $plugin_id, $plugin_definition */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( - $configuration, $plugin_id, $plugin_definition, $container->get('request'), $container->get('module_handler')); + $configuration, $plugin_id, $plugin_definition, $container->get('request_stack')->getCurrentRequest(), $container->get('module_handler')); } /** diff --git a/core/modules/system/src/Tests/Common/HtmlIdentifierUnitTest.php b/core/modules/system/src/Tests/Common/HtmlIdentifierUnitTest.php index ec9bbb4..2876401 100644 --- a/core/modules/system/src/Tests/Common/HtmlIdentifierUnitTest.php +++ b/core/modules/system/src/Tests/Common/HtmlIdentifierUnitTest.php @@ -29,8 +29,7 @@ public function setUp() { parent::setUp(); $container = \Drupal::getContainer(); - $request = new Request(); - $container->set('request', $request); + $container->get('request_stack')->push(Request::create('/')); \Drupal::setContainer($container); } diff --git a/core/modules/system/src/Tests/Common/TableSortExtenderUnitTest.php b/core/modules/system/src/Tests/Common/TableSortExtenderUnitTest.php index 7b5ab6b..cb88444 100644 --- a/core/modules/system/src/Tests/Common/TableSortExtenderUnitTest.php +++ b/core/modules/system/src/Tests/Common/TableSortExtenderUnitTest.php @@ -41,7 +41,7 @@ function testTableSortInit() { ); $request = Request::createFromGlobals(); $request->query->replace(array()); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $this->verbose(strtr('$ts:
!ts
', array('!ts' => check_plain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers sorted correctly.'); @@ -54,7 +54,7 @@ function testTableSortInit() { // headers are overridable. 'order' => 'bar', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $this->verbose(strtr('$ts:
!ts
', array('!ts' => check_plain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers plus non-overriding $_GET parameters sorted correctly.'); @@ -68,7 +68,7 @@ function testTableSortInit() { // it in the links that it creates. 'alpha' => 'beta', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $expected_ts['sort'] = 'desc'; $expected_ts['query'] = array('alpha' => 'beta'); $ts = tablesort_init($headers); @@ -96,7 +96,7 @@ function testTableSortInit() { $request->query->replace(array( 'order' => '2', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $expected_ts = array( 'name' => '2', @@ -115,7 +115,7 @@ function testTableSortInit() { // exist. 'order' => 'bar', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $expected_ts = array( 'name' => '1', @@ -136,7 +136,7 @@ function testTableSortInit() { // it in the links that it creates. 'alpha' => 'beta', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $expected_ts = array( 'name' => '1', 'sql' => 'one', diff --git a/core/modules/system/src/Tests/Database/SelectPagerDefaultTest.php b/core/modules/system/src/Tests/Database/SelectPagerDefaultTest.php index 79c93d2..1f69f5b 100644 --- a/core/modules/system/src/Tests/Database/SelectPagerDefaultTest.php +++ b/core/modules/system/src/Tests/Database/SelectPagerDefaultTest.php @@ -141,7 +141,7 @@ function testElementNumbers() { $request->query->replace(array( 'page' => '3, 2, 1, 0', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $name = db_select('test', 't') ->extend('Drupal\Core\Database\Query\PagerSelectExtender') diff --git a/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php b/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php index 17e4b4b..7a4f999 100644 --- a/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php +++ b/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php @@ -10,6 +10,7 @@ use Drupal\Core\DrupalKernel; use Drupal\Core\Site\Settings; use Drupal\simpletest\DrupalUnitTestBase; +use Symfony\Component\HttpFoundation\Request; /** * Tests compilation of the DIC. @@ -100,13 +101,15 @@ function testCompileDIC() { // registered to the new container. $module_enabled['service_provider_test'] = 'service_provider_test'; $kernel = new DrupalKernel('testing', $classloader); - $kernel->updateModules($module_enabled); $kernel->boot(); + $kernel->getContainer()->get('request_stack')->push(Request::create('/')); + $kernel->updateModules($module_enabled); // Instantiate it a second time and we should still get a ContainerBuilder // class because we are using the read-only PHP storage. $kernel = new DrupalKernel('testing', $classloader); - $kernel->updateModules($module_enabled); $kernel->boot(); + $kernel->getContainer()->get('request_stack')->push(Request::create('/')); + $kernel->updateModules($module_enabled); $container = $kernel->getContainer(); $refClass = new \ReflectionClass($container); $is_container_builder = $refClass->isSubclassOf('Symfony\Component\DependencyInjection\ContainerBuilder'); diff --git a/core/modules/system/src/Tests/DrupalKernel/ServiceDestructionTest.php b/core/modules/system/src/Tests/DrupalKernel/ServiceDestructionTest.php index a48e883..9a8094f 100644 --- a/core/modules/system/src/Tests/DrupalKernel/ServiceDestructionTest.php +++ b/core/modules/system/src/Tests/DrupalKernel/ServiceDestructionTest.php @@ -37,7 +37,7 @@ public function testDestructionUsed() { // Call the class and then terminate the kernel $this->container->get('service_provider_test_class'); $response = new Response(); - $this->container->get('kernel')->terminate($this->container->get('request'), $response); + $this->container->get('kernel')->terminate($this->container->get('request_stack')->getCurrentRequest(), $response); $this->assertTrue(\Drupal::state()->get('service_provider_test.destructed')); } @@ -54,7 +54,7 @@ public function testDestructionUnused() { // Terminate the kernel. The test class has not been called, so it should not // be destructed. $response = new Response(); - $this->container->get('kernel')->terminate($this->container->get('request'), $response); + $this->container->get('kernel')->terminate($this->container->get('request_stack')->getCurrentRequest(), $response); $this->assertNull(\Drupal::state()->get('service_provider_test.destructed')); } } diff --git a/core/modules/system/src/Tests/Entity/EntityQueryTest.php b/core/modules/system/src/Tests/Entity/EntityQueryTest.php index a3be1e8..2b33228 100644 --- a/core/modules/system/src/Tests/Entity/EntityQueryTest.php +++ b/core/modules/system/src/Tests/Entity/EntityQueryTest.php @@ -356,7 +356,7 @@ function testSort() { $request->query->replace(array( 'page' => '0,2', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $this->queryResults = $this->factory->get('entity_test_mulrev') ->sort("$figures.color") ->sort("$greetings.format") @@ -388,7 +388,7 @@ protected function testTableSort() { 'sort' => 'asc', 'order' => 'Type', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $header = array( 'id' => array('data' => 'Id', 'specifier' => 'id'), @@ -403,7 +403,7 @@ protected function testTableSort() { $request->query->add(array( 'sort' => 'desc', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $header = array( 'id' => array('data' => 'Id', 'specifier' => 'id'), @@ -418,7 +418,7 @@ protected function testTableSort() { $request->query->add(array( 'order' => 'Id', )); - \Drupal::getContainer()->set('request', $request); + \Drupal::getContainer()->get('request_stack')->push($request); $this->queryResults = $this->factory->get('entity_test_mulrev') ->tableSort($header) ->execute(); diff --git a/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php b/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php index 6ac4a62..fc7b71f 100644 --- a/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php +++ b/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php @@ -40,8 +40,9 @@ public function setUp() { */ public function testEntityViewBuilderCache() { // Force a request via GET so we can get drupal_render() cache working. - $request_method = \Drupal::request()->server->get('REQUEST_METHOD'); - $this->container->get('request')->setMethod('GET'); + $request = \Drupal::request(); + $request_method = $request->server->get('REQUEST_METHOD'); + $request->setMethod('GET'); $entity_test = $this->createTestEntity('entity_test'); @@ -77,7 +78,7 @@ public function testEntityViewBuilderCache() { $this->assertFalse($this->container->get('cache.' . $bin)->get($cid), 'The entity render cache has been cleared when the entity was deleted.'); // Restore the previous request method. - $this->container->get('request')->setMethod($request_method); + $request->setMethod($request_method); } /** @@ -85,8 +86,9 @@ public function testEntityViewBuilderCache() { */ public function testEntityViewBuilderCacheWithReferences() { // Force a request via GET so we can get drupal_render() cache working. - $request_method = \Drupal::request()->server->get('REQUEST_METHOD'); - $this->container->get('request')->setMethod('GET'); + $request = \Drupal::request(); + $request_method = $request->server->get('REQUEST_METHOD'); + $request->setMethod('GET'); // Create an entity reference field and an entity that will be referenced. entity_reference_create_instance('entity_test', 'entity_test', 'reference_field', 'Reference', 'entity_test'); @@ -131,7 +133,7 @@ public function testEntityViewBuilderCacheWithReferences() { $this->assertFalse($this->container->get('cache.' . $bin_reference)->get($cid_reference), 'The entity render cache for the referenced entity has been cleared when the entity was deleted.'); // Restore the previous request method. - $this->container->get('request')->setMethod($request_method); + $request->setMethod($request_method); } /** diff --git a/core/modules/system/src/Tests/File/UrlRewritingTest.php b/core/modules/system/src/Tests/File/UrlRewritingTest.php index 11f9d16..ce8e809 100644 --- a/core/modules/system/src/Tests/File/UrlRewritingTest.php +++ b/core/modules/system/src/Tests/File/UrlRewritingTest.php @@ -99,7 +99,7 @@ function testRelativeFileURL() { // Create a mock Request for file_url_transform_relative(). $request = Request::create($GLOBALS['base_url']); - $this->container->set('request', $request); + $this->container->get('request_stack')->push($request); \Drupal::setContainer($this->container); // Shipped file. diff --git a/core/modules/system/src/Tests/Session/SessionHttpsTest.php b/core/modules/system/src/Tests/Session/SessionHttpsTest.php index a9c709c..f76be1b 100644 --- a/core/modules/system/src/Tests/Session/SessionHttpsTest.php +++ b/core/modules/system/src/Tests/Session/SessionHttpsTest.php @@ -35,17 +35,17 @@ public static function getInfo() { public function setUp() { parent::setUp(); $this->request = Request::createFromGlobals(); - $this->container->set('request', $this->request); + $this->container->get('request_stack')->push($this->request); } protected function testHttpsSession() { if ($this->request->isSecure()) { - $secure_session_name = session_name(); - $insecure_session_name = substr(session_name(), 1); + $secure_session_name = $this->getSessionName(); + $insecure_session_name = substr($this->getSessionName(), 1); } else { - $secure_session_name = 'S' . session_name(); - $insecure_session_name = session_name(); + $secure_session_name = 'S' . $this->getSessionName(); + $insecure_session_name = $this->getSessionName(); } $user = $this->drupalCreateUser(array('access administration pages')); @@ -124,8 +124,8 @@ protected function testMixedModeSslSession() { return; } else { - $secure_session_name = 'S' . session_name(); - $insecure_session_name = session_name(); + $secure_session_name = 'S' . $this->getSessionName(); + $insecure_session_name = $this->getSessionName(); } // Enable secure pages. @@ -231,12 +231,12 @@ protected function testMixedModeSslSession() { */ protected function testCsrfTokenWithMixedModeSsl() { if ($this->request->isSecure()) { - $secure_session_name = session_name(); - $insecure_session_name = substr(session_name(), 1); + $secure_session_name = $this->getSessionName(); + $insecure_session_name = substr($this->getSessionName(), 1); } else { - $secure_session_name = 'S' . session_name(); - $insecure_session_name = session_name(); + $secure_session_name = 'S' . $this->getSessionName(); + $insecure_session_name = $this->getSessionName(); } // Enable mixed mode SSL. diff --git a/core/modules/system/src/Tests/Session/SessionTest.php b/core/modules/system/src/Tests/Session/SessionTest.php index 720f16f..c64d1ad 100644 --- a/core/modules/system/src/Tests/Session/SessionTest.php +++ b/core/modules/system/src/Tests/Session/SessionTest.php @@ -36,7 +36,7 @@ public static function getInfo() { */ function testSessionSaveRegenerate() { $session_manager = $this->container->get('session_manager'); - $this->assertFalse($session_manager->isEnabled(), 'SessionManager->isEnabled() initially returns FALSE (in testing framework).'); + $this->assertTrue($session_manager->isEnabled(), 'SessionManager->isEnabled() initially returns TRUE.'); $this->assertFalse($session_manager->disable()->isEnabled(), 'SessionManager->isEnabled() returns FALSE after disabling.'); $this->assertTrue($session_manager->enable()->isEnabled(), 'SessionManager->isEnabled() returns TRUE after enabling.'); diff --git a/core/modules/system/system.module b/core/modules/system/system.module index 7fbfd99..61ddc30 100644 --- a/core/modules/system/system.module +++ b/core/modules/system/system.module @@ -978,7 +978,7 @@ function system_page_build(&$page) { 'path' => current_path(), 'front' => drupal_is_front_page(), 'language' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->id, - 'query' => \Drupal::service('request')->query->all(), + 'query' => \Drupal::request()->query->all(), ) ); } diff --git a/core/modules/views/src/Form/ViewsForm.php b/core/modules/views/src/Form/ViewsForm.php index 45f1730..988aa4f 100644 --- a/core/modules/views/src/Form/ViewsForm.php +++ b/core/modules/views/src/Form/ViewsForm.php @@ -16,7 +16,7 @@ use Drupal\Core\Routing\UrlGeneratorInterface; use Drupal\views\ViewExecutable; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; /** * Provides a base class for single- or multistep view forms. @@ -36,11 +36,11 @@ class ViewsForm extends DependencySerialization implements FormInterface, Contai protected $classResolver; /** - * The current request. + * The request stack. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * The url generator to generate the form action. @@ -70,17 +70,17 @@ class ViewsForm extends DependencySerialization implements FormInterface, Contai * The class resolver to get the subform form objects. * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator * The url generator to generate the form action. - * @param \Symfony\Component\HttpFoundation\Request $request - * The current request. + * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack + * The request stack. * @param string $view_id * The ID of the view. * @param string $view_display_id * The ID of the active view's display. */ - public function __construct(ClassResolverInterface $controller_resolver, UrlGeneratorInterface $url_generator, Request $request, $view_id, $view_display_id) { + public function __construct(ClassResolverInterface $controller_resolver, UrlGeneratorInterface $url_generator, RequestStack $requestStack, $view_id, $view_display_id) { $this->classResolver = $controller_resolver; $this->urlGenerator = $url_generator; - $this->request = $request; + $this->requestStack = $requestStack; $this->viewId = $view_id; $this->viewDisplayId = $view_display_id; } @@ -92,7 +92,7 @@ public static function create(ContainerInterface $container, $view_id = NULL, $v return new static( $container->get('controller_resolver'), $container->get('url_generator'), - $container->get('request'), + $container->get('request_stack'), $view_id, $view_display_id ); @@ -126,7 +126,7 @@ public function buildForm(array $form, array &$form_state, ViewExecutable $view $form = array(); - $query = $this->request->query->all(); + $query = $this->requestStack->getCurrentRequest()->query->all(); $query = UrlHelper::filterQueryParameters($query, array(), ''); $form['#action'] = $this->urlGenerator->generateFromPath($view->getUrl(), array('query' => $query)); diff --git a/core/modules/views/src/Tests/Plugin/DisplayPageTest.php b/core/modules/views/src/Tests/Plugin/DisplayPageTest.php index a7d4418..035a0df 100644 --- a/core/modules/views/src/Tests/Plugin/DisplayPageTest.php +++ b/core/modules/views/src/Tests/Plugin/DisplayPageTest.php @@ -76,7 +76,7 @@ public function testPageResponses() { $this->assertEqual($response->getStatusCode(), 200); $subrequest = Request::create('/test_page_display_200', 'GET'); - \Drupal::getContainer()->set('request', $subrequest); + \Drupal::getContainer()->get('request_stack')->push($subrequest); // Test accessing a disabled page for a view. $view = Views::getView('test_page_display'); diff --git a/core/modules/views/src/Tests/ViewTestBase.php b/core/modules/views/src/Tests/ViewTestBase.php index 8527c44..82e42e2 100644 --- a/core/modules/views/src/Tests/ViewTestBase.php +++ b/core/modules/views/src/Tests/ViewTestBase.php @@ -232,7 +232,6 @@ protected function helperButtonHasLabel($id, $expected_label, $message = 'Label protected function executeView(ViewExecutable $view, $args = array()) { // A view does not really work outside of a request scope, due to many // dependencies like the current user. - $this->container->enterScope('request'); $view->setDisplay(); $view->preExecute($args); $view->execute(); diff --git a/core/modules/views/views.theme.inc b/core/modules/views/views.theme.inc index 7d1060c..1603d81 100644 --- a/core/modules/views/views.theme.inc +++ b/core/modules/views/views.theme.inc @@ -120,7 +120,7 @@ function template_preprocess_views_view(&$variables) { } $container = \Drupal::getContainer(); - $form_object = new ViewsForm($container->get('class_resolver'), $container->get('url_generator'), $container->get('request'), $view->storage->id(), $view->current_display); + $form_object = new ViewsForm($container->get('class_resolver'), $container->get('url_generator'), $container->get('request_stack'), $view->storage->id(), $view->current_display); $form = \Drupal::formBuilder()->getForm($form_object, $view, $output); // The form is requesting that all non-essential views elements be hidden, // usually because the rendered step is not a view result. diff --git a/core/modules/views_ui/src/Tests/TagTest.php b/core/modules/views_ui/src/Tests/TagTest.php index db2df4f..abe7c0c 100644 --- a/core/modules/views_ui/src/Tests/TagTest.php +++ b/core/modules/views_ui/src/Tests/TagTest.php @@ -47,7 +47,7 @@ public function testViewsUiAutocompleteTag() { // Make sure just ten results are returns. $controller = ViewsUIController::create($this->container); - $request = $this->container->get('request'); + $request = $this->container->get('request_stack')->getCurrentRequest(); $request->query->set('q', 'autocomplete_tag_test'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); diff --git a/core/modules/views_ui/src/ViewEditForm.php b/core/modules/views_ui/src/ViewEditForm.php index 5a4b23c..bd276b9 100644 --- a/core/modules/views_ui/src/ViewEditForm.php +++ b/core/modules/views_ui/src/ViewEditForm.php @@ -16,7 +16,7 @@ use Drupal\Core\Render\Element; use Drupal\user\TempStoreFactory; use Drupal\views\Views; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -34,21 +34,21 @@ class ViewEditForm extends ViewFormBase { /** * The request object. * - * @var \Symfony\Component\HttpFoundation\Request + * @var \Symfony\Component\HttpFoundation\RequestStack */ - protected $request; + protected $requestStack; /** * Constructs a new ViewEditForm object. * * @param \Drupal\user\TempStoreFactory $temp_store_factory * The factory for the temp store object. - * @param \Symfony\Component\HttpFoundation\Request $request - * The request object. + * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack + * The request stack object. */ - public function __construct(TempStoreFactory $temp_store_factory, Request $request) { + public function __construct(TempStoreFactory $temp_store_factory, RequestStack $requestStack) { $this->tempStore = $temp_store_factory->get('views'); - $this->request = $request; + $this->requestStack = $requestStack; } /** @@ -57,7 +57,7 @@ public function __construct(TempStoreFactory $temp_store_factory, Request $reque public static function create(ContainerInterface $container) { return new static( $container->get('user.tempstore'), - $container->get('request') + $container->get('request_stack') ); } @@ -292,7 +292,7 @@ public function submit(array $form, array &$form_state) { $view->set('display', $displays); // @todo: Revisit this when http://drupal.org/node/1668866 is in. - $query = $this->request->query; + $query = $this->requestStack->getCurrentRequest()->query; $destination = $query->get('destination'); if (!empty($destination)) { @@ -765,7 +765,7 @@ public function renderDisplayTop(ViewUI $view) { * should not yet redirect to the destination. */ public function submitDelayDestination($form, &$form_state) { - $query = $this->request->query; + $query = $this->requestStack->getCurrentRequest()->query; // @todo: Revisit this when http://drupal.org/node/1668866 is in. $destination = $query->get('destination'); if (isset($destination) && $form_state['redirect'] !== FALSE) { diff --git a/core/scripts/run-tests.sh b/core/scripts/run-tests.sh index 8eff2a2..ee38802 100755 --- a/core/scripts/run-tests.sh +++ b/core/scripts/run-tests.sh @@ -389,8 +389,6 @@ function simpletest_script_bootstrap() { $request = Request::createFromGlobals(); $container = $kernel->getContainer(); - $container->enterScope('request'); - $container->set('request', $request, 'request'); $container->get('request_stack')->push($request); $module_handler = $container->get('module_handler'); diff --git a/core/tests/Drupal/Tests/Core/Access/AccessManagerTest.php b/core/tests/Drupal/Tests/Core/Access/AccessManagerTest.php index bb43565..be2aced 100644 --- a/core/tests/Drupal/Tests/Core/Access/AccessManagerTest.php +++ b/core/tests/Drupal/Tests/Core/Access/AccessManagerTest.php @@ -16,6 +16,7 @@ use Symfony\Cmf\Component\Routing\RouteObjectInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; @@ -83,6 +84,8 @@ class AccessManagerTest extends UnitTestCase { */ protected $argumentsResolver; + protected $requestStack; + public static function getInfo() { return array( 'name' => 'Access manager tests', @@ -131,7 +134,9 @@ protected function setUp() { $this->account = $this->getMock('Drupal\Core\Session\AccountInterface'); $this->argumentsResolver = $this->getMock('Drupal\Core\Access\AccessArgumentsResolverInterface'); - $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver); + $this->requestStack = new RequestStack(); + + $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver, $this->requestStack); $this->accessManager->setContainer($this->container); } @@ -160,7 +165,7 @@ public function testSetChecks() { */ public function testSetChecksWithDynamicAccessChecker() { // Setup the access manager. - $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver); + $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver, $this->requestStack); $this->accessManager->setContainer($this->container); // Setup the dynamic access checker. @@ -415,7 +420,7 @@ public function testCheckNamedRoute() { $this->assertTrue($this->accessManager->checkNamedRoute('test_route_4', array(), $this->account, $request)); // Tests the access with routes without given request. - $this->accessManager->setRequest(new Request()); + $this->requestStack->push(new Request()); $this->paramConverter->expects($this->at(0)) ->method('convert') @@ -462,9 +467,9 @@ public function testCheckNamedRouteWithUpcastedValues() { $subrequest = Request::create('/test-route-1/example'); - $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver); + $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver, $this->requestStack); $this->accessManager->setContainer($this->container); - $this->accessManager->setRequest(new Request()); + $this->requestStack->push(new Request()); $access_check = $this->getMock('Drupal\Tests\Core\Access\TestAccessCheckInterface'); $access_check->expects($this->any()) @@ -516,9 +521,9 @@ public function testCheckNamedRouteWithDefaultValue() { $subrequest = Request::create('/test-route-1/example'); - $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver); + $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver, $this->requestStack); $this->accessManager->setContainer($this->container); - $this->accessManager->setRequest(new Request()); + $this->requestStack->push(new Request()); $access_check = $this->getMock('Drupal\Tests\Core\Access\TestAccessCheckInterface'); $access_check->expects($this->any()) @@ -594,7 +599,7 @@ public function testCheckException($return_value, $access_mode) { ->will($this->returnValue($return_value)); $container->set('test_incorrect_value', $access_check); - $access_manager = new AccessManager($route_provider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver); + $access_manager = new AccessManager($route_provider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver, $this->requestStack); $access_manager->setContainer($container); $access_manager->addCheckService('test_incorrect_value', 'access'); @@ -649,7 +654,7 @@ protected static function convertAccessCheckInterfaceToString($constant) { * Adds a default access check service to the container and the access manager. */ protected function setupAccessChecker() { - $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver); + $this->accessManager = new AccessManager($this->routeProvider, $this->urlGenerator, $this->paramConverter, $this->argumentsResolver, $this->requestStack); $this->accessManager->setContainer($this->container); $access_check = new DefaultAccessCheck(); $this->container->register('test_access_default', $access_check); diff --git a/core/tests/Drupal/Tests/Core/DrupalTest.php b/core/tests/Drupal/Tests/Core/DrupalTest.php index 5ace241..54a5a20 100644 --- a/core/tests/Drupal/Tests/Core/DrupalTest.php +++ b/core/tests/Drupal/Tests/Core/DrupalTest.php @@ -56,14 +56,6 @@ public function testService() { } /** - * Tests the service() method. - */ - public function testRequest() { - $this->setMockContainerService('request'); - $this->assertNotNull(\Drupal::request()); - } - - /** * Tests the currentUser() method. */ public function testCurrentUser() { diff --git a/core/tests/Drupal/Tests/Core/Entity/ContentEntityDatabaseStorageTest.php b/core/tests/Drupal/Tests/Core/Entity/ContentEntityDatabaseStorageTest.php index 0b8f6e2..80c0b88 100644 --- a/core/tests/Drupal/Tests/Core/Entity/ContentEntityDatabaseStorageTest.php +++ b/core/tests/Drupal/Tests/Core/Entity/ContentEntityDatabaseStorageTest.php @@ -1048,7 +1048,7 @@ protected function setUpEntityStorage() { ->disableOriginalConstructor() ->getMock(); - $this->entityManager->expects($this->once()) + $this->entityManager->expects($this->any()) ->method('getBaseFieldDefinitions') ->will($this->returnValue($this->fieldDefinitions)); diff --git a/core/tests/Drupal/Tests/Core/Form/FormTestBase.php b/core/tests/Drupal/Tests/Core/Form/FormTestBase.php index 640ce98..a6c2e76 100644 --- a/core/tests/Drupal/Tests/Core/Form/FormTestBase.php +++ b/core/tests/Drupal/Tests/Core/Form/FormTestBase.php @@ -129,7 +129,7 @@ protected $translationManager; /** - * @var \Drupal\Core\HttpKernel|\PHPUnit_Framework_MockObject_MockObject + * @var \Symfony\Component\HttpKernel\HttpKernel|\PHPUnit_Framework_MockObject_MockObject */ protected $httpKernel; @@ -153,7 +153,7 @@ public function setUp() { $this->csrfToken = $this->getMockBuilder('Drupal\Core\Access\CsrfTokenGenerator') ->disableOriginalConstructor() ->getMock(); - $this->httpKernel = $this->getMockBuilder('Drupal\Core\HttpKernel') + $this->httpKernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel') ->disableOriginalConstructor() ->getMock(); $this->account = $this->getMock('Drupal\Core\Session\AccountInterface'); diff --git a/core/tests/Drupal/Tests/Core/HttpKernelTest.php b/core/tests/Drupal/Tests/Core/HttpKernelTest.php deleted file mode 100644 index 8115ada..0000000 --- a/core/tests/Drupal/Tests/Core/HttpKernelTest.php +++ /dev/null @@ -1,69 +0,0 @@ - 'HttpKernel (Unit)', - 'description' => 'Tests the HttpKernel.', - 'group' => 'Routing', - ); - } - - /** - * Tests the forward method. - * - * @see \Drupal\Core\HttpKernel::setupSubrequest() - */ - public function testSetupSubrequest() { - $container = new ContainerBuilder(); - - $request = new Request(); - $container->addScope(new Scope('request')); - $container->enterScope('request'); - $container->set('request', $request, 'request'); - - $dispatcher = new EventDispatcher(); - $class_resolver = new ClassResolver(); - $class_resolver->setContainer($container); - $controller_resolver = new ControllerResolver($class_resolver); - - $http_kernel = new HttpKernel($dispatcher, $controller_resolver); - $http_kernel->setContainer($container); - - $test_controller = '\Drupal\Tests\Core\Controller\TestController'; - $random_attribute = $this->randomName(); - $subrequest = $http_kernel->setupSubrequest($test_controller, array('custom_attribute' => $random_attribute), array('custom_query' => $random_attribute)); - $this->assertNotSame($subrequest, $request, 'The subrequest is not the same as the main request.'); - $this->assertEquals($subrequest->attributes->get('custom_attribute'), $random_attribute, 'Attributes are set from the subrequest.'); - $this->assertEquals($subrequest->query->get('custom_query'), $random_attribute, 'Query attributes are set from the subrequest.'); - $this->assertEquals($subrequest->attributes->get('_controller'), $test_controller, 'Controller attribute got set.'); - - $subrequest = $http_kernel->setupSubrequest(NULL, array(), array()); - $this->assertFalse($subrequest->attributes->has('_controller'), 'Ensure that _controller is not copied when no controller was set before.'); - } - -} diff --git a/core/tests/Drupal/Tests/Core/Logger/LoggerChannelTest.php b/core/tests/Drupal/Tests/Core/Logger/LoggerChannelTest.php index 51c7e86..3366287 100644 --- a/core/tests/Drupal/Tests/Core/Logger/LoggerChannelTest.php +++ b/core/tests/Drupal/Tests/Core/Logger/LoggerChannelTest.php @@ -11,6 +11,7 @@ use Drupal\Core\Session\AccountInterface; use Drupal\Tests\UnitTestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; // @todo Remove once watchdog() is removed. if (!defined('WATCHDOG_EMERGENCY')) { @@ -63,7 +64,7 @@ public static function getInfo() { * @dataProvider providerTestLog * @covers ::log * @covers ::setCurrentUser - * @covers ::setRequest + * @covers ::setRequestStack */ public function testLog(callable $expected, Request $request = NULL, AccountInterface $current_user = NULL) { $channel = new LoggerChannel('test'); @@ -74,7 +75,9 @@ public function testLog(callable $expected, Request $request = NULL, AccountInte ->with($this->anything(), $message, $this->callback($expected)); $channel->addLogger($logger); if ($request) { - $channel->setRequest($request); + $requestStack = new RequestStack(); + $requestStack->push($request); + $channel->setRequestStack($requestStack); } if ($current_user) { $channel->setCurrentUser($current_user); diff --git a/core/tests/Drupal/Tests/Core/Routing/UrlGeneratorTest.php b/core/tests/Drupal/Tests/Core/Routing/UrlGeneratorTest.php index 5226261..4dd528c 100644 --- a/core/tests/Drupal/Tests/Core/Routing/UrlGeneratorTest.php +++ b/core/tests/Drupal/Tests/Core/Routing/UrlGeneratorTest.php @@ -13,6 +13,7 @@ use Drupal\Core\Site\Settings; use Drupal\Tests\UnitTestCase; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RequestContext; @@ -121,7 +122,7 @@ function setUp() { $this->aliasManager = $alias_manager; $context = new RequestContext(); - $context->fromRequest(Request::create('/some/path')); + $context->fromRequest($request = Request::create('/some/path')); $processor = new PathProcessorAlias($this->aliasManager); $processor_manager = new PathProcessorManager(); @@ -133,12 +134,15 @@ function setUp() { $config_factory_stub = $this->getConfigFactoryStub(array('system.filter' => array('protocols' => array('http', 'https')))); - $generator = new UrlGenerator($provider, $processor_manager, $this->routeProcessorManager, $config_factory_stub, new Settings(array())); + $requestStack = new RequestStack(); + $requestStack->push($request); + + $generator = new UrlGenerator($provider, $processor_manager, $this->routeProcessorManager, $config_factory_stub, new Settings(array()), null, $requestStack); $generator->setContext($context); $this->generator = $generator; // Second generator for mixed-mode sessions. - $generator = new UrlGenerator($provider, $processor_manager, $this->routeProcessorManager, $config_factory_stub, new Settings(array('mixed_mode_sessions' => TRUE))); + $generator = new UrlGenerator($provider, $processor_manager, $this->routeProcessorManager, $config_factory_stub, new Settings(array('mixed_mode_sessions' => TRUE)), null, $requestStack); $generator->setContext($context); $this->generatorMixedMode = $generator; } diff --git a/core/tests/Drupal/Tests/Core/Session/AnonymousUserSessionTest.php b/core/tests/Drupal/Tests/Core/Session/AnonymousUserSessionTest.php index 2fb144d..db93ce7 100644 --- a/core/tests/Drupal/Tests/Core/Session/AnonymousUserSessionTest.php +++ b/core/tests/Drupal/Tests/Core/Session/AnonymousUserSessionTest.php @@ -12,6 +12,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Scope; +use Symfony\Component\HttpFoundation\RequestStack; /** * Tests the AnonymousUserSession class. @@ -44,9 +45,9 @@ public function testAnonymousUserSessionWithRequest() { ->method('getClientIp') ->will($this->returnValue('test')); $container = new ContainerBuilder(); - $container->addScope(new Scope('request')); - $container->enterScope('request'); - $container->set('request', $request, 'request'); + $requestStack = new RequestStack(); + $requestStack->push($request); + $container->set('request_stack', $requestStack); \Drupal::setContainer($container); $anonymous_user = new AnonymousUserSession(); @@ -62,11 +63,6 @@ public function testAnonymousUserSessionWithRequest() { public function testAnonymousUserSessionWithNoRequest() { $container = new ContainerBuilder(); - // Set a synthetic 'request' definition on the container. - $definition = new Definition(); - $definition->setSynthetic(TRUE); - - $container->setDefinition('request', $definition); \Drupal::setContainer($container); $anonymous_user = new AnonymousUserSession(); diff --git a/core/update.php b/core/update.php index b6accf3..a7f3ecc 100644 --- a/core/update.php +++ b/core/update.php @@ -336,13 +336,12 @@ function update_task_list($active = NULL) { $kernel->boot(); $request = Request::createFromGlobals(); $container = \Drupal::getContainer(); -$container->set('request', $request); $container->get('request_stack')->push($request); // Determine if the current user has access to run update.php. drupal_bootstrap(DRUPAL_BOOTSTRAP_PAGE_CACHE); -\Drupal::service('session_manager')->initialize(); +\Drupal::service('session_manager')->startLazy(); // Ensure that URLs generated for the home and admin pages don't have 'update.php' // in them. diff --git a/index.php b/index.php index a453ecc..4d81060 100644 --- a/index.php +++ b/index.php @@ -22,6 +22,10 @@ $rebuild_path = $GLOBALS['base_url'] . '/rebuild.php'; $message .= " or run the rebuild script"; } + + // Set the response code manually. Otherwise, this response will default to a + // 200. + http_response_code(500); print $message; throw $e; }