Skip to content

Commit 6a7775b

Browse files
authored
Fixed bug that SetCookie::fromString cannot not work by invalid types. (#6836)
1 parent f96e372 commit 6a7775b

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

src/Cookie/SetCookie.php

+19-1
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,24 @@ public function __toString()
6868
return rtrim($str, '; ');
6969
}
7070

71+
public static function fromArray(array $data): static
72+
{
73+
foreach ($data as $key => $value) {
74+
if ($value === null) {
75+
continue;
76+
}
77+
78+
$data[$key] = match ($key) {
79+
'Name', 'Value', 'Domain', 'Path' => (string) $value,
80+
'Max-Age' => (int) $value,
81+
'Secure', 'Discard', 'HttpOnly' => (bool) $value,
82+
default => $value,
83+
};
84+
}
85+
86+
return new static($data);
87+
}
88+
7189
/**
7290
* Create a new SetCookie object from a string.
7391
*
@@ -107,7 +125,7 @@ public static function fromString(string $cookie): self
107125
}
108126
}
109127

110-
return new self($data);
128+
return static::fromArray($data);
111129
}
112130

113131
public function toArray(): array

tests/CookieTest.php

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
/**
5+
* This file is part of Hyperf.
6+
*
7+
* @link https://www.hyperf.io
8+
* @document https://hyperf.wiki
9+
* @contact [email protected]
10+
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
11+
*/
12+
13+
namespace HyperfTest\HttpMessage;
14+
15+
use Hyperf\HttpMessage\Cookie\SetCookie;
16+
use PHPUnit\Framework\Attributes\CoversNothing;
17+
use PHPUnit\Framework\TestCase;
18+
19+
/**
20+
* @internal
21+
* @coversNothing
22+
*/
23+
#[CoversNothing]
24+
class CookieTest extends TestCase
25+
{
26+
public function testSetCookeFromString()
27+
{
28+
$cookie = SetCookie::fromString('ltoken_v2=v2_RaLe3_kws2BrlGKF2aqhcCWH7PEybgGpmdcZXcOmEuu3sEgoA==.CAE=; Path=/; Domain=miyoushe.com; Max-Age=31536000; HttpOnly; Secure');
29+
$this->assertSame(31536000, $cookie->getMaxAge());
30+
$this->assertIsInt($cookie->getExpires());
31+
$this->assertTrue($cookie->getSecure());
32+
}
33+
}

0 commit comments

Comments
 (0)