fix:更新已知bug,优化代码

This commit is contained in:
Ying
2022-11-28 19:11:12 +08:00
parent f6aee95cfc
commit 9445b206a2
1378 changed files with 53759 additions and 20789 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,10 +122,8 @@ class AcceptHeader
/**
* Returns first item.
*
* @return AcceptHeaderItem|null
*/
public function first()
public function first(): ?AcceptHeaderItem
{
$this->sort();

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

@@ -45,7 +45,7 @@ class BinaryFileResponse extends Response
* @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();
@@ -204,17 +180,21 @@ class BinaryFileResponse extends Response
/**
* {@inheritdoc}
*/
public function prepare(Request $request)
public function prepare(Request $request): static
{
if ($this->isInformational() || $this->isEmpty()) {
parent::prepare($request);
$this->maxlen = 0;
return $this;
}
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
}
if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
$this->setProtocolVersion('1.1');
}
$this->ensureIEOverSSLCompatibility($request);
parent::prepare($request);
$this->offset = 0;
$this->maxlen = -1;
@@ -222,6 +202,7 @@ class BinaryFileResponse extends Response
if (false === $fileSize = $this->file->getSize()) {
return $this;
}
$this->headers->remove('Transfer-Encoding');
$this->headers->set('Content-Length', $fileSize);
if (!$this->headers->has('Accept-Ranges')) {
@@ -291,6 +272,10 @@ class BinaryFileResponse extends Response
}
}
if ($request->isMethod('HEAD')) {
$this->maxlen = 0;
}
return $this;
}
@@ -310,42 +295,44 @@ class BinaryFileResponse extends Response
/**
* {@inheritdoc}
*/
public function sendContent()
public function sendContent(): static
{
if (!$this->isSuccessful()) {
return parent::sendContent();
}
if (0 === $this->maxlen) {
return $this;
}
$out = fopen('php://output', 'w');
$file = fopen($this->file->getPathname(), 'r');
ignore_user_abort(true);
if (0 !== $this->offset) {
fseek($file, $this->offset);
}
$length = $this->maxlen;
while ($length && !feof($file)) {
$read = ($length > $this->chunkSize) ? $this->chunkSize : $length;
$length -= $read;
stream_copy_to_stream($file, $out, $read);
if (connection_aborted()) {
break;
try {
if (!$this->isSuccessful()) {
return parent::sendContent();
}
}
fclose($out);
fclose($file);
if (0 === $this->maxlen) {
return $this;
}
if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) {
unlink($this->file->getPathname());
$out = fopen('php://output', 'w');
$file = fopen($this->file->getPathname(), 'r');
ignore_user_abort(true);
if (0 !== $this->offset) {
fseek($file, $this->offset);
}
$length = $this->maxlen;
while ($length && !feof($file)) {
$read = ($length > $this->chunkSize) ? $this->chunkSize : $length;
$length -= $read;
stream_copy_to_stream($file, $out, $read);
if (connection_aborted()) {
break;
}
}
fclose($out);
fclose($file);
} finally {
if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) {
unlink($this->file->getPathname());
}
}
return $this;
@@ -356,7 +343,7 @@ class BinaryFileResponse extends Response
*
* @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.');
@@ -368,7 +355,7 @@ class BinaryFileResponse extends Response
/**
* {@inheritdoc}
*/
public function getContent()
public function getContent(): string|false
{
return false;
}
@@ -387,7 +374,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,24 @@
CHANGELOG
=========
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
---

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,7 @@ 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
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);
}
@@ -89,7 +87,7 @@ class Cookie
*
* @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 = 'lax')
{
// from PHP source code
if ($raw && false !== strpbrk($name, self::RESERVED_CHARS_LIST)) {
@@ -113,10 +111,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 +122,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 +133,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 +144,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 +163,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 +174,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 +185,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 +196,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));
@@ -231,10 +211,8 @@ class Cookie
/**
* Creates a cookie copy with SameSite attribute.
*
* @return static
*/
public function withSameSite(?string $sameSite): self
public function withSameSite(?string $sameSite): static
{
if ('' === $sameSite) {
$sameSite = null;
@@ -254,10 +232,8 @@ class Cookie
/**
* Returns the cookie as a string.
*
* @return string
*/
public function __toString()
public function __toString(): string
{
if ($this->isRaw()) {
$str = $this->getName();
@@ -302,50 +278,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 +320,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
*/
public function getSameSite()
public function getSameSite(): ?string
{
return $this->sameSite;
}

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\HttpFoundation;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
/**
@@ -23,15 +24,15 @@ class ExpressionRequestMatcher extends RequestMatcher
private $language;
private $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

@@ -43,7 +43,7 @@ class FileBag extends ParameterBag
/**
* {@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.');
@@ -65,11 +65,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 +104,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,10 +64,10 @@ 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;
@@ -86,7 +76,7 @@ final class InputBag extends ParameterBag
/**
* {@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 +86,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];

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);
@@ -54,29 +51,6 @@ class JsonResponse extends Response
$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.
*
@@ -88,10 +62,8 @@ class JsonResponse extends Response
* @param string $data The JSON response string
* @param int $status The response status code
* @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,7 +77,7 @@ 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 (null !== $callback) {
// partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/
@@ -136,7 +108,7 @@ class JsonResponse extends Response
*
* @return $this
*/
public function setJson(string $json)
public function setJson(string $json): static
{
$this->data = $json;
@@ -146,13 +118,11 @@ 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);
@@ -163,7 +133,7 @@ class JsonResponse extends Response
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 +146,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 +157,7 @@ class JsonResponse extends Response
*
* @return $this
*/
public function setEncodingOptions(int $encodingOptions)
public function setEncodingOptions(int $encodingOptions): static
{
$this->encodingOptions = $encodingOptions;
@@ -201,7 +169,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,20 +127,16 @@ 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);
}
@@ -174,15 +144,11 @@ class ParameterBag implements \IteratorAggregate, \Countable
/**
* 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

@@ -35,9 +35,7 @@ abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface
foreach ($limiters as $limiter) {
$rateLimit = $limiter->consume(1);
if (null === $minimalRateLimit || $rateLimit->getRemainingTokens() < $minimalRateLimit->getRemainingTokens()) {
$minimalRateLimit = $rateLimit;
}
$minimalRateLimit = $minimalRateLimit ? self::getMinimalRateLimit($minimalRateLimit, $rateLimit) : $rateLimit;
}
return $minimalRateLimit;
@@ -54,4 +52,20 @@ abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface
* @return LimiterInterface[] a set of limiters using keys extracted from the request
*/
abstract protected function getLimiters(Request $request): array;
private static function getMinimalRateLimit(RateLimit $first, RateLimit $second): RateLimit
{
if ($first->isAccepted() !== $second->isAccepted()) {
return $first->isAccepted() ? $second : $first;
}
$firstRemainingTokens = $first->getRemainingTokens();
$secondRemainingTokens = $second->getRemainingTokens();
if ($firstRemainingTokens === $secondRemainingTokens) {
return $first->getRetryAfter() < $second->getRetryAfter() ? $second : $first;
}
return $firstRemainingTokens > $secondRemainingTokens ? $second : $first;
}
}

View File

@@ -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
@@ -207,19 +205,12 @@ class Request
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;
@@ -601,10 +578,8 @@ class Request
/**
* Gets the list of trusted proxies.
*
* @return array
*/
public static function getTrustedProxies()
public static function getTrustedProxies(): array
{
return self::$trustedProxies;
}
@@ -614,7 +589,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;
}
@@ -637,10 +612,8 @@ class Request
/**
* Gets the list of trusted host patterns.
*
* @return array
*/
public static function getTrustedHosts()
public static function getTrustedHosts(): array
{
return self::$trustedHostPatterns;
}
@@ -650,10 +623,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 +654,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 +669,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;
@@ -725,10 +690,8 @@ class Request
/**
* Gets the Session.
*
* @return SessionInterface
*/
public function getSession()
public function getSession(): SessionInterface
{
$session = $this->session;
if (!$session instanceof SessionInterface && null !== $session) {
@@ -745,10 +708,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 +723,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 +753,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 +779,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 +791,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,7 +811,7 @@ 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();
@@ -881,7 +832,7 @@ 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();
@@ -900,7 +851,7 @@ class Request
*
* @return string The raw URL (i.e. not urldecoded)
*/
public function getBaseUrl()
public function getBaseUrl(): string
{
$trustedPrefix = '';
@@ -929,10 +880,8 @@ class Request
/**
* Gets the request's scheme.
*
* @return string
*/
public function getScheme()
public function getScheme(): string
{
return $this->isSecure() ? 'https' : 'http';
}
@@ -947,7 +896,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 +921,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 +940,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,10 +956,8 @@ 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();
@@ -1031,7 +974,7 @@ 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();
@@ -1045,10 +988,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 +997,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 +1012,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 +1032,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 +1074,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 +1089,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 +1109,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 +1183,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 +1223,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();
@@ -1321,10 +1244,8 @@ class Request
/**
* Gets the mime types associated with the format.
*
* @return array
*/
public static function getMimeTypes(string $format)
public static function getMimeTypes(string $format): array
{
if (null === static::$formats) {
static::initializeFormats();
@@ -1335,10 +1256,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, ';')) {
@@ -1366,7 +1285,7 @@ class Request
*
* @param string|array $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,10 +1304,8 @@ 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');
@@ -1407,10 +1324,8 @@ class Request
/**
* Gets the format associated with the request.
*
* @return string|null
*/
public function getContentType()
public function getContentType(): ?string
{
return $this->getFormat($this->headers->get('CONTENT_TYPE', ''));
}
@@ -1429,10 +1344,8 @@ class Request
/**
* Get the default locale.
*
* @return string
*/
public function getDefaultLocale()
public function getDefaultLocale(): string
{
return $this->defaultLocale;
}
@@ -1447,10 +1360,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 +1370,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 +1380,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 +1398,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 +1412,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);
@@ -1574,25 +1475,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 +1497,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 +1535,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();
@@ -1678,10 +1566,8 @@ class Request
/**
* Gets a list of languages acceptable by the client browser ordered in the user browser preferences.
*
* @return array
*/
public function getLanguages()
public function getLanguages(): array
{
if (null !== $this->languages) {
return $this->languages;
@@ -1689,7 +1575,8 @@ class Request
$languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
$this->languages = [];
foreach ($languages as $lang => $acceptHeaderItem) {
foreach ($languages as $acceptHeaderItem) {
$lang = $acceptHeaderItem->getValue();
if (str_contains($lang, '-')) {
$codes = explode('-', $lang);
if ('i' === $codes[0]) {
@@ -1718,44 +1605,38 @@ class Request
/**
* Gets a list of charsets acceptable by the client browser in preferable order.
*
* @return array
*/
public function getCharsets()
public function getCharsets(): array
{
if (null !== $this->charsets) {
return $this->charsets;
}
return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
return $this->charsets = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()));
}
/**
* Gets a list of encodings acceptable by the client browser in preferable order.
*
* @return array
*/
public function getEncodings()
public function getEncodings(): array
{
if (null !== $this->encodings) {
return $this->encodings;
}
return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
return $this->encodings = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all()));
}
/**
* Gets a list of content types acceptable by the client browser in preferable order.
*
* @return array
*/
public function getAcceptableContentTypes()
public function getAcceptableContentTypes(): array
{
if (null !== $this->acceptableContentTypes) {
return $this->acceptableContentTypes;
}
return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
return $this->acceptableContentTypes = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()));
}
/**
@@ -1765,10 +1646,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');
}
@@ -1780,7 +1659,7 @@ class Request
*/
public function preferSafeContent(): bool
{
if (null !== $this->isSafeContentPreferred) {
if (isset($this->isSafeContentPreferred)) {
return $this->isSafeContentPreferred;
}
@@ -1847,10 +1726,8 @@ class Request
/**
* Prepares the base URL.
*
* @return string
*/
protected function prepareBaseUrl()
protected function prepareBaseUrl(): string
{
$filename = basename($this->server->get('SCRIPT_FILENAME', ''));
@@ -1916,10 +1793,8 @@ class Request
/**
* Prepares the base path.
*
* @return string
*/
protected function prepareBasePath()
protected function prepareBasePath(): string
{
$baseUrl = $this->getBaseUrl();
if (empty($baseUrl)) {
@@ -1942,10 +1817,8 @@ class Request
/**
* Prepares the path info.
*
* @return string
*/
protected function preparePathInfo()
protected function preparePathInfo(): string
{
if (null === ($requestUri = $this->getRequestUri())) {
return '/';
@@ -2024,7 +1897,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);
@@ -2044,10 +1917,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);
}

View File

@@ -18,47 +18,36 @@ namespace Symfony\Component\HttpFoundation;
*/
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 +66,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 +112,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 +126,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) : [];
}
@@ -153,7 +142,7 @@ class RequestMatcher implements RequestMatcherInterface
/**
* {@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

@@ -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

@@ -220,25 +220,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 +227,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 +254,7 @@ class Response
*
* @return $this
*/
public function prepare(Request $request)
public function prepare(Request $request): static
{
$headers = $this->headers;
@@ -345,7 +324,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 +355,7 @@ class Response
*
* @return $this
*/
public function sendContent()
public function sendContent(): static
{
echo $this->content;
@@ -388,7 +367,7 @@ class Response
*
* @return $this
*/
public function send()
public function send(): static
{
$this->sendHeaders();
$this->sendContent();
@@ -399,6 +378,7 @@ class Response
litespeed_finish_request();
} elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
static::closeOutputBuffers(0, true);
flush();
}
return $this;
@@ -409,7 +389,7 @@ class Response
*
* @return $this
*/
public function setContent(?string $content)
public function setContent(?string $content): static
{
$this->content = $content ?? '';
@@ -418,10 +398,8 @@ class Response
/**
* Gets the current response content.
*
* @return string|false
*/
public function getContent()
public function getContent(): string|false
{
return $this->content;
}
@@ -433,7 +411,7 @@ class Response
*
* @final
*/
public function setProtocolVersion(string $version): object
public function setProtocolVersion(string $version): static
{
$this->version = $version;
@@ -462,7 +440,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()) {
@@ -503,7 +481,7 @@ class Response
*
* @final
*/
public function setCharset(string $charset): object
public function setCharset(string $charset): static
{
$this->charset = $charset;
@@ -584,7 +562,7 @@ class Response
*
* @final
*/
public function setPrivate(): object
public function setPrivate(): static
{
$this->headers->removeCacheControlDirective('public');
$this->headers->addCacheControlDirective('private');
@@ -601,7 +579,7 @@ class Response
*
* @final
*/
public function setPublic(): object
public function setPublic(): static
{
$this->headers->addCacheControlDirective('public');
$this->headers->removeCacheControlDirective('private');
@@ -616,7 +594,7 @@ class Response
*
* @final
*/
public function setImmutable(bool $immutable = true): object
public function setImmutable(bool $immutable = true): static
{
if ($immutable) {
$this->headers->addCacheControlDirective('immutable');
@@ -671,7 +649,7 @@ class Response
*
* @final
*/
public function setDate(\DateTimeInterface $date): object
public function setDate(\DateTimeInterface $date): static
{
if ($date instanceof \DateTime) {
$date = \DateTimeImmutable::createFromMutable($date);
@@ -702,7 +680,7 @@ class Response
*
* @return $this
*/
public function expire()
public function expire(): static
{
if ($this->isFresh()) {
$this->headers->set('Age', $this->getMaxAge());
@@ -736,7 +714,7 @@ class Response
*
* @final
*/
public function setExpires(\DateTimeInterface $date = null): object
public function setExpires(\DateTimeInterface $date = null): static
{
if (null === $date) {
$this->headers->remove('Expires');
@@ -789,7 +767,7 @@ class Response
*
* @final
*/
public function setMaxAge(int $value): object
public function setMaxAge(int $value): static
{
$this->headers->addCacheControlDirective('max-age', $value);
@@ -805,7 +783,7 @@ class Response
*
* @final
*/
public function setSharedMaxAge(int $value): object
public function setSharedMaxAge(int $value): static
{
$this->setPublic();
$this->headers->addCacheControlDirective('s-maxage', $value);
@@ -839,7 +817,7 @@ class Response
*
* @final
*/
public function setTtl(int $seconds): object
public function setTtl(int $seconds): static
{
$this->setSharedMaxAge($this->getAge() + $seconds);
@@ -855,7 +833,7 @@ class Response
*
* @final
*/
public function setClientTtl(int $seconds): object
public function setClientTtl(int $seconds): static
{
$this->setMaxAge($this->getAge() + $seconds);
@@ -883,7 +861,7 @@ class Response
*
* @final
*/
public function setLastModified(\DateTimeInterface $date = null): object
public function setLastModified(\DateTimeInterface $date = null): static
{
if (null === $date) {
$this->headers->remove('Last-Modified');
@@ -921,7 +899,7 @@ class Response
*
* @final
*/
public function setEtag(string $etag = null, bool $weak = false): object
public function setEtag(string $etag = null, bool $weak = false): static
{
if (null === $etag) {
$this->headers->remove('Etag');
@@ -947,7 +925,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)));
@@ -1010,7 +988,7 @@ class Response
*
* @final
*/
public function setNotModified(): object
public function setNotModified(): static
{
$this->setStatusCode(304);
$this->setContent(null);
@@ -1055,14 +1033,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);
@@ -1245,7 +1222,6 @@ class Response
while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
if ($flush) {
ob_end_flush();
flush();
} else {
ob_end_clean();
}

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) {
@@ -88,7 +86,7 @@ class ResponseHeaderBag extends HeaderBag
/**
* {@inheritdoc}
*/
public function all(string $key = null)
public function all(string $key = null): array
{
$headers = parent::all();
@@ -108,7 +106,7 @@ class ResponseHeaderBag extends HeaderBag
/**
* {@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);
@@ -164,7 +162,7 @@ class ResponseHeaderBag extends HeaderBag
/**
* {@inheritdoc}
*/
public function hasCacheControlDirective(string $key)
public function hasCacheControlDirective(string $key): bool
{
return \array_key_exists($key, $this->computedCacheControl);
}
@@ -172,7 +170,7 @@ class ResponseHeaderBag extends HeaderBag
/**
* {@inheritdoc}
*/
public function getCacheControlDirective(string $key)
public function getCacheControlDirective(string $key): bool|string|null
{
return $this->computedCacheControl[$key] ?? null;
}
@@ -214,7 +212,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 +255,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 = [];
@@ -34,7 +34,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -55,7 +55,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
@@ -63,7 +63,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
/**
* {@inheritdoc}
*/
public function has(string $name)
public function has(string $name): bool
{
return \array_key_exists($name, $this->attributes);
}
@@ -71,7 +71,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
/**
* {@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;
}
@@ -79,7 +79,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
/**
* {@inheritdoc}
*/
public function set(string $name, $value)
public function set(string $name, mixed $value)
{
$this->attributes[$name] = $value;
}
@@ -87,7 +87,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
return $this->attributes;
}
@@ -106,7 +106,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)) {
@@ -120,7 +120,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
$return = $this->attributes;
$this->attributes = [];
@@ -133,19 +133,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
@@ -33,7 +33,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -60,7 +60,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function add(string $type, $message)
public function add(string $type, mixed $message)
{
$this->flashes['new'][$type][] = $message;
}
@@ -68,7 +68,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@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;
}
@@ -76,7 +76,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function peekAll()
public function peekAll(): array
{
return \array_key_exists('display', $this->flashes) ? $this->flashes['display'] : [];
}
@@ -84,7 +84,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function get(string $type, array $default = [])
public function get(string $type, array $default = []): array
{
$return = $default;
@@ -103,7 +103,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
$return = $this->flashes['display'];
$this->flashes['display'] = [];
@@ -122,7 +122,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function set(string $type, $messages)
public function set(string $type, string|array $messages)
{
$this->flashes['new'][$type] = (array) $messages;
}
@@ -130,7 +130,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function has(string $type)
public function has(string $type): bool
{
return \array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type];
}
@@ -138,7 +138,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function keys()
public function keys(): array
{
return array_keys($this->flashes['display']);
}
@@ -146,7 +146,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
@@ -154,7 +154,7 @@ class AutoExpireFlashBag implements FlashBagInterface
/**
* {@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
@@ -33,7 +33,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -54,7 +54,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function add(string $type, $message)
public function add(string $type, mixed $message)
{
$this->flashes[$type][] = $message;
}
@@ -62,7 +62,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function peek(string $type, array $default = [])
public function peek(string $type, array $default = []): array
{
return $this->has($type) ? $this->flashes[$type] : $default;
}
@@ -70,7 +70,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function peekAll()
public function peekAll(): array
{
return $this->flashes;
}
@@ -78,7 +78,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function get(string $type, array $default = [])
public function get(string $type, array $default = []): array
{
if (!$this->has($type)) {
return $default;
@@ -94,7 +94,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
$return = $this->peekAll();
$this->flashes = [];
@@ -105,7 +105,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function set(string $type, $messages)
public function set(string $type, string|array $messages)
{
$this->flashes[$type] = (array) $messages;
}
@@ -121,7 +121,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function has(string $type)
public function has(string $type): bool
{
return \array_key_exists($type, $this->flashes) && $this->flashes[$type];
}
@@ -129,7 +129,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function keys()
public function keys(): array
{
return array_keys($this->flashes);
}
@@ -137,7 +137,7 @@ class FlashBag implements FlashBagInterface
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
@@ -145,7 +145,7 @@ class FlashBag implements FlashBagInterface
/**
* {@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

@@ -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;
@@ -33,16 +34,16 @@ class Session implements SessionInterface, \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 = $usageReporter instanceof \Closure || !\is_callable($usageReporter) ? $usageReporter : \Closure::fromCallable($usageReporter);
$attributes = $attributes ?? new AttributeBag();
$this->attributeName = $attributes->getName();
@@ -56,7 +57,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
return $this->storage->start();
}
@@ -64,7 +65,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function has(string $name)
public function has(string $name): bool
{
return $this->getAttributeBag()->has($name);
}
@@ -72,7 +73,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function get(string $name, $default = null)
public function get(string $name, mixed $default = null): mixed
{
return $this->getAttributeBag()->get($name, $default);
}
@@ -80,7 +81,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function set(string $name, $value)
public function set(string $name, mixed $value)
{
$this->getAttributeBag()->set($name, $value);
}
@@ -88,7 +89,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function all()
public function all(): array
{
return $this->getAttributeBag()->all();
}
@@ -104,7 +105,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function remove(string $name)
public function remove(string $name): mixed
{
return $this->getAttributeBag()->remove($name);
}
@@ -120,7 +121,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function isStarted()
public function isStarted(): bool
{
return $this->storage->isStarted();
}
@@ -130,19 +131,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());
}
@@ -175,7 +172,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function invalidate(int $lifetime = null)
public function invalidate(int $lifetime = null): bool
{
$this->storage->clear();
@@ -185,7 +182,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@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);
}
@@ -201,7 +198,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function getId()
public function getId(): string
{
return $this->storage->getId();
}
@@ -219,7 +216,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->storage->getName();
}
@@ -235,7 +232,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function getMetadataBag()
public function getMetadataBag(): MetadataBag
{
++$this->usageIndex;
if ($this->usageReporter && 0 <= $this->usageIndex) {
@@ -256,7 +253,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
/**
* {@inheritdoc}
*/
public function getBag(string $name)
public function getBag(string $name): SessionBagInterface
{
$bag = $this->storage->getBag($name);
@@ -265,10 +262,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

@@ -19,16 +19,16 @@ namespace Symfony\Component\HttpFoundation\Session;
final class SessionBagProxy implements SessionBagInterface
{
private $bag;
private $data;
private $usageIndex;
private $usageReporter;
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 = $usageReporter instanceof \Closure || !\is_callable($usageReporter) ? $usageReporter : \Closure::fromCallable($usageReporter);
}
public function getBag(): SessionBagInterface
@@ -88,7 +88,7 @@ final class SessionBagProxy implements SessionBagInterface
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
return $this->bag->clear();
}

View File

@@ -24,13 +24,13 @@ class SessionFactory implements SessionFactoryInterface
{
private $requestStack;
private $storageFactory;
private $usageReporter;
private ?\Closure $usageReporter;
public function __construct(RequestStack $requestStack, SessionStorageFactoryInterface $storageFactory, callable $usageReporter = null)
{
$this->requestStack = $requestStack;
$this->storageFactory = $storageFactory;
$this->usageReporter = $usageReporter;
$this->usageReporter = $usageReporter instanceof \Closure || !\is_callable($usageReporter) ? $usageReporter : \Closure::fromCallable($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 (!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

@@ -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

@@ -24,14 +24,14 @@ class MemcachedSessionHandler extends AbstractSessionHandler
private $memcached;
/**
* @var int Time to live in seconds
* Time to live in seconds.
*/
private $ttl;
private ?int $ttl;
/**
* @var string Key prefix for shared environments
* Key prefix for shared environments.
*/
private $prefix;
private string $prefix;
/**
* Constructor.
@@ -54,11 +54,7 @@ class MemcachedSessionHandler extends AbstractSessionHandler
$this->prefix = $options['prefix'] ?? 'sf2s';
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return $this->memcached->quit();
}
@@ -66,16 +62,12 @@ class MemcachedSessionHandler extends AbstractSessionHandler
/**
* {@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, time() + (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')));
@@ -85,7 +77,7 @@ class MemcachedSessionHandler extends AbstractSessionHandler
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
return $this->memcached->set($this->prefix.$sessionId, $data, time() + (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')));
}
@@ -93,18 +85,14 @@ class MemcachedSessionHandler extends AbstractSessionHandler
/**
* {@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;
@@ -112,10 +100,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

@@ -27,16 +27,8 @@ use MongoDB\Collection;
class MongoDbSessionHandler extends AbstractSessionHandler
{
private $mongo;
/**
* @var Collection
*/
private $collection;
/**
* @var array
*/
private $options;
private array $options;
/**
* Constructor.
@@ -84,11 +76,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
], $options);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
return true;
}
@@ -96,7 +84,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId)
protected function doDestroy(string $sessionId): bool
{
$this->getCollection()->deleteOne([
$this->options['id_field'] => $sessionId,
@@ -105,11 +93,7 @@ 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()],
@@ -119,7 +103,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
/**
* {@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);
@@ -138,11 +122,7 @@ 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);
@@ -160,7 +140,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
/**
* {@inheritdoc}
*/
protected function doRead(string $sessionId)
protected function doRead(string $sessionId): string
{
$dbData = $this->getCollection()->findOne([
$this->options['id_field'] => $sessionId,
@@ -176,17 +156,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

@@ -18,20 +18,12 @@ 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;
}
@@ -39,16 +31,12 @@ class NullSessionHandler extends AbstractSessionHandler
/**
* {@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;
}
@@ -56,7 +44,7 @@ class NullSessionHandler extends AbstractSessionHandler
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
return true;
}
@@ -64,16 +52,12 @@ class NullSessionHandler extends AbstractSessionHandler
/**
* {@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,61 @@ 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;
/**
* 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;
/**
* @var string|null
*/
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 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';
/**
* 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
@@ -186,7 +142,7 @@ class PdoSessionHandler extends AbstractSessionHandler
*
* @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)) {
@@ -267,34 +223,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 +251,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.
@@ -321,7 +263,7 @@ class PdoSessionHandler extends AbstractSessionHandler
/**
* {@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";
@@ -342,7 +284,7 @@ class PdoSessionHandler extends AbstractSessionHandler
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
$maxlifetime = (int) \ini_get('session.gc_maxlifetime');
@@ -385,11 +327,7 @@ 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');
@@ -410,11 +348,7 @@ class PdoSessionHandler extends AbstractSessionHandler
return true;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
$this->commit();
@@ -426,27 +360,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;
@@ -649,10 +570,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 +588,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;
@@ -804,14 +720,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 +735,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 +844,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

@@ -26,37 +26,24 @@ class RedisSessionHandler extends AbstractSessionHandler
private $redis;
/**
* @var string Key prefix for shared environments
* Key prefix for shared environments.
*/
private $prefix;
private string $prefix;
/**
* @var int Time to live in seconds
* Time to live in seconds.
*/
private $ttl;
private ?int $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 = [])
public function __construct(\Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $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)));
}
if ($diff = array_diff(array_keys($options), ['prefix', 'ttl'])) {
throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff)));
}
@@ -115,23 +102,13 @@ class RedisSessionHandler extends AbstractSessionHandler
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')));
return $this->redis->expire($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')));
}
}

View File

@@ -21,15 +21,8 @@ use Symfony\Component\Cache\Traits\RedisProxy;
*/
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): 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 ($options = \is_string($connection) ? parse_url($connection) : false) {
parse_str($options['query'] ?? '', $options);
}

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)
{
@@ -31,10 +31,16 @@ class StrictSessionHandler extends AbstractSessionHandler
}
/**
* @return bool
* Returns true if this handler wraps an internal PHP session save handler using \SessionHandler.
*
* @internal
*/
#[\ReturnTypeWillChange]
public function open($savePath, $sessionName)
public function isWrapper(): bool
{
return $this->handler instanceof \SessionHandler;
}
public function open(string $savePath, string $sessionName): bool
{
parent::open($savePath, $sessionName);
@@ -44,16 +50,12 @@ class StrictSessionHandler extends AbstractSessionHandler
/**
* {@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);
}
@@ -61,16 +63,12 @@ class StrictSessionHandler extends AbstractSessionHandler
/**
* {@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);
@@ -81,27 +79,19 @@ class StrictSessionHandler extends AbstractSessionHandler
/**
* {@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
@@ -84,10 +72,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];
}
@@ -108,7 +94,7 @@ class MetadataBag implements SessionBagInterface
/**
* {@inheritdoc}
*/
public function getStorageKey()
public function getStorageKey(): string
{
return $this->storageKey;
}
@@ -118,7 +104,7 @@ class MetadataBag implements SessionBagInterface
*
* @return int Unix timestamp
*/
public function getCreated()
public function getCreated(): int
{
return $this->meta[self::CREATED];
}
@@ -128,7 +114,7 @@ class MetadataBag implements SessionBagInterface
*
* @return int Unix timestamp
*/
public function getLastUsed()
public function getLastUsed(): int
{
return $this->lastUsed;
}
@@ -136,7 +122,7 @@ class MetadataBag implements SessionBagInterface
/**
* {@inheritdoc}
*/
public function clear()
public function clear(): mixed
{
// nothing to do
return null;
@@ -145,7 +131,7 @@ class MetadataBag implements SessionBagInterface
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}

View File

@@ -76,7 +76,7 @@ class MockArraySessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;
@@ -94,7 +94,7 @@ class MockArraySessionStorage implements SessionStorageInterface
/**
* {@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();
@@ -109,7 +109,7 @@ class MockArraySessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function getId()
public function getId(): string
{
return $this->id;
}
@@ -129,7 +129,7 @@ class MockArraySessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -183,7 +183,7 @@ class MockArraySessionStorage implements SessionStorageInterface
/**
* {@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));
@@ -199,7 +199,7 @@ class MockArraySessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function isStarted()
public function isStarted(): bool
{
return $this->started;
}
@@ -215,10 +215,8 @@ class MockArraySessionStorage implements SessionStorageInterface
/**
* Gets the MetadataBag.
*
* @return MetadataBag
*/
public function getMetadataBag()
public function getMetadataBag(): MetadataBag
{
return $this->metadataBag;
}
@@ -228,10 +226,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));
}

View File

@@ -25,7 +25,7 @@ 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
@@ -48,7 +48,7 @@ class MockFileSessionStorage extends MockArraySessionStorage
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;
@@ -68,7 +68,7 @@ class MockFileSessionStorage extends MockArraySessionStorage
/**
* {@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();

View File

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

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,10 +112,8 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* Gets the save handler instance.
*
* @return AbstractProxy|\SessionHandlerInterface
*/
public function getSaveHandler()
public function getSaveHandler(): AbstractProxy|\SessionHandlerInterface
{
return $this->saveHandler;
}
@@ -131,7 +121,7 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;
@@ -186,13 +176,6 @@ 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;
@@ -201,7 +184,7 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function getId()
public function getId(): string
{
return $this->saveHandler->getId();
}
@@ -217,7 +200,7 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function getName()
public function getName(): string
{
return $this->saveHandler->getName();
}
@@ -233,7 +216,7 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* {@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,16 +237,7 @@ 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);
}
/**
@@ -340,7 +314,7 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* {@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));
@@ -366,10 +340,8 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* Gets the MetadataBag.
*
* @return MetadataBag
*/
public function getMetadataBag()
public function getMetadataBag(): MetadataBag
{
return $this->metadataBag;
}
@@ -377,7 +349,7 @@ class NativeSessionStorage implements SessionStorageInterface
/**
* {@inheritdoc}
*/
public function isStarted()
public function isStarted(): bool
{
return $this->started;
}
@@ -404,31 +376,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,11 +406,9 @@ 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 &&

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 array $options;
private $handler;
private $metaBag;
private $secure;
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;

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.');
@@ -36,7 +33,7 @@ class PhpBridgeSessionStorage extends NativeSessionStorage
/**
* {@inheritdoc}
*/
public function start()
public function start(): bool
{
if ($this->started) {
return true;

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);
@@ -23,12 +24,9 @@ class PhpBridgeSessionStorageFactory implements SessionStorageFactoryInterface
{
private $handler;
private $metaBag;
private $secure;
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;

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

@@ -11,6 +11,8 @@
namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler;
/**
* @author Drak <drak@zikula.org>
*/
@@ -22,87 +24,52 @@ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterf
{
$this->handler = $handler;
$this->wrapper = $handler instanceof \SessionHandler;
$this->saveHandlerName = $this->wrapper ? \ini_get('session.save_handler') : 'user';
$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,7 +28,7 @@ class StreamedResponse extends Response
{
protected $callback;
protected $streamed;
private $headersSent;
private bool $headersSent;
public function __construct(callable $callback = null, int $status = 200, array $headers = [])
{
@@ -41,28 +41,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;
@@ -76,7 +60,7 @@ class StreamedResponse extends Response
*
* @return $this
*/
public function sendHeaders()
public function sendHeaders(): static
{
if ($this->headersSent) {
return $this;
@@ -94,7 +78,7 @@ class StreamedResponse extends Response
*
* @return $this
*/
public function sendContent()
public function sendContent(): static
{
if ($this->streamed) {
return $this;
@@ -118,7 +102,7 @@ class StreamedResponse extends Response
*
* @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.');
@@ -132,7 +116,7 @@ class StreamedResponse extends Response
/**
* {@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)
{

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)
{

View File

@@ -23,7 +23,7 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseFormatSame extends Constraint
{
private $request;
private $format;
private ?string $format;
public function __construct(Request $request, ?string $format)
{

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)
{

View File

@@ -16,7 +16,7 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseHasHeader extends Constraint
{
private $headerName;
private string $headerName;
public function __construct(string $headerName)
{

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)
{

View File

@@ -16,7 +16,7 @@ use Symfony\Component\HttpFoundation\Response;
final class ResponseStatusCodeSame extends Constraint
{
private $statusCode;
private int $statusCode;
public function __construct(int $statusCode)
{

View File

@@ -16,16 +16,18 @@
}
],
"require": {
"php": ">=7.2.5",
"php": ">=8.0.2",
"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/mime": "^4.4|^5.0|^6.0",
"symfony/expression-language": "^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": "^5.4|^6.0",
"symfony/expression-language": "^5.4|^6.0",
"symfony/rate-limiter": "^5.2|^6.0"
},
"suggest" : {
"symfony/mime": "To use the file extension guesser"