Skip to content

Commit

Permalink
New getCookieDomain #10098
Browse files Browse the repository at this point in the history
  • Loading branch information
PowerKiKi committed Jan 29, 2024
1 parent 79fe9e1 commit 36c6ba8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Utility.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
19 changes: 19 additions & 0 deletions tests/UtilityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 36c6ba8

Please sign in to comment.