static public function fromString($cookie, $url = null)
{
$parts = explode(';', $cookie);
if (false === strpos($parts[0], '=')) {
throw new \InvalidArgumentException('The cookie string "%s" is not valid.');
}
list($name, $value) = explode('=', array_shift($parts), 2);
$values = array(
'name' => trim($name),
'value' => trim($value),
'expires' => null,
'path' => null,
'domain' => '',
'secure' => false,
'httponly' => false,
'passedRawValue' => true,
);
if (null !== $url) {
if ((false === $urlParts = parse_url($url)) || !isset($urlParts['host']) || !isset($urlParts['path'])) {
throw new \InvalidArgumentException(sprintf('The URL "%s" is not valid.', $url));
}
$parts = array_merge($urlParts, $parts);
$values['domain'] = $parts['host'];
$values['path'] = substr($parts['path'], 0, strrpos($parts['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 (!$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' === $elements[0]) {
if (false === $date = \DateTime::createFromFormat(static::DATE_FORMAT, $elements[1], new \DateTimeZone('UTC'))) {
throw new \InvalidArgumentException(sprintf('The expires part of cookie is not valid (%s).', $elements[1]));
}
$elements[1] = $date->getTimestamp();
}
$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']
);
}