Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. Cookie.php

function Cookie::fromString

Same name in this branch
  1. 11.1.x vendor/symfony/http-foundation/Cookie.php \Symfony\Component\HttpFoundation\Cookie::fromString()

Creates a Cookie instance from a Set-Cookie header value.

Throws

InvalidArgumentException

1 call to Cookie::fromString()
CookieJar::updateFromSetCookie in vendor/symfony/browser-kit/CookieJar.php
Updates the cookie jar from a response Set-Cookie headers.

File

vendor/symfony/browser-kit/Cookie.php, line 126

Class

Cookie
Cookie represents an HTTP cookie.

Namespace

Symfony\Component\BrowserKit

Code

public static function fromString(string $cookie, ?string $url = null) : static {
    $parts = explode(';', $cookie);
    if (!str_contains($parts[0], '=')) {
        throw new InvalidArgumentException(\sprintf('The cookie string "%s" is not valid.', $parts[0]));
    }
    [
        $name,
        $value,
    ] = explode('=', array_shift($parts), 2);
    $values = [
        'name' => trim($name),
        'value' => trim($value),
        'expires' => null,
        'path' => '/',
        'domain' => '',
        'secure' => false,
        'httponly' => false,
        'passedRawValue' => true,
        'samesite' => null,
    ];
    if (null !== $url) {
        if (false === ($urlParts = parse_url($url)) || !isset($urlParts['host'])) {
            throw new InvalidArgumentException(\sprintf('The URL "%s" is not valid.', $url));
        }
        $values['domain'] = $urlParts['host'];
        $values['path'] = isset($urlParts['path']) ? substr($urlParts['path'], 0, strrpos($urlParts['path'], '/')) : '';
    }
    foreach ($parts as $part) {
        $part = trim($part);
        if ('secure' === strtolower($part)) {
            // Ignore the secure flag if the original URI is not given or is not HTTPS
            if (null === $url || !isset($urlParts['scheme']) || 'https' !== $urlParts['scheme']) {
                continue;
            }
            $values['secure'] = true;
            continue;
        }
        if ('httponly' === strtolower($part)) {
            $values['httponly'] = true;
            continue;
        }
        if (2 === \count($elements = explode('=', $part, 2))) {
            if ('expires' === strtolower($elements[0])) {
                $elements[1] = self::parseDate($elements[1]);
            }
            $values[strtolower($elements[0])] = $elements[1];
        }
    }
    return new static($values['name'], $values['value'], $values['expires'], $values['path'], $values['domain'], $values['secure'], $values['httponly'], $values['passedRawValue'], $values['samesite']);
}
RSS feed
Powered by Drupal