Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make buildSetCookieHeaderFromBrowserCookie robust #171

Merged
merged 5 commits into from
Oct 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 31 additions & 26 deletions src/Loader/Http/Cookies/CookieJar.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,37 +123,42 @@ protected function getForDomainFromUrl(string|UriInterface|Url $url): ?string

protected function buildSetCookieHeaderFromBrowserCookie(BrowserCookie $cookie): string
{
$header = $cookie->getName() . '=' . $cookie->getValue();

if ($cookie->getDomain() !== null) {
$header .= '; Domain=' . $cookie->getDomain();
}

if ($cookie->offsetExists('expires') && $cookie->offsetGet('expires') !== -1) {
$header .= '; Expires=' . $this->formatExpiresValue($cookie->offsetGet('expires'));
}

if ($cookie->offsetExists('max-age') && !empty($cookie->offsetGet('max-age'))) {
$header .= '; Max-Age=' . $cookie->offsetGet('max-age');
}

if ($cookie->offsetExists('path') && !empty($cookie->offsetGet('path'))) {
$header .= '; Path=' . $cookie->offsetGet('path');
}
$attributes = [
'domain' => 'Domain',
'expires' => 'Expires',
'max-age' => 'Max-Age',
'path' => 'Path',
'secure' => 'Secure',
'httpOnly' => 'HttpOnly',
'sameSite' => 'SameSite',
];

$parts = [sprintf('%s=%s', $cookie->getName(), $cookie->getValue())];

foreach ($attributes as $name => $setCookieName) {
$setCookieValue = $cookie->offsetGet($name);
if (empty($setCookieValue)) {
continue;
}

if ($cookie->offsetExists('secure') && $cookie->offsetGet('secure') === true) {
$header .= '; Secure';
}
// "Expires" attribute
if ($name === 'expires') {
if ($setCookieValue !== -1) {
$parts[] = sprintf('%s=%s', $setCookieName, $this->formatExpiresValue($setCookieValue));
}
continue;
}

if ($cookie->offsetExists('httpOnly') && $cookie->offsetGet('httpOnly') === true) {
$header .= '; HttpOnly';
}
// Flag attributes
if ($setCookieValue === true) {
$parts[] = $setCookieName;
continue;
}

if ($cookie->offsetExists('sameSite') && !empty($cookie->offsetGet('sameSite'))) {
$header .= '; SameSite=' . $cookie->offsetGet('sameSite');
$parts[] = sprintf('%s=%s', $setCookieName, $setCookieValue);
}

return $header;
return implode('; ', $parts);
}

private function formatExpiresValue(mixed $value): string
Expand Down