From 36c6ba8710641b9e6e8ac1e91715b42948234db3 Mon Sep 17 00:00:00 2001 From: Adrien Crivelli Date: Mon, 29 Jan 2024 17:08:09 +0800 Subject: [PATCH] New `getCookieDomain` #10098 --- src/Utility.php | 20 ++++++++++++++++++++ tests/UtilityTest.php | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/Utility.php b/src/Utility.php index 6273ed0..d003129 100644 --- a/src/Utility.php +++ b/src/Utility.php @@ -104,4 +104,24 @@ public static function quoteArray(array $value): string return implode(', ', $quoted); } + + /** + * Return the domain to be used for cookie. + * + * We look for domain name to build the string ".mydomain.com" to specify + * that cookies (session) are available on all subdomains. + * + * This will not work for domain without TLD such as "localhost", because + * RFC specify the domain string must contain two "." characters. + */ + public static function getCookieDomain(string $input): ?string + { + if ($input && preg_match('/([^.]+\.[^.:]+)(:\d+)?$/', $input, $match)) { + $cookieDomain = '.' . $match[1]; + } else { + $cookieDomain = null; + } + + return $cookieDomain; + } } diff --git a/tests/UtilityTest.php b/tests/UtilityTest.php index cf400a9..1fe9f11 100644 --- a/tests/UtilityTest.php +++ b/tests/UtilityTest.php @@ -159,4 +159,23 @@ public static function providerQuoteArray(): iterable yield [[true], "'1'"]; yield [[1.23], "'1.23'"]; } + + public function getCookieDomainProvider(): iterable + { + yield ['', null]; + yield ['localhost', null]; + yield ['example.com', '.example.com']; + yield ['www.example.com', '.example.com']; + yield ['example.com:123', '.example.com']; + yield ['www.example.com:123', '.example.com']; + } + + /** + * @dataProvider getCookieDomainProvider + */ + public function testGetCookieDomain(string $input, ?string $expected): void + { + $actual = Utility::getCookieDomain($input); + self::assertSame($expected, $actual); + } }