我修改的目的主要是為了使用中間件能對cookie進行透明的加解密,在這里分享一下,同時如果有大佬發(fā)現(xiàn)有什么問題也歡迎指出。
Webman\Http\Request
類添加updateCookie
方法用來刷新請求實例中的cookie,目的是為了使用中間件來對請求Cookie進行解密。不過需要注意的是,webman會對request
對象進行緩存,就是滿足一定條件的兩個請求,后面的請求webman會直接取出緩存而不再構造新的request
對象。還沒有具體看怎么判斷當前request
對象是緩存對象還是新建對象。
public function updateCookie($name, $value)
{
if (!isset($this->_data['cookie'])) {
$this->_data['cookie'] = array();
}
$this->_data['cookie'][$name] = $value;
}
Webman\Http\Response
添加若干方法用于在發(fā)送響應之前修改cookie,需要先調(diào)用cookiesToJar
將響應中的Cookie解析出來,然后使用updateCookie
來更新,我這里主要用來在中間件中加密,這個方法不支持添加不存在的cookie,最后使用saveCookie
將cookie重新寫入到響應中。
...
protected $cookieJar = [];
...
public function cookiesToJar()
{
if (isset($this->_header['Set-Cookie'])) {
foreach ($this->_header['Set-Cookie'] as $cookie) {
$setcookie = [];
\parse_str(\preg_replace('/; ?/', '&', $cookie), $setcookie);
$name = array_key_first($setcookie);
if (!isset($this->cookieJar[$name])) {
$this->cookieJar[$name] = [];
}
if (isset($setcookie['path'])) {
$this->cookieJar[$name][$setcookie['path']] = array_merge($setcookie, [
'value' => $setcookie[$name],
]);
} else {
$this->cookieJar[$name][] = array_merge($setcookie, [
'value' => $setcookie[$name],
]);
}
}
}
return $this->cookieJar;
}
public function updateCookie($name, $value, $path = null)
{
if (empty($this->cookieJar)) {
return $this;
}
if (isset($this->cookieJar[$name])) {
if ($path !== null && isset($this->cookieJar[$name][$path])) {
$this->cookieJar[$name][$path]['value'] = $value;
return $this;
}
$last_key = array_key_last($this->cookieJar[$name]);
$this->cookieJar[$name][$last_key]['value'] = $value;
}
return $this;
}
public function saveCookie()
{
if (isset($this->_header['Set-Cookie'])) {
unset($this->_header['Set-Cookie']);
}
foreach ($this->cookieJar as $name => $name_cookies) {
foreach ($name_cookies as $cookie) {var_dump($cookie);
$this->cookie(
$name, $cookie['value'], $cookie['max_age'] ?? 0, $cookie['path'] ?? '', $cookie['domain'] ?? '',
$cookie['secure'] ?? false, $cookie['http_only'] ?? false, $cookie['same_site'] ?? false
);
}
}
}