Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,439 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\HostIdentity;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Cookie jar that stores cookies as an array
*/
class CookieJar implements CookieJarInterface
{
private const MAX_SET_COOKIE_FIELD_LENGTH = 8190;
private const MAX_SET_COOKIE_FIELDS = 50;
private const MAX_REQUEST_COOKIES = 150;
private const MAX_COOKIE_HEADER_LENGTH = 8190;
/**
* @var SetCookie[] Loaded cookie data
*/
private array $cookies = [];
private bool $strictMode;
/**
* @param bool $strictMode Set to true to throw exceptions when invalid
* cookies are added to the cookie jar.
* @param array $cookieArray Array of SetCookie objects or a hash of
* arrays that can be used with the SetCookie
* constructor
*/
public function __construct(
bool $strictMode = false,
#[\SensitiveParameter]
array $cookieArray = []
) {
$this->strictMode = $strictMode;
foreach ($cookieArray as $cookie) {
if (!$cookie instanceof SetCookie) {
$cookie = new SetCookie($cookie);
}
$this->setCookie($cookie);
}
}
/**
* Create a new Cookie jar from an associative array and domain.
*
* @param array $cookies Cookies to create the jar from
* @param string $domain Domain to set the cookies to
*/
public static function fromArray(
#[\SensitiveParameter]
array $cookies,
string $domain
): self {
$cookieJar = new self();
foreach ($cookies as $name => $value) {
if (!\is_scalar($value) && !(\is_object($value) && \method_exists($value, '__toString'))) {
throw new \InvalidArgumentException('Cookie value must be scalar or stringable');
}
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => (string) $name,
'Value' => (string) $value,
'Discard' => true,
]));
}
return $cookieJar;
}
/**
* Evaluate if this cookie should be persisted to storage
* that survives between requests.
*
* @param SetCookie $cookie Being evaluated.
* @param bool $allowSessionCookies If we should persist session cookies
*/
public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
{
if ($cookie->getExpires() || $allowSessionCookies) {
if (!$cookie->getDiscard()) {
return true;
}
}
return false;
}
/**
* Finds and returns the cookie based on the name
*
* @param string $name cookie name to search for
*
* @return SetCookie|null cookie that was found or null if not found
*/
public function getCookieByName(string $name): ?SetCookie
{
foreach ($this->cookies as $cookie) {
if ($cookie->getName() === $name) {
return $cookie;
}
}
return null;
}
public function toArray(): array
{
return \array_map(static function (SetCookie $cookie): array {
return $cookie->toArray();
}, $this->getIterator()->getArrayCopy());
}
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void
{
if ($domain === null) {
$this->cookies = [];
return;
} elseif ($path === null) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($domain): bool {
return $cookie->getDomain() === null || !$cookie->matchesDomain($domain);
}
);
} elseif ($name === null) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain): bool {
return !($cookie->getDomain() !== null
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
} else {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain, $name): bool {
return !($cookie->getDomain() !== null
&& $cookie->getName() === $name
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
}
}
public function clearSessionCookies(): void
{
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie): bool {
return !$cookie->getDiscard() && $cookie->getExpires();
}
);
}
public function setCookie(
#[\SensitiveParameter]
SetCookie $cookie
): bool {
// If the name string is empty (but not 0), ignore the set-cookie
// string entirely.
$name = $cookie->getName();
if (!$name && $name !== '0') {
return false;
}
// Only allow cookies with set and valid domain, name, value
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new \RuntimeException('Invalid cookie: '.$result);
}
$this->removeCookieIfEmpty($cookie);
return false;
}
$maxAge = $cookie->getMaxAge();
if ($maxAge !== null && $maxAge <= 0) {
if ($cookie->getDomain() !== null) {
$this->removeCookie($cookie);
}
return false;
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, and domain are
// identical.
if ($c->getPath() !== $cookie->getPath()
|| $c->getDomain() !== $cookie->getDomain()
|| $c->getHostOnly() !== $cookie->getHostOnly()
|| $c->getName() !== $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$this->cookies[] = $cookie;
return true;
}
public function count(): int
{
return \count($this->cookies);
}
/**
* @return \ArrayIterator<int, SetCookie>
*/
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator(\array_values($this->cookies));
}
public function extractCookies(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
ResponseInterface $response
): void {
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
$uri = $request->getUri();
$requestHost = HostIdentity::canonicalHost($uri->getHost());
$secure = $uri->getScheme() === 'https';
$accepted = 0;
foreach ($cookieHeader as $cookie) {
if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
continue;
}
$sc = SetCookie::fromString($cookie);
$domain = $sc->getDomain();
if ($domain === null || $domain === '') {
$sc->setDomain($requestHost);
$sc->setHostOnly(true);
} else {
$sc->setHostOnly(false);
}
if (0 !== \strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
}
if (!$sc->matchesDomain($requestHost)) {
continue;
}
if (!$secure && ($sc->getSecure() || $this->overlaysSecureCookie($sc))) {
continue;
}
$prefixName = Psr7\Utils::asciiToLower((string) $sc->getName());
if (\str_starts_with($prefixName, '__secure-') && !$sc->getSecure()) {
continue;
}
if (\str_starts_with($prefixName, '__host-') && (!$sc->getSecure() || !$sc->getHostOnly() || $sc->getPath() !== '/' || !self::hasPathAttribute($cookie))) {
continue;
}
// Note: At this point `$sc->getDomain()` being a public suffix should
// be rejected, but we don't want to pull in the full PSL dependency.
if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
break;
}
}
}
}
private function overlaysSecureCookie(SetCookie $cookie): bool
{
foreach ($this->cookies as $stored) {
if (self::isSecureCookieOverlay($cookie, $stored)) {
return true;
}
}
return false;
}
private static function isSecureCookieOverlay(SetCookie $cookie, SetCookie $stored): bool
{
if ($stored->getName() !== $cookie->getName() || !$stored->getSecure() || $stored->isExpired()) {
return false;
}
$domain = $cookie->getDomain();
$storedDomain = $stored->getDomain();
if ($domain === null || $storedDomain === null) {
return false;
}
if (!HostIdentity::cookieDomainMatches($storedDomain, $domain) && !HostIdentity::cookieDomainMatches($domain, $storedDomain)) {
return false;
}
return $stored->matchesPath($cookie->getPath());
}
/**
* Mirrors SetCookie::fromString()'s splitting because parsed cookies cannot
* distinguish an absent Path attribute from a defaulted path.
*/
private static function hasPathAttribute(string $header): bool
{
$parts = \explode(';', $header);
\array_shift($parts);
foreach ($parts as $part) {
$separator = \strpos($part, '=');
if ($separator !== false && Psr7\Utils::caselessEquals(\trim(\substr($part, 0, $separator), " \t"), 'Path')) {
return true;
}
}
return false;
}
/**
* Computes cookie path following RFC 6265 section 5.1.4
*
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
*/
private function getCookiePathFromRequest(RequestInterface $request): string
{
$uriPath = $request->getUri()->getPath();
if ('' === $uriPath) {
return '/';
}
if (0 !== \strpos($uriPath, '/')) {
return '/';
}
if ('/' === $uriPath) {
return '/';
}
$lastSlashPos = \strrpos($uriPath, '/');
if (0 === $lastSlashPos || false === $lastSlashPos) {
return '/';
}
return \substr($uriPath, 0, $lastSlashPos);
}
public function withCookieHeader(
#[\SensitiveParameter]
RequestInterface $request
): RequestInterface {
$values = [];
$headerLength = 8;
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = HostIdentity::canonicalHost($uri->getHost());
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
if ($cookie->getDomain() !== null
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($host)
&& !$cookie->isExpired()
&& (!$cookie->getSecure() || $scheme === 'https')
) {
$name = (string) $cookie->getName();
$value = (string) $cookie->getValue();
$separatorLength = $values === [] ? 0 : 2;
$valueLength = \strlen($name) + 1 + \strlen($value);
if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) {
break;
}
$values[] = $name.'='.$value;
$headerLength += $separatorLength + $valueLength;
if (\count($values) === self::MAX_REQUEST_COOKIES) {
break;
}
}
}
return $values
? $request->withHeader('Cookie', \implode('; ', $values))
: $request;
}
/**
* If a cookie already exists and the server asks to set it again with a
* null value, the cookie must be deleted.
*/
private function removeCookieIfEmpty(SetCookie $cookie): void
{
$cookieValue = $cookie->getValue();
if (($cookieValue === null || $cookieValue === '') && $cookie->getDomain() !== null) {
$this->removeCookie($cookie);
}
}
private function removeCookie(SetCookie $cookie): void
{
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $stored) use ($cookie): bool {
return !($stored->getName() === $cookie->getName()
&& $stored->getPath() === $cookie->getPath()
&& $stored->getDomain() === $cookie->getDomain()
&& $stored->getHostOnly() === $cookie->getHostOnly());
}
);
}
}

View file

@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Stores HTTP cookies.
*
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
* CookieJarInterface instances automatically expire contained cookies when
* necessary. Subclasses are also responsible for storing and retrieving
* cookies from a file, database, etc.
*
* @see https://docs.python.org/2/library/cookielib.html Inspiration
*
* @extends \IteratorAggregate<SetCookie>
*/
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
/**
* Create a request with added cookie headers.
*
* If no matching cookies are found in the cookie jar, then no Cookie
* header is added to the request and the same request is returned.
*
* @param RequestInterface $request Request object to modify.
*
* @return RequestInterface returns the modified request.
*/
public function withCookieHeader(RequestInterface $request): RequestInterface;
/**
* Extract cookies from an HTTP response and store them in the CookieJar.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
*/
public function extractCookies(RequestInterface $request, ResponseInterface $response): void;
/**
* Sets a cookie in the cookie jar.
*
* @param SetCookie $cookie Cookie to set.
*
* @return bool Returns true on success or false on failure
*/
public function setCookie(SetCookie $cookie): bool;
/**
* Remove cookies currently held in the cookie jar.
*
* Invoking this method without arguments will empty the whole cookie jar.
* If given a $domain argument only cookies belonging to that domain will
* be removed. If given a $domain and $path argument, cookies belonging to
* the specified path within that domain are removed. If given all three
* arguments, then the cookie with the specified name, path and domain is
* removed.
*
* @param string|null $domain Clears cookies matching a domain
* @param string|null $path Clears cookies matching a domain and path
* @param string|null $name Clears cookies matching a domain, path, and name
*/
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void;
/**
* Discard all sessions cookies.
*
* Removes cookies that don't have an expire field or a have a discard
* field set to true. To be called when the user agent shuts down according
* to RFC 2965.
*/
public function clearSessionCookies(): void;
/**
* Converts the cookie jar to an array.
*/
public function toArray(): array;
}

View file

@ -0,0 +1,168 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\DiagnosticValue;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
use NonSerializableTrait;
/**
* @var string filename
*/
private string $filename;
/**
* @var bool Control whether to persist session cookies or not.
*/
private bool $storeSessionCookies;
/**
* @var bool Whether to save the cookie jar on destruction.
*
* Disabled by __wakeup() to prevent FileCookieJar from being used as a
* PHP object injection file-write gadget when an application unserializes
* attacker-controlled data.
*/
private bool $autoSave = false;
/**
* Create a new FileCookieJar object
*
* @param string $cookieFile File to store the cookie data
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the file cannot be loaded or is invalid
*/
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
{
parent::__construct();
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
if (\file_exists($cookieFile)) {
$this->load($cookieFile);
}
$this->autoSave = true;
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
if ($this->autoSave) {
$this->save($this->filename);
}
}
/**
* Disable automatic persistence after unserialization.
*/
public function __wakeup(): void
{
$this->autoSave = false;
}
public function __unserialize(array $data): void
{
$this->autoSave = false;
throw new \LogicException(static::class.' should never be unserialized');
}
/**
* Saves the cookies to a file.
*
* @param string $filename File to save
*
* @throws \RuntimeException if the cookie data cannot be encoded or the
* file cannot be written
*/
public function save(string $filename): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
try {
$jsonStr = \json_encode($json, \JSON_HEX_TAG | \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
}
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
throw new \RuntimeException(\sprintf('Unable to save file %s', DiagnosticValue::escape($filename)));
}
// Best-effort: restrict the cookie file to the owner so persisted
// cookies are not world-readable.
@\chmod($filename, 0600);
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
* Cookie records are constructed before any are passed to setCookie().
*
* @param string $filename Cookie file to load.
*
* @throws \RuntimeException if the file cannot be loaded or is invalid
*/
public function load(string $filename): void
{
$json = \file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException(\sprintf('Unable to load file %s', DiagnosticValue::escape($filename)));
}
if ($json === '') {
return;
}
$message = \sprintf('Invalid cookie file: %s', DiagnosticValue::escape($filename));
try {
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException($message, 0, $e);
}
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
throw new \RuntimeException($message);
}
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException($message);
}
try {
$cookies[] = new SetCookie($cookie);
} catch (\InvalidArgumentException $e) {
throw new \RuntimeException($message, 0, $e);
}
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
}
}

View file

@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\NonSerializableTrait;
/**
* Persists cookies in the client session
*/
class SessionCookieJar extends CookieJar
{
use NonSerializableTrait;
/**
* @var string session key
*/
private string $sessionKey;
/**
* @var bool Control whether to persist session cookies or not.
*/
private bool $storeSessionCookies;
/**
* @var bool Whether to save the cookie jar on destruction.
*
* Disabled by __wakeup() to prevent SessionCookieJar from being used as a
* PHP object injection $_SESSION-write gadget when an application
* unserializes attacker-controlled data.
*/
private bool $autoSave = false;
/**
* Create a new SessionCookieJar object
*
* @param string $sessionKey Session key name to store the cookie
* data in session
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the session contains invalid cookie data
*/
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
{
parent::__construct();
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
$this->autoSave = true;
}
/**
* Saves cookies to session when shutting down
*/
public function __destruct()
{
if ($this->autoSave) {
$this->save();
}
}
/**
* Disable automatic persistence after unserialization.
*/
public function __wakeup(): void
{
$this->autoSave = false;
}
public function __unserialize(array $data): void
{
$this->autoSave = false;
throw new \LogicException(static::class.' should never be unserialized');
}
/**
* Save cookies to the client session.
*
* @throws \RuntimeException if the cookie data cannot be encoded
*/
public function save(): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
try {
$json = \json_encode($json, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
}
$_SESSION[$this->sessionKey] = $json;
}
/**
* Load cookies from the client session.
*
* @throws \RuntimeException if the session contains invalid cookie data
*/
protected function load(): void
{
if (!isset($_SESSION[$this->sessionKey])) {
return;
}
$message = 'Invalid cookie data';
$json = $_SESSION[$this->sessionKey];
if (!\is_string($json)) {
throw new \RuntimeException($message);
}
try {
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException($message, 0, $e);
}
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
throw new \RuntimeException($message);
}
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException($message);
}
try {
$cookies[] = new SetCookie($cookie);
} catch (\InvalidArgumentException $e) {
throw new \RuntimeException($message, 0, $e);
}
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
}
}

View file

@ -0,0 +1,596 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\HostIdentity;
use GuzzleHttp\Psr7;
/**
* Set-Cookie object
*/
class SetCookie
{
/**
* @var array
*/
private const DEFAULTS = [
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
];
/**
* @var array Cookie data
*/
private array $data;
/**
* @var bool Whether this cookie was set without a Domain attribute.
*/
private bool $hostOnly = false;
/**
* Create a new SetCookie object from a string.
*
* @param string $cookie Set-Cookie header string
*/
public static function fromString(
#[\SensitiveParameter]
string $cookie
): self {
// Create the default return array
$data = self::DEFAULTS;
// Explode the cookie string using a series of semicolons
$pieces = \array_filter(\array_map(static function (string $piece): string {
return \trim($piece, " \t");
}, \explode(';', $cookie)));
// The name of the cookie (first kvp) must exist and include an equal sign.
if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
return new self($data);
}
// Add the cookie pieces into the parsed data array
foreach ($pieces as $part) {
$cookieParts = \explode('=', $part, 2);
$key = \trim($cookieParts[0], " \t");
$value = isset($cookieParts[1])
? \trim($cookieParts[1], " \t")
: true;
// Only check for non-cookies when cookies have been found
if (!isset($data['Name'])) {
$data['Name'] = $key;
$data['Value'] = $value;
} else {
foreach (\array_keys(self::DEFAULTS) as $search) {
if (Psr7\Utils::caselessEquals($search, $key)) {
if ($search === 'Max-Age') {
if (\is_string($value) && \preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
$maxAge = self::parseNumericInteger($value);
if ($maxAge !== null) {
$data[$search] = $maxAge;
}
}
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
if ($value) {
$data[$search] = true;
}
} elseif (\is_string($value)) {
$data[$search] = $value;
}
continue 2;
}
}
if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
continue;
}
$data[$key] = $value;
}
}
return new self($data);
}
/**
* @param array $data Array of cookie data provided by a Cookie parser
*/
public function __construct(
#[\SensitiveParameter]
array $data = []
) {
$this->data = self::DEFAULTS;
self::validateFieldTypes($data);
if (\array_key_exists('HostOnly', $data)) {
$this->setHostOnly($data['HostOnly']);
unset($data['HostOnly']);
}
if (isset($data['Name'])) {
$this->setName($data['Name']);
}
if (isset($data['Value'])) {
$this->setValue($data['Value']);
}
if (isset($data['Domain'])) {
$this->setDomain($data['Domain']);
}
if (isset($data['Path'])) {
$this->setPath($data['Path']);
}
if (isset($data['Max-Age'])) {
$this->setMaxAge($data['Max-Age']);
}
if (isset($data['Expires'])) {
$this->setExpires($data['Expires']);
}
if (isset($data['Secure'])) {
$this->setSecure($data['Secure']);
}
if (isset($data['Discard'])) {
$this->setDiscard($data['Discard']);
}
if (isset($data['HttpOnly'])) {
$this->setHttpOnly($data['HttpOnly']);
}
// Set the remaining values that don't have extra validation logic
foreach (array_diff(array_keys($data), array_keys(self::DEFAULTS)) as $key) {
$this->data[$key] = $data[$key];
}
// Extract the Expires value and turn it into a UNIX timestamp if needed
$maxAge = $this->getMaxAge();
if ($maxAge !== null) {
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
}
}
public function __toString(): string
{
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
foreach ($this->data as $k => $v) {
if ($k === 'Domain' && $this->getHostOnly()) {
continue;
}
if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
if ($k === 'Expires') {
$str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
} else {
$str .= ($v === true ? $k : "{$k}={$v}").'; ';
}
}
}
return \rtrim($str, '; ');
}
public function toArray(): array
{
$data = $this->data;
if ($this->getHostOnly()) {
$data['HostOnly'] = true;
}
return $data;
}
/**
* Get the cookie name.
*/
public function getName(): ?string
{
return $this->data['Name'];
}
/**
* Set the cookie name.
*
* @param string $name Cookie name
*/
public function setName(string $name): void
{
$this->data['Name'] = $name;
}
/**
* Get the cookie value.
*/
public function getValue(): ?string
{
return $this->data['Value'];
}
/**
* Set the cookie value.
*
* @param string $value Cookie value
*/
public function setValue(string $value): void
{
$this->data['Value'] = $value;
}
/**
* Get the domain.
*/
public function getDomain(): ?string
{
return $this->data['Domain'];
}
/**
* Set the domain of the cookie.
*
* @param string|null $domain Domain of the cookie
*/
public function setDomain(?string $domain): void
{
$this->data['Domain'] = null === $domain ? null : self::normalizeDomain($domain);
}
/**
* Get whether this cookie is scoped to the origin host only.
*/
public function getHostOnly(): bool
{
return $this->hostOnly;
}
/**
* Set whether this cookie is scoped to the origin host only.
*
* @param bool $hostOnly Set to true for host-only cookies
*/
public function setHostOnly(bool $hostOnly): void
{
$this->hostOnly = $hostOnly;
}
/**
* Get the path.
*/
public function getPath(): string
{
return $this->data['Path'];
}
/**
* Set the path of the cookie.
*
* @param string $path Path of the cookie
*/
public function setPath(string $path): void
{
$this->data['Path'] = $path;
}
/**
* Maximum lifetime of the cookie in seconds.
*/
public function getMaxAge(): ?int
{
return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
}
/**
* Set the max-age of the cookie.
*
* @param int|null $maxAge Max age of the cookie in seconds
*/
public function setMaxAge(?int $maxAge): void
{
$this->data['Max-Age'] = $maxAge;
}
/**
* The UNIX timestamp when the cookie Expires.
*/
public function getExpires(): ?int
{
return $this->data['Expires'];
}
/**
* Set the unix timestamp for which the cookie will expire.
*
* @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
*/
public function setExpires($timestamp): void
{
if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
// TODO: Move this to the parameter definition in 9.0.
throw new \TypeError(__METHOD__.'(): Argument #1 ($timestamp) must be of type int|string|null');
}
if ($timestamp === null) {
$this->data['Expires'] = null;
return;
}
if (\is_string($timestamp)) {
if (\is_numeric($timestamp)) {
$this->data['Expires'] = self::parseNumericInteger($timestamp);
return;
}
} elseif (\is_int($timestamp)) {
$this->data['Expires'] = $timestamp;
return;
}
$expires = \strtotime($timestamp);
$this->data['Expires'] = $expires === false ? null : $expires;
}
/**
* Get whether or not this is a secure cookie.
*/
public function getSecure(): bool
{
return $this->data['Secure'];
}
/**
* Set whether or not the cookie is secure.
*
* @param bool $secure Set to true or false if secure
*/
public function setSecure(bool $secure): void
{
$this->data['Secure'] = $secure;
}
/**
* Get whether or not this is a session cookie.
*/
public function getDiscard(): bool
{
return $this->data['Discard'];
}
/**
* Set whether or not this is a session cookie.
*
* @param bool $discard Set to true or false if this is a session cookie
*/
public function setDiscard(bool $discard): void
{
$this->data['Discard'] = $discard;
}
/**
* Get whether or not this is an HTTP only cookie.
*/
public function getHttpOnly(): bool
{
return $this->data['HttpOnly'];
}
/**
* Set whether or not this is an HTTP only cookie.
*
* @param bool $httpOnly Set to true or false if this is HTTP only
*/
public function setHttpOnly(bool $httpOnly): void
{
$this->data['HttpOnly'] = $httpOnly;
}
/**
* Check if the cookie matches a path value.
*
* A request-path path-matches a given cookie-path if at least one of
* the following conditions holds:
*
* - The cookie-path and the request-path are identical.
* - The cookie-path is a prefix of the request-path, and the last
* character of the cookie-path is %x2F ("/").
* - The cookie-path is a prefix of the request-path, and the first
* character of the request-path that is not included in the cookie-
* path is a %x2F ("/") character.
*
* @param string $requestPath Path to check against
*/
public function matchesPath(string $requestPath): bool
{
$cookiePath = $this->getPath();
// Match on exact matches or when path is the default empty "/"
if ($cookiePath === '/' || $cookiePath === $requestPath) {
return true;
}
// Ensure that the cookie-path is a prefix of the request path.
if (0 !== \strpos($requestPath, $cookiePath)) {
return false;
}
// Match if the last character of the cookie-path is "/"
if (\substr($cookiePath, -1, 1) === '/') {
return true;
}
// Match if the first character not included in cookie path is "/"
return \substr($requestPath, \strlen($cookiePath), 1) === '/';
}
/**
* Check if the cookie matches a domain value.
*
* @param string $domain Domain to check against
*/
public function matchesDomain(string $domain): bool
{
$cookieDomain = $this->getDomain();
if (null === $cookieDomain || $cookieDomain === '') {
return false;
}
if ($this->getHostOnly()) {
return HostIdentity::canonicalCookieDomain($domain) === HostIdentity::canonicalCookieDomain($cookieDomain);
}
return HostIdentity::cookieDomainMatches($domain, $cookieDomain);
}
/**
* Check if the cookie is expired.
*/
public function isExpired(): bool
{
return $this->getExpires() !== null && \time() > $this->getExpires();
}
/**
* Check if the cookie is valid according to RFC 6265.
*
* @return string|true Returns true if valid or an error message if invalid
*/
public function validate()
{
$name = $this->getName();
if ($name === null || $name === '') {
return 'The cookie name must not be empty';
}
// Check if any of the invalid characters are present in the cookie name
if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 0) {
return 'Cookie name must not contain invalid characters: ASCII '
.'Control characters (0-31;127), space, tab and the '
.'following characters: ()<>@,;:\"/?={}';
}
// Value must not be null. 0 and empty string are valid. Empty strings
// are technically against RFC 6265, but known to happen in the wild.
$value = $this->getValue();
if ($value === null) {
return 'The cookie value must not be empty';
}
// Domains must not be empty, but may be omitted. "0" is not a valid
// internet domain, but may be used as server name in a private network.
$domain = $this->getDomain();
if ($domain === '' || ($domain !== null && \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.') === '')) {
return 'The cookie domain must not be empty';
}
if ($this->getHostOnly() && $domain === null) {
return 'Host-only cookies must have a domain';
}
return true;
}
private static function normalizeDomain(string $domain): string
{
$domain = Psr7\Utils::asciiToLower($domain);
// Treat trailing-dot domains as host-only, but keep pure-dot domains invalid.
if ($domain !== '' && \substr($domain, -1) === '.' && \trim($domain, '.') !== '') {
return '';
}
if ($domain !== '' && $domain !== '.' && $domain[0] === '.') {
$domain = \substr_replace($domain, '', 0, 1);
}
return HostIdentity::canonicalCookieDomain($domain);
}
private static function maxAgeToExpires(int $maxAge, int $now): int
{
if ($maxAge <= 0) {
return $now - 1;
}
// Clamp absurd Max-Age values so addition cannot promote to float
if ($maxAge > \PHP_INT_MAX - $now) {
return \PHP_INT_MAX;
}
return $now + $maxAge;
}
private static function parseNumericInteger(string $value): ?int
{
if (!\is_numeric($value)) {
return null;
}
if (\preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
$negative = $value[0] === '-';
$digits = \ltrim($value, '+-');
$digits = \ltrim($digits, '0');
$digits = $digits === '' ? '0' : $digits;
$limit = $negative ? \substr((string) \PHP_INT_MIN, 1) : (string) \PHP_INT_MAX;
if (\strlen($digits) > \strlen($limit) || (\strlen($digits) === \strlen($limit) && \strcmp($digits, $limit) > 0)) {
return null;
}
return (int) ($negative ? '-'.$digits : $digits);
}
$number = (float) $value;
if (!\is_finite($number) || $number < \PHP_INT_MIN || $number > \PHP_INT_MAX) {
return null;
}
if (\PHP_INT_SIZE === 8 && ($number <= (float) \PHP_INT_MIN || $number >= (float) \PHP_INT_MAX)) {
return null;
}
return (int) $number;
}
/**
* @param mixed[] $data
*/
private static function validateFieldTypes(
#[\SensitiveParameter]
array $data
): void {
foreach (['Name', 'Value', 'Domain', 'Path'] as $field) {
if (isset($data[$field]) && !\is_string($data[$field])) {
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a string', $field));
}
}
if (isset($data['Max-Age']) && !\is_int($data['Max-Age'])) {
throw new \InvalidArgumentException('Cookie field "Max-Age" must be an integer');
}
if (isset($data['Expires']) && !\is_int($data['Expires']) && !\is_string($data['Expires'])) {
throw new \InvalidArgumentException('Cookie field "Expires" must be an integer or string');
}
foreach (['Secure', 'Discard', 'HttpOnly'] as $field) {
if (isset($data[$field]) && !\is_bool($data[$field])) {
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a boolean', $field));
}
}
if (\array_key_exists('HostOnly', $data) && !\is_bool($data['HostOnly'])) {
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
}
}
}