Session.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace Drupal\Core\StackMiddleware;
  3. use Symfony\Component\DependencyInjection\ContainerAwareTrait;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpKernel\HttpKernelInterface;
  6. /**
  7. * Wrap session logic around a HTTP request.
  8. *
  9. * Note, the session service is not injected into this class in order to prevent
  10. * premature initialization of session storage (database). Instead the session
  11. * service is retrieved from the container only when handling the request.
  12. */
  13. class Session implements HttpKernelInterface {
  14. use ContainerAwareTrait;
  15. /**
  16. * The wrapped HTTP kernel.
  17. *
  18. * @var \Symfony\Component\HttpKernel\HttpKernelInterface
  19. */
  20. protected $httpKernel;
  21. /**
  22. * The session service name.
  23. *
  24. * @var string
  25. */
  26. protected $sessionServiceName;
  27. /**
  28. * Constructs a Session stack middleware object.
  29. *
  30. * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
  31. * The decorated kernel.
  32. * @param string $service_name
  33. * The name of the session service, defaults to "session".
  34. */
  35. public function __construct(HttpKernelInterface $http_kernel, $service_name = 'session') {
  36. $this->httpKernel = $http_kernel;
  37. $this->sessionServiceName = $service_name;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
  43. if ($type === self::MASTER_REQUEST && PHP_SAPI !== 'cli') {
  44. $session = $this->container->get($this->sessionServiceName);
  45. $session->start();
  46. $request->setSession($session);
  47. }
  48. $result = $this->httpKernel->handle($request, $type, $catch);
  49. if ($type === self::MASTER_REQUEST && $request->hasSession()) {
  50. $request->getSession()->save();
  51. }
  52. return $result;
  53. }
  54. }