Skip to content

Commit

Permalink
Fixed bug that SetCookie::fromString cannot not work by invalid typ…
Browse files Browse the repository at this point in the history
…es. (#6836)
  • Loading branch information
limingxinleo authored Jun 5, 2024
1 parent f96e372 commit 6a7775b
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Cookie/SetCookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,24 @@ public function __toString()
return rtrim($str, '; ');
}

public static function fromArray(array $data): static
{
foreach ($data as $key => $value) {
if ($value === null) {
continue;
}

$data[$key] = match ($key) {
'Name', 'Value', 'Domain', 'Path' => (string) $value,
'Max-Age' => (int) $value,
'Secure', 'Discard', 'HttpOnly' => (bool) $value,
default => $value,
};
}

return new static($data);
}

/**
* Create a new SetCookie object from a string.
*
Expand Down Expand Up @@ -107,7 +125,7 @@ public static function fromString(string $cookie): self
}
}

return new self($data);
return static::fromArray($data);
}

public function toArray(): array
Expand Down
33 changes: 33 additions & 0 deletions tests/CookieTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/

namespace HyperfTest\HttpMessage;

use Hyperf\HttpMessage\Cookie\SetCookie;
use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;

/**
* @internal
* @coversNothing
*/
#[CoversNothing]
class CookieTest extends TestCase
{
public function testSetCookeFromString()
{
$cookie = SetCookie::fromString('ltoken_v2=v2_RaLe3_kws2BrlGKF2aqhcCWH7PEybgGpmdcZXcOmEuu3sEgoA==.CAE=; Path=/; Domain=miyoushe.com; Max-Age=31536000; HttpOnly; Secure');
$this->assertSame(31536000, $cookie->getMaxAge());
$this->assertIsInt($cookie->getExpires());
$this->assertTrue($cookie->getSecure());
}
}

0 comments on commit 6a7775b

Please sign in to comment.