Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[HttpFoundation] Add HeaderUtils class#24699

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
fabpot merged 1 commit intosymfony:masterfromc960657:header-utils
Apr 22, 2018
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletionssrc/Symfony/Component/HttpFoundation/AcceptHeader.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -52,12 +52,17 @@ public static function fromString($headerValue)
{
$index = 0;

return new self(array_map(function ($itemValue) use (&$index) {
$item = AcceptHeaderItem::fromString($itemValue);
$parts = HeaderUtils::split((string) $headerValue, ',;=');

return new self(array_map(function ($subParts) use (&$index) {
$part = array_shift($subParts);
$attributes = HeaderUtils::combineParts($subParts);

$item = new AcceptHeaderItem($part[0], $attributes);
$item->setIndex($index++);

return $item;
},preg_split('/\s*(?:,*("[^"]+"),*|,*(\'[^\']+\'),*|,+)\s*/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)));
},$parts));
}

/**
Expand Down
26 changes: 6 additions & 20 deletionssrc/Symfony/Component/HttpFoundation/AcceptHeaderItem.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,24 +40,12 @@ public function __construct(string $value, array $attributes = array())
*/
public static function fromString($itemValue)
{
$bits = preg_split('/\s*(?:;*("[^"]+");*|;*(\'[^\']+\');*|;+)\s*/', $itemValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$value = array_shift($bits);
$attributes = array();

$lastNullAttribute = null;
foreach ($bits as $bit) {
if (($start = substr($bit, 0, 1)) === ($end = substr($bit, -1)) && ('"' === $start || '\'' === $start)) {
$attributes[$lastNullAttribute] = substr($bit, 1, -1);
} elseif ('=' === $end) {
$lastNullAttribute = $bit = substr($bit, 0, -1);
$attributes[$bit] = null;
} else {
$parts = explode('=', $bit);
$attributes[$parts[0]] = isset($parts[1]) && strlen($parts[1]) > 0 ? $parts[1] : '';
}
}
$parts = HeaderUtils::split($itemValue, ';=');

$part = array_shift($parts);
$attributes = HeaderUtils::combineParts($parts, 1);

return new self(($start = substr($value, 0, 1)) === ($end = substr($value, -1)) && ('"' === $start || '\'' === $start) ? substr($value, 1, -1) : $value, $attributes);
return new self($part[0], $attributes);
}

/**
Expand All@@ -69,9 +57,7 @@ public function __toString()
{
$string = $this->value.($this->quality < 1 ? ';q='.$this->quality : '');
if (count($this->attributes) > 0) {
$string .= ';'.implode(';', array_map(function ($name, $value) {
return sprintf(preg_match('/[,;=]/', $value) ? '%s="%s"' : '%s=%s', $name, $value);
}, array_keys($this->attributes), $this->attributes));
$string .= '; '.HeaderUtils::joinAssoc($this->attributes, ';');
}

return $string;
Expand Down
17 changes: 6 additions & 11 deletionssrc/Symfony/Component/HttpFoundation/BinaryFileResponse.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,17 +218,12 @@ public function prepare(Request $request)
if ('x-accel-redirect' === strtolower($type)) {
// Do X-Accel-Mapping substitutions.
// @link http://wiki.nginx.org/X-accel#X-Accel-Redirect
foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) {
$mapping = explode('=', $mapping, 2);

if (2 === count($mapping)) {
$pathPrefix = trim($mapping[0]);
$location = trim($mapping[1]);

if (substr($path, 0, strlen($pathPrefix)) === $pathPrefix) {
$path = $location.substr($path, strlen($pathPrefix));
break;
}
$parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
$mappings = HeaderUtils::combineParts($parts);
foreach ($mappings as $pathPrefix => $location) {
if (substr($path, 0, strlen($pathPrefix)) === $pathPrefix) {
$path = $location.substr($path, strlen($pathPrefix));
break;
}
}
}
Expand Down
1 change: 1 addition & 0 deletionssrc/Symfony/Component/HttpFoundation/CHANGELOG.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@ CHANGELOG
`IniSizeFileException`, `NoFileException`, `NoTmpDirFileException`, `PartialFileException` to
handle failed `UploadedFile`.
* added `MigratingSessionHandler` for migrating between two session handlers without losing sessions
* added `HeaderUtils`.

4.0.0
-----
Expand Down
38 changes: 12 additions & 26 deletionssrc/Symfony/Component/HttpFoundation/Cookie.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,34 +50,20 @@ public static function fromString($cookie, $decode = false)
'raw' => !$decode,
'samesite' => null,
);
foreach (explode(';', $cookie) as $part) {
if (false === strpos($part, '=')) {
$key = trim($part);
$value = true;
} else {
list($key, $value) = explode('=', trim($part), 2);
$key = trim($key);
$value = trim($value);
}
if (!isset($data['name'])) {
$data['name'] = $decode ? urldecode($key) : $key;
$data['value'] = true === $value ? null : ($decode ? urldecode($value) : $value);
continue;
}
switch ($key = strtolower($key)) {
case 'name':
case 'value':
break;
case 'max-age':
$data['expires'] = time() + (int) $value;
break;
default:
$data[$key] = $value;
break;
}

$parts = HeaderUtils::split($cookie, ';=');
$part = array_shift($parts);

$name = $decode ? urldecode($part[0]) : $part[0];
$value = isset($part[1]) ? ($decode ? urldecode($part[1]) : $part[1]) : null;

$data = HeaderUtils::combineParts($parts) + $data;

if (isset($data['max-age'])) {
$data['expires'] = time() + (int) $data['max-age'];
}

return new static($data['name'], $data['value'], $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']);
return new static($name, $value, $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']);
}

/**
Expand Down
22 changes: 3 additions & 19 deletionssrc/Symfony/Component/HttpFoundation/HeaderBag.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -294,21 +294,9 @@ public function count()

protected function getCacheControlHeader()
{
$parts = array();
ksort($this->cacheControl);
foreach ($this->cacheControl as $key => $value) {
if (true === $value) {
$parts[] = $key;
} else {
if (preg_match('#[^a-zA-Z0-9._-]#', $value)) {
$value = '"'.$value.'"';
}

$parts[] = "$key=$value";
}
}

return implode(', ', $parts);
return HeaderUtils::joinAssoc($this->cacheControl, ',');
}

/**
Expand All@@ -320,12 +308,8 @@ protected function getCacheControlHeader()
*/
protected function parseCacheControl($header)
{
$cacheControl = array();
preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$cacheControl[strtolower($match[1])] = isset($match[3]) ? $match[3] : (isset($match[2]) ? $match[2] : true);
}
$parts = HeaderUtils::split($header, ',=');

return$cacheControl;
returnHeaderUtils::combineParts($parts);
}
}
174 changes: 174 additions & 0 deletionssrc/Symfony/Component/HttpFoundation/HeaderUtils.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
<?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\HttpFoundation;

/**
* HTTP header utility functions.
*
* @author Christian Schmidt <github@chsc.dk>
*/
class HeaderUtils
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Shall this class be marked@internal?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I don't think so. It is generally useful when parsing HTTP headers, including those not supported directly by HttpFoundation. It may even be used in other contexts than parsing incoming HTTP request headers.

ro0NL reacted with thumbs up emoji
{
/**
* This class should not be instantiated.
*/
private function __construct()
{
}

/**
* Splits an HTTP header by one or more separators.
*
* Example:
*
* HeaderUtils::split("da, en-gb;q=0.8", ",;")
* // => array(array("da"), array("en-gb"), array("q", "0.8"))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Are you sure about this example ? Why is the header split on= when giving,; as separator ?

*
* @param string $header HTTP header value
* @param string $separators List of characters to split on, ordered by
* precedence, e.g. ",", ";=", or ",;="
*
* @return array Nested array with as many levels as there are characters in
* $separators
*/
public static function split(string $header, string $separators): array
{
$quotedSeparators = preg_quote($separators);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

this should include the regex delimiter (/ as second argument of the call, in case it is one of the separators


preg_match_all('
/
(?!\s)
(?:
# quoted-string
"(?:[^"\\\\]|\\\\.)*(?:"|\\\\|$)
|
# token
[^"'.$quotedSeparators.']+
)+
(?<!\s)
|
# separator
\s*
(?<separator>['.$quotedSeparators.'])
\s*
/x', trim($header), $matches, PREG_SET_ORDER);

return self::groupParts($matches, $separators);
}

/**
* Combines an array of arrays into one associative array.
*
* Each of the nested arrays should have one or two elements. The first
* value will be used as the keys in the associative array, and the second
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

that's not what is done. The key is the associative array is thelowercased first value, not the first value.

* will be used as the values, or true if the nested array only contains one
* element.
*
* Example:
*
* HeaderUtils::combineParts(array(array("foo", "abc"), array("bar")))
* // => array("foo" => "abc", "bar" => true)
*/
public static function combineParts(array $parts): array
{
$assoc = array();
foreach ($parts as $part) {
$name = strtolower($part[0]);
$value = $part[1] ?? true;
$assoc[$name] = $value;
}

return $assoc;
}

/**
* Joins an associative array into a string for use in an HTTP header.
*
* The key and value of each entry are joined with "=", and all entries
* is joined with the specified separator and an additional space (for
* readability). Values are quoted if necessary.
*
* Example:
*
* HeaderUtils::joinAssoc(array("foo" => "abc", "bar" => true, "baz" => "a b c"), ",")
* // => 'foo=bar, baz, baz="a b c"'
*/
public static function joinAssoc(array $assoc, string $separator): string
{
$parts = array();
foreach ($assoc as $name => $value) {
if (true === $value) {
$parts[] = $name;
} else {
$parts[] = $name.'='.self::quote($value);
}
}

return implode($separator.' ', $parts);
}

/**
* Encodes a string as a quoted string, if necessary.
*
* If a string contains characters not allowed by the "token" construct in
* the HTTP specification, it is backslash-escaped and enclosed in quotes
* to match the "quoted-string" construct.
*/
public static function quote(string $s): string
{
if (preg_match('/^[a-z0-9!#$%&\'*.^_`|~-]+$/i', $s)) {
return $s;
}

return '"'.addcslashes($s, '"\\"').'"';
}

/**
* Decodes a quoted string.
*
* If passed an unquoted string that matches the "token" construct (as
* defined in the HTTP specification), it is passed through verbatimly.
*/
public static function unquote(string $s): string
{
return preg_replace('/\\\\(.)|"/', '$1', $s);
}

private static function groupParts(array $matches, string $separators): array
{
$separator = $separators[0];
$partSeparators = substr($separators, 1);

$i = 0;
$partMatches = array();
foreach ($matches as $match) {
if (isset($match['separator']) && $match['separator'] === $separator) {
++$i;
} else {
$partMatches[$i][] = $match;
}
}

$parts = array();
if ($partSeparators) {
foreach ($partMatches as $matches) {
$parts[] = self::groupParts($matches, $partSeparators);
}
} else {
foreach ($partMatches as $matches) {
$parts[] = self::unquote($matches[0][0]);
}
}

return $parts;
}
}
26 changes: 21 additions & 5 deletionssrc/Symfony/Component/HttpFoundation/Request.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1944,8 +1944,16 @@ private function getTrustedValues($type, $ip = null)
}

if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) {
$forwardedValues = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
$forwardedValues = preg_match_all(sprintf('{(?:%s)=(?:"?\[?)([a-zA-Z0-9\.:_\-/]*+)}', self::$forwardedParams[$type]), $forwardedValues, $matches) ? $matches[1] : array();
$forwarded = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
$parts = HeaderUtils::split($forwarded, ',;=');
$forwardedValues = array();
$param = self::$forwardedParams[$type];
foreach ($parts as $subParts) {
$assoc = HeaderUtils::combineParts($subParts);
if (isset($assoc[$param])) {
$forwardedValues[] = $assoc[$param];
}
}
}

if (null !== $ip) {
Expand DownExpand Up@@ -1978,9 +1986,17 @@ private function normalizeAndFilterClientIps(array $clientIps, $ip)
$firstTrustedIp = null;

foreach ($clientIps as $key => $clientIp) {
// Remove port (unfortunately, it does happen)
if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
$clientIps[$key] = $clientIp = $match[1];
if (strpos($clientIp, '.')) {
// Strip :port from IPv4 addresses. This is allowed in Forwarded
// and may occur in X-Forwarded-For.
$i = strpos($clientIp, ':');
if ($i) {
$clientIps[$key] = $clientIp = substr($clientIp, 0, $i);
}
} elseif ('[' == $clientIp[0]) {
// Strip brackets and :port from IPv6 addresses.
$i = strpos($clientIp, ']', 1);
$clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1);
}

if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp