<?php
namespace Yurun\Util\YurunHttp\Cookie;
class CookieItem
{
public $name;
public $value;
public $expires = 0;
public $path = '/';
public $domain = '';
public $secure = false;
public $httpOnly = false;
public function __construct($name, $value, $expires = 0, $path = '/', $domain = '', $secure = false, $httpOnly = false)
{
$this->name = $name;
$this->value = $value;
$this->expires = (int)$expires;
$this->path = $path;
$this->domain = $domain;
$this->secure = $secure;
$this->httpOnly = $httpOnly;
}
public static function newInstance($data)
{
$object = new static('', '');
foreach($data as $k => $v)
{
$object->$k = $v;
}
return $object;
}
public static function fromSetCookie($setCookieContent)
{
if(preg_match_all('/;?\s*((?P<name>[^=;]+)=(?P<value>[^;]+)|((?P<name2>[^=;]+)))/', $setCookieContent, $matches) > 0)
{
$name = $matches['name'][0];
$value = $matches['value'][0];
unset($matches['name'][0], $matches['value'][0]);
$data = array_combine(array_map('strtolower', $matches['name']), $matches['value']);
if(isset($data['']))
{
unset($data['']);
}
if(isset($data['max-age']))
{
$expires = time() + $data['max-age'];
}
else if(isset($data['expires']))
{
$expires = strtotime($data['expires']);
}
else
{
$expires = null;
}
foreach($matches['name2'] as $boolItemName)
{
if('' !== $boolItemName)
{
$data[strtolower($boolItemName)] = true;
}
}
$object = new static($name, $value, $expires, isset($data['path']) ? $data['path'] : '/', isset($data['domain']) ? $data['domain'] : '', isset($data['secure']) ? $data['secure'] : false, isset($data['httponly']) ? $data['httponly'] : false);
return $object;
}
else
{
return null;
}
}
}