package and depencies

This commit is contained in:
RafficMohammed
2023-01-08 02:57:24 +05:30
parent d5332eb421
commit 1d54b8bc7f
4309 changed files with 193331 additions and 172289 deletions

View File

@@ -27,12 +27,9 @@ class AcceptHeader
/**
* @var AcceptHeaderItem[]
*/
private $items = [];
private array $items = [];
/**
* @var bool
*/
private $sorted = true;
private bool $sorted = true;
/**
* @param AcceptHeaderItem[] $items
@@ -46,10 +43,8 @@ class AcceptHeader
/**
* Builds an AcceptHeader instance from a string.
*
* @return self
*/
public static function fromString(?string $headerValue)
public static function fromString(?string $headerValue): self
{
$index = 0;
@@ -68,30 +63,24 @@ class AcceptHeader
/**
* Returns header value's string representation.
*
* @return string
*/
public function __toString()
public function __toString(): string
{
return implode(',', $this->items);
}
/**
* Tests if header has given value.
*
* @return bool
*/
public function has(string $value)
public function has(string $value): bool
{
return isset($this->items[$value]);
}
/**
* Returns given value's item, if exists.
*
* @return AcceptHeaderItem|null
*/
public function get(string $value)
public function get(string $value): ?AcceptHeaderItem
{
return $this->items[$value] ?? $this->items[explode('/', $value)[0].'/*'] ?? $this->items['*/*'] ?? $this->items['*'] ?? null;
}
@@ -101,7 +90,7 @@ class AcceptHeader
*
* @return $this
*/
public function add(AcceptHeaderItem $item)
public function add(AcceptHeaderItem $item): static
{
$this->items[$item->getValue()] = $item;
$this->sorted = false;
@@ -114,7 +103,7 @@ class AcceptHeader
*
* @return AcceptHeaderItem[]
*/
public function all()
public function all(): array
{
$this->sort();
@@ -123,10 +112,8 @@ class AcceptHeader
/**
* Filters items on their value using given regex.
*
* @return self
*/
public function filter(string $pattern)
public function filter(string $pattern): self
{
return new self(array_filter($this->items, function (AcceptHeaderItem $item) use ($pattern) {
return preg_match($pattern, $item->getValue());
@@ -135,14 +122,12 @@ class AcceptHeader
/**
* Returns first item.
*
* @return AcceptHeaderItem|null
*/
public function first()
public function first(): ?AcceptHeaderItem
{
$this->sort();
return !empty($this->items) ? reset($this->items) : null;
return $this->items ? reset($this->items) : null;
}
/**

View File

@@ -18,10 +18,10 @@ namespace Symfony\Component\HttpFoundation;
*/
class AcceptHeaderItem
{
private $value;
private $quality = 1.0;
private $index = 0;
private $attributes = [];
private string $value;
private float $quality = 1.0;
private int $index = 0;
private array $attributes = [];
public function __construct(string $value, array $attributes = [])
{
@@ -33,10 +33,8 @@ class AcceptHeaderItem
/**
* Builds an AcceptHeaderInstance instance from a string.
*
* @return self
*/
public static function fromString(?string $itemValue)
public static function fromString(?string $itemValue): self
{
$parts = HeaderUtils::split($itemValue ?? '', ';=');
@@ -48,10 +46,8 @@ class AcceptHeaderItem
/**
* Returns header value's string representation.
*
* @return string
*/
public function __toString()
public function __toString(): string
{
$string = $this->value.($this->quality < 1 ? ';q='.$this->quality : '');
if (\count($this->attributes) > 0) {
@@ -66,7 +62,7 @@ class AcceptHeaderItem
*
* @return $this
*/
public function setValue(string $value)
public function setValue(string $value): static
{
$this->value = $value;
@@ -75,10 +71,8 @@ class AcceptHeaderItem
/**
* Returns the item value.
*
* @return string
*/
public function getValue()
public function getValue(): string
{
return $this->value;
}
@@ -88,7 +82,7 @@ class AcceptHeaderItem
*
* @return $this
*/
public function setQuality(float $quality)
public function setQuality(float $quality): static
{
$this->quality = $quality;
@@ -97,10 +91,8 @@ class AcceptHeaderItem
/**
* Returns the item quality.
*
* @return float
*/
public function getQuality()
public function getQuality(): float
{
return $this->quality;
}
@@ -110,7 +102,7 @@ class AcceptHeaderItem
*
* @return $this
*/
public function setIndex(int $index)
public function setIndex(int $index): static
{
$this->index = $index;
@@ -119,42 +111,32 @@ class AcceptHeaderItem
/**
* Returns the item index.
*
* @return int
*/
public function getIndex()
public function getIndex(): int
{
return $this->index;
}
/**
* Tests if an attribute exists.
*
* @return bool
*/
public function hasAttribute(string $name)
public function hasAttribute(string $name): bool
{
return isset($this->attributes[$name]);
}
/**
* Returns an attribute by its name.
*
* @param mixed $default
*
* @return mixed
*/
public function getAttribute(string $name, $default = null)
public function getAttribute(string $name, mixed $default = null): mixed
{
return $this->attributes[$name] ?? $default;
}
/**
* Returns all attributes.
*
* @return array
*/
public function getAttributes()
public function getAttributes(): array
{
return $this->attributes;
}
@@ -164,7 +146,7 @@ class AcceptHeaderItem
*
* @return $this
*/
public function setAttribute(string $name, string $value)
public function setAttribute(string $name, string $value): static
{
if ('q' === $name) {
$this->quality = (float) $value;

View File

@@ -38,14 +38,14 @@ class BinaryFileResponse extends Response
/**
* @param \SplFileInfo|string $file The file to stream
* @param int $status The response status code
* @param int $status The response status code (200 "OK" by default)
* @param array $headers An array of response headers
* @param bool $public Files are public by default
* @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
* @param bool $autoEtag Whether the ETag header should be automatically set
* @param bool $autoLastModified Whether the Last-Modified header should be automatically set
*/
public function __construct($file, int $status = 200, array $headers = [], bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
public function __construct(\SplFileInfo|string $file, int $status = 200, array $headers = [], bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
{
parent::__construct(null, $status, $headers);
@@ -56,36 +56,14 @@ class BinaryFileResponse extends Response
}
}
/**
* @param \SplFileInfo|string $file The file to stream
* @param int $status The response status code
* @param array $headers An array of response headers
* @param bool $public Files are public by default
* @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
* @param bool $autoEtag Whether the ETag header should be automatically set
* @param bool $autoLastModified Whether the Last-Modified header should be automatically set
*
* @return static
*
* @deprecated since Symfony 5.2, use __construct() instead.
*/
public static function create($file = null, int $status = 200, array $headers = [], bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
{
trigger_deprecation('symfony/http-foundation', '5.2', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class);
return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
}
/**
* Sets the file to stream.
*
* @param \SplFileInfo|string $file The file to stream
*
* @return $this
*
* @throws FileException
*/
public function setFile($file, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
public function setFile(\SplFileInfo|string $file, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true): static
{
if (!$file instanceof File) {
if ($file instanceof \SplFileInfo) {
@@ -118,10 +96,8 @@ class BinaryFileResponse extends Response
/**
* Gets the file.
*
* @return File
*/
public function getFile()
public function getFile(): File
{
return $this->file;
}
@@ -131,7 +107,7 @@ class BinaryFileResponse extends Response
*
* @return $this
*/
public function setChunkSize(int $chunkSize): self
public function setChunkSize(int $chunkSize): static
{
if ($chunkSize < 1 || $chunkSize > \PHP_INT_MAX) {
throw new \LogicException('The chunk size of a BinaryFileResponse cannot be less than 1 or greater than PHP_INT_MAX.');
@@ -147,7 +123,7 @@ class BinaryFileResponse extends Response
*
* @return $this
*/
public function setAutoLastModified()
public function setAutoLastModified(): static
{
$this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
@@ -159,7 +135,7 @@ class BinaryFileResponse extends Response
*
* @return $this
*/
public function setAutoEtag()
public function setAutoEtag(): static
{
$this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
@@ -175,7 +151,7 @@ class BinaryFileResponse extends Response
*
* @return $this
*/
public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = '')
public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = ''): static
{
if ('' === $filename) {
$filename = $this->file->getFilename();
@@ -201,10 +177,7 @@ class BinaryFileResponse extends Response
return $this;
}
/**
* {@inheritdoc}
*/
public function prepare(Request $request)
public function prepare(Request $request): static
{
if ($this->isInformational() || $this->isEmpty()) {
parent::prepare($request);
@@ -248,7 +221,7 @@ class BinaryFileResponse extends Response
$parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
foreach ($parts as $part) {
[$pathPrefix, $location] = $part;
if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
if (str_starts_with($path, $pathPrefix)) {
$path = $location.substr($path, \strlen($pathPrefix));
// Only set X-Accel-Redirect header if a valid URI can be produced
// as nginx does not serve arbitrary file paths.
@@ -316,10 +289,7 @@ class BinaryFileResponse extends Response
return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
}
/**
* {@inheritdoc}
*/
public function sendContent()
public function sendContent(): static
{
try {
if (!$this->isSuccessful()) {
@@ -363,11 +333,9 @@ class BinaryFileResponse extends Response
}
/**
* {@inheritdoc}
*
* @throws \LogicException when the content is not null
*/
public function setContent(?string $content)
public function setContent(?string $content): static
{
if (null !== $content) {
throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
@@ -376,10 +344,7 @@ class BinaryFileResponse extends Response
return $this;
}
/**
* {@inheritdoc}
*/
public function getContent()
public function getContent(): string|false
{
return false;
}
@@ -398,7 +363,7 @@ class BinaryFileResponse extends Response
*
* @return $this
*/
public function deleteFileAfterSend(bool $shouldDelete = true)
public function deleteFileAfterSend(bool $shouldDelete = true): static
{
$this->deleteFileAfterSend = $shouldDelete;

View File

@@ -1,6 +1,40 @@
CHANGELOG
=========
6.2
---
* The HTTP cache store uses the `xxh128` algorithm
* Deprecate calling `JsonResponse::setCallback()`, `Response::setExpires/setLastModified/setEtag()`, `MockArraySessionStorage/NativeSessionStorage::setMetadataBag()`, `NativeSessionStorage::setSaveHandler()` without arguments
* Add request matchers under the `Symfony\Component\HttpFoundation\RequestMatcher` namespace
* Deprecate `RequestMatcher` in favor of `ChainRequestMatcher`
* Deprecate `Symfony\Component\HttpFoundation\ExpressionRequestMatcher` in favor of `Symfony\Component\HttpFoundation\RequestMatcher\ExpressionRequestMatcher`
6.1
---
* Add stale while revalidate and stale if error cache header
* Allow dynamic session "ttl" when using a remote storage
* Deprecate `Request::getContentType()`, use `Request::getContentTypeFormat()` instead
6.0
---
* Remove the `NamespacedAttributeBag` class
* Removed `Response::create()`, `JsonResponse::create()`,
`RedirectResponse::create()`, `StreamedResponse::create()` and
`BinaryFileResponse::create()` methods (use `__construct()` instead)
* Not passing a `Closure` together with `FILTER_CALLBACK` to `ParameterBag::filter()` throws an `\InvalidArgumentException`; wrap your filter in a closure instead
* Not passing a `Closure` together with `FILTER_CALLBACK` to `InputBag::filter()` throws an `\InvalidArgumentException`; wrap your filter in a closure instead
* Removed the `Request::HEADER_X_FORWARDED_ALL` constant, use either `Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO` or `Request::HEADER_X_FORWARDED_AWS_ELB` or `Request::HEADER_X_FORWARDED_TRAEFIK`constants instead
* Rename `RequestStack::getMasterRequest()` to `getMainRequest()`
* Not passing `FILTER_REQUIRE_ARRAY` or `FILTER_FORCE_ARRAY` flags to `InputBag::filter()` when filtering an array will throw `BadRequestException`
* Removed the `Request::HEADER_X_FORWARDED_ALL` constant
* Retrieving non-scalar values using `InputBag::get()` will throw `BadRequestException` (use `InputBad::all()` instead to retrieve an array)
* Passing non-scalar default value as the second argument `InputBag::get()` will throw `\InvalidArgumentException`
* Passing non-scalar, non-array value as the second argument `InputBag::set()` will throw `\InvalidArgumentException`
* Passing `null` as `$requestIp` to `IpUtils::__checkIp()`, `IpUtils::__checkIp4()` or `IpUtils::__checkIp6()` is not supported anymore.
5.4
---
@@ -70,7 +104,7 @@ CHANGELOG
make sure to run `ALTER TABLE sessions MODIFY sess_lifetime INTEGER UNSIGNED NOT NULL` to
update your database.
* `PdoSessionHandler` now precalculates the expiry timestamp in the lifetime column,
make sure to run `CREATE INDEX EXPIRY ON sessions (sess_lifetime)` to update your database
make sure to run `CREATE INDEX expiry ON sessions (sess_lifetime)` to update your database
to speed up garbage collection of expired sessions.
* added `SessionHandlerFactory` to create session handlers with a DSN
* added `IpUtils::anonymize()` to help with GDPR compliance.

View File

@@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
/**
* ChainRequestMatcher verifies that all checks match against a Request instance.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ChainRequestMatcher implements RequestMatcherInterface
{
/**
* @param iterable<RequestMatcherInterface> $matchers
*/
public function __construct(private iterable $matchers)
{
}
public function matches(Request $request): bool
{
foreach ($this->matchers as $matcher) {
if (!$matcher->matches($request)) {
return false;
}
}
return true;
}
}

View File

@@ -30,9 +30,9 @@ class Cookie
protected $secure;
protected $httpOnly;
private $raw;
private $sameSite;
private $secureDefault = false;
private bool $raw;
private ?string $sameSite = null;
private bool $secureDefault = false;
private const RESERVED_CHARS_LIST = "=,; \t\r\n\v\f";
private const RESERVED_CHARS_FROM = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"];
@@ -40,10 +40,8 @@ class Cookie
/**
* Creates cookie from raw header string.
*
* @return static
*/
public static function fromString(string $cookie, bool $decode = false)
public static function fromString(string $cookie, bool $decode = false): static
{
$data = [
'expires' => 0,
@@ -71,7 +69,12 @@ class Cookie
return new static($name, $value, $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']);
}
public static function create(string $name, string $value = null, $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = self::SAMESITE_LAX): self
/**
* @see self::__construct
*
* @param self::SAMESITE_*|''|null $sameSite
*/
public static function create(string $name, string $value = null, int|string|\DateTimeInterface $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = self::SAMESITE_LAX): self
{
return new self($name, $value, $expire, $path, $domain, $secure, $httpOnly, $raw, $sameSite);
}
@@ -85,11 +88,11 @@ class Cookie
* @param bool|null $secure Whether the client should send back the cookie only over HTTPS or null to auto-enable this when the request is already using HTTPS
* @param bool $httpOnly Whether the cookie will be made accessible only through the HTTP protocol
* @param bool $raw Whether the cookie value should be sent with no url encoding
* @param string|null $sameSite Whether the cookie will be available for cross-site requests
* @param self::SAMESITE_*|''|null $sameSite Whether the cookie will be available for cross-site requests
*
* @throws \InvalidArgumentException
*/
public function __construct(string $name, string $value = null, $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = 'lax')
public function __construct(string $name, string $value = null, int|string|\DateTimeInterface $expire = 0, ?string $path = '/', string $domain = null, bool $secure = null, bool $httpOnly = true, bool $raw = false, ?string $sameSite = self::SAMESITE_LAX)
{
// from PHP source code
if ($raw && false !== strpbrk($name, self::RESERVED_CHARS_LIST)) {
@@ -113,10 +116,8 @@ class Cookie
/**
* Creates a cookie copy with a new value.
*
* @return static
*/
public function withValue(?string $value): self
public function withValue(?string $value): static
{
$cookie = clone $this;
$cookie->value = $value;
@@ -126,10 +127,8 @@ class Cookie
/**
* Creates a cookie copy with a new domain that the cookie is available to.
*
* @return static
*/
public function withDomain(?string $domain): self
public function withDomain(?string $domain): static
{
$cookie = clone $this;
$cookie->domain = $domain;
@@ -139,12 +138,8 @@ class Cookie
/**
* Creates a cookie copy with a new time the cookie expires.
*
* @param int|string|\DateTimeInterface $expire
*
* @return static
*/
public function withExpires($expire = 0): self
public function withExpires(int|string|\DateTimeInterface $expire = 0): static
{
$cookie = clone $this;
$cookie->expire = self::expiresTimestamp($expire);
@@ -154,10 +149,8 @@ class Cookie
/**
* Converts expires formats to a unix timestamp.
*
* @param int|string|\DateTimeInterface $expire
*/
private static function expiresTimestamp($expire = 0): int
private static function expiresTimestamp(int|string|\DateTimeInterface $expire = 0): int
{
// convert expiration time to a Unix timestamp
if ($expire instanceof \DateTimeInterface) {
@@ -175,10 +168,8 @@ class Cookie
/**
* Creates a cookie copy with a new path on the server in which the cookie will be available on.
*
* @return static
*/
public function withPath(string $path): self
public function withPath(string $path): static
{
$cookie = clone $this;
$cookie->path = '' === $path ? '/' : $path;
@@ -188,10 +179,8 @@ class Cookie
/**
* Creates a cookie copy that only be transmitted over a secure HTTPS connection from the client.
*
* @return static
*/
public function withSecure(bool $secure = true): self
public function withSecure(bool $secure = true): static
{
$cookie = clone $this;
$cookie->secure = $secure;
@@ -201,10 +190,8 @@ class Cookie
/**
* Creates a cookie copy that be accessible only through the HTTP protocol.
*
* @return static
*/
public function withHttpOnly(bool $httpOnly = true): self
public function withHttpOnly(bool $httpOnly = true): static
{
$cookie = clone $this;
$cookie->httpOnly = $httpOnly;
@@ -214,10 +201,8 @@ class Cookie
/**
* Creates a cookie copy that uses no url encoding.
*
* @return static
*/
public function withRaw(bool $raw = true): self
public function withRaw(bool $raw = true): static
{
if ($raw && false !== strpbrk($this->name, self::RESERVED_CHARS_LIST)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $this->name));
@@ -232,9 +217,9 @@ class Cookie
/**
* Creates a cookie copy with SameSite attribute.
*
* @return static
* @param self::SAMESITE_*|''|null $sameSite
*/
public function withSameSite(?string $sameSite): self
public function withSameSite(?string $sameSite): static
{
if ('' === $sameSite) {
$sameSite = null;
@@ -254,10 +239,8 @@ class Cookie
/**
* Returns the cookie as a string.
*
* @return string
*/
public function __toString()
public function __toString(): string
{
if ($this->isRaw()) {
$str = $this->getName();
@@ -268,12 +251,12 @@ class Cookie
$str .= '=';
if ('' === (string) $this->getValue()) {
$str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0';
$str .= 'deleted; expires='.gmdate('D, d M Y H:i:s T', time() - 31536001).'; Max-Age=0';
} else {
$str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
if (0 !== $this->getExpiresTime()) {
$str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
$str .= '; expires='.gmdate('D, d M Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
}
}
@@ -302,50 +285,40 @@ class Cookie
/**
* Gets the name of the cookie.
*
* @return string
*/
public function getName()
public function getName(): string
{
return $this->name;
}
/**
* Gets the value of the cookie.
*
* @return string|null
*/
public function getValue()
public function getValue(): ?string
{
return $this->value;
}
/**
* Gets the domain that the cookie is available to.
*
* @return string|null
*/
public function getDomain()
public function getDomain(): ?string
{
return $this->domain;
}
/**
* Gets the time the cookie expires.
*
* @return int
*/
public function getExpiresTime()
public function getExpiresTime(): int
{
return $this->expire;
}
/**
* Gets the max-age attribute.
*
* @return int
*/
public function getMaxAge()
public function getMaxAge(): int
{
$maxAge = $this->expire - time();
@@ -354,60 +327,48 @@ class Cookie
/**
* Gets the path on the server in which the cookie will be available on.
*
* @return string
*/
public function getPath()
public function getPath(): string
{
return $this->path;
}
/**
* Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
*
* @return bool
*/
public function isSecure()
public function isSecure(): bool
{
return $this->secure ?? $this->secureDefault;
}
/**
* Checks whether the cookie will be made accessible only through the HTTP protocol.
*
* @return bool
*/
public function isHttpOnly()
public function isHttpOnly(): bool
{
return $this->httpOnly;
}
/**
* Whether this cookie is about to be cleared.
*
* @return bool
*/
public function isCleared()
public function isCleared(): bool
{
return 0 !== $this->expire && $this->expire < time();
}
/**
* Checks if the cookie value should be sent with no url encoding.
*
* @return bool
*/
public function isRaw()
public function isRaw(): bool
{
return $this->raw;
}
/**
* Gets the SameSite attribute.
*
* @return string|null
* @return self::SAMESITE_*|null
*/
public function getSameSite()
public function getSameSite(): ?string
{
return $this->sameSite;
}

View File

@@ -11,27 +11,33 @@
namespace Symfony\Component\HttpFoundation;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\RequestMatcher\ExpressionRequestMatcher as NewExpressionRequestMatcher;
trigger_deprecation('symfony/http-foundation', '6.2', 'The "%s" class is deprecated, use "%s" instead.', ExpressionRequestMatcher::class, NewExpressionRequestMatcher::class);
/**
* ExpressionRequestMatcher uses an expression to match a Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 6.2, use "Symfony\Component\HttpFoundation\RequestMatcher\ExpressionRequestMatcher" instead
*/
class ExpressionRequestMatcher extends RequestMatcher
{
private $language;
private $expression;
private ExpressionLanguage $language;
private Expression|string $expression;
public function setExpression(ExpressionLanguage $language, $expression)
public function setExpression(ExpressionLanguage $language, Expression|string $expression)
{
$this->language = $language;
$this->expression = $expression;
}
public function matches(Request $request)
public function matches(Request $request): bool
{
if (!$this->language) {
if (!isset($this->language)) {
throw new \LogicException('Unable to match the request as the expression language is not available.');
}

View File

@@ -13,7 +13,7 @@ namespace Symfony\Component\HttpFoundation\File\Exception;
class UnexpectedTypeException extends FileException
{
public function __construct($value, string $expectedType)
public function __construct(mixed $value, string $expectedType)
{
parent::__construct(sprintf('Expected argument of type %s, %s given', $expectedType, get_debug_type($value)));
}

View File

@@ -47,12 +47,10 @@ class File extends \SplFileInfo
* This method uses the mime type as guessed by getMimeType()
* to guess the file extension.
*
* @return string|null
*
* @see MimeTypes
* @see getMimeType()
*/
public function guessExtension()
public function guessExtension(): ?string
{
if (!class_exists(MimeTypes::class)) {
throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".');
@@ -68,11 +66,9 @@ class File extends \SplFileInfo
* which uses finfo_file() then the "file" system binary,
* depending on which of those are available.
*
* @return string|null
*
* @see MimeTypes
*/
public function getMimeType()
public function getMimeType(): ?string
{
if (!class_exists(MimeTypes::class)) {
throw new \LogicException('You cannot guess the mime type as the Mime component is not installed. Try running "composer require symfony/mime".');
@@ -84,11 +80,9 @@ class File extends \SplFileInfo
/**
* Moves the file to a new location.
*
* @return self
*
* @throws FileException if the target file could not be created
*/
public function move(string $directory, string $name = null)
public function move(string $directory, string $name = null): self
{
$target = $this->getTargetFile($directory, $name);
@@ -118,10 +112,7 @@ class File extends \SplFileInfo
return $content;
}
/**
* @return self
*/
protected function getTargetFile(string $directory, string $name = null)
protected function getTargetFile(string $directory, string $name = null): self
{
if (!is_dir($directory)) {
if (false === @mkdir($directory, 0777, true) && !is_dir($directory)) {
@@ -138,10 +129,8 @@ class File extends \SplFileInfo
/**
* Returns locale independent base name of the given path.
*
* @return string
*/
protected function getName(string $name)
protected function getName(string $name): string
{
$originalName = str_replace('\\', '/', $name);
$pos = strrpos($originalName, '/');

View File

@@ -18,13 +18,7 @@ namespace Symfony\Component\HttpFoundation\File;
*/
class Stream extends File
{
/**
* {@inheritdoc}
*
* @return int|false
*/
#[\ReturnTypeWillChange]
public function getSize()
public function getSize(): int|false
{
return false;
}

View File

@@ -31,10 +31,10 @@ use Symfony\Component\Mime\MimeTypes;
*/
class UploadedFile extends File
{
private $test;
private $originalName;
private $mimeType;
private $error;
private bool $test;
private string $originalName;
private string $mimeType;
private int $error;
/**
* Accepts the information of the uploaded file as provided by the PHP global $_FILES.
@@ -75,10 +75,8 @@ class UploadedFile extends File
*
* It is extracted from the request from which the file has been uploaded.
* Then it should not be considered as a safe value.
*
* @return string
*/
public function getClientOriginalName()
public function getClientOriginalName(): string
{
return $this->originalName;
}
@@ -88,10 +86,8 @@ class UploadedFile extends File
*
* It is extracted from the original file name that was uploaded.
* Then it should not be considered as a safe value.
*
* @return string
*/
public function getClientOriginalExtension()
public function getClientOriginalExtension(): string
{
return pathinfo($this->originalName, \PATHINFO_EXTENSION);
}
@@ -105,11 +101,9 @@ class UploadedFile extends File
* For a trusted mime type, use getMimeType() instead (which guesses the mime
* type based on the file content).
*
* @return string
*
* @see getMimeType()
*/
public function getClientMimeType()
public function getClientMimeType(): string
{
return $this->mimeType;
}
@@ -126,12 +120,10 @@ class UploadedFile extends File
* For a trusted extension, use guessExtension() instead (which guesses
* the extension based on the guessed mime type for the file).
*
* @return string|null
*
* @see guessExtension()
* @see getClientMimeType()
*/
public function guessClientExtension()
public function guessClientExtension(): ?string
{
if (!class_exists(MimeTypes::class)) {
throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".');
@@ -145,20 +137,16 @@ class UploadedFile extends File
*
* If the upload was successful, the constant UPLOAD_ERR_OK is returned.
* Otherwise one of the other UPLOAD_ERR_XXX constants is returned.
*
* @return int
*/
public function getError()
public function getError(): int
{
return $this->error;
}
/**
* Returns whether the file has been uploaded with HTTP and no error occurred.
*
* @return bool
*/
public function isValid()
public function isValid(): bool
{
$isOk = \UPLOAD_ERR_OK === $this->error;
@@ -168,11 +156,9 @@ class UploadedFile extends File
/**
* Moves the file to a new location.
*
* @return File
*
* @throws FileException if, for any reason, the file could not have been moved
*/
public function move(string $directory, string $name = null)
public function move(string $directory, string $name = null): File
{
if ($this->isValid()) {
if ($this->test) {
@@ -221,7 +207,7 @@ class UploadedFile extends File
*
* @return int|float The maximum size of an uploaded file in bytes (returns float if size > PHP_INT_MAX)
*/
public static function getMaxFilesize()
public static function getMaxFilesize(): int|float
{
$sizePostMax = self::parseFilesize(\ini_get('post_max_size'));
$sizeUploadMax = self::parseFilesize(\ini_get('upload_max_filesize'));
@@ -229,12 +215,7 @@ class UploadedFile extends File
return min($sizePostMax ?: \PHP_INT_MAX, $sizeUploadMax ?: \PHP_INT_MAX);
}
/**
* Returns the given size from an ini value in bytes.
*
* @return int|float Returns float if size > PHP_INT_MAX
*/
private static function parseFilesize(string $size)
private static function parseFilesize(string $size): int|float
{
if ('' === $size) {
return 0;
@@ -266,10 +247,8 @@ class UploadedFile extends File
/**
* Returns an informative upload error message.
*
* @return string
*/
public function getErrorMessage()
public function getErrorMessage(): string
{
static $errors = [
\UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).',

View File

@@ -31,19 +31,13 @@ class FileBag extends ParameterBag
$this->replace($parameters);
}
/**
* {@inheritdoc}
*/
public function replace(array $files = [])
{
$this->parameters = [];
$this->add($files);
}
/**
* {@inheritdoc}
*/
public function set(string $key, $value)
public function set(string $key, mixed $value)
{
if (!\is_array($value) && !$value instanceof UploadedFile) {
throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.');
@@ -52,9 +46,6 @@ class FileBag extends ParameterBag
parent::set($key, $this->convertFileInformation($value));
}
/**
* {@inheritdoc}
*/
public function add(array $files = [])
{
foreach ($files as $key => $file) {
@@ -65,11 +56,9 @@ class FileBag extends ParameterBag
/**
* Converts uploaded files to UploadedFile instances.
*
* @param array|UploadedFile $file A (multi-dimensional) array of uploaded file information
*
* @return UploadedFile[]|UploadedFile|null
*/
protected function convertFileInformation($file)
protected function convertFileInformation(array|UploadedFile $file): array|UploadedFile|null
{
if ($file instanceof UploadedFile) {
return $file;
@@ -106,10 +95,8 @@ class FileBag extends ParameterBag
*
* It's safe to pass an already converted array, in which case this method
* just returns the original array unmodified.
*
* @return array
*/
protected function fixPhpFilesArray(array $data)
protected function fixPhpFilesArray(array $data): array
{
// Remove extra key added by PHP 8.1.
unset($data['full_path']);

View File

@@ -38,10 +38,8 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Returns the headers as a string.
*
* @return string
*/
public function __toString()
public function __toString(): string
{
if (!$headers = $this->all()) {
return '';
@@ -67,7 +65,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*
* @return array<string, array<int, string|null>>|array<int, string|null>
*/
public function all(string $key = null)
public function all(string $key = null): array
{
if (null !== $key) {
return $this->headers[strtr($key, self::UPPER, self::LOWER)] ?? [];
@@ -81,7 +79,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*
* @return string[]
*/
public function keys()
public function keys(): array
{
return array_keys($this->all());
}
@@ -107,10 +105,8 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Returns the first header by name or the default one.
*
* @return string|null
*/
public function get(string $key, string $default = null)
public function get(string $key, string $default = null): ?string
{
$headers = $this->all($key);
@@ -131,7 +127,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
* @param string|string[]|null $values The value or an array of values
* @param bool $replace Whether to replace the actual value or not (true by default)
*/
public function set(string $key, $values, bool $replace = true)
public function set(string $key, string|array|null $values, bool $replace = true)
{
$key = strtr($key, self::UPPER, self::LOWER);
@@ -158,20 +154,16 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Returns true if the HTTP header is defined.
*
* @return bool
*/
public function has(string $key)
public function has(string $key): bool
{
return \array_key_exists(strtr($key, self::UPPER, self::LOWER), $this->all());
}
/**
* Returns true if the given HTTP header contains the given value.
*
* @return bool
*/
public function contains(string $key, string $value)
public function contains(string $key, string $value): bool
{
return \in_array($value, $this->all($key));
}
@@ -193,11 +185,9 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Returns the HTTP header value converted to a date.
*
* @return \DateTimeInterface|null
*
* @throws \RuntimeException When the HTTP header is not parseable
*/
public function getDate(string $key, \DateTime $default = null)
public function getDate(string $key, \DateTime $default = null): ?\DateTimeInterface
{
if (null === $value = $this->get($key)) {
return $default;
@@ -212,10 +202,8 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Adds a custom Cache-Control directive.
*
* @param bool|string $value The Cache-Control directive value
*/
public function addCacheControlDirective(string $key, $value = true)
public function addCacheControlDirective(string $key, bool|string $value = true)
{
$this->cacheControl[$key] = $value;
@@ -224,20 +212,16 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Returns true if the Cache-Control directive is defined.
*
* @return bool
*/
public function hasCacheControlDirective(string $key)
public function hasCacheControlDirective(string $key): bool
{
return \array_key_exists($key, $this->cacheControl);
}
/**
* Returns a Cache-Control directive value by name.
*
* @return bool|string|null
*/
public function getCacheControlDirective(string $key)
public function getCacheControlDirective(string $key): bool|string|null
{
return $this->cacheControl[$key] ?? null;
}
@@ -257,19 +241,15 @@ class HeaderBag implements \IteratorAggregate, \Countable
*
* @return \ArrayIterator<string, list<string|null>>
*/
#[\ReturnTypeWillChange]
public function getIterator()
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->headers);
}
/**
* Returns the number of headers.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return \count($this->headers);
}
@@ -283,10 +263,8 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Parses a Cache-Control HTTP header.
*
* @return array
*/
protected function parseCacheControl(string $header)
protected function parseCacheControl(string $header): array
{
$parts = HeaderUtils::split($header, ',=');

View File

@@ -24,32 +24,22 @@ final class InputBag extends ParameterBag
* Returns a scalar input value by name.
*
* @param string|int|float|bool|null $default The default value if the input key does not exist
*
* @return string|int|float|bool|null
*/
public function get(string $key, $default = null)
public function get(string $key, mixed $default = null): string|int|float|bool|null
{
if (null !== $default && !\is_scalar($default) && !(\is_object($default) && method_exists($default, '__toString'))) {
trigger_deprecation('symfony/http-foundation', '5.1', 'Passing a non-scalar value as 2nd argument to "%s()" is deprecated, pass a scalar or null instead.', __METHOD__);
if (null !== $default && !\is_scalar($default) && !$default instanceof \Stringable) {
throw new \InvalidArgumentException(sprintf('Expected a scalar value as a 2nd argument to "%s()", "%s" given.', __METHOD__, get_debug_type($default)));
}
$value = parent::get($key, $this);
if (null !== $value && $this !== $value && !\is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
trigger_deprecation('symfony/http-foundation', '5.1', 'Retrieving a non-scalar value from "%s()" is deprecated, and will throw a "%s" exception in Symfony 6.0, use "%s::all($key)" instead.', __METHOD__, BadRequestException::class, __CLASS__);
if (null !== $value && $this !== $value && !\is_scalar($value) && !$value instanceof \Stringable) {
throw new BadRequestException(sprintf('Input value "%s" contains a non-scalar value.', $key));
}
return $this === $value ? $default : $value;
}
/**
* {@inheritdoc}
*/
public function all(string $key = null): array
{
return parent::all($key);
}
/**
* Replaces the current input values by a new set.
*/
@@ -74,19 +64,16 @@ final class InputBag extends ParameterBag
*
* @param string|int|float|bool|array|null $value
*/
public function set(string $key, $value)
public function set(string $key, mixed $value)
{
if (null !== $value && !\is_scalar($value) && !\is_array($value) && !method_exists($value, '__toString')) {
trigger_deprecation('symfony/http-foundation', '5.1', 'Passing "%s" as a 2nd Argument to "%s()" is deprecated, pass a scalar, array, or null instead.', get_debug_type($value), __METHOD__);
if (null !== $value && !\is_scalar($value) && !\is_array($value) && !$value instanceof \Stringable) {
throw new \InvalidArgumentException(sprintf('Expected a scalar, or an array as a 2nd argument to "%s()", "%s" given.', __METHOD__, get_debug_type($value)));
}
$this->parameters[$key] = $value;
}
/**
* {@inheritdoc}
*/
public function filter(string $key, $default = null, int $filter = \FILTER_DEFAULT, $options = [])
public function filter(string $key, mixed $default = null, int $filter = \FILTER_DEFAULT, mixed $options = []): mixed
{
$value = $this->has($key) ? $this->all()[$key] : $default;
@@ -96,16 +83,11 @@ final class InputBag extends ParameterBag
}
if (\is_array($value) && !(($options['flags'] ?? 0) & (\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY))) {
trigger_deprecation('symfony/http-foundation', '5.1', 'Filtering an array value with "%s()" without passing the FILTER_REQUIRE_ARRAY or FILTER_FORCE_ARRAY flag is deprecated', __METHOD__);
if (!isset($options['flags'])) {
$options['flags'] = \FILTER_REQUIRE_ARRAY;
}
throw new BadRequestException(sprintf('Input value "%s" contains an array, but "FILTER_REQUIRE_ARRAY" or "FILTER_FORCE_ARRAY" flags were not set.', $key));
}
if ((\FILTER_CALLBACK & $filter) && !(($options['options'] ?? null) instanceof \Closure)) {
trigger_deprecation('symfony/http-foundation', '5.2', 'Not passing a Closure together with FILTER_CALLBACK to "%s()" is deprecated. Wrap your filter in a closure instead.', __METHOD__);
// throw new \InvalidArgumentException(sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null)));
throw new \InvalidArgumentException(sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null)));
}
return filter_var($value, $filter, $options);

View File

@@ -18,7 +18,7 @@ namespace Symfony\Component\HttpFoundation;
*/
class IpUtils
{
private static $checkedIps = [];
private static array $checkedIps = [];
/**
* This class should not be instantiated.
@@ -31,17 +31,9 @@ class IpUtils
* Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets.
*
* @param string|array $ips List of IPs or subnets (can be a string if only a single one)
*
* @return bool
*/
public static function checkIp(?string $requestIp, $ips)
public static function checkIp(string $requestIp, string|array $ips): bool
{
if (null === $requestIp) {
trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
return false;
}
if (!\is_array($ips)) {
$ips = [$ips];
}
@@ -65,14 +57,8 @@ class IpUtils
*
* @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
*/
public static function checkIp4(?string $requestIp, string $ip)
public static function checkIp4(string $requestIp, string $ip): bool
{
if (null === $requestIp) {
trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
return false;
}
$cacheKey = $requestIp.'-'.$ip;
if (isset(self::$checkedIps[$cacheKey])) {
return self::$checkedIps[$cacheKey];
@@ -114,18 +100,10 @@ class IpUtils
*
* @param string $ip IPv6 address or subnet in CIDR notation
*
* @return bool
*
* @throws \RuntimeException When IPV6 support is not enabled
*/
public static function checkIp6(?string $requestIp, string $ip)
public static function checkIp6(string $requestIp, string $ip): bool
{
if (null === $requestIp) {
trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
return false;
}
$cacheKey = $requestIp.'-'.$ip;
if (isset(self::$checkedIps[$cacheKey])) {
return self::$checkedIps[$cacheKey];
@@ -190,7 +168,7 @@ class IpUtils
public static function anonymize(string $ip): string
{
$wrappedIPv6 = false;
if ('[' === substr($ip, 0, 1) && ']' === substr($ip, -1, 1)) {
if (str_starts_with($ip, '[') && str_ends_with($ip, ']')) {
$wrappedIPv6 = true;
$ip = substr($ip, 1, -1);
}

View File

@@ -34,12 +34,9 @@ class JsonResponse extends Response
protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS;
/**
* @param mixed $data The response data
* @param int $status The response status code
* @param array $headers An array of response headers
* @param bool $json If the data is already a JSON string
* @param bool $json If the data is already a JSON string
*/
public function __construct($data = null, int $status = 200, array $headers = [], bool $json = false)
public function __construct(mixed $data = null, int $status = 200, array $headers = [], bool $json = false)
{
parent::__construct('', $status, $headers);
@@ -47,36 +44,11 @@ class JsonResponse extends Response
throw new \TypeError(sprintf('"%s": If $json is set to true, argument $data must be a string or object implementing __toString(), "%s" given.', __METHOD__, get_debug_type($data)));
}
if (null === $data) {
$data = new \ArrayObject();
}
$data ??= new \ArrayObject();
$json ? $this->setJson($data) : $this->setData($data);
}
/**
* Factory method for chainability.
*
* Example:
*
* return JsonResponse::create(['key' => 'value'])
* ->setSharedMaxAge(300);
*
* @param mixed $data The JSON response data
* @param int $status The response status code
* @param array $headers An array of response headers
*
* @return static
*
* @deprecated since Symfony 5.1, use __construct() instead.
*/
public static function create($data = null, int $status = 200, array $headers = [])
{
trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class);
return new static($data, $status, $headers);
}
/**
* Factory method for chainability.
*
@@ -86,12 +58,10 @@ class JsonResponse extends Response
* ->setSharedMaxAge(300);
*
* @param string $data The JSON response string
* @param int $status The response status code
* @param int $status The response status code (200 "OK" by default)
* @param array $headers An array of response headers
*
* @return static
*/
public static function fromJsonString(string $data, int $status = 200, array $headers = [])
public static function fromJsonString(string $data, int $status = 200, array $headers = []): static
{
return new static($data, $status, $headers, true);
}
@@ -105,8 +75,11 @@ class JsonResponse extends Response
*
* @throws \InvalidArgumentException When the callback name is not valid
*/
public function setCallback(string $callback = null)
public function setCallback(string $callback = null): static
{
if (1 > \func_num_args()) {
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
if (null !== $callback) {
// partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/
// partially taken from https://github.com/willdurand/JsonpCallbackValidator
@@ -136,7 +109,7 @@ class JsonResponse extends Response
*
* @return $this
*/
public function setJson(string $json)
public function setJson(string $json): static
{
$this->data = $json;
@@ -146,24 +119,22 @@ class JsonResponse extends Response
/**
* Sets the data to be sent as JSON.
*
* @param mixed $data
*
* @return $this
*
* @throws \InvalidArgumentException
*/
public function setData($data = [])
public function setData(mixed $data = []): static
{
try {
$data = json_encode($data, $this->encodingOptions);
} catch (\Exception $e) {
if ('Exception' === \get_class($e) && str_starts_with($e->getMessage(), 'Failed calling ')) {
if ('Exception' === $e::class && str_starts_with($e->getMessage(), 'Failed calling ')) {
throw $e->getPrevious() ?: $e;
}
throw $e;
}
if (\PHP_VERSION_ID >= 70300 && (\JSON_THROW_ON_ERROR & $this->encodingOptions)) {
if (\JSON_THROW_ON_ERROR & $this->encodingOptions) {
return $this->setJson($data);
}
@@ -176,10 +147,8 @@ class JsonResponse extends Response
/**
* Returns options used while encoding data to JSON.
*
* @return int
*/
public function getEncodingOptions()
public function getEncodingOptions(): int
{
return $this->encodingOptions;
}
@@ -189,7 +158,7 @@ class JsonResponse extends Response
*
* @return $this
*/
public function setEncodingOptions(int $encodingOptions)
public function setEncodingOptions(int $encodingOptions): static
{
$this->encodingOptions = $encodingOptions;
@@ -201,7 +170,7 @@ class JsonResponse extends Response
*
* @return $this
*/
protected function update()
protected function update(): static
{
if (null !== $this->callback) {
// Not using application/javascript for compatibility reasons with older browsers.

View File

@@ -36,13 +36,9 @@ class ParameterBag implements \IteratorAggregate, \Countable
* Returns the parameters.
*
* @param string|null $key The name of the parameter to return or null to get them all
*
* @return array
*/
public function all(/* string $key = null */)
public function all(string $key = null): array
{
$key = \func_num_args() > 0 ? func_get_arg(0) : null;
if (null === $key) {
return $this->parameters;
}
@@ -56,10 +52,8 @@ class ParameterBag implements \IteratorAggregate, \Countable
/**
* Returns the parameter keys.
*
* @return array
*/
public function keys()
public function keys(): array
{
return array_keys($this->parameters);
}
@@ -80,34 +74,20 @@ class ParameterBag implements \IteratorAggregate, \Countable
$this->parameters = array_replace($this->parameters, $parameters);
}
/**
* Returns a parameter by name.
*
* @param mixed $default The default value if the parameter key does not exist
*
* @return mixed
*/
public function get(string $key, $default = null)
public function get(string $key, mixed $default = null): mixed
{
return \array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
}
/**
* Sets a parameter by name.
*
* @param mixed $value The value
*/
public function set(string $key, $value)
public function set(string $key, mixed $value)
{
$this->parameters[$key] = $value;
}
/**
* Returns true if the parameter is defined.
*
* @return bool
*/
public function has(string $key)
public function has(string $key): bool
{
return \array_key_exists($key, $this->parameters);
}
@@ -122,30 +102,24 @@ class ParameterBag implements \IteratorAggregate, \Countable
/**
* Returns the alphabetic characters of the parameter value.
*
* @return string
*/
public function getAlpha(string $key, string $default = '')
public function getAlpha(string $key, string $default = ''): string
{
return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default));
}
/**
* Returns the alphabetic characters and digits of the parameter value.
*
* @return string
*/
public function getAlnum(string $key, string $default = '')
public function getAlnum(string $key, string $default = ''): string
{
return preg_replace('/[^[:alnum:]]/', '', $this->get($key, $default));
}
/**
* Returns the digits of the parameter value.
*
* @return string
*/
public function getDigits(string $key, string $default = '')
public function getDigits(string $key, string $default = ''): string
{
// we need to remove - and + because they're allowed in the filter
return str_replace(['-', '+'], '', $this->filter($key, $default, \FILTER_SANITIZE_NUMBER_INT));
@@ -153,36 +127,28 @@ class ParameterBag implements \IteratorAggregate, \Countable
/**
* Returns the parameter value converted to integer.
*
* @return int
*/
public function getInt(string $key, int $default = 0)
public function getInt(string $key, int $default = 0): int
{
return (int) $this->get($key, $default);
}
/**
* Returns the parameter value converted to boolean.
*
* @return bool
*/
public function getBoolean(string $key, bool $default = false)
public function getBoolean(string $key, bool $default = false): bool
{
return $this->filter($key, $default, \FILTER_VALIDATE_BOOLEAN);
return $this->filter($key, $default, \FILTER_VALIDATE_BOOL);
}
/**
* Filter key.
*
* @param mixed $default Default = null
* @param int $filter FILTER_* constant
* @param mixed $options Filter options
* @param int $filter FILTER_* constant
*
* @see https://php.net/filter-var
*
* @return mixed
*/
public function filter(string $key, $default = null, int $filter = \FILTER_DEFAULT, $options = [])
public function filter(string $key, mixed $default = null, int $filter = \FILTER_DEFAULT, mixed $options = []): mixed
{
$value = $this->get($key, $default);
@@ -197,8 +163,7 @@ class ParameterBag implements \IteratorAggregate, \Countable
}
if ((\FILTER_CALLBACK & $filter) && !(($options['options'] ?? null) instanceof \Closure)) {
trigger_deprecation('symfony/http-foundation', '5.2', 'Not passing a Closure together with FILTER_CALLBACK to "%s()" is deprecated. Wrap your filter in a closure instead.', __METHOD__);
// throw new \InvalidArgumentException(sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null)));
throw new \InvalidArgumentException(sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null)));
}
return filter_var($value, $filter, $options);
@@ -209,19 +174,15 @@ class ParameterBag implements \IteratorAggregate, \Countable
*
* @return \ArrayIterator<string, mixed>
*/
#[\ReturnTypeWillChange]
public function getIterator()
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->parameters);
}
/**
* Returns the number of parameters.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return \count($this->parameters);
}

View File

@@ -4,16 +4,6 @@ HttpFoundation Component
The HttpFoundation component defines an object-oriented layer for the HTTP
specification.
Sponsor
-------
The HttpFoundation component for Symfony 5.4/6.0 is [backed][1] by [Laravel][2].
Laravel is a PHP web development framework that is passionate about maximum developer
happiness. Laravel is built using a variety of bespoke and Symfony based components.
Help Symfony by [sponsoring][3] its development!
Resources
---------
@@ -22,7 +12,3 @@ Resources
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
[1]: https://symfony.com/backers
[2]: https://laravel.com/
[3]: https://symfony.com/sponsor

View File

@@ -17,14 +17,24 @@ use Symfony\Component\RateLimiter\Policy\NoLimiter;
use Symfony\Component\RateLimiter\RateLimit;
/**
* An implementation of RequestRateLimiterInterface that
* An implementation of PeekableRequestRateLimiterInterface that
* fits most use-cases.
*
* @author Wouter de Jong <wouter@wouterj.nl>
*/
abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface
abstract class AbstractRequestRateLimiter implements PeekableRequestRateLimiterInterface
{
public function consume(Request $request): RateLimit
{
return $this->doConsume($request, 1);
}
public function peek(Request $request): RateLimit
{
return $this->doConsume($request, 0);
}
private function doConsume(Request $request, int $tokens): RateLimit
{
$limiters = $this->getLimiters($request);
if (0 === \count($limiters)) {
@@ -33,7 +43,7 @@ abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface
$minimalRateLimit = null;
foreach ($limiters as $limiter) {
$rateLimit = $limiter->consume(1);
$rateLimit = $limiter->consume($tokens);
$minimalRateLimit = $minimalRateLimit ? self::getMinimalRateLimit($minimalRateLimit, $rateLimit) : $rateLimit;
}

View File

@@ -0,0 +1,35 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RateLimiter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\RateLimiter\RateLimit;
/**
* A request limiter which allows peeking ahead.
*
* This is valuable to reduce the cache backend load in scenarios
* like a login when we only want to consume a token on login failure,
* and where the majority of requests will be successful and thus not
* need to consume a token.
*
* This way we can peek ahead before allowing the request through, and
* only consume if the request failed (1 backend op). This is compared
* to always consuming and then resetting the limit if the request
* is successful (2 backend ops).
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface PeekableRequestRateLimiterInterface extends RequestRateLimiterInterface
{
public function peek(Request $request): RateLimit;
}

View File

@@ -25,7 +25,7 @@ class RedirectResponse extends Response
*
* @param string $url The URL to redirect to. The URL should be a full URL, with schema etc.,
* but practically every browser redirects on paths only as well
* @param int $status The status code (302 by default)
* @param int $status The HTTP status code (302 "Found" by default)
* @param array $headers The headers (Location is always set to the given URL)
*
* @throws \InvalidArgumentException
@@ -47,28 +47,10 @@ class RedirectResponse extends Response
}
}
/**
* Factory method for chainability.
*
* @param string $url The URL to redirect to
*
* @return static
*
* @deprecated since Symfony 5.1, use __construct() instead.
*/
public static function create($url = '', int $status = 302, array $headers = [])
{
trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class);
return new static($url, $status, $headers);
}
/**
* Returns the target URL.
*
* @return string
*/
public function getTargetUrl()
public function getTargetUrl(): string
{
return $this->targetUrl;
}
@@ -80,7 +62,7 @@ class RedirectResponse extends Response
*
* @throws \InvalidArgumentException
*/
public function setTargetUrl(string $url)
public function setTargetUrl(string $url): static
{
if ('' === $url) {
throw new \InvalidArgumentException('Cannot redirect to an empty URL.');

View File

@@ -48,8 +48,6 @@ class Request
public const HEADER_X_FORWARDED_PORT = 0b010000;
public const HEADER_X_FORWARDED_PREFIX = 0b100000;
/** @deprecated since Symfony 5.2, use either "HEADER_X_FORWARDED_FOR | HEADER_X_FORWARDED_HOST | HEADER_X_FORWARDED_PORT | HEADER_X_FORWARDED_PROTO" or "HEADER_X_FORWARDED_AWS_ELB" or "HEADER_X_FORWARDED_TRAEFIK" constants instead. */
public const HEADER_X_FORWARDED_ALL = 0b1011110; // All "X-Forwarded-*" headers sent by "usual" reverse proxy
public const HEADER_X_FORWARDED_AWS_ELB = 0b0011010; // AWS ELB doesn't send X-Forwarded-Host
public const HEADER_X_FORWARDED_TRAEFIK = 0b0111110; // All "X-Forwarded-*" headers sent by Traefik reverse proxy
@@ -136,22 +134,22 @@ class Request
protected $content;
/**
* @var array
* @var string[]
*/
protected $languages;
/**
* @var array
* @var string[]
*/
protected $charsets;
/**
* @var array
* @var string[]
*/
protected $encodings;
/**
* @var array
* @var string[]
*/
protected $acceptableContentTypes;
@@ -201,25 +199,18 @@ class Request
protected $defaultLocale = 'en';
/**
* @var array
* @var array<string, string[]>
*/
protected static $formats;
protected static $requestFactory;
/**
* @var string|null
*/
private $preferredFormat;
private $isHostValid = true;
private $isForwardedValid = true;
private ?string $preferredFormat = null;
private bool $isHostValid = true;
private bool $isForwardedValid = true;
private bool $isSafeContentPreferred;
/**
* @var bool|null
*/
private $isSafeContentPreferred;
private static $trustedHeaderSet = -1;
private static int $trustedHeaderSet = -1;
private const FORWARDED_PARAMS = [
self::HEADER_X_FORWARDED_FOR => 'for',
@@ -298,10 +289,8 @@ class Request
/**
* Creates a new request with values from PHP's super globals.
*
* @return static
*/
public static function createFromGlobals()
public static function createFromGlobals(): static
{
$request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER);
@@ -328,10 +317,8 @@ class Request
* @param array $files The request files ($_FILES)
* @param array $server The server parameters ($_SERVER)
* @param string|resource|null $content The raw body data
*
* @return static
*/
public static function create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null)
public static function create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null): static
{
$server = array_replace([
'SERVER_NAME' => 'localhost',
@@ -445,10 +432,8 @@ class Request
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
*
* @return static
*/
public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null): static
{
$dup = clone $this;
if (null !== $query) {
@@ -509,12 +494,7 @@ class Request
$this->headers = clone $this->headers;
}
/**
* Returns the request as a string.
*
* @return string
*/
public function __toString()
public function __toString(): string
{
$content = $this->getContent();
@@ -584,9 +564,6 @@ class Request
*/
public static function setTrustedProxies(array $proxies, int $trustedHeaderSet)
{
if (self::HEADER_X_FORWARDED_ALL === $trustedHeaderSet) {
trigger_deprecation('symfony/http-foundation', '5.2', 'The "HEADER_X_FORWARDED_ALL" constant is deprecated, use either "HEADER_X_FORWARDED_FOR | HEADER_X_FORWARDED_HOST | HEADER_X_FORWARDED_PORT | HEADER_X_FORWARDED_PROTO" or "HEADER_X_FORWARDED_AWS_ELB" or "HEADER_X_FORWARDED_TRAEFIK" constants instead.');
}
self::$trustedProxies = array_reduce($proxies, function ($proxies, $proxy) {
if ('REMOTE_ADDR' !== $proxy) {
$proxies[] = $proxy;
@@ -602,9 +579,9 @@ class Request
/**
* Gets the list of trusted proxies.
*
* @return array
* @return string[]
*/
public static function getTrustedProxies()
public static function getTrustedProxies(): array
{
return self::$trustedProxies;
}
@@ -614,7 +591,7 @@ class Request
*
* @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies
*/
public static function getTrustedHeaderSet()
public static function getTrustedHeaderSet(): int
{
return self::$trustedHeaderSet;
}
@@ -638,9 +615,9 @@ class Request
/**
* Gets the list of trusted host patterns.
*
* @return array
* @return string[]
*/
public static function getTrustedHosts()
public static function getTrustedHosts(): array
{
return self::$trustedHostPatterns;
}
@@ -650,10 +627,8 @@ class Request
*
* It builds a normalized query string, where keys/value pairs are alphabetized,
* have consistent escaping and unneeded delimiters are removed.
*
* @return string
*/
public static function normalizeQueryString(?string $qs)
public static function normalizeQueryString(?string $qs): string
{
if ('' === ($qs ?? '')) {
return '';
@@ -683,10 +658,8 @@ class Request
/**
* Checks whether support for the _method request parameter is enabled.
*
* @return bool
*/
public static function getHttpMethodParameterOverride()
public static function getHttpMethodParameterOverride(): bool
{
return self::$httpMethodParameterOverride;
}
@@ -700,13 +673,9 @@ class Request
*
* Order of precedence: PATH (routing placeholders or custom attributes), GET, POST
*
* @param mixed $default The default value if the parameter key does not exist
*
* @return mixed
*
* @internal since Symfony 5.4, use explicit input sources instead
* @internal use explicit input sources instead
*/
public function get(string $key, $default = null)
public function get(string $key, mixed $default = null): mixed
{
if ($this !== $result = $this->attributes->get($key, $this)) {
return $result;
@@ -726,9 +695,9 @@ class Request
/**
* Gets the Session.
*
* @return SessionInterface
* @throws SessionNotFoundException When session is not set properly
*/
public function getSession()
public function getSession(): SessionInterface
{
$session = $this->session;
if (!$session instanceof SessionInterface && null !== $session) {
@@ -745,10 +714,8 @@ class Request
/**
* Whether the request contains a Session which was started in one of the
* previous requests.
*
* @return bool
*/
public function hasPreviousSession()
public function hasPreviousSession(): bool
{
// the check for $this->session avoids malicious users trying to fake a session cookie with proper name
return $this->hasSession() && $this->cookies->has($this->getSession()->getName());
@@ -762,13 +729,9 @@ class Request
* is associated with a Session instance.
*
* @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory`
*
* @return bool
*/
public function hasSession(/* bool $skipIfUninitialized = false */)
public function hasSession(bool $skipIfUninitialized = false): bool
{
$skipIfUninitialized = \func_num_args() > 0 ? func_get_arg(0) : false;
return null !== $this->session && (!$skipIfUninitialized || $this->session instanceof SessionInterface);
}
@@ -796,11 +759,9 @@ class Request
*
* Use this method carefully; you should use getClientIp() instead.
*
* @return array
*
* @see getClientIp()
*/
public function getClientIps()
public function getClientIps(): array
{
$ip = $this->server->get('REMOTE_ADDR');
@@ -824,12 +785,10 @@ class Request
* ("Client-Ip" for instance), configure it via the $trustedHeaderSet
* argument of the Request::setTrustedProxies() method instead.
*
* @return string|null
*
* @see getClientIps()
* @see https://wikipedia.org/wiki/X-Forwarded-For
*/
public function getClientIp()
public function getClientIp(): ?string
{
$ipAddresses = $this->getClientIps();
@@ -838,10 +797,8 @@ class Request
/**
* Returns current script name.
*
* @return string
*/
public function getScriptName()
public function getScriptName(): string
{
return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
}
@@ -860,13 +817,9 @@ class Request
*
* @return string The raw path (i.e. not urldecoded)
*/
public function getPathInfo()
public function getPathInfo(): string
{
if (null === $this->pathInfo) {
$this->pathInfo = $this->preparePathInfo();
}
return $this->pathInfo;
return $this->pathInfo ??= $this->preparePathInfo();
}
/**
@@ -881,13 +834,9 @@ class Request
*
* @return string The raw path (i.e. not urldecoded)
*/
public function getBasePath()
public function getBasePath(): string
{
if (null === $this->basePath) {
$this->basePath = $this->prepareBasePath();
}
return $this->basePath;
return $this->basePath ??= $this->prepareBasePath();
}
/**
@@ -900,7 +849,7 @@ class Request
*
* @return string The raw URL (i.e. not urldecoded)
*/
public function getBaseUrl()
public function getBaseUrl(): string
{
$trustedPrefix = '';
@@ -920,19 +869,13 @@ class Request
*/
private function getBaseUrlReal(): string
{
if (null === $this->baseUrl) {
$this->baseUrl = $this->prepareBaseUrl();
}
return $this->baseUrl;
return $this->baseUrl ??= $this->prepareBaseUrl();
}
/**
* Gets the request's scheme.
*
* @return string
*/
public function getScheme()
public function getScheme(): string
{
return $this->isSecure() ? 'https' : 'http';
}
@@ -947,7 +890,7 @@ class Request
*
* @return int|string|null Can be a string if fetched from the server bag
*/
public function getPort()
public function getPort(): int|string|null
{
if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_PORT)) {
$host = $host[0];
@@ -972,20 +915,16 @@ class Request
/**
* Returns the user.
*
* @return string|null
*/
public function getUser()
public function getUser(): ?string
{
return $this->headers->get('PHP_AUTH_USER');
}
/**
* Returns the password.
*
* @return string|null
*/
public function getPassword()
public function getPassword(): ?string
{
return $this->headers->get('PHP_AUTH_PW');
}
@@ -995,7 +934,7 @@ class Request
*
* @return string|null A user name if any and, optionally, scheme-specific information about how to gain authorization to access the server
*/
public function getUserInfo()
public function getUserInfo(): ?string
{
$userinfo = $this->getUser();
@@ -1011,15 +950,13 @@ class Request
* Returns the HTTP host being requested.
*
* The port name will be appended to the host if it's non-standard.
*
* @return string
*/
public function getHttpHost()
public function getHttpHost(): string
{
$scheme = $this->getScheme();
$port = $this->getPort();
if (('http' == $scheme && 80 == $port) || ('https' == $scheme && 443 == $port)) {
if (('http' === $scheme && 80 == $port) || ('https' === $scheme && 443 == $port)) {
return $this->getHost();
}
@@ -1031,13 +968,9 @@ class Request
*
* @return string The raw URI (i.e. not URI decoded)
*/
public function getRequestUri()
public function getRequestUri(): string
{
if (null === $this->requestUri) {
$this->requestUri = $this->prepareRequestUri();
}
return $this->requestUri;
return $this->requestUri ??= $this->prepareRequestUri();
}
/**
@@ -1045,10 +978,8 @@ class Request
*
* If the URL was called with basic authentication, the user
* and the password are not added to the generated string.
*
* @return string
*/
public function getSchemeAndHttpHost()
public function getSchemeAndHttpHost(): string
{
return $this->getScheme().'://'.$this->getHttpHost();
}
@@ -1056,11 +987,9 @@ class Request
/**
* Generates a normalized URI (URL) for the Request.
*
* @return string
*
* @see getQueryString()
*/
public function getUri()
public function getUri(): string
{
if (null !== $qs = $this->getQueryString()) {
$qs = '?'.$qs;
@@ -1073,10 +1002,8 @@ class Request
* Generates a normalized URI for the given path.
*
* @param string $path A path to use instead of the current one
*
* @return string
*/
public function getUriForPath(string $path)
public function getUriForPath(string $path): string
{
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
}
@@ -1095,10 +1022,8 @@ class Request
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*
* @return string
*/
public function getRelativeUriForPath(string $path)
public function getRelativeUriForPath(string $path): string
{
// be sure that we are dealing with an absolute path
if (!isset($path[0]) || '/' !== $path[0]) {
@@ -1139,10 +1064,8 @@ class Request
*
* It builds a normalized query string, where keys/value pairs are alphabetized
* and have consistent escaping.
*
* @return string|null
*/
public function getQueryString()
public function getQueryString(): ?string
{
$qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
@@ -1156,10 +1079,8 @@ class Request
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
*
* @return bool
*/
public function isSecure()
public function isSecure(): bool
{
if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) {
return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true);
@@ -1178,11 +1099,9 @@ class Request
*
* The "X-Forwarded-Host" header must contain the client host name.
*
* @return string
*
* @throws SuspiciousOperationException when the host name is invalid or not trusted
*/
public function getHost()
public function getHost(): string
{
if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
$host = $host[0];
@@ -1254,11 +1173,9 @@ class Request
*
* The method is always an uppercased string.
*
* @return string
*
* @see getRealMethod()
*/
public function getMethod()
public function getMethod(): string
{
if (null !== $this->method) {
return $this->method;
@@ -1296,21 +1213,17 @@ class Request
/**
* Gets the "real" request method.
*
* @return string
*
* @see getMethod()
*/
public function getRealMethod()
public function getRealMethod(): string
{
return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
}
/**
* Gets the mime type associated with the format.
*
* @return string|null
*/
public function getMimeType(string $format)
public function getMimeType(string $format): ?string
{
if (null === static::$formats) {
static::initializeFormats();
@@ -1322,9 +1235,9 @@ class Request
/**
* Gets the mime types associated with the format.
*
* @return array
* @return string[]
*/
public static function getMimeTypes(string $format)
public static function getMimeTypes(string $format): array
{
if (null === static::$formats) {
static::initializeFormats();
@@ -1335,10 +1248,8 @@ class Request
/**
* Gets the format associated with the mime type.
*
* @return string|null
*/
public function getFormat(?string $mimeType)
public function getFormat(?string $mimeType): ?string
{
$canonicalMimeType = null;
if ($mimeType && false !== $pos = strpos($mimeType, ';')) {
@@ -1364,9 +1275,9 @@ class Request
/**
* Associates a format with mime types.
*
* @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
* @param string|string[] $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
*/
public function setFormat(?string $format, $mimeTypes)
public function setFormat(?string $format, string|array $mimeTypes)
{
if (null === static::$formats) {
static::initializeFormats();
@@ -1385,14 +1296,10 @@ class Request
* * $default
*
* @see getPreferredFormat
*
* @return string|null
*/
public function getRequestFormat(?string $default = 'html')
public function getRequestFormat(?string $default = 'html'): ?string
{
if (null === $this->format) {
$this->format = $this->attributes->get('_format');
}
$this->format ??= $this->attributes->get('_format');
return $this->format ?? $default;
}
@@ -1406,11 +1313,23 @@ class Request
}
/**
* Gets the format associated with the request.
* Gets the usual name of the format associated with the request's media type (provided in the Content-Type header).
*
* @return string|null
* @deprecated since Symfony 6.2, use getContentTypeFormat() instead
*/
public function getContentType()
public function getContentType(): ?string
{
trigger_deprecation('symfony/http-foundation', '6.2', 'The "%s()" method is deprecated, use "getContentTypeFormat()" instead.', __METHOD__);
return $this->getContentTypeFormat();
}
/**
* Gets the usual name of the format associated with the request's media type (provided in the Content-Type header).
*
* @see Request::$formats
*/
public function getContentTypeFormat(): ?string
{
return $this->getFormat($this->headers->get('CONTENT_TYPE', ''));
}
@@ -1429,10 +1348,8 @@ class Request
/**
* Get the default locale.
*
* @return string
*/
public function getDefaultLocale()
public function getDefaultLocale(): string
{
return $this->defaultLocale;
}
@@ -1447,10 +1364,8 @@ class Request
/**
* Get the locale.
*
* @return string
*/
public function getLocale()
public function getLocale(): string
{
return null === $this->locale ? $this->defaultLocale : $this->locale;
}
@@ -1459,10 +1374,8 @@ class Request
* Checks if the request method is of specified type.
*
* @param string $method Uppercase request method (GET, POST etc)
*
* @return bool
*/
public function isMethod(string $method)
public function isMethod(string $method): bool
{
return $this->getMethod() === strtoupper($method);
}
@@ -1471,20 +1384,16 @@ class Request
* Checks whether or not the method is safe.
*
* @see https://tools.ietf.org/html/rfc7231#section-4.2.1
*
* @return bool
*/
public function isMethodSafe()
public function isMethodSafe(): bool
{
return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']);
}
/**
* Checks whether or not the method is idempotent.
*
* @return bool
*/
public function isMethodIdempotent()
public function isMethodIdempotent(): bool
{
return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']);
}
@@ -1493,10 +1402,8 @@ class Request
* Checks whether the method is cacheable or not.
*
* @see https://tools.ietf.org/html/rfc7231#section-4.2.3
*
* @return bool
*/
public function isMethodCacheable()
public function isMethodCacheable(): bool
{
return \in_array($this->getMethod(), ['GET', 'HEAD']);
}
@@ -1509,10 +1416,8 @@ class Request
* server might be different. This returns the former (from the "Via" header)
* if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns
* the latter (from the "SERVER_PROTOCOL" server parameter).
*
* @return string|null
*/
public function getProtocolVersion()
public function getProtocolVersion(): ?string
{
if ($this->isFromTrustedProxy()) {
preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via') ?? '', $matches);
@@ -1531,6 +1436,7 @@ class Request
* @param bool $asResource If true, a resource will be returned
*
* @return string|resource
* @psalm-return ($asResource is true ? resource : string)
*/
public function getContent(bool $asResource = false)
{
@@ -1574,25 +1480,19 @@ class Request
* Gets the request body decoded as array, typically from a JSON payload.
*
* @throws JsonException When the body cannot be decoded to an array
*
* @return array
*/
public function toArray()
public function toArray(): array
{
if ('' === $content = $this->getContent()) {
throw new JsonException('Request body is empty.');
}
try {
$content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0));
$content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new JsonException('Could not decode request body.', $e->getCode(), $e);
}
if (\PHP_VERSION_ID < 70300 && \JSON_ERROR_NONE !== json_last_error()) {
throw new JsonException('Could not decode request body: '.json_last_error_msg(), json_last_error());
}
if (!\is_array($content)) {
throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned.', get_debug_type($content)));
}
@@ -1602,18 +1502,13 @@ class Request
/**
* Gets the Etags.
*
* @return array
*/
public function getETags()
public function getETags(): array
{
return preg_split('/\s*,\s*/', $this->headers->get('If-None-Match', ''), -1, \PREG_SPLIT_NO_EMPTY);
}
/**
* @return bool
*/
public function isNoCache()
public function isNoCache(): bool
{
return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
}
@@ -1645,10 +1540,8 @@ class Request
* Returns the preferred language.
*
* @param string[] $locales An array of ordered available locales
*
* @return string|null
*/
public function getPreferredLanguage(array $locales = null)
public function getPreferredLanguage(array $locales = null): ?string
{
$preferredLanguages = $this->getLanguages();
@@ -1679,9 +1572,9 @@ class Request
/**
* Gets a list of languages acceptable by the client browser ordered in the user browser preferences.
*
* @return array
* @return string[]
*/
public function getLanguages()
public function getLanguages(): array
{
if (null !== $this->languages) {
return $this->languages;
@@ -1720,9 +1613,9 @@ class Request
/**
* Gets a list of charsets acceptable by the client browser in preferable order.
*
* @return array
* @return string[]
*/
public function getCharsets()
public function getCharsets(): array
{
if (null !== $this->charsets) {
return $this->charsets;
@@ -1734,9 +1627,9 @@ class Request
/**
* Gets a list of encodings acceptable by the client browser in preferable order.
*
* @return array
* @return string[]
*/
public function getEncodings()
public function getEncodings(): array
{
if (null !== $this->encodings) {
return $this->encodings;
@@ -1748,9 +1641,9 @@ class Request
/**
* Gets a list of content types acceptable by the client browser in preferable order.
*
* @return array
* @return string[]
*/
public function getAcceptableContentTypes()
public function getAcceptableContentTypes(): array
{
if (null !== $this->acceptableContentTypes) {
return $this->acceptableContentTypes;
@@ -1766,10 +1659,8 @@ class Request
* It is known to work with common JavaScript frameworks:
*
* @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
*
* @return bool
*/
public function isXmlHttpRequest()
public function isXmlHttpRequest(): bool
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}
@@ -1781,7 +1672,7 @@ class Request
*/
public function preferSafeContent(): bool
{
if (null !== $this->isSafeContentPreferred) {
if (isset($this->isSafeContentPreferred)) {
return $this->isSafeContentPreferred;
}
@@ -1848,10 +1739,8 @@ class Request
/**
* Prepares the base URL.
*
* @return string
*/
protected function prepareBaseUrl()
protected function prepareBaseUrl(): string
{
$filename = basename($this->server->get('SCRIPT_FILENAME', ''));
@@ -1917,10 +1806,8 @@ class Request
/**
* Prepares the base path.
*
* @return string
*/
protected function prepareBasePath()
protected function prepareBasePath(): string
{
$baseUrl = $this->getBaseUrl();
if (empty($baseUrl)) {
@@ -1943,10 +1830,8 @@ class Request
/**
* Prepares the path info.
*
* @return string
*/
protected function preparePathInfo()
protected function preparePathInfo(): string
{
if (null === ($requestUri = $this->getRequestUri())) {
return '/';
@@ -2002,7 +1887,7 @@ class Request
if (class_exists(\Locale::class, false)) {
\Locale::setDefault($locale);
}
} catch (\Exception $e) {
} catch (\Exception) {
}
}
@@ -2025,7 +1910,7 @@ class Request
return null;
}
private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): self
private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): static
{
if (self::$requestFactory) {
$request = (self::$requestFactory)($query, $request, $attributes, $cookies, $files, $server, $content);
@@ -2045,10 +1930,8 @@ class Request
*
* This can be useful to determine whether or not to trust the
* contents of a proxy-specific header.
*
* @return bool
*/
public function isFromTrustedProxy()
public function isFromTrustedProxy(): bool
{
return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR', ''), self::$trustedProxies);
}
@@ -2136,9 +2019,7 @@ class Request
unset($clientIps[$key]);
// Fallback to this when the client IP falls into the range of trusted proxies
if (null === $firstTrustedIp) {
$firstTrustedIp = $clientIp;
}
$firstTrustedIp ??= $clientIp;
}
}

View File

@@ -11,54 +11,47 @@
namespace Symfony\Component\HttpFoundation;
trigger_deprecation('symfony/http-foundation', '6.2', 'The "%s" class is deprecated, use "%s" instead.', RequestMatcher::class, ChainRequestMatcher::class);
/**
* RequestMatcher compares a pre-defined set of checks against a Request instance.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 6.2, use ChainRequestMatcher instead
*/
class RequestMatcher implements RequestMatcherInterface
{
/**
* @var string|null
*/
private $path;
/**
* @var string|null
*/
private $host;
/**
* @var int|null
*/
private $port;
private ?string $path = null;
private ?string $host = null;
private ?int $port = null;
/**
* @var string[]
*/
private $methods = [];
private array $methods = [];
/**
* @var string[]
*/
private $ips = [];
/**
* @var array
*/
private $attributes = [];
private array $ips = [];
/**
* @var string[]
*/
private $schemes = [];
private array $attributes = [];
/**
* @var string[]
*/
private array $schemes = [];
/**
* @param string|string[]|null $methods
* @param string|string[]|null $ips
* @param string|string[]|null $schemes
*/
public function __construct(string $path = null, string $host = null, $methods = null, $ips = null, array $attributes = [], $schemes = null, int $port = null)
public function __construct(string $path = null, string $host = null, string|array $methods = null, string|array $ips = null, array $attributes = [], string|array $schemes = null, int $port = null)
{
$this->matchPath($path);
$this->matchHost($host);
@@ -77,7 +70,7 @@ class RequestMatcher implements RequestMatcherInterface
*
* @param string|string[]|null $scheme An HTTP scheme or an array of HTTP schemes
*/
public function matchScheme($scheme)
public function matchScheme(string|array|null $scheme)
{
$this->schemes = null !== $scheme ? array_map('strtolower', (array) $scheme) : [];
}
@@ -123,7 +116,7 @@ class RequestMatcher implements RequestMatcherInterface
*
* @param string|string[]|null $ips A specific IP address or a range specified using IP/netmask like 192.168.1.0/24
*/
public function matchIps($ips)
public function matchIps(string|array|null $ips)
{
$ips = null !== $ips ? (array) $ips : [];
@@ -137,7 +130,7 @@ class RequestMatcher implements RequestMatcherInterface
*
* @param string|string[]|null $method An HTTP method or an array of HTTP methods
*/
public function matchMethod($method)
public function matchMethod(string|array|null $method)
{
$this->methods = null !== $method ? array_map('strtoupper', (array) $method) : [];
}
@@ -150,10 +143,7 @@ class RequestMatcher implements RequestMatcherInterface
$this->attributes[$key] = $regexp;
}
/**
* {@inheritdoc}
*/
public function matches(Request $request)
public function matches(Request $request): bool
{
if ($this->schemes && !\in_array($request->getScheme(), $this->schemes, true)) {
return false;

View File

@@ -0,0 +1,45 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the Request attributes matches all regular expressions.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AttributesRequestMatcher implements RequestMatcherInterface
{
/**
* @param array<string, string> $regexps
*/
public function __construct(private array $regexps)
{
}
public function matches(Request $request): bool
{
foreach ($this->regexps as $key => $regexp) {
$attribute = $request->attributes->get($key);
if (!\is_string($attribute)) {
return false;
}
if (!preg_match('{'.$regexp.'}', $attribute)) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,43 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* ExpressionRequestMatcher uses an expression to match a Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExpressionRequestMatcher implements RequestMatcherInterface
{
public function __construct(
private ExpressionLanguage $language,
private Expression|string $expression,
) {
}
public function matches(Request $request): bool
{
return $this->language->evaluate($this->expression, [
'request' => $request,
'method' => $request->getMethod(),
'path' => rawurldecode($request->getPathInfo()),
'host' => $request->getHost(),
'ip' => $request->getClientIp(),
'attributes' => $request->attributes->all(),
]);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the Request URL host name matches a regular expression.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class HostRequestMatcher implements RequestMatcherInterface
{
public function __construct(private string $regexp)
{
}
public function matches(Request $request): bool
{
return preg_match('{'.$this->regexp.'}i', $request->getHost());
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the client IP of a Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class IpsRequestMatcher implements RequestMatcherInterface
{
private array $ips;
/**
* @param string[]|string $ips A specific IP address or a range specified using IP/netmask like 192.168.1.0/24
* Strings can contain a comma-delimited list of IPs/ranges
*/
public function __construct(array|string $ips)
{
$this->ips = array_reduce((array) $ips, static function (array $ips, string $ip) {
return array_merge($ips, preg_split('/\s*,\s*/', $ip));
}, []);
}
public function matches(Request $request): bool
{
if (!$this->ips) {
return true;
}
return IpUtils::checkIp($request->getClientIp() ?? '', $this->ips);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the Request content is valid JSON.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class IsJsonRequestMatcher implements RequestMatcherInterface
{
public function matches(Request $request): bool
{
try {
json_decode($request->getContent(), true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the HTTP method of a Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class MethodRequestMatcher implements RequestMatcherInterface
{
/**
* @var string[]
*/
private array $methods = [];
/**
* @param string[]|string $methods An HTTP method or an array of HTTP methods
* Strings can contain a comma-delimited list of methods
*/
public function __construct(array|string $methods)
{
$this->methods = array_reduce(array_map('strtoupper', (array) $methods), static function (array $methods, string $method) {
return array_merge($methods, preg_split('/\s*,\s*/', $method));
}, []);
}
public function matches(Request $request): bool
{
if (!$this->methods) {
return true;
}
return \in_array($request->getMethod(), $this->methods, true);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the Request URL path info matches a regular expression.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class PathRequestMatcher implements RequestMatcherInterface
{
public function __construct(private string $regexp)
{
}
public function matches(Request $request): bool
{
return preg_match('{'.$this->regexp.'}', rawurldecode($request->getPathInfo()));
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the HTTP port of a Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class PortRequestMatcher implements RequestMatcherInterface
{
public function __construct(private int $port)
{
}
public function matches(Request $request): bool
{
return $request->getPort() === $this->port;
}
}

View File

@@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Checks the HTTP scheme of a Request.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SchemeRequestMatcher implements RequestMatcherInterface
{
/**
* @var string[]
*/
private array $schemes;
/**
* @param string[]|string $schemes A scheme or a list of schemes
* Strings can contain a comma-delimited list of schemes
*/
public function __construct(array|string $schemes)
{
$this->schemes = array_reduce(array_map('strtolower', (array) $schemes), static function (array $schemes, string $scheme) {
return array_merge($schemes, preg_split('/\s*,\s*/', $scheme));
}, []);
}
public function matches(Request $request): bool
{
if (!$this->schemes) {
return true;
}
return \in_array($request->getScheme(), $this->schemes, true);
}
}

View File

@@ -20,8 +20,6 @@ interface RequestMatcherInterface
{
/**
* Decides whether the rule(s) implemented by the strategy matches the supplied request.
*
* @return bool
*/
public function matches(Request $request);
public function matches(Request $request): bool;
}

View File

@@ -24,7 +24,7 @@ class RequestStack
/**
* @var Request[]
*/
private $requests = [];
private array $requests = [];
/**
* Pushes a Request on the stack.
@@ -44,10 +44,8 @@ class RequestStack
*
* This method should generally not be called directly as the stack
* management should be taken care of by the application itself.
*
* @return Request|null
*/
public function pop()
public function pop(): ?Request
{
if (!$this->requests) {
return null;
@@ -56,10 +54,7 @@ class RequestStack
return array_pop($this->requests);
}
/**
* @return Request|null
*/
public function getCurrentRequest()
public function getCurrentRequest(): ?Request
{
return end($this->requests) ?: null;
}
@@ -80,20 +75,6 @@ class RequestStack
return $this->requests[0];
}
/**
* Gets the master request.
*
* @return Request|null
*
* @deprecated since symfony/http-foundation 5.3, use getMainRequest() instead
*/
public function getMasterRequest()
{
trigger_deprecation('symfony/http-foundation', '5.3', '"%s()" is deprecated, use "getMainRequest()" instead.', __METHOD__);
return $this->getMainRequest();
}
/**
* Returns the parent request of the current.
*
@@ -102,10 +83,8 @@ class RequestStack
* like ESI support.
*
* If current Request is the main request, it returns null.
*
* @return Request|null
*/
public function getParentRequest()
public function getParentRequest(): ?Request
{
$pos = \count($this->requests) - 2;

View File

@@ -98,6 +98,8 @@ class Response
'proxy_revalidate' => false,
'max_age' => true,
's_maxage' => true,
'stale_if_error' => true, // RFC5861
'stale_while_revalidate' => true, // RFC5861
'immutable' => false,
'last_modified' => true,
'etag' => true,
@@ -210,6 +212,8 @@ class Response
];
/**
* @param int $status The HTTP status code (200 "OK" by default)
*
* @throws \InvalidArgumentException When the HTTP status code is not valid
*/
public function __construct(?string $content = '', int $status = 200, array $headers = [])
@@ -220,25 +224,6 @@ class Response
$this->setProtocolVersion('1.0');
}
/**
* Factory method for chainability.
*
* Example:
*
* return Response::create($body, 200)
* ->setSharedMaxAge(300);
*
* @return static
*
* @deprecated since Symfony 5.1, use __construct() instead.
*/
public static function create(?string $content = '', int $status = 200, array $headers = [])
{
trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class);
return new static($content, $status, $headers);
}
/**
* Returns the Response as an HTTP string.
*
@@ -246,11 +231,9 @@ class Response
* one that will be sent to the client only if the prepare() method
* has been called before.
*
* @return string
*
* @see prepare()
*/
public function __toString()
public function __toString(): string
{
return
sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
@@ -275,7 +258,7 @@ class Response
*
* @return $this
*/
public function prepare(Request $request)
public function prepare(Request $request): static
{
$headers = $this->headers;
@@ -345,7 +328,7 @@ class Response
*
* @return $this
*/
public function sendHeaders()
public function sendHeaders(): static
{
// headers have already been sent by the developer
if (headers_sent()) {
@@ -376,7 +359,7 @@ class Response
*
* @return $this
*/
public function sendContent()
public function sendContent(): static
{
echo $this->content;
@@ -388,7 +371,7 @@ class Response
*
* @return $this
*/
public function send()
public function send(): static
{
$this->sendHeaders();
$this->sendContent();
@@ -410,7 +393,7 @@ class Response
*
* @return $this
*/
public function setContent(?string $content)
public function setContent(?string $content): static
{
$this->content = $content ?? '';
@@ -419,10 +402,8 @@ class Response
/**
* Gets the current response content.
*
* @return string|false
*/
public function getContent()
public function getContent(): string|false
{
return $this->content;
}
@@ -434,7 +415,7 @@ class Response
*
* @final
*/
public function setProtocolVersion(string $version): object
public function setProtocolVersion(string $version): static
{
$this->version = $version;
@@ -463,7 +444,7 @@ class Response
*
* @final
*/
public function setStatusCode(int $code, string $text = null): object
public function setStatusCode(int $code, string $text = null): static
{
$this->statusCode = $code;
if ($this->isInvalid()) {
@@ -504,7 +485,7 @@ class Response
*
* @final
*/
public function setCharset(string $charset): object
public function setCharset(string $charset): static
{
$this->charset = $charset;
@@ -585,7 +566,7 @@ class Response
*
* @final
*/
public function setPrivate(): object
public function setPrivate(): static
{
$this->headers->removeCacheControlDirective('public');
$this->headers->addCacheControlDirective('private');
@@ -602,7 +583,7 @@ class Response
*
* @final
*/
public function setPublic(): object
public function setPublic(): static
{
$this->headers->addCacheControlDirective('public');
$this->headers->removeCacheControlDirective('private');
@@ -617,7 +598,7 @@ class Response
*
* @final
*/
public function setImmutable(bool $immutable = true): object
public function setImmutable(bool $immutable = true): static
{
if ($immutable) {
$this->headers->addCacheControlDirective('immutable');
@@ -672,7 +653,7 @@ class Response
*
* @final
*/
public function setDate(\DateTimeInterface $date): object
public function setDate(\DateTimeInterface $date): static
{
if ($date instanceof \DateTime) {
$date = \DateTimeImmutable::createFromMutable($date);
@@ -703,7 +684,7 @@ class Response
*
* @return $this
*/
public function expire()
public function expire(): static
{
if ($this->isFresh()) {
$this->headers->set('Age', $this->getMaxAge());
@@ -722,7 +703,7 @@ class Response
{
try {
return $this->headers->getDate('Expires');
} catch (\RuntimeException $e) {
} catch (\RuntimeException) {
// according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
return \DateTime::createFromFormat('U', time() - 172800);
}
@@ -737,8 +718,11 @@ class Response
*
* @final
*/
public function setExpires(\DateTimeInterface $date = null): object
public function setExpires(\DateTimeInterface $date = null): static
{
if (1 > \func_num_args()) {
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
if (null === $date) {
$this->headers->remove('Expires');
@@ -790,13 +774,45 @@ class Response
*
* @final
*/
public function setMaxAge(int $value): object
public function setMaxAge(int $value): static
{
$this->headers->addCacheControlDirective('max-age', $value);
return $this;
}
/**
* Sets the number of seconds after which the response should no longer be returned by shared caches when backend is down.
*
* This method sets the Cache-Control stale-if-error directive.
*
* @return $this
*
* @final
*/
public function setStaleIfError(int $value): static
{
$this->headers->addCacheControlDirective('stale-if-error', $value);
return $this;
}
/**
* Sets the number of seconds after which the response should no longer return stale content by shared caches.
*
* This method sets the Cache-Control stale-while-revalidate directive.
*
* @return $this
*
* @final
*/
public function setStaleWhileRevalidate(int $value): static
{
$this->headers->addCacheControlDirective('stale-while-revalidate', $value);
return $this;
}
/**
* Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
*
@@ -806,7 +822,7 @@ class Response
*
* @final
*/
public function setSharedMaxAge(int $value): object
public function setSharedMaxAge(int $value): static
{
$this->setPublic();
$this->headers->addCacheControlDirective('s-maxage', $value);
@@ -840,7 +856,7 @@ class Response
*
* @final
*/
public function setTtl(int $seconds): object
public function setTtl(int $seconds): static
{
$this->setSharedMaxAge($this->getAge() + $seconds);
@@ -856,7 +872,7 @@ class Response
*
* @final
*/
public function setClientTtl(int $seconds): object
public function setClientTtl(int $seconds): static
{
$this->setMaxAge($this->getAge() + $seconds);
@@ -884,8 +900,11 @@ class Response
*
* @final
*/
public function setLastModified(\DateTimeInterface $date = null): object
public function setLastModified(\DateTimeInterface $date = null): static
{
if (1 > \func_num_args()) {
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
if (null === $date) {
$this->headers->remove('Last-Modified');
@@ -922,8 +941,11 @@ class Response
*
* @final
*/
public function setEtag(string $etag = null, bool $weak = false): object
public function setEtag(string $etag = null, bool $weak = false): static
{
if (1 > \func_num_args()) {
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
if (null === $etag) {
$this->headers->remove('Etag');
} else {
@@ -948,7 +970,7 @@ class Response
*
* @final
*/
public function setCache(array $options): object
public function setCache(array $options): static
{
if ($diff = array_diff(array_keys($options), array_keys(self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES))) {
throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff)));
@@ -970,6 +992,14 @@ class Response
$this->setSharedMaxAge($options['s_maxage']);
}
if (isset($options['stale_while_revalidate'])) {
$this->setStaleWhileRevalidate($options['stale_while_revalidate']);
}
if (isset($options['stale_if_error'])) {
$this->setStaleIfError($options['stale_if_error']);
}
foreach (self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES as $directive => $hasValue) {
if (!$hasValue && isset($options[$directive])) {
if ($options[$directive]) {
@@ -1011,7 +1041,7 @@ class Response
*
* @final
*/
public function setNotModified(): object
public function setNotModified(): static
{
$this->setStatusCode(304);
$this->setContent(null);
@@ -1056,14 +1086,13 @@ class Response
/**
* Sets the Vary header.
*
* @param string|array $headers
* @param bool $replace Whether to replace the actual value or not (true by default)
* @param bool $replace Whether to replace the actual value or not (true by default)
*
* @return $this
*
* @final
*/
public function setVary($headers, bool $replace = true): object
public function setVary(string|array $headers, bool $replace = true): static
{
$this->headers->set('Vary', $headers, $replace);

View File

@@ -44,10 +44,8 @@ class ResponseHeaderBag extends HeaderBag
/**
* Returns the headers, with original capitalizations.
*
* @return array
*/
public function allPreserveCase()
public function allPreserveCase(): array
{
$headers = [];
foreach ($this->all() as $name => $value) {
@@ -67,9 +65,6 @@ class ResponseHeaderBag extends HeaderBag
return $headers;
}
/**
* {@inheritdoc}
*/
public function replace(array $headers = [])
{
$this->headerNames = [];
@@ -85,10 +80,7 @@ class ResponseHeaderBag extends HeaderBag
}
}
/**
* {@inheritdoc}
*/
public function all(string $key = null)
public function all(string $key = null): array
{
$headers = parent::all();
@@ -105,10 +97,7 @@ class ResponseHeaderBag extends HeaderBag
return $headers;
}
/**
* {@inheritdoc}
*/
public function set(string $key, $values, bool $replace = true)
public function set(string $key, string|array|null $values, bool $replace = true)
{
$uniqueKey = strtr($key, self::UPPER, self::LOWER);
@@ -136,9 +125,6 @@ class ResponseHeaderBag extends HeaderBag
}
}
/**
* {@inheritdoc}
*/
public function remove(string $key)
{
$uniqueKey = strtr($key, self::UPPER, self::LOWER);
@@ -161,18 +147,12 @@ class ResponseHeaderBag extends HeaderBag
}
}
/**
* {@inheritdoc}
*/
public function hasCacheControlDirective(string $key)
public function hasCacheControlDirective(string $key): bool
{
return \array_key_exists($key, $this->computedCacheControl);
}
/**
* {@inheritdoc}
*/
public function getCacheControlDirective(string $key)
public function getCacheControlDirective(string $key): bool|string|null
{
return $this->computedCacheControl[$key] ?? null;
}
@@ -188,9 +168,7 @@ class ResponseHeaderBag extends HeaderBag
*/
public function removeCookie(string $name, ?string $path = '/', string $domain = null)
{
if (null === $path) {
$path = '/';
}
$path ??= '/';
unset($this->cookies[$domain][$path][$name]);
@@ -214,7 +192,7 @@ class ResponseHeaderBag extends HeaderBag
*
* @throws \InvalidArgumentException When the $format is invalid
*/
public function getCookies(string $format = self::COOKIES_FLAT)
public function getCookies(string $format = self::COOKIES_FLAT): array
{
if (!\in_array($format, [self::COOKIES_FLAT, self::COOKIES_ARRAY])) {
throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', [self::COOKIES_FLAT, self::COOKIES_ARRAY])));
@@ -257,10 +235,8 @@ class ResponseHeaderBag extends HeaderBag
*
* This considers several other headers and calculates or modifies the
* cache-control header to a sensible, conservative value.
*
* @return string
*/
protected function computeCacheControlValue()
protected function computeCacheControlValue(): string
{
if (!$this->cacheControl) {
if ($this->has('Last-Modified') || $this->has('Expires')) {

View File

@@ -22,10 +22,8 @@ class ServerBag extends ParameterBag
{
/**
* Gets the HTTP headers.
*
* @return array
*/
public function getHeaders()
public function getHeaders(): array
{
$headers = [];
foreach ($this->parameters as $key => $value) {

View File

@@ -18,8 +18,8 @@ namespace Symfony\Component\HttpFoundation\Session\Attribute;
*/
class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Countable
{
private $name = 'attributes';
private $storageKey;
private string $name = 'attributes';
private string $storageKey;
protected $attributes = [];
@@ -31,10 +31,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
$this->storageKey = $storageKey;
}
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -44,57 +41,36 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function initialize(array &$attributes)
{
$this->attributes = &$attributes;
}
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
/**
* {@inheritdoc}
*/
public function has(string $name)
public function has(string $name): bool
{
return \array_key_exists($name, $this->attributes);
}
/**
* {@inheritdoc}
*/
public function get(string $name, $default = null)
public function get(string $name, mixed $default = null): mixed
{
return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default;
}
/**
* {@inheritdoc}
*/
public function set(string $name, $value)
public function set(string $name, mixed $value)
{
$this->attributes[$name] = $value;
}
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
return $this->attributes;
}
/**
* {@inheritdoc}
*/
public function replace(array $attributes)
{
$this->attributes = [];
@@ -103,10 +79,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
}
}
/**
* {@inheritdoc}
*/
public function remove(string $name)
public function remove(string $name): mixed
{
$retval = null;
if (\array_key_exists($name, $this->attributes)) {
@@ -117,10 +90,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
return $retval;
}
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
$return = $this->attributes;
$this->attributes = [];
@@ -133,19 +103,15 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
*
* @return \ArrayIterator<string, mixed>
*/
#[\ReturnTypeWillChange]
public function getIterator()
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->attributes);
}
/**
* Returns the number of attributes.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return \count($this->attributes);
}

View File

@@ -22,33 +22,25 @@ interface AttributeBagInterface extends SessionBagInterface
{
/**
* Checks if an attribute is defined.
*
* @return bool
*/
public function has(string $name);
public function has(string $name): bool;
/**
* Returns an attribute.
*
* @param mixed $default The default value if not found
*
* @return mixed
*/
public function get(string $name, $default = null);
public function get(string $name, mixed $default = null): mixed;
/**
* Sets an attribute.
*
* @param mixed $value
*/
public function set(string $name, $value);
public function set(string $name, mixed $value);
/**
* Returns attributes.
*
* @return array<string, mixed>
*/
public function all();
public function all(): array;
public function replace(array $attributes);
@@ -57,5 +49,5 @@ interface AttributeBagInterface extends SessionBagInterface
*
* @return mixed The removed value or null when it does not exist
*/
public function remove(string $name);
public function remove(string $name): mixed;
}

View File

@@ -1,161 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Session\Attribute;
trigger_deprecation('symfony/http-foundation', '5.3', 'The "%s" class is deprecated.', NamespacedAttributeBag::class);
/**
* This class provides structured storage of session attributes using
* a name spacing character in the key.
*
* @author Drak <drak@zikula.org>
*
* @deprecated since Symfony 5.3
*/
class NamespacedAttributeBag extends AttributeBag
{
private $namespaceCharacter;
/**
* @param string $storageKey Session storage key
* @param string $namespaceCharacter Namespace character to use in keys
*/
public function __construct(string $storageKey = '_sf2_attributes', string $namespaceCharacter = '/')
{
$this->namespaceCharacter = $namespaceCharacter;
parent::__construct($storageKey);
}
/**
* {@inheritdoc}
*/
public function has(string $name)
{
// reference mismatch: if fixed, re-introduced in array_key_exists; keep as it is
$attributes = $this->resolveAttributePath($name);
$name = $this->resolveKey($name);
if (null === $attributes) {
return false;
}
return \array_key_exists($name, $attributes);
}
/**
* {@inheritdoc}
*/
public function get(string $name, $default = null)
{
// reference mismatch: if fixed, re-introduced in array_key_exists; keep as it is
$attributes = $this->resolveAttributePath($name);
$name = $this->resolveKey($name);
if (null === $attributes) {
return $default;
}
return \array_key_exists($name, $attributes) ? $attributes[$name] : $default;
}
/**
* {@inheritdoc}
*/
public function set(string $name, $value)
{
$attributes = &$this->resolveAttributePath($name, true);
$name = $this->resolveKey($name);
$attributes[$name] = $value;
}
/**
* {@inheritdoc}
*/
public function remove(string $name)
{
$retval = null;
$attributes = &$this->resolveAttributePath($name);
$name = $this->resolveKey($name);
if (null !== $attributes && \array_key_exists($name, $attributes)) {
$retval = $attributes[$name];
unset($attributes[$name]);
}
return $retval;
}
/**
* Resolves a path in attributes property and returns it as a reference.
*
* This method allows structured namespacing of session attributes.
*
* @param string $name Key name
* @param bool $writeContext Write context, default false
*
* @return array|null
*/
protected function &resolveAttributePath(string $name, bool $writeContext = false)
{
$array = &$this->attributes;
$name = (str_starts_with($name, $this->namespaceCharacter)) ? substr($name, 1) : $name;
// Check if there is anything to do, else return
if (!$name) {
return $array;
}
$parts = explode($this->namespaceCharacter, $name);
if (\count($parts) < 2) {
if (!$writeContext) {
return $array;
}
$array[$parts[0]] = [];
return $array;
}
unset($parts[\count($parts) - 1]);
foreach ($parts as $part) {
if (null !== $array && !\array_key_exists($part, $array)) {
if (!$writeContext) {
$null = null;
return $null;
}
$array[$part] = [];
}
$array = &$array[$part];
}
return $array;
}
/**
* Resolves the key from the name.
*
* This is the last part in a dot separated string.
*
* @return string
*/
protected function resolveKey(string $name)
{
if (false !== $pos = strrpos($name, $this->namespaceCharacter)) {
$name = substr($name, $pos + 1);
}
return $name;
}
}

View File

@@ -18,9 +18,9 @@ namespace Symfony\Component\HttpFoundation\Session\Flash;
*/
class AutoExpireFlashBag implements FlashBagInterface
{
private $name = 'flashes';
private $flashes = ['display' => [], 'new' => []];
private $storageKey;
private string $name = 'flashes';
private array $flashes = ['display' => [], 'new' => []];
private string $storageKey;
/**
* @param string $storageKey The key used to store flashes in the session
@@ -30,10 +30,7 @@ class AutoExpireFlashBag implements FlashBagInterface
$this->storageKey = $storageKey;
}
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -43,9 +40,6 @@ class AutoExpireFlashBag implements FlashBagInterface
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function initialize(array &$flashes)
{
$this->flashes = &$flashes;
@@ -57,34 +51,22 @@ class AutoExpireFlashBag implements FlashBagInterface
$this->flashes['new'] = [];
}
/**
* {@inheritdoc}
*/
public function add(string $type, $message)
public function add(string $type, mixed $message)
{
$this->flashes['new'][$type][] = $message;
}
/**
* {@inheritdoc}
*/
public function peek(string $type, array $default = [])
public function peek(string $type, array $default = []): array
{
return $this->has($type) ? $this->flashes['display'][$type] : $default;
}
/**
* {@inheritdoc}
*/
public function peekAll()
public function peekAll(): array
{
return \array_key_exists('display', $this->flashes) ? $this->flashes['display'] : [];
}
/**
* {@inheritdoc}
*/
public function get(string $type, array $default = [])
public function get(string $type, array $default = []): array
{
$return = $default;
@@ -100,10 +82,7 @@ class AutoExpireFlashBag implements FlashBagInterface
return $return;
}
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
$return = $this->flashes['display'];
$this->flashes['display'] = [];
@@ -111,50 +90,32 @@ class AutoExpireFlashBag implements FlashBagInterface
return $return;
}
/**
* {@inheritdoc}
*/
public function setAll(array $messages)
{
$this->flashes['new'] = $messages;
}
/**
* {@inheritdoc}
*/
public function set(string $type, $messages)
public function set(string $type, string|array $messages)
{
$this->flashes['new'][$type] = (array) $messages;
}
/**
* {@inheritdoc}
*/
public function has(string $type)
public function has(string $type): bool
{
return \array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type];
}
/**
* {@inheritdoc}
*/
public function keys()
public function keys(): array
{
return array_keys($this->flashes['display']);
}
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
return $this->all();
}

View File

@@ -18,9 +18,9 @@ namespace Symfony\Component\HttpFoundation\Session\Flash;
*/
class FlashBag implements FlashBagInterface
{
private $name = 'flashes';
private $flashes = [];
private $storageKey;
private string $name = 'flashes';
private array $flashes = [];
private string $storageKey;
/**
* @param string $storageKey The key used to store flashes in the session
@@ -30,10 +30,7 @@ class FlashBag implements FlashBagInterface
$this->storageKey = $storageKey;
}
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -43,42 +40,27 @@ class FlashBag implements FlashBagInterface
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function initialize(array &$flashes)
{
$this->flashes = &$flashes;
}
/**
* {@inheritdoc}
*/
public function add(string $type, $message)
public function add(string $type, mixed $message)
{
$this->flashes[$type][] = $message;
}
/**
* {@inheritdoc}
*/
public function peek(string $type, array $default = [])
public function peek(string $type, array $default = []): array
{
return $this->has($type) ? $this->flashes[$type] : $default;
}
/**
* {@inheritdoc}
*/
public function peekAll()
public function peekAll(): array
{
return $this->flashes;
}
/**
* {@inheritdoc}
*/
public function get(string $type, array $default = [])
public function get(string $type, array $default = []): array
{
if (!$this->has($type)) {
return $default;
@@ -91,10 +73,7 @@ class FlashBag implements FlashBagInterface
return $return;
}
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
$return = $this->peekAll();
$this->flashes = [];
@@ -102,50 +81,32 @@ class FlashBag implements FlashBagInterface
return $return;
}
/**
* {@inheritdoc}
*/
public function set(string $type, $messages)
public function set(string $type, string|array $messages)
{
$this->flashes[$type] = (array) $messages;
}
/**
* {@inheritdoc}
*/
public function setAll(array $messages)
{
$this->flashes = $messages;
}
/**
* {@inheritdoc}
*/
public function has(string $type)
public function has(string $type): bool
{
return \array_key_exists($type, $this->flashes) && $this->flashes[$type];
}
/**
* {@inheritdoc}
*/
public function keys()
public function keys(): array
{
return array_keys($this->flashes);
}
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
return $this->all();
}

View File

@@ -22,50 +22,38 @@ interface FlashBagInterface extends SessionBagInterface
{
/**
* Adds a flash message for the given type.
*
* @param mixed $message
*/
public function add(string $type, $message);
public function add(string $type, mixed $message);
/**
* Registers one or more messages for a given type.
*
* @param string|array $messages
*/
public function set(string $type, $messages);
public function set(string $type, string|array $messages);
/**
* Gets flash messages for a given type.
*
* @param string $type Message category type
* @param array $default Default value if $type does not exist
*
* @return array
*/
public function peek(string $type, array $default = []);
public function peek(string $type, array $default = []): array;
/**
* Gets all flash messages.
*
* @return array
*/
public function peekAll();
public function peekAll(): array;
/**
* Gets and clears flash from the stack.
*
* @param array $default Default value if $type does not exist
*
* @return array
*/
public function get(string $type, array $default = []);
public function get(string $type, array $default = []): array;
/**
* Gets and clears flashes from the stack.
*
* @return array
*/
public function all();
public function all(): array;
/**
* Sets all flash messages.
@@ -74,15 +62,11 @@ interface FlashBagInterface extends SessionBagInterface
/**
* Has flash messages for a given type?
*
* @return bool
*/
public function has(string $type);
public function has(string $type): bool;
/**
* Returns a list of all defined types.
*
* @return array
*/
public function keys();
public function keys(): array;
}

View File

@@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Session;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
/**
* Interface for session with a flashbag.
*/
interface FlashBagAwareSessionInterface extends SessionInterface
{
public function getFlashBag(): FlashBagInterface;
}

View File

@@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
@@ -29,98 +30,71 @@ class_exists(SessionBagProxy::class);
*
* @implements \IteratorAggregate<string, mixed>
*/
class Session implements SessionInterface, \IteratorAggregate, \Countable
class Session implements FlashBagAwareSessionInterface, \IteratorAggregate, \Countable
{
protected $storage;
private $flashName;
private $attributeName;
private $data = [];
private $usageIndex = 0;
private $usageReporter;
private string $flashName;
private string $attributeName;
private array $data = [];
private int $usageIndex = 0;
private ?\Closure $usageReporter;
public function __construct(SessionStorageInterface $storage = null, AttributeBagInterface $attributes = null, FlashBagInterface $flashes = null, callable $usageReporter = null)
{
$this->storage = $storage ?? new NativeSessionStorage();
$this->usageReporter = $usageReporter;
$this->usageReporter = null === $usageReporter ? null : $usageReporter(...);
$attributes = $attributes ?? new AttributeBag();
$attributes ??= new AttributeBag();
$this->attributeName = $attributes->getName();
$this->registerBag($attributes);
$flashes = $flashes ?? new FlashBag();
$flashes ??= new FlashBag();
$this->flashName = $flashes->getName();
$this->registerBag($flashes);
}
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
return $this->storage->start();
}
/**
* {@inheritdoc}
*/
public function has(string $name)
public function has(string $name): bool
{
return $this->getAttributeBag()->has($name);
}
/**
* {@inheritdoc}
*/
public function get(string $name, $default = null)
public function get(string $name, mixed $default = null): mixed
{
return $this->getAttributeBag()->get($name, $default);
}
/**
* {@inheritdoc}
*/
public function set(string $name, $value)
public function set(string $name, mixed $value)
{
$this->getAttributeBag()->set($name, $value);
}
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
return $this->getAttributeBag()->all();
}
/**
* {@inheritdoc}
*/
public function replace(array $attributes)
{
$this->getAttributeBag()->replace($attributes);
}
/**
* {@inheritdoc}
*/
public function remove(string $name)
public function remove(string $name): mixed
{
return $this->getAttributeBag()->remove($name);
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->getAttributeBag()->clear();
}
/**
* {@inheritdoc}
*/
public function isStarted()
public function isStarted(): bool
{
return $this->storage->isStarted();
}
@@ -130,19 +104,15 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
*
* @return \ArrayIterator<string, mixed>
*/
#[\ReturnTypeWillChange]
public function getIterator()
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->getAttributeBag()->all());
}
/**
* Returns the number of attributes.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return \count($this->getAttributeBag()->all());
}
@@ -172,43 +142,28 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
return true;
}
/**
* {@inheritdoc}
*/
public function invalidate(int $lifetime = null)
public function invalidate(int $lifetime = null): bool
{
$this->storage->clear();
return $this->migrate(true, $lifetime);
}
/**
* {@inheritdoc}
*/
public function migrate(bool $destroy = false, int $lifetime = null)
public function migrate(bool $destroy = false, int $lifetime = null): bool
{
return $this->storage->regenerate($destroy, $lifetime);
}
/**
* {@inheritdoc}
*/
public function save()
{
$this->storage->save();
}
/**
* {@inheritdoc}
*/
public function getId()
public function getId(): string
{
return $this->storage->getId();
}
/**
* {@inheritdoc}
*/
public function setId(string $id)
{
if ($this->storage->getId() !== $id) {
@@ -216,26 +171,17 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
}
}
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->storage->getName();
}
/**
* {@inheritdoc}
*/
public function setName(string $name)
{
$this->storage->setName($name);
}
/**
* {@inheritdoc}
*/
public function getMetadataBag()
public function getMetadataBag(): MetadataBag
{
++$this->usageIndex;
if ($this->usageReporter && 0 <= $this->usageIndex) {
@@ -245,18 +191,12 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
return $this->storage->getMetadataBag();
}
/**
* {@inheritdoc}
*/
public function registerBag(SessionBagInterface $bag)
{
$this->storage->registerBag(new SessionBagProxy($bag, $this->data, $this->usageIndex, $this->usageReporter));
}
/**
* {@inheritdoc}
*/
public function getBag(string $name)
public function getBag(string $name): SessionBagInterface
{
$bag = $this->storage->getBag($name);
@@ -265,10 +205,8 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* Gets the flashbag interface.
*
* @return FlashBagInterface
*/
public function getFlashBag()
public function getFlashBag(): FlashBagInterface
{
return $this->getBag($this->flashName);
}

View File

@@ -20,10 +20,8 @@ interface SessionBagInterface
{
/**
* Gets this bag's name.
*
* @return string
*/
public function getName();
public function getName(): string;
/**
* Initializes the Bag.
@@ -32,15 +30,13 @@ interface SessionBagInterface
/**
* Gets the storage key for this bag.
*
* @return string
*/
public function getStorageKey();
public function getStorageKey(): string;
/**
* Clears out data from bag.
*
* @return mixed Whatever data was contained
*/
public function clear();
public function clear(): mixed;
}

View File

@@ -18,17 +18,17 @@ namespace Symfony\Component\HttpFoundation\Session;
*/
final class SessionBagProxy implements SessionBagInterface
{
private $bag;
private $data;
private $usageIndex;
private $usageReporter;
private SessionBagInterface $bag;
private array $data;
private ?int $usageIndex;
private ?\Closure $usageReporter;
public function __construct(SessionBagInterface $bag, array &$data, ?int &$usageIndex, ?callable $usageReporter)
{
$this->bag = $bag;
$this->data = &$data;
$this->usageIndex = &$usageIndex;
$this->usageReporter = $usageReporter;
$this->usageReporter = null === $usageReporter ? null : $usageReporter(...);
}
public function getBag(): SessionBagInterface
@@ -54,17 +54,11 @@ final class SessionBagProxy implements SessionBagInterface
return empty($this->data[$this->bag->getStorageKey()]);
}
/**
* {@inheritdoc}
*/
public function getName(): string
{
return $this->bag->getName();
}
/**
* {@inheritdoc}
*/
public function initialize(array &$array): void
{
++$this->usageIndex;
@@ -77,18 +71,12 @@ final class SessionBagProxy implements SessionBagInterface
$this->bag->initialize($array);
}
/**
* {@inheritdoc}
*/
public function getStorageKey(): string
{
return $this->bag->getStorageKey();
}
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
return $this->bag->clear();
}

View File

@@ -22,15 +22,15 @@ class_exists(Session::class);
*/
class SessionFactory implements SessionFactoryInterface
{
private $requestStack;
private $storageFactory;
private $usageReporter;
private RequestStack $requestStack;
private SessionStorageFactoryInterface $storageFactory;
private ?\Closure $usageReporter;
public function __construct(RequestStack $requestStack, SessionStorageFactoryInterface $storageFactory, callable $usageReporter = null)
{
$this->requestStack = $requestStack;
$this->storageFactory = $storageFactory;
$this->usageReporter = $usageReporter;
$this->usageReporter = null === $usageReporter ? null : $usageReporter(...);
}
public function createSession(): SessionInterface

View File

@@ -23,18 +23,14 @@ interface SessionInterface
/**
* Starts the session storage.
*
* @return bool
*
* @throws \RuntimeException if session fails to start
*/
public function start();
public function start(): bool;
/**
* Returns the session ID.
*
* @return string
*/
public function getId();
public function getId(): string;
/**
* Sets the session ID.
@@ -43,10 +39,8 @@ interface SessionInterface
/**
* Returns the session name.
*
* @return string
*/
public function getName();
public function getName(): string;
/**
* Sets the session name.
@@ -63,10 +57,8 @@ interface SessionInterface
* will leave the system settings unchanged, 0 sets the cookie
* to expire with browser session. Time is in seconds, and is
* not a Unix timestamp.
*
* @return bool
*/
public function invalidate(int $lifetime = null);
public function invalidate(int $lifetime = null): bool;
/**
* Migrates the current session to a new session id while maintaining all
@@ -77,10 +69,8 @@ interface SessionInterface
* will leave the system settings unchanged, 0 sets the cookie
* to expire with browser session. Time is in seconds, and is
* not a Unix timestamp.
*
* @return bool
*/
public function migrate(bool $destroy = false, int $lifetime = null);
public function migrate(bool $destroy = false, int $lifetime = null): bool;
/**
* Force the session to be saved and closed.
@@ -93,33 +83,23 @@ interface SessionInterface
/**
* Checks if an attribute is defined.
*
* @return bool
*/
public function has(string $name);
public function has(string $name): bool;
/**
* Returns an attribute.
*
* @param mixed $default The default value if not found
*
* @return mixed
*/
public function get(string $name, $default = null);
public function get(string $name, mixed $default = null): mixed;
/**
* Sets an attribute.
*
* @param mixed $value
*/
public function set(string $name, $value);
public function set(string $name, mixed $value);
/**
* Returns attributes.
*
* @return array
*/
public function all();
public function all(): array;
/**
* Sets attributes.
@@ -131,7 +111,7 @@ interface SessionInterface
*
* @return mixed The removed value or null when it does not exist
*/
public function remove(string $name);
public function remove(string $name): mixed;
/**
* Clears all attributes.
@@ -140,10 +120,8 @@ interface SessionInterface
/**
* Checks if the session was started.
*
* @return bool
*/
public function isStarted();
public function isStarted(): bool;
/**
* Registers a SessionBagInterface with the session.
@@ -152,15 +130,11 @@ interface SessionInterface
/**
* Gets a bag instance by name.
*
* @return SessionBagInterface
*/
public function getBag(string $name);
public function getBag(string $name): SessionBagInterface;
/**
* Gets session meta.
*
* @return MetadataBag
*/
public function getMetadataBag();
public function getMetadataBag(): MetadataBag;
}

View File

@@ -22,17 +22,13 @@ use Symfony\Component\HttpFoundation\Session\SessionUtils;
*/
abstract class AbstractSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
{
private $sessionName;
private $prefetchId;
private $prefetchData;
private $newSessionId;
private $igbinaryEmptyData;
private string $sessionName;
private string $prefetchId;
private string $prefetchData;
private ?string $newSessionId = null;
private string $igbinaryEmptyData;
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function open($savePath, $sessionName)
public function open(string $savePath, string $sessionName): bool
{
$this->sessionName = $sessionName;
if (!headers_sent() && !\ini_get('session.cache_limiter') && '0' !== \ini_get('session.cache_limiter')) {
@@ -42,52 +38,26 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
return true;
}
/**
* @return string
*/
abstract protected function doRead(string $sessionId);
abstract protected function doRead(string $sessionId): string;
/**
* @return bool
*/
abstract protected function doWrite(string $sessionId, string $data);
abstract protected function doWrite(string $sessionId, string $data): bool;
/**
* @return bool
*/
abstract protected function doDestroy(string $sessionId);
abstract protected function doDestroy(string $sessionId): bool;
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function validateId($sessionId)
public function validateId(string $sessionId): bool
{
$this->prefetchData = $this->read($sessionId);
$this->prefetchId = $sessionId;
if (\PHP_VERSION_ID < 70317 || (70400 <= \PHP_VERSION_ID && \PHP_VERSION_ID < 70405)) {
// work around https://bugs.php.net/79413
foreach (debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) {
if (!isset($frame['class']) && isset($frame['function']) && \in_array($frame['function'], ['session_regenerate_id', 'session_create_id'], true)) {
return '' === $this->prefetchData;
}
}
}
return '' !== $this->prefetchData;
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function read($sessionId)
public function read(string $sessionId): string
{
if (null !== $this->prefetchId) {
if (isset($this->prefetchId)) {
$prefetchId = $this->prefetchId;
$prefetchData = $this->prefetchData;
$this->prefetchId = $this->prefetchData = null;
unset($this->prefetchId, $this->prefetchData);
if ($prefetchId === $sessionId || '' === $prefetchData) {
$this->newSessionId = '' === $prefetchData ? $sessionId : null;
@@ -102,16 +72,10 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
return $data;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function write($sessionId, $data)
public function write(string $sessionId, string $data): bool
{
if (null === $this->igbinaryEmptyData) {
// see https://github.com/igbinary/igbinary/issues/146
$this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize([]) : '';
}
// see https://github.com/igbinary/igbinary/issues/146
$this->igbinaryEmptyData ??= \function_exists('igbinary_serialize') ? igbinary_serialize([]) : '';
if ('' === $data || $this->igbinaryEmptyData === $data) {
return $this->destroy($sessionId);
}
@@ -120,14 +84,10 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
return $this->doWrite($sessionId, $data);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function destroy($sessionId)
public function destroy(string $sessionId): bool
{
if (!headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN)) {
if (!$this->sessionName) {
if (!headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL)) {
if (!isset($this->sessionName)) {
throw new \LogicException(sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', static::class));
}
$cookie = SessionUtils::popSessionCookie($this->sessionName, $sessionId);
@@ -140,13 +100,9 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
* started the session).
*/
if (null === $cookie || isset($_COOKIE[$this->sessionName])) {
if (\PHP_VERSION_ID < 70300) {
setcookie($this->sessionName, '', 0, \ini_get('session.cookie_path'), \ini_get('session.cookie_domain'), filter_var(\ini_get('session.cookie_secure'), \FILTER_VALIDATE_BOOLEAN), filter_var(\ini_get('session.cookie_httponly'), \FILTER_VALIDATE_BOOLEAN));
} else {
$params = session_get_cookie_params();
unset($params['lifetime']);
setcookie($this->sessionName, '', $params);
}
$params = session_get_cookie_params();
unset($params['lifetime']);
setcookie($this->sessionName, '', $params);
}
}

View File

@@ -18,9 +18,6 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface;
*/
class IdentityMarshaller implements MarshallerInterface
{
/**
* {@inheritdoc}
*/
public function marshall(array $values, ?array &$failed): array
{
foreach ($values as $key => $value) {
@@ -32,9 +29,6 @@ class IdentityMarshaller implements MarshallerInterface
return $values;
}
/**
* {@inheritdoc}
*/
public function unmarshall(string $value): string
{
return $value;

View File

@@ -18,8 +18,8 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface;
*/
class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
{
private $handler;
private $marshaller;
private AbstractSessionHandler $handler;
private MarshallerInterface $marshaller;
public function __construct(AbstractSessionHandler $handler, MarshallerInterface $marshaller)
{
@@ -27,56 +27,32 @@ class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpd
$this->marshaller = $marshaller;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function open($savePath, $name)
public function open(string $savePath, string $name): bool
{
return $this->handler->open($savePath, $name);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return $this->handler->close();
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function destroy($sessionId)
public function destroy(string $sessionId): bool
{
return $this->handler->destroy($sessionId);
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
return $this->handler->gc($maxlifetime);
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function read($sessionId)
public function read(string $sessionId): string
{
return $this->marshaller->unmarshall($this->handler->read($sessionId));
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function write($sessionId, $data)
public function write(string $sessionId, string $data): bool
{
$failed = [];
$marshalledData = $this->marshaller->marshall(['data' => $data], $failed);
@@ -88,20 +64,12 @@ class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpd
return $this->handler->write($sessionId, $marshalledData['data']);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function validateId($sessionId)
public function validateId(string $sessionId): bool
{
return $this->handler->validateId($sessionId);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
return $this->handler->updateTimestamp($sessionId, $data);
}

View File

@@ -21,17 +21,17 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
*/
class MemcachedSessionHandler extends AbstractSessionHandler
{
private $memcached;
private \Memcached $memcached;
/**
* @var int Time to live in seconds
* Time to live in seconds.
*/
private $ttl;
private int|\Closure|null $ttl;
/**
* @var string Key prefix for shared environments
* Key prefix for shared environments.
*/
private $prefix;
private string $prefix;
/**
* Constructor.
@@ -54,45 +54,31 @@ class MemcachedSessionHandler extends AbstractSessionHandler
$this->prefix = $options['prefix'] ?? 'sf2s';
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return $this->memcached->quit();
}
/**
* {@inheritdoc}
*/
protected function doRead(string $sessionId)
protected function doRead(string $sessionId): string
{
return $this->memcached->get($this->prefix.$sessionId) ?: '';
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
$this->memcached->touch($this->prefix.$sessionId, $this->getCompatibleTtl());
return true;
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
return $this->memcached->set($this->prefix.$sessionId, $data, $this->getCompatibleTtl());
}
private function getCompatibleTtl(): int
{
$ttl = (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime'));
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
// If the relative TTL that is used exceeds 30 days, memcached will treat the value as Unix time.
// We have to convert it to an absolute Unix time at this point, to make sure the TTL is correct.
@@ -103,21 +89,14 @@ class MemcachedSessionHandler extends AbstractSessionHandler
return $ttl;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId)
protected function doDestroy(string $sessionId): bool
{
$result = $this->memcached->delete($this->prefix.$sessionId);
return $result || \Memcached::RES_NOTFOUND == $this->memcached->getResultCode();
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
// not required here because memcached will auto expire the records anyhow.
return 0;
@@ -125,10 +104,8 @@ class MemcachedSessionHandler extends AbstractSessionHandler
/**
* Return a Memcached instance.
*
* @return \Memcached
*/
protected function getMemcached()
protected function getMemcached(): \Memcached
{
return $this->memcached;
}

View File

@@ -25,12 +25,12 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
/**
* @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface
*/
private $currentHandler;
private \SessionHandlerInterface $currentHandler;
/**
* @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface
*/
private $writeOnlyHandler;
private \SessionHandlerInterface $writeOnlyHandler;
public function __construct(\SessionHandlerInterface $currentHandler, \SessionHandlerInterface $writeOnlyHandler)
{
@@ -45,11 +45,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
$this->writeOnlyHandler = $writeOnlyHandler;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
$result = $this->currentHandler->close();
$this->writeOnlyHandler->close();
@@ -57,11 +53,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
return $result;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function destroy($sessionId)
public function destroy(string $sessionId): bool
{
$result = $this->currentHandler->destroy($sessionId);
$this->writeOnlyHandler->destroy($sessionId);
@@ -69,11 +61,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
return $result;
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
$result = $this->currentHandler->gc($maxlifetime);
$this->writeOnlyHandler->gc($maxlifetime);
@@ -81,11 +69,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
return $result;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function open($savePath, $sessionName)
public function open(string $savePath, string $sessionName): bool
{
$result = $this->currentHandler->open($savePath, $sessionName);
$this->writeOnlyHandler->open($savePath, $sessionName);
@@ -93,21 +77,13 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
return $result;
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function read($sessionId)
public function read(string $sessionId): string
{
// No reading from new handler until switch-over
return $this->currentHandler->read($sessionId);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function write($sessionId, $sessionData)
public function write(string $sessionId, string $sessionData): bool
{
$result = $this->currentHandler->write($sessionId, $sessionData);
$this->writeOnlyHandler->write($sessionId, $sessionData);
@@ -115,21 +91,13 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
return $result;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function validateId($sessionId)
public function validateId(string $sessionId): bool
{
// No reading from new handler until switch-over
return $this->currentHandler->validateId($sessionId);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $sessionData)
public function updateTimestamp(string $sessionId, string $sessionData): bool
{
$result = $this->currentHandler->updateTimestamp($sessionId, $sessionData);
$this->writeOnlyHandler->updateTimestamp($sessionId, $sessionData);

View File

@@ -26,17 +26,10 @@ use MongoDB\Collection;
*/
class MongoDbSessionHandler extends AbstractSessionHandler
{
private $mongo;
/**
* @var Collection
*/
private $collection;
/**
* @var array
*/
private $options;
private Client $mongo;
private Collection $collection;
private array $options;
private int|\Closure|null $ttl;
/**
* Constructor.
@@ -47,7 +40,8 @@ class MongoDbSessionHandler extends AbstractSessionHandler
* * id_field: The field name for storing the session id [default: _id]
* * data_field: The field name for storing the session data [default: data]
* * time_field: The field name for storing the timestamp [default: time]
* * expiry_field: The field name for storing the expiry-timestamp [default: expires_at].
* * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]
* * ttl: The time to live in seconds.
*
* It is strongly recommended to put an index on the `expiry_field` for
* garbage-collection. Alternatively it's possible to automatically expire
@@ -82,21 +76,15 @@ class MongoDbSessionHandler extends AbstractSessionHandler
'time_field' => 'time',
'expiry_field' => 'expires_at',
], $options);
$this->ttl = $this->options['ttl'] ?? null;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return true;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId)
protected function doDestroy(string $sessionId): bool
{
$this->getCollection()->deleteOne([
$this->options['id_field'] => $sessionId,
@@ -105,23 +93,17 @@ class MongoDbSessionHandler extends AbstractSessionHandler
return true;
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
return $this->getCollection()->deleteMany([
$this->options['expiry_field'] => ['$lt' => new UTCDateTime()],
])->getDeletedCount();
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
$expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000);
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
$expiry = new UTCDateTime((time() + (int) $ttl) * 1000);
$fields = [
$this->options['time_field'] => new UTCDateTime(),
@@ -138,13 +120,10 @@ class MongoDbSessionHandler extends AbstractSessionHandler
return true;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
$expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000);
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
$expiry = new UTCDateTime((time() + (int) $ttl) * 1000);
$this->getCollection()->updateOne(
[$this->options['id_field'] => $sessionId],
@@ -157,10 +136,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
return true;
}
/**
* {@inheritdoc}
*/
protected function doRead(string $sessionId)
protected function doRead(string $sessionId): string
{
$dbData = $this->getCollection()->findOne([
$this->options['id_field'] => $sessionId,
@@ -176,17 +152,10 @@ class MongoDbSessionHandler extends AbstractSessionHandler
private function getCollection(): Collection
{
if (null === $this->collection) {
$this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
}
return $this->collection;
return $this->collection ??= $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
}
/**
* @return Client
*/
protected function getMongo()
protected function getMongo(): Client
{
return $this->mongo;
}

View File

@@ -30,11 +30,7 @@ class NativeFileSessionHandler extends \SessionHandler
*/
public function __construct(string $savePath = null)
{
if (null === $savePath) {
$savePath = \ini_get('session.save_path');
}
$baseDir = $savePath;
$baseDir = $savePath ??= \ini_get('session.save_path');
if ($count = substr_count($savePath, ';')) {
if ($count > 2) {

View File

@@ -18,62 +18,37 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
*/
class NullSessionHandler extends AbstractSessionHandler
{
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return true;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function validateId($sessionId)
public function validateId(string $sessionId): bool
{
return true;
}
/**
* {@inheritdoc}
*/
protected function doRead(string $sessionId)
protected function doRead(string $sessionId): string
{
return '';
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
return true;
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
return true;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId)
protected function doDestroy(string $sessionId): bool
{
return true;
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
return 0;
}

View File

@@ -65,105 +65,66 @@ class PdoSessionHandler extends AbstractSessionHandler
*/
public const LOCK_TRANSACTIONAL = 2;
private const MAX_LIFETIME = 315576000;
/**
* @var \PDO|null PDO instance or null when not connected yet
*/
private $pdo;
private \PDO $pdo;
/**
* DSN string or null for session.save_path or false when lazy connection disabled.
*
* @var string|false|null
*/
private $dsn = false;
private string|false|null $dsn = false;
private string $driver;
private string $table = 'sessions';
private string $idCol = 'sess_id';
private string $dataCol = 'sess_data';
private string $lifetimeCol = 'sess_lifetime';
private string $timeCol = 'sess_time';
/**
* @var string|null
* Time to live in seconds.
*/
private $driver;
/**
* @var string
*/
private $table = 'sessions';
/**
* @var string
*/
private $idCol = 'sess_id';
/**
* @var string
*/
private $dataCol = 'sess_data';
/**
* @var string
*/
private $lifetimeCol = 'sess_lifetime';
/**
* @var string
*/
private $timeCol = 'sess_time';
private int|\Closure|null $ttl;
/**
* Username when lazy-connect.
*
* @var string
*/
private $username = '';
private string $username = '';
/**
* Password when lazy-connect.
*
* @var string
*/
private $password = '';
private string $password = '';
/**
* Connection options when lazy-connect.
*
* @var array
*/
private $connectionOptions = [];
private array $connectionOptions = [];
/**
* The strategy for locking, see constants.
*
* @var int
*/
private $lockMode = self::LOCK_TRANSACTIONAL;
private int $lockMode = self::LOCK_TRANSACTIONAL;
/**
* It's an array to support multiple reads before closing which is manual, non-standard usage.
*
* @var \PDOStatement[] An array of statements to release advisory locks
*/
private $unlockStatements = [];
private array $unlockStatements = [];
/**
* True when the current session exists but expired according to session.gc_maxlifetime.
*
* @var bool
*/
private $sessionExpired = false;
private bool $sessionExpired = false;
/**
* Whether a transaction is active.
*
* @var bool
*/
private $inTransaction = false;
private bool $inTransaction = false;
/**
* Whether gc() has been called.
*
* @var bool
*/
private $gcCalled = false;
private bool $gcCalled = false;
/**
* You can either pass an existing database connection as PDO instance or
@@ -181,12 +142,13 @@ class PdoSessionHandler extends AbstractSessionHandler
* * db_password: The password when lazy-connect [default: '']
* * db_connection_options: An array of driver-specific connection options [default: []]
* * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
* * ttl: The time to live in seconds.
*
* @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null
*
* @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
*/
public function __construct($pdoOrDsn = null, array $options = [])
public function __construct(\PDO|string $pdoOrDsn = null, array $options = [])
{
if ($pdoOrDsn instanceof \PDO) {
if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
@@ -210,6 +172,7 @@ class PdoSessionHandler extends AbstractSessionHandler
$this->password = $options['db_password'] ?? $this->password;
$this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
$this->lockMode = $options['lock_mode'] ?? $this->lockMode;
$this->ttl = $options['ttl'] ?? null;
}
/**
@@ -228,34 +191,23 @@ class PdoSessionHandler extends AbstractSessionHandler
// connect if we are not yet
$this->getConnection();
switch ($this->driver) {
case 'mysql':
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
// - language processing like é == e
$sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB";
break;
case 'sqlite':
$sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'pgsql':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'oci':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'sqlsrv':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
default:
throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver));
}
$sql = match ($this->driver) {
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
// - language processing like é == e
'mysql' => "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB",
'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
default => throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)),
};
try {
$this->pdo->exec($sql);
$this->pdo->exec("CREATE INDEX EXPIRY ON $this->table ($this->lifetimeCol)");
$this->pdo->exec("CREATE INDEX expiry ON $this->table ($this->lifetimeCol)");
} catch (\PDOException $e) {
$this->rollback();
@@ -267,34 +219,24 @@ class PdoSessionHandler extends AbstractSessionHandler
* Returns true when the current session exists but expired according to session.gc_maxlifetime.
*
* Can be used to distinguish between a new session and one that expired due to inactivity.
*
* @return bool
*/
public function isSessionExpired()
public function isSessionExpired(): bool
{
return $this->sessionExpired;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function open($savePath, $sessionName)
public function open(string $savePath, string $sessionName): bool
{
$this->sessionExpired = false;
if (null === $this->pdo) {
if (!isset($this->pdo)) {
$this->connect($this->dsn ?: $savePath);
}
return parent::open($savePath, $sessionName);
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function read($sessionId)
public function read(string $sessionId): string
{
try {
return parent::read($sessionId);
@@ -305,11 +247,7 @@ class PdoSessionHandler extends AbstractSessionHandler
}
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
// We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
// This way, pruning expired sessions does not block them from being started while the current session is used.
@@ -318,10 +256,7 @@ class PdoSessionHandler extends AbstractSessionHandler
return 0;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId)
protected function doDestroy(string $sessionId): bool
{
// delete the record associated with this id
$sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
@@ -339,12 +274,9 @@ class PdoSessionHandler extends AbstractSessionHandler
return true;
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
$maxlifetime = (int) \ini_get('session.gc_maxlifetime');
$maxlifetime = (int) (($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'));
try {
// We use a single MERGE SQL query when supported by the database.
@@ -385,13 +317,9 @@ class PdoSessionHandler extends AbstractSessionHandler
return true;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
$expiry = time() + (int) \ini_get('session.gc_maxlifetime');
$expiry = time() + (int) (($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'));
try {
$updateStmt = $this->pdo->prepare(
@@ -410,11 +338,7 @@ class PdoSessionHandler extends AbstractSessionHandler
return true;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
$this->commit();
@@ -426,27 +350,14 @@ class PdoSessionHandler extends AbstractSessionHandler
$this->gcCalled = false;
// delete the session records that have expired
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time AND $this->lifetimeCol > :min";
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
$stmt->execute();
// to be removed in 6.0
if ('mysql' === $this->driver) {
$legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol + $this->timeCol < :time";
} else {
$legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol < :time - $this->timeCol";
}
$stmt = $this->pdo->prepare($legacySql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
$stmt->execute();
}
if (false !== $this->dsn) {
$this->pdo = null; // only close lazy-connection
$this->driver = null;
unset($this->pdo, $this->driver); // only close lazy-connection
}
return true;
@@ -533,7 +444,7 @@ class PdoSessionHandler extends AbstractSessionHandler
// If "unix_socket" is not in the query, we continue with the same process as pgsql
// no break
case 'pgsql':
$dsn ?? $dsn = 'pgsql:';
$dsn ??= 'pgsql:';
if (isset($params['host']) && '' !== $params['host']) {
$dsn .= 'host='.$params['host'].';';
@@ -649,10 +560,8 @@ class PdoSessionHandler extends AbstractSessionHandler
*
* We need to make sure we do not return session data that is already considered garbage according
* to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
*
* @return string
*/
protected function doRead(string $sessionId)
protected function doRead(string $sessionId): string
{
if (self::LOCK_ADVISORY === $this->lockMode) {
$this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
@@ -669,9 +578,6 @@ class PdoSessionHandler extends AbstractSessionHandler
if ($sessionRows) {
$expiry = (int) $sessionRows[0][1];
if ($expiry <= self::MAX_LIFETIME) {
$expiry += $sessionRows[0][2];
}
if ($expiry < time()) {
$this->sessionExpired = true;
@@ -687,7 +593,7 @@ class PdoSessionHandler extends AbstractSessionHandler
throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.');
}
if (!filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
if (!filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOL) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
// In strict mode, session fixation is not possible: new sessions always start with a unique
// random id, so that concurrency is not possible and this code path can be skipped.
// Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
@@ -804,14 +710,13 @@ class PdoSessionHandler extends AbstractSessionHandler
if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
$this->beginTransaction();
// selecting the time column should be removed in 6.0
switch ($this->driver) {
case 'mysql':
case 'oci':
case 'pgsql':
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
case 'sqlsrv':
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
case 'sqlite':
// we already locked when starting transaction
break;
@@ -820,7 +725,7 @@ class PdoSessionHandler extends AbstractSessionHandler
}
}
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id";
}
/**
@@ -929,12 +834,10 @@ class PdoSessionHandler extends AbstractSessionHandler
/**
* Return a PDO instance.
*
* @return \PDO
*/
protected function getConnection()
protected function getConnection(): \PDO
{
if (null === $this->pdo) {
if (!isset($this->pdo)) {
$this->connect($this->dsn ?: \ini_get('session.save_path'));
}

View File

@@ -12,8 +12,6 @@
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Predis\Response\ErrorInterface;
use Symfony\Component\Cache\Traits\RedisClusterProxy;
use Symfony\Component\Cache\Traits\RedisProxy;
/**
* Redis based session storage handler based on the Redis class
@@ -23,70 +21,48 @@ use Symfony\Component\Cache\Traits\RedisProxy;
*/
class RedisSessionHandler extends AbstractSessionHandler
{
private $redis;
/**
* Key prefix for shared environments.
*/
private string $prefix;
/**
* @var string Key prefix for shared environments
* Time to live in seconds.
*/
private $prefix;
/**
* @var int Time to live in seconds
*/
private $ttl;
private int|\Closure|null $ttl;
/**
* List of available options:
* * prefix: The prefix to use for the keys in order to avoid collision on the Redis server
* * ttl: The time to live in seconds.
*
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis
*
* @throws \InvalidArgumentException When unsupported client or options are passed
*/
public function __construct($redis, array $options = [])
{
if (
!$redis instanceof \Redis &&
!$redis instanceof \RedisArray &&
!$redis instanceof \RedisCluster &&
!$redis instanceof \Predis\ClientInterface &&
!$redis instanceof RedisProxy &&
!$redis instanceof RedisClusterProxy
) {
throw new \InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($redis)));
}
public function __construct(
private \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface $redis,
array $options = [],
) {
if ($diff = array_diff(array_keys($options), ['prefix', 'ttl'])) {
throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff)));
}
$this->redis = $redis;
$this->prefix = $options['prefix'] ?? 'sf_s';
$this->ttl = $options['ttl'] ?? null;
}
/**
* {@inheritdoc}
*/
protected function doRead(string $sessionId): string
{
return $this->redis->get($this->prefix.$sessionId) ?: '';
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data): bool
{
$result = $this->redis->setEx($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')), $data);
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
$result = $this->redis->setEx($this->prefix.$sessionId, (int) $ttl, $data);
return $result && !$result instanceof ErrorInterface;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId): bool
{
static $unlink = true;
@@ -94,7 +70,7 @@ class RedisSessionHandler extends AbstractSessionHandler
if ($unlink) {
try {
$unlink = false !== $this->redis->unlink($this->prefix.$sessionId);
} catch (\Throwable $e) {
} catch (\Throwable) {
$unlink = false;
}
}
@@ -106,32 +82,21 @@ class RedisSessionHandler extends AbstractSessionHandler
return true;
}
/**
* {@inheritdoc}
*/
#[\ReturnTypeWillChange]
public function close(): bool
{
return true;
}
/**
* {@inheritdoc}
*
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
return 0;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
return (bool) $this->redis->expire($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')));
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
return $this->redis->expire($this->prefix.$sessionId, (int) $ttl);
}
}

View File

@@ -13,34 +13,28 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Doctrine\DBAL\DriverManager;
use Symfony\Component\Cache\Adapter\AbstractAdapter;
use Symfony\Component\Cache\Traits\RedisClusterProxy;
use Symfony\Component\Cache\Traits\RedisProxy;
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class SessionHandlerFactory
{
/**
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy|\Memcached|\PDO|string $connection Connection or DSN
*/
public static function createHandler($connection): AbstractSessionHandler
public static function createHandler(object|string $connection, array $options = []): AbstractSessionHandler
{
if (!\is_string($connection) && !\is_object($connection)) {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a string or a connection object, "%s" given.', __METHOD__, get_debug_type($connection)));
}
if ($query = \is_string($connection) ? parse_url($connection) : false) {
parse_str($query['query'] ?? '', $query);
if ($options = \is_string($connection) ? parse_url($connection) : false) {
parse_str($options['query'] ?? '', $options);
if (($options['ttl'] ?? null) instanceof \Closure) {
$query['ttl'] = $options['ttl'];
}
}
$options = ($query ?: []) + $options;
switch (true) {
case $connection instanceof \Redis:
case $connection instanceof \RedisArray:
case $connection instanceof \RedisCluster:
case $connection instanceof \Predis\ClientInterface:
case $connection instanceof RedisProxy:
case $connection instanceof RedisClusterProxy:
return new RedisSessionHandler($connection);
case $connection instanceof \Memcached:
@@ -65,7 +59,7 @@ class SessionHandlerFactory
$handlerClass = str_starts_with($connection, 'memcached:') ? MemcachedSessionHandler::class : RedisSessionHandler::class;
$connection = AbstractAdapter::createConnection($connection, ['lazy' => true]);
return new $handlerClass($connection, array_intersect_key($options ?: [], ['prefix' => 1, 'ttl' => 1]));
return new $handlerClass($connection, array_intersect_key($options, ['prefix' => 1, 'ttl' => 1]));
case str_starts_with($connection, 'pdo_oci://'):
if (!class_exists(DriverManager::class)) {
@@ -83,7 +77,7 @@ class SessionHandlerFactory
case str_starts_with($connection, 'sqlsrv://'):
case str_starts_with($connection, 'sqlite://'):
case str_starts_with($connection, 'sqlite3://'):
return new PdoSessionHandler($connection, $options ?: []);
return new PdoSessionHandler($connection, $options);
}
throw new \InvalidArgumentException(sprintf('Unsupported Connection: "%s".', $connection));

View File

@@ -18,8 +18,8 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
*/
class StrictSessionHandler extends AbstractSessionHandler
{
private $handler;
private $doDestroy;
private \SessionHandlerInterface $handler;
private bool $doDestroy;
public function __construct(\SessionHandlerInterface $handler)
{
@@ -40,47 +40,29 @@ class StrictSessionHandler extends AbstractSessionHandler
return $this->handler instanceof \SessionHandler;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function open($savePath, $sessionName)
public function open(string $savePath, string $sessionName): bool
{
parent::open($savePath, $sessionName);
return $this->handler->open($savePath, $sessionName);
}
/**
* {@inheritdoc}
*/
protected function doRead(string $sessionId)
protected function doRead(string $sessionId): string
{
return $this->handler->read($sessionId);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
return $this->write($sessionId, $data);
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
return $this->handler->write($sessionId, $data);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function destroy($sessionId)
public function destroy(string $sessionId): bool
{
$this->doDestroy = true;
$destroyed = parent::destroy($sessionId);
@@ -88,30 +70,19 @@ class StrictSessionHandler extends AbstractSessionHandler
return $this->doDestroy ? $this->doDestroy($sessionId) : $destroyed;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId)
protected function doDestroy(string $sessionId): bool
{
$this->doDestroy = false;
return $this->handler->destroy($sessionId);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return $this->handler->close();
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
return $this->handler->gc($maxlifetime);
}

View File

@@ -26,15 +26,8 @@ class MetadataBag implements SessionBagInterface
public const UPDATED = 'u';
public const LIFETIME = 'l';
/**
* @var string
*/
private $name = '__metadata';
/**
* @var string
*/
private $storageKey;
private string $name = '__metadata';
private string $storageKey;
/**
* @var array
@@ -43,15 +36,10 @@ class MetadataBag implements SessionBagInterface
/**
* Unix timestamp.
*
* @var int
*/
private $lastUsed;
private int $lastUsed;
/**
* @var int
*/
private $updateThreshold;
private int $updateThreshold;
/**
* @param string $storageKey The key used to store bag in the session
@@ -63,9 +51,6 @@ class MetadataBag implements SessionBagInterface
$this->updateThreshold = $updateThreshold;
}
/**
* {@inheritdoc}
*/
public function initialize(array &$array)
{
$this->meta = &$array;
@@ -84,10 +69,8 @@ class MetadataBag implements SessionBagInterface
/**
* Gets the lifetime that the session cookie was set with.
*
* @return int
*/
public function getLifetime()
public function getLifetime(): int
{
return $this->meta[self::LIFETIME];
}
@@ -105,10 +88,7 @@ class MetadataBag implements SessionBagInterface
$this->stampCreated($lifetime);
}
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
@@ -118,7 +98,7 @@ class MetadataBag implements SessionBagInterface
*
* @return int Unix timestamp
*/
public function getCreated()
public function getCreated(): int
{
return $this->meta[self::CREATED];
}
@@ -128,24 +108,18 @@ class MetadataBag implements SessionBagInterface
*
* @return int Unix timestamp
*/
public function getLastUsed()
public function getLastUsed(): int
{
return $this->lastUsed;
}
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
// nothing to do
return null;
}
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}

View File

@@ -73,10 +73,7 @@ class MockArraySessionStorage implements SessionStorageInterface
$this->data = $array;
}
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;
@@ -91,10 +88,7 @@ class MockArraySessionStorage implements SessionStorageInterface
return true;
}
/**
* {@inheritdoc}
*/
public function regenerate(bool $destroy = false, int $lifetime = null)
public function regenerate(bool $destroy = false, int $lifetime = null): bool
{
if (!$this->started) {
$this->start();
@@ -106,17 +100,11 @@ class MockArraySessionStorage implements SessionStorageInterface
return true;
}
/**
* {@inheritdoc}
*/
public function getId()
public function getId(): string
{
return $this->id;
}
/**
* {@inheritdoc}
*/
public function setId(string $id)
{
if ($this->started) {
@@ -126,25 +114,16 @@ class MockArraySessionStorage implements SessionStorageInterface
$this->id = $id;
}
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function setName(string $name)
{
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function save()
{
if (!$this->started || $this->closed) {
@@ -155,9 +134,6 @@ class MockArraySessionStorage implements SessionStorageInterface
$this->started = false;
}
/**
* {@inheritdoc}
*/
public function clear()
{
// clear out the bags
@@ -172,18 +148,12 @@ class MockArraySessionStorage implements SessionStorageInterface
$this->loadSession();
}
/**
* {@inheritdoc}
*/
public function registerBag(SessionBagInterface $bag)
{
$this->bags[$bag->getName()] = $bag;
}
/**
* {@inheritdoc}
*/
public function getBag(string $name)
public function getBag(string $name): SessionBagInterface
{
if (!isset($this->bags[$name])) {
throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name));
@@ -196,29 +166,23 @@ class MockArraySessionStorage implements SessionStorageInterface
return $this->bags[$name];
}
/**
* {@inheritdoc}
*/
public function isStarted()
public function isStarted(): bool
{
return $this->started;
}
public function setMetadataBag(MetadataBag $bag = null)
{
if (null === $bag) {
$bag = new MetadataBag();
if (1 > \func_num_args()) {
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
$this->metadataBag = $bag;
$this->metadataBag = $bag ?? new MetadataBag();
}
/**
* Gets the MetadataBag.
*
* @return MetadataBag
*/
public function getMetadataBag()
public function getMetadataBag(): MetadataBag
{
return $this->metadataBag;
}
@@ -228,10 +192,8 @@ class MockArraySessionStorage implements SessionStorageInterface
*
* This doesn't need to be particularly cryptographically secure since this is just
* a mock.
*
* @return string
*/
protected function generateId()
protected function generateId(): string
{
return hash('sha256', uniqid('ss_mock_', true));
}
@@ -242,7 +204,7 @@ class MockArraySessionStorage implements SessionStorageInterface
foreach ($bags as $bag) {
$key = $bag->getStorageKey();
$this->data[$key] = $this->data[$key] ?? [];
$this->data[$key] ??= [];
$bag->initialize($this->data[$key]);
}

View File

@@ -25,16 +25,14 @@ namespace Symfony\Component\HttpFoundation\Session\Storage;
*/
class MockFileSessionStorage extends MockArraySessionStorage
{
private $savePath;
private string $savePath;
/**
* @param string|null $savePath Path of directory to save session files
*/
public function __construct(string $savePath = null, string $name = 'MOCKSESSID', MetadataBag $metaBag = null)
{
if (null === $savePath) {
$savePath = sys_get_temp_dir();
}
$savePath ??= sys_get_temp_dir();
if (!is_dir($savePath) && !@mkdir($savePath, 0777, true) && !is_dir($savePath)) {
throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s".', $savePath));
@@ -45,10 +43,7 @@ class MockFileSessionStorage extends MockArraySessionStorage
parent::__construct($name, $metaBag);
}
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;
@@ -65,10 +60,7 @@ class MockFileSessionStorage extends MockArraySessionStorage
return true;
}
/**
* {@inheritdoc}
*/
public function regenerate(bool $destroy = false, int $lifetime = null)
public function regenerate(bool $destroy = false, int $lifetime = null): bool
{
if (!$this->started) {
$this->start();
@@ -81,9 +73,6 @@ class MockFileSessionStorage extends MockArraySessionStorage
return parent::regenerate($destroy, $lifetime);
}
/**
* {@inheritdoc}
*/
public function save()
{
if (!$this->started) {

View File

@@ -21,9 +21,9 @@ class_exists(MockFileSessionStorage::class);
*/
class MockFileSessionStorageFactory implements SessionStorageFactoryInterface
{
private $savePath;
private $name;
private $metaBag;
private ?string $savePath;
private string $name;
private ?MetadataBag $metaBag;
/**
* @see MockFileSessionStorage constructor.

View File

@@ -12,7 +12,6 @@
namespace Symfony\Component\HttpFoundation\Session\Storage;
use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionUtils;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
@@ -54,11 +53,6 @@ class NativeSessionStorage implements SessionStorageInterface
*/
protected $metadataBag;
/**
* @var string|null
*/
private $emulateSameSite;
/**
* Depending on how you want the storage driver to behave you probably
* want to override this constructor entirely.
@@ -94,10 +88,8 @@ class NativeSessionStorage implements SessionStorageInterface
* sid_bits_per_character, "5"
* trans_sid_hosts, $_SERVER['HTTP_HOST']
* trans_sid_tags, "a=href,area=href,frame=src,form="
*
* @param AbstractProxy|\SessionHandlerInterface|null $handler
*/
public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null)
public function __construct(array $options = [], AbstractProxy|\SessionHandlerInterface $handler = null, MetadataBag $metaBag = null)
{
if (!\extension_loaded('session')) {
throw new \LogicException('PHP extension "session" is required.');
@@ -120,18 +112,13 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* Gets the save handler instance.
*
* @return AbstractProxy|\SessionHandlerInterface
*/
public function getSaveHandler()
public function getSaveHandler(): AbstractProxy|\SessionHandlerInterface
{
return $this->saveHandler;
}
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;
@@ -141,7 +128,7 @@ class NativeSessionStorage implements SessionStorageInterface
throw new \RuntimeException('Failed to start the session: already started by PHP.');
}
if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) {
if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL) && headers_sent($file, $line)) {
throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
}
@@ -186,54 +173,32 @@ class NativeSessionStorage implements SessionStorageInterface
throw new \RuntimeException('Failed to start the session.');
}
if (null !== $this->emulateSameSite) {
$originalCookie = SessionUtils::popSessionCookie(session_name(), session_id());
if (null !== $originalCookie) {
header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false);
}
}
$this->loadSession();
return true;
}
/**
* {@inheritdoc}
*/
public function getId()
public function getId(): string
{
return $this->saveHandler->getId();
}
/**
* {@inheritdoc}
*/
public function setId(string $id)
{
$this->saveHandler->setId($id);
}
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->saveHandler->getName();
}
/**
* {@inheritdoc}
*/
public function setName(string $name)
{
$this->saveHandler->setName($name);
}
/**
* {@inheritdoc}
*/
public function regenerate(bool $destroy = false, int $lifetime = null)
public function regenerate(bool $destroy = false, int $lifetime = null): bool
{
// Cannot regenerate the session ID for non-active sessions.
if (\PHP_SESSION_ACTIVE !== session_status()) {
@@ -254,21 +219,9 @@ class NativeSessionStorage implements SessionStorageInterface
$this->metadataBag->stampNew();
}
$isRegenerated = session_regenerate_id($destroy);
if (null !== $this->emulateSameSite) {
$originalCookie = SessionUtils::popSessionCookie(session_name(), session_id());
if (null !== $originalCookie) {
header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false);
}
}
return $isRegenerated;
return session_regenerate_id($destroy);
}
/**
* {@inheritdoc}
*/
public function save()
{
// Store a copy so we can restore the bags in case the session was not left empty
@@ -287,7 +240,7 @@ class NativeSessionStorage implements SessionStorageInterface
$previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) {
if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
$handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
$msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler));
$msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', $handler::class);
}
return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false;
@@ -308,9 +261,6 @@ class NativeSessionStorage implements SessionStorageInterface
$this->started = false;
}
/**
* {@inheritdoc}
*/
public function clear()
{
// clear out the bags
@@ -325,9 +275,6 @@ class NativeSessionStorage implements SessionStorageInterface
$this->loadSession();
}
/**
* {@inheritdoc}
*/
public function registerBag(SessionBagInterface $bag)
{
if ($this->started) {
@@ -337,10 +284,7 @@ class NativeSessionStorage implements SessionStorageInterface
$this->bags[$bag->getName()] = $bag;
}
/**
* {@inheritdoc}
*/
public function getBag(string $name)
public function getBag(string $name): SessionBagInterface
{
if (!isset($this->bags[$name])) {
throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name));
@@ -357,27 +301,22 @@ class NativeSessionStorage implements SessionStorageInterface
public function setMetadataBag(MetadataBag $metaBag = null)
{
if (null === $metaBag) {
$metaBag = new MetadataBag();
if (1 > \func_num_args()) {
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
$this->metadataBag = $metaBag ?? new MetadataBag();
$this->metadataBag = $metaBag;
}
/**
* Gets the MetadataBag.
*
* @return MetadataBag
*/
public function getMetadataBag()
public function getMetadataBag(): MetadataBag
{
return $this->metadataBag;
}
/**
* {@inheritdoc}
*/
public function isStarted()
public function isStarted(): bool
{
return $this->started;
}
@@ -404,31 +343,16 @@ class NativeSessionStorage implements SessionStorageInterface
'gc_divisor', 'gc_maxlifetime', 'gc_probability',
'lazy_write', 'name', 'referer_check',
'serialize_handler', 'use_strict_mode', 'use_cookies',
'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags',
'use_only_cookies', 'use_trans_sid',
'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
]);
foreach ($options as $key => $value) {
if (isset($validOptions[$key])) {
if (str_starts_with($key, 'upload_progress.')) {
trigger_deprecation('symfony/http-foundation', '5.4', 'Support for the "%s" session option is deprecated. The settings prefixed with "session.upload_progress." can not be changed at runtime.', $key);
continue;
}
if ('url_rewriter.tags' === $key) {
trigger_deprecation('symfony/http-foundation', '5.4', 'Support for the "%s" session option is deprecated. Use "trans_sid_tags" instead.', $key);
}
if ('cookie_samesite' === $key && \PHP_VERSION_ID < 70300) {
// PHP < 7.3 does not support same_site cookies. We will emulate it in
// the start() method instead.
$this->emulateSameSite = $value;
continue;
}
if ('cookie_secure' === $key && 'auto' === $value) {
continue;
}
ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value);
ini_set('session.'.$key, $value);
}
}
}
@@ -449,16 +373,12 @@ class NativeSessionStorage implements SessionStorageInterface
* @see https://php.net/sessionhandlerinterface
* @see https://php.net/sessionhandler
*
* @param AbstractProxy|\SessionHandlerInterface|null $saveHandler
*
* @throws \InvalidArgumentException
*/
public function setSaveHandler($saveHandler = null)
public function setSaveHandler(AbstractProxy|\SessionHandlerInterface $saveHandler = null)
{
if (!$saveHandler instanceof AbstractProxy &&
!$saveHandler instanceof \SessionHandlerInterface &&
null !== $saveHandler) {
throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
if (1 > \func_num_args()) {
trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
// Wrap $saveHandler in proxy and prevent double wrapping of proxy

View File

@@ -12,6 +12,7 @@
namespace Symfony\Component\HttpFoundation\Session\Storage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
// Help opcache.preload discover always-needed symbols
class_exists(NativeSessionStorage::class);
@@ -21,15 +22,15 @@ class_exists(NativeSessionStorage::class);
*/
class NativeSessionStorageFactory implements SessionStorageFactoryInterface
{
private $options;
private $handler;
private $metaBag;
private $secure;
private array $options;
private AbstractProxy|\SessionHandlerInterface|null $handler;
private ?MetadataBag $metaBag;
private bool $secure;
/**
* @see NativeSessionStorage constructor.
*/
public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null, bool $secure = false)
public function __construct(array $options = [], AbstractProxy|\SessionHandlerInterface $handler = null, MetadataBag $metaBag = null, bool $secure = false)
{
$this->options = $options;
$this->handler = $handler;
@@ -40,7 +41,7 @@ class NativeSessionStorageFactory implements SessionStorageFactoryInterface
public function createStorage(?Request $request): SessionStorageInterface
{
$storage = new NativeSessionStorage($this->options, $this->handler, $this->metaBag);
if ($this->secure && $request && $request->isSecure()) {
if ($this->secure && $request?->isSecure()) {
$storage->setOptions(['cookie_secure' => true]);
}

View File

@@ -20,10 +20,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
*/
class PhpBridgeSessionStorage extends NativeSessionStorage
{
/**
* @param AbstractProxy|\SessionHandlerInterface|null $handler
*/
public function __construct($handler = null, MetadataBag $metaBag = null)
public function __construct(AbstractProxy|\SessionHandlerInterface $handler = null, MetadataBag $metaBag = null)
{
if (!\extension_loaded('session')) {
throw new \LogicException('PHP extension "session" is required.');
@@ -33,10 +30,7 @@ class PhpBridgeSessionStorage extends NativeSessionStorage
$this->setSaveHandler($handler);
}
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;
@@ -47,9 +41,6 @@ class PhpBridgeSessionStorage extends NativeSessionStorage
return true;
}
/**
* {@inheritdoc}
*/
public function clear()
{
// clear out the bags and nothing else that may be set

View File

@@ -12,6 +12,7 @@
namespace Symfony\Component\HttpFoundation\Session\Storage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
// Help opcache.preload discover always-needed symbols
class_exists(PhpBridgeSessionStorage::class);
@@ -21,14 +22,11 @@ class_exists(PhpBridgeSessionStorage::class);
*/
class PhpBridgeSessionStorageFactory implements SessionStorageFactoryInterface
{
private $handler;
private $metaBag;
private $secure;
private AbstractProxy|\SessionHandlerInterface|null $handler;
private ?MetadataBag $metaBag;
private bool $secure;
/**
* @see PhpBridgeSessionStorage constructor.
*/
public function __construct($handler = null, MetadataBag $metaBag = null, bool $secure = false)
public function __construct(AbstractProxy|\SessionHandlerInterface $handler = null, MetadataBag $metaBag = null, bool $secure = false)
{
$this->handler = $handler;
$this->metaBag = $metaBag;
@@ -38,7 +36,7 @@ class PhpBridgeSessionStorageFactory implements SessionStorageFactoryInterface
public function createStorage(?Request $request): SessionStorageInterface
{
$storage = new PhpBridgeSessionStorage($this->handler, $this->metaBag);
if ($this->secure && $request && $request->isSecure()) {
if ($this->secure && $request?->isSecure()) {
$storage->setOptions(['cookie_secure' => true]);
}

View File

@@ -30,50 +30,40 @@ abstract class AbstractProxy
/**
* Gets the session.save_handler name.
*
* @return string|null
*/
public function getSaveHandlerName()
public function getSaveHandlerName(): ?string
{
return $this->saveHandlerName;
}
/**
* Is this proxy handler and instance of \SessionHandlerInterface.
*
* @return bool
*/
public function isSessionHandlerInterface()
public function isSessionHandlerInterface(): bool
{
return $this instanceof \SessionHandlerInterface;
}
/**
* Returns true if this handler wraps an internal PHP session save handler using \SessionHandler.
*
* @return bool
*/
public function isWrapper()
public function isWrapper(): bool
{
return $this->wrapper;
}
/**
* Has a session started?
*
* @return bool
*/
public function isActive()
public function isActive(): bool
{
return \PHP_SESSION_ACTIVE === session_status();
}
/**
* Gets the session ID.
*
* @return string
*/
public function getId()
public function getId(): string
{
return session_id();
}
@@ -94,10 +84,8 @@ abstract class AbstractProxy
/**
* Gets the session name.
*
* @return string
*/
public function getName()
public function getName(): string
{
return session_name();
}

View File

@@ -27,84 +27,49 @@ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterf
$this->saveHandlerName = $this->wrapper || ($handler instanceof StrictSessionHandler && $handler->isWrapper()) ? \ini_get('session.save_handler') : 'user';
}
/**
* @return \SessionHandlerInterface
*/
public function getHandler()
public function getHandler(): \SessionHandlerInterface
{
return $this->handler;
}
// \SessionHandlerInterface
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function open($savePath, $sessionName)
public function open(string $savePath, string $sessionName): bool
{
return $this->handler->open($savePath, $sessionName);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return $this->handler->close();
}
/**
* @return string|false
*/
#[\ReturnTypeWillChange]
public function read($sessionId)
public function read(string $sessionId): string|false
{
return $this->handler->read($sessionId);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function write($sessionId, $data)
public function write(string $sessionId, string $data): bool
{
return $this->handler->write($sessionId, $data);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function destroy($sessionId)
public function destroy(string $sessionId): bool
{
return $this->handler->destroy($sessionId);
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
return $this->handler->gc($maxlifetime);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function validateId($sessionId)
public function validateId(string $sessionId): bool
{
return !$this->handler instanceof \SessionUpdateTimestampHandlerInterface || $this->handler->validateId($sessionId);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
return $this->handler instanceof \SessionUpdateTimestampHandlerInterface ? $this->handler->updateTimestamp($sessionId, $data) : $this->write($sessionId, $data);
}

View File

@@ -1,38 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Session\Storage;
use Symfony\Component\HttpFoundation\Request;
/**
* @author Jérémy Derussé <jeremy@derusse.com>
*
* @internal to be removed in Symfony 6
*/
final class ServiceSessionFactory implements SessionStorageFactoryInterface
{
private $storage;
public function __construct(SessionStorageInterface $storage)
{
$this->storage = $storage;
}
public function createStorage(?Request $request): SessionStorageInterface
{
if ($this->storage instanceof NativeSessionStorage && $request && $request->isSecure()) {
$this->storage->setOptions(['cookie_secure' => true]);
}
return $this->storage;
}
}

View File

@@ -24,25 +24,19 @@ interface SessionStorageInterface
/**
* Starts the session.
*
* @return bool
*
* @throws \RuntimeException if something goes wrong starting the session
*/
public function start();
public function start(): bool;
/**
* Checks if the session is started.
*
* @return bool
*/
public function isStarted();
public function isStarted(): bool;
/**
* Returns the session ID.
*
* @return string
*/
public function getId();
public function getId(): string;
/**
* Sets the session ID.
@@ -51,10 +45,8 @@ interface SessionStorageInterface
/**
* Returns the session name.
*
* @return string
*/
public function getName();
public function getName(): string;
/**
* Sets the session name.
@@ -86,11 +78,9 @@ interface SessionStorageInterface
* to expire with browser session. Time is in seconds, and is
* not a Unix timestamp.
*
* @return bool
*
* @throws \RuntimeException If an error occurs while regenerating this storage
*/
public function regenerate(bool $destroy = false, int $lifetime = null);
public function regenerate(bool $destroy = false, int $lifetime = null): bool;
/**
* Force the session to be saved and closed.
@@ -113,19 +103,14 @@ interface SessionStorageInterface
/**
* Gets a SessionBagInterface by name.
*
* @return SessionBagInterface
*
* @throws \InvalidArgumentException If the bag does not exist
*/
public function getBag(string $name);
public function getBag(string $name): SessionBagInterface;
/**
* Registers a SessionBagInterface for use.
*/
public function registerBag(SessionBagInterface $bag);
/**
* @return MetadataBag
*/
public function getMetadataBag();
public function getMetadataBag(): MetadataBag;
}

View File

@@ -28,8 +28,11 @@ class StreamedResponse extends Response
{
protected $callback;
protected $streamed;
private $headersSent;
private bool $headersSent;
/**
* @param int $status The HTTP status code (200 "OK" by default)
*/
public function __construct(callable $callback = null, int $status = 200, array $headers = [])
{
parent::__construct(null, $status, $headers);
@@ -41,28 +44,12 @@ class StreamedResponse extends Response
$this->headersSent = false;
}
/**
* Factory method for chainability.
*
* @param callable|null $callback A valid PHP callback or null to set it later
*
* @return static
*
* @deprecated since Symfony 5.1, use __construct() instead.
*/
public static function create($callback = null, int $status = 200, array $headers = [])
{
trigger_deprecation('symfony/http-foundation', '5.1', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class);
return new static($callback, $status, $headers);
}
/**
* Sets the PHP callback associated with this Response.
*
* @return $this
*/
public function setCallback(callable $callback)
public function setCallback(callable $callback): static
{
$this->callback = $callback;
@@ -70,13 +57,11 @@ class StreamedResponse extends Response
}
/**
* {@inheritdoc}
*
* This method only sends the headers once.
*
* @return $this
*/
public function sendHeaders()
public function sendHeaders(): static
{
if ($this->headersSent) {
return $this;
@@ -88,13 +73,11 @@ class StreamedResponse extends Response
}
/**
* {@inheritdoc}
*
* This method only sends the content once.
*
* @return $this
*/
public function sendContent()
public function sendContent(): static
{
if ($this->streamed) {
return $this;
@@ -112,13 +95,11 @@ class StreamedResponse extends Response
}
/**
* {@inheritdoc}
* @return $this
*
* @throws \LogicException when the content is not null
*
* @return $this
*/
public function setContent(?string $content)
public function setContent(?string $content): static
{
if (null !== $content) {
throw new \LogicException('The content cannot be set on a StreamedResponse instance.');
@@ -129,10 +110,7 @@ class StreamedResponse extends Response
return $this;
}
/**
* {@inheritdoc}
*/
public function getContent()
public function getContent(): string|false
{
return false;
}

View File

@@ -16,8 +16,8 @@ use Symfony\Component\HttpFoundation\Request;
final class RequestAttributeValueSame extends Constraint
{
private $name;
private $value;
private string $name;
private string $value;
public function __construct(string $name, string $value)
{
@@ -25,9 +25,6 @@ final class RequestAttributeValueSame extends Constraint
$this->value = $value;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has attribute "%s" with value "%s"', $this->name, $this->value);
@@ -35,8 +32,6 @@ final class RequestAttributeValueSame extends Constraint
/**
* @param Request $request
*
* {@inheritdoc}
*/
protected function matches($request): bool
{
@@ -45,8 +40,6 @@ final class RequestAttributeValueSame extends Constraint
/**
* @param Request $request
*
* {@inheritdoc}
*/
protected function failureDescription($request): string
{

View File

@@ -17,10 +17,10 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseCookieValueSame extends Constraint
{
private $name;
private $value;
private $path;
private $domain;
private string $name;
private string $value;
private string $path;
private ?string $domain;
public function __construct(string $name, string $value, string $path = '/', string $domain = null)
{
@@ -30,9 +30,6 @@ final class ResponseCookieValueSame extends Constraint
$this->domain = $domain;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
$str = sprintf('has cookie "%s"', $this->name);
@@ -49,8 +46,6 @@ final class ResponseCookieValueSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -64,8 +59,6 @@ final class ResponseCookieValueSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{

View File

@@ -22,8 +22,8 @@ use Symfony\Component\HttpFoundation\Response;
*/
final class ResponseFormatSame extends Constraint
{
private $request;
private $format;
private Request $request;
private ?string $format;
public function __construct(Request $request, ?string $format)
{
@@ -31,9 +31,6 @@ final class ResponseFormatSame extends Constraint
$this->format = $format;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return 'format is '.($this->format ?? 'null');
@@ -41,8 +38,6 @@ final class ResponseFormatSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -51,8 +46,6 @@ final class ResponseFormatSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{
@@ -61,8 +54,6 @@ final class ResponseFormatSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function additionalFailureDescription($response): string
{

View File

@@ -17,9 +17,9 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseHasCookie extends Constraint
{
private $name;
private $path;
private $domain;
private string $name;
private string $path;
private ?string $domain;
public function __construct(string $name, string $path = '/', string $domain = null)
{
@@ -28,9 +28,6 @@ final class ResponseHasCookie extends Constraint
$this->domain = $domain;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
$str = sprintf('has cookie "%s"', $this->name);
@@ -46,8 +43,6 @@ final class ResponseHasCookie extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -56,8 +51,6 @@ final class ResponseHasCookie extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{

View File

@@ -16,16 +16,13 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseHasHeader extends Constraint
{
private $headerName;
private string $headerName;
public function __construct(string $headerName)
{
$this->headerName = $headerName;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has header "%s"', $this->headerName);
@@ -33,8 +30,6 @@ final class ResponseHasHeader extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -43,8 +38,6 @@ final class ResponseHasHeader extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{

View File

@@ -16,8 +16,8 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseHeaderSame extends Constraint
{
private $headerName;
private $expectedValue;
private string $headerName;
private string $expectedValue;
public function __construct(string $headerName, string $expectedValue)
{
@@ -25,9 +25,6 @@ final class ResponseHeaderSame extends Constraint
$this->expectedValue = $expectedValue;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('has header "%s" with value "%s"', $this->headerName, $this->expectedValue);
@@ -35,8 +32,6 @@ final class ResponseHeaderSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -45,8 +40,6 @@ final class ResponseHeaderSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{

View File

@@ -16,9 +16,6 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseIsRedirected extends Constraint
{
/**
* {@inheritdoc}
*/
public function toString(): string
{
return 'is redirected';
@@ -26,8 +23,6 @@ final class ResponseIsRedirected extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -36,8 +31,6 @@ final class ResponseIsRedirected extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{
@@ -46,8 +39,6 @@ final class ResponseIsRedirected extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function additionalFailureDescription($response): string
{

View File

@@ -16,9 +16,6 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseIsSuccessful extends Constraint
{
/**
* {@inheritdoc}
*/
public function toString(): string
{
return 'is successful';
@@ -26,8 +23,6 @@ final class ResponseIsSuccessful extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -36,8 +31,6 @@ final class ResponseIsSuccessful extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{
@@ -46,8 +39,6 @@ final class ResponseIsSuccessful extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function additionalFailureDescription($response): string
{

View File

@@ -16,9 +16,6 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseIsUnprocessable extends Constraint
{
/**
* {@inheritdoc}
*/
public function toString(): string
{
return 'is unprocessable';
@@ -26,8 +23,6 @@ final class ResponseIsUnprocessable extends Constraint
/**
* @param Response $other
*
* {@inheritdoc}
*/
protected function matches($other): bool
{
@@ -36,8 +31,6 @@ final class ResponseIsUnprocessable extends Constraint
/**
* @param Response $other
*
* {@inheritdoc}
*/
protected function failureDescription($other): string
{
@@ -46,8 +39,6 @@ final class ResponseIsUnprocessable extends Constraint
/**
* @param Response $other
*
* {@inheritdoc}
*/
protected function additionalFailureDescription($other): string
{

View File

@@ -16,16 +16,13 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseStatusCodeSame extends Constraint
{
private $statusCode;
private int $statusCode;
public function __construct(int $statusCode)
{
$this->statusCode = $statusCode;
}
/**
* {@inheritdoc}
*/
public function toString(): string
{
return 'status code is '.$this->statusCode;
@@ -33,8 +30,6 @@ final class ResponseStatusCodeSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
@@ -43,8 +38,6 @@ final class ResponseStatusCodeSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{
@@ -53,8 +46,6 @@ final class ResponseStatusCodeSame extends Constraint
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function additionalFailureDescription($response): string
{

View File

@@ -20,8 +20,8 @@ use Symfony\Component\Routing\RequestContext;
*/
final class UrlHelper
{
private $requestStack;
private $requestContext;
private RequestStack $requestStack;
private ?RequestContext $requestContext;
public function __construct(RequestStack $requestStack, RequestContext $requestContext = null)
{
@@ -31,7 +31,7 @@ final class UrlHelper
public function getAbsoluteUrl(string $path): string
{
if (str_contains($path, '://') || '//' === substr($path, 0, 2)) {
if (str_contains($path, '://') || str_starts_with($path, '//')) {
return $path;
}
@@ -60,7 +60,7 @@ final class UrlHelper
public function getRelativePath(string $path): string
{
if (str_contains($path, '://') || '//' === substr($path, 0, 2)) {
if (str_contains($path, '://') || str_starts_with($path, '//')) {
return $path;
}

View File

@@ -16,20 +16,22 @@
}
],
"require": {
"php": ">=7.2.5",
"php": ">=8.1",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/polyfill-mbstring": "~1.1",
"symfony/polyfill-php80": "^1.16"
"symfony/polyfill-mbstring": "~1.1"
},
"require-dev": {
"predis/predis": "~1.0",
"symfony/cache": "^4.4|^5.0|^6.0",
"symfony/cache": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/http-kernel": "^5.4.12|^6.0.12|^6.1.4",
"symfony/mime": "^4.4|^5.0|^6.0",
"symfony/expression-language": "^4.4|^5.0|^6.0",
"symfony/mime": "^5.4|^6.0",
"symfony/expression-language": "^5.4|^6.0",
"symfony/rate-limiter": "^5.2|^6.0"
},
"conflict": {
"symfony/cache": "<6.2"
},
"suggest" : {
"symfony/mime": "To use the file extension guesser"
},