-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[WebLink] Add class to parse Link headers from HTTP responses #60420
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[WebLink] Add class to parse Link headers from HTTP responses
- Loading branch information
commit 461f7930053f4a09ea3c52cf7cbf1f23d729dfa6
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\WebLink; | ||
|
||
use Psr\Link\EvolvableLinkProviderInterface; | ||
|
||
/** | ||
* Parse a list of HTTP Link headers into a list of Link instances. | ||
* | ||
* @see https://tools.ietf.org/html/rfc5988 | ||
* | ||
* @author Jérôme Tamarelle <jerome@tamarelle.net> | ||
*/ | ||
class HttpHeaderParser | ||
{ | ||
// Regex to match each link entry: <...>; param1=...; param2=... | ||
private const LINK_PATTERN = '/<([^>]*)>\s*((?:\s*;\s*[a-zA-Z0-9\-_]+(?:\s*=\s*(?:"(?:[^"\\\\]|\\\\.)*"|[^";,\s]+))?)*)/'; | ||
|
||
// Regex to match parameters: ; key[=value] | ||
private const PARAM_PATTERN = '/;\s*([a-zA-Z0-9\-_]+)(?:\s*=\s*(?:"((?:[^"\\\\]|\\\\.)*)"|([^";,\s]+)))?/'; | ||
|
||
/** | ||
* @param string|string[] $headers Value of the "Link" HTTP header | ||
*/ | ||
public function parse(string|array $headers): EvolvableLinkProviderInterface | ||
{ | ||
if (is_array($headers)) { | ||
$headers = implode(', ', $headers); | ||
} | ||
$links = new GenericLinkProvider(); | ||
|
||
if (!preg_match_all(self::LINK_PATTERN, $headers, $matches, \PREG_SET_ORDER)) { | ||
return $links; | ||
} | ||
|
||
foreach ($matches as $match) { | ||
$href = $match[1]; | ||
$attributesString = $match[2]; | ||
|
||
$attributes = []; | ||
if (preg_match_all(self::PARAM_PATTERN, $attributesString, $attributeMatches, \PREG_SET_ORDER)) { | ||
$rels = null; | ||
foreach ($attributeMatches as $pm) { | ||
$key = $pm[1]; | ||
$value = match (true) { | ||
// Quoted value, unescape quotes | ||
($pm[2] ?? '') !== '' => stripcslashes($pm[2]), | ||
($pm[3] ?? '') !== '' => $pm[3], | ||
// No value | ||
default => true, | ||
}; | ||
|
||
if ($key === 'rel') { | ||
// Only the first occurrence of the "rel" attribute is read | ||
$rels ??= $value === true ? [] : preg_split('/\s+/', $value, 0, \PREG_SPLIT_NO_EMPTY); | ||
} elseif (is_array($attributes[$key] ?? null)) { | ||
$attributes[$key][] = $value; | ||
} elseif (isset($attributes[$key])) { | ||
$attributes[$key] = [$attributes[$key], $value]; | ||
} else { | ||
$attributes[$key] = $value; | ||
} | ||
} | ||
} | ||
|
||
$link = new Link(null, $href); | ||
foreach ($rels ?? [] as $rel) { | ||
$link = $link->withRel($rel); | ||
} | ||
foreach ($attributes as $k => $v) { | ||
$link = $link->withAttribute($k, $v); | ||
} | ||
$links = $links->withLink($link); | ||
} | ||
|
||
return $links; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
src/Symfony/Component/WebLink/Tests/HttpHeaderParserTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\WebLink\Tests; | ||
nicolas-grekas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
use PHPUnit\Framework\Attributes\DataProvider; | ||
use PHPUnit\Framework\TestCase; | ||
use Symfony\Component\WebLink\HttpHeaderParser; | ||
|
||
class HttpHeaderParserTest extends TestCase | ||
{ | ||
public function testParse() | ||
{ | ||
$parser = new HttpHeaderParser(); | ||
|
||
$header = [ | ||
'</1>; rel="prerender",</2>; rel="dns-prefetch"; pr="0.7",</3>; rel="preload"; as="script"', | ||
'</4>; rel="preload"; as="image"; nopush,</5>; rel="alternate next"; hreflang="fr"; hreflang="de"; title="Hello"' | ||
]; | ||
$provider = $parser->parse($header); | ||
$links = $provider->getLinks(); | ||
|
||
self::assertCount(5, $links); | ||
|
||
self::assertSame(['prerender'], $links[0]->getRels()); | ||
self::assertSame('/1', $links[0]->getHref()); | ||
self::assertSame([], $links[0]->getAttributes()); | ||
|
||
self::assertSame(['dns-prefetch'], $links[1]->getRels()); | ||
self::assertSame('/2', $links[1]->getHref()); | ||
self::assertSame(['pr' => '0.7'], $links[1]->getAttributes()); | ||
|
||
self::assertSame(['preload'], $links[2]->getRels()); | ||
self::assertSame('/3', $links[2]->getHref()); | ||
self::assertSame(['as' => 'script'], $links[2]->getAttributes()); | ||
|
||
self::assertSame(['preload'], $links[3]->getRels()); | ||
self::assertSame('/4', $links[3]->getHref()); | ||
self::assertSame(['as' => 'image', 'nopush' => true], $links[3]->getAttributes()); | ||
|
||
self::assertSame(['alternate', 'next'], $links[4]->getRels()); | ||
self::assertSame('/5', $links[4]->getHref()); | ||
self::assertSame(['hreflang' => ['fr', 'de'], 'title' => 'Hello'], $links[4]->getAttributes()); | ||
} | ||
|
||
public function testParseEmpty() | ||
{ | ||
$parser = new HttpHeaderParser(); | ||
$provider = $parser->parse(''); | ||
self::assertCount(0, $provider->getLinks()); | ||
} | ||
|
||
/** @dataProvider provideHeaderParsingCases */ | ||
#[DataProvider('provideHeaderParsingCases')] | ||
public function testParseVariousAttributes(string $header, array $expectedRels, array $expectedAttributes) | ||
{ | ||
$parser = new HttpHeaderParser(); | ||
$links = $parser->parse($header)->getLinks(); | ||
|
||
self::assertCount(1, $links); | ||
self::assertSame('/foo', $links[0]->getHref()); | ||
self::assertSame($expectedRels, $links[0]->getRels()); | ||
self::assertSame($expectedAttributes, $links[0]->getAttributes()); | ||
} | ||
|
||
public static function provideHeaderParsingCases() | ||
{ | ||
yield 'double_quotes_in_attribute_value' => [ | ||
'</foo>; rel="alternate"; title="\"escape me\" \"already escaped\" \"\"\""', | ||
['alternate'], | ||
['title' => '"escape me" "already escaped" """'], | ||
]; | ||
|
||
yield 'unquoted_attribute_value' => [ | ||
'</foo>; rel=alternate; type=text/html', | ||
['alternate'], | ||
['type' => 'text/html'], | ||
]; | ||
|
||
yield 'attribute_with_punctuation' => [ | ||
'</foo>; rel="alternate"; title=">; hello, world; test:case"', | ||
['alternate'], | ||
['title' => '>; hello, world; test:case'], | ||
]; | ||
|
||
yield 'no_rel' => [ | ||
'</foo>; type=text/html', | ||
[], | ||
['type' => 'text/html'], | ||
]; | ||
|
||
yield 'empty_rel' => [ | ||
'</foo>; rel', | ||
[], | ||
[], | ||
]; | ||
|
||
yield 'multiple_rel_attributes_get_first' => [ | ||
'</foo>; rel="alternate" rel="next"', | ||
['alternate'], | ||
[], | ||
]; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.