ALPHA 3.0.2a

This commit is contained in:
TheGamecraft
2018-09-10 08:51:18 -04:00
parent 7fe13ae0a7
commit 0e0ef86b71
1404 changed files with 10604 additions and 33714 deletions

View File

@@ -56,7 +56,7 @@ class AcceptHeaderItem
public function __toString()
{
$string = $this->value.($this->quality < 1 ? ';q='.$this->quality : '');
if (count($this->attributes) > 0) {
if (\count($this->attributes) > 0) {
$string .= '; '.HeaderUtils::toString($this->attributes, ';');
}

View File

@@ -35,7 +35,7 @@ class ApacheRequest extends Request
if (false === strpos($this->server->get('REQUEST_URI'), $baseUrl)) {
// assume mod_rewrite
return rtrim(dirname($baseUrl), '/\\');
return rtrim(\dirname($baseUrl), '/\\');
}
return $baseUrl;

View File

@@ -11,8 +11,8 @@
namespace Symfony\Component\HttpFoundation;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\File;
/**
* BinaryFileResponse represents an HTTP response delivering a file.
@@ -31,8 +31,8 @@ class BinaryFileResponse extends Response
* @var File
*/
protected $file;
protected $offset;
protected $maxlen;
protected $offset = 0;
protected $maxlen = -1;
protected $deleteFileAfterSend = false;
/**
@@ -165,7 +165,7 @@ class BinaryFileResponse extends Response
for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
$char = mb_substr($filename, $i, 1, $encoding);
if ('%' === $char || ord($char) < 32 || ord($char) > 126) {
if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
$filenameFallback .= '_';
} else {
$filenameFallback .= $char;
@@ -221,8 +221,8 @@ class BinaryFileResponse extends Response
$parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
$mappings = HeaderUtils::combine($parts);
foreach ($mappings as $pathPrefix => $location) {
if (substr($path, 0, strlen($pathPrefix)) === $pathPrefix) {
$path = $location.substr($path, strlen($pathPrefix));
if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
$path = $location.substr($path, \strlen($pathPrefix));
break;
}
}

View File

@@ -1,6 +1,12 @@
CHANGELOG
=========
4.1.3
-----
* [BC BREAK] Support for the IIS-only `X_ORIGINAL_URL` and `X_REWRITE_URL`
HTTP headers has been dropped for security reasons.
4.1.0
-----

View File

@@ -114,7 +114,7 @@ class Cookie
$sameSite = strtolower($sameSite);
}
if (!in_array($sameSite, array(self::SAMESITE_LAX, self::SAMESITE_STRICT, null), true)) {
if (!\in_array($sameSite, array(self::SAMESITE_LAX, self::SAMESITE_STRICT, null), true)) {
throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.');
}
@@ -252,7 +252,7 @@ class Cookie
*/
public function isCleared()
{
return $this->expire < time();
return 0 !== $this->expire && $this->expire < time();
}
/**

View File

@@ -15,6 +15,6 @@ class UnexpectedTypeException extends FileException
{
public function __construct($value, string $expectedType)
{
parent::__construct(sprintf('Expected argument of type %s, %s given', $expectedType, is_object($value) ? get_class($value) : gettype($value)));
parent::__construct(sprintf('Expected argument of type %s, %s given', $expectedType, \is_object($value) ? \get_class($value) : \gettype($value)));
}
}

View File

@@ -13,8 +13,8 @@ namespace Symfony\Component\HttpFoundation\File;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
/**
* A file in the file system.
@@ -115,7 +115,7 @@ class File extends \SplFileInfo
throw new FileException(sprintf('Unable to write in the "%s" directory', $directory));
}
$target = rtrim($directory, '/\\').DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name));
$target = rtrim($directory, '/\\').\DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name));
return new self($target, false);
}

View File

@@ -11,8 +11,8 @@
namespace Symfony\Component\HttpFoundation\File\MimeType;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
/**
* Guesses the mime type with the binary "file" (only available on *nix).
@@ -49,7 +49,7 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface
return $supported;
}
if ('\\' === DIRECTORY_SEPARATOR || !function_exists('passthru') || !function_exists('escapeshellarg')) {
if ('\\' === \DIRECTORY_SEPARATOR || !\function_exists('passthru') || !\function_exists('escapeshellarg')) {
return $supported = false;
}

View File

@@ -11,8 +11,8 @@
namespace Symfony\Component\HttpFoundation\File\MimeType;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
/**
* Guesses the mime type using the PECL extension FileInfo.
@@ -40,7 +40,7 @@ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface
*/
public static function isSupported()
{
return function_exists('finfo_open');
return \function_exists('finfo_open');
}
/**

View File

@@ -11,8 +11,8 @@
namespace Symfony\Component\HttpFoundation\File\MimeType;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
/**
* A singleton mime type guesser.

View File

@@ -11,8 +11,8 @@
namespace Symfony\Component\HttpFoundation\File\MimeType;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
/**
* Guesses the mime type of a file.

View File

@@ -65,10 +65,10 @@ class UploadedFile extends File
$this->originalName = $this->getName($originalName);
$this->mimeType = $mimeType ?: 'application/octet-stream';
if (4 < func_num_args() ? !is_bool($test) : null !== $error && @filesize($path) === $error) {
if (4 < \func_num_args() ? !\is_bool($test) : null !== $error && @filesize($path) === $error) {
@trigger_error(sprintf('Passing a size as 4th argument to the constructor of "%s" is deprecated since Symfony 4.1.', __CLASS__), E_USER_DEPRECATED);
$error = $test;
$test = 5 < func_num_args() ? func_get_arg(5) : false;
$test = 5 < \func_num_args() ? func_get_arg(5) : false;
}
$this->error = $error ?: UPLOAD_ERR_OK;
@@ -158,7 +158,7 @@ class UploadedFile extends File
*/
public function getClientSize()
{
@trigger_error(sprintf('"%s" is deprecated since Symfony 4.1. Use getSize() instead.', __METHOD__), E_USER_DEPRECATED);
@trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.1. Use getSize() instead.', __METHOD__), E_USER_DEPRECATED);
return $this->getSize();
}
@@ -254,9 +254,9 @@ class UploadedFile extends File
$max = ltrim($iniMax, '+');
if (0 === strpos($max, '0x')) {
$max = intval($max, 16);
$max = \intval($max, 16);
} elseif (0 === strpos($max, '0')) {
$max = intval($max, 8);
$max = \intval($max, 8);
} else {
$max = (int) $max;
}

View File

@@ -45,7 +45,7 @@ class FileBag extends ParameterBag
*/
public function set($key, $value)
{
if (!is_array($value) && !$value instanceof UploadedFile) {
if (!\is_array($value) && !$value instanceof UploadedFile) {
throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.');
}
@@ -76,7 +76,7 @@ class FileBag extends ParameterBag
}
$file = $this->fixPhpFilesArray($file);
if (is_array($file)) {
if (\is_array($file)) {
$keys = array_keys($file);
sort($keys);
@@ -113,14 +113,14 @@ class FileBag extends ParameterBag
*/
protected function fixPhpFilesArray($data)
{
if (!is_array($data)) {
if (!\is_array($data)) {
return $data;
}
$keys = array_keys($data);
sort($keys);
if (self::$fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
if (self::$fileKeys != $keys || !isset($data['name']) || !\is_array($data['name'])) {
return $data;
}

View File

@@ -101,11 +101,11 @@ class HeaderBag implements \IteratorAggregate, \Countable
/**
* Returns a header value by name.
*
* @param string $key The header name
* @param string|string[] $default The default value
* @param bool $first Whether to return the first value or all header values
* @param string $key The header name
* @param string|string[]|null $default The default value
* @param bool $first Whether to return the first value or all header values
*
* @return string|string[] The first header value or default value if $first is true, an array of values otherwise
* @return string|string[]|null The first header value or default value if $first is true, an array of values otherwise
*/
public function get($key, $default = null, $first = true)
{
@@ -181,7 +181,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*/
public function contains($key, $value)
{
return in_array($value, $this->get($key, null, false));
return \in_array($value, $this->get($key, null, false));
}
/**
@@ -289,7 +289,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*/
public function count()
{
return count($this->headers);
return \count($this->headers);
}
protected function getCacheControlHeader()

View File

@@ -37,7 +37,7 @@ class IpUtils
*/
public static function checkIp($requestIp, $ips)
{
if (!is_array($ips)) {
if (!\is_array($ips)) {
$ips = array($ips);
}
@@ -116,7 +116,7 @@ class IpUtils
return self::$checkedIps[$cacheKey];
}
if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) {
if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) {
throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
}

View File

@@ -101,7 +101,7 @@ class JsonResponse extends Response
);
$parts = explode('.', $callback);
foreach ($parts as $part) {
if (!preg_match($pattern, $part) || in_array($part, $reserved, true)) {
if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) {
throw new \InvalidArgumentException('The callback name is not valid.');
}
}
@@ -142,7 +142,7 @@ class JsonResponse extends Response
try {
$data = json_encode($data, $this->encodingOptions);
} catch (\Exception $e) {
if ('Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
if ('Exception' === \get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
throw $e->getPrevious() ?: $e;
}
throw $e;

View File

@@ -200,12 +200,12 @@ class ParameterBag implements \IteratorAggregate, \Countable
$value = $this->get($key, $default);
// Always turn $options into an array - this allows filter_var option shortcuts.
if (!is_array($options) && $options) {
if (!\is_array($options) && $options) {
$options = array('flags' => $options);
}
// Add a convenience check for arrays.
if (is_array($value) && !isset($options['flags'])) {
if (\is_array($value) && !isset($options['flags'])) {
$options['flags'] = FILTER_REQUIRE_ARRAY;
}
@@ -229,6 +229,6 @@ class ParameterBag implements \IteratorAggregate, \Countable
*/
public function count()
{
return count($this->parameters);
return \count($this->parameters);
}
}

View File

@@ -281,7 +281,7 @@ class Request
$request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
&& in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
&& \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
) {
parse_str($request->getContent(), $data);
$request->request = new ParameterBag($data);
@@ -533,7 +533,7 @@ class Request
foreach ($this->headers->all() as $key => $value) {
$key = strtoupper(str_replace('-', '_', $key));
if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
if (\in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
$_SERVER[$key] = implode(', ', $value);
} else {
$_SERVER['HTTP_'.$key] = implode(', ', $value);
@@ -1072,7 +1072,7 @@ class Request
}
$targetDirs[] = $targetFile;
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
$path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs);
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
@@ -1111,7 +1111,7 @@ class Request
public function isSecure()
{
if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) {
return in_array(strtolower($proto[0]), array('https', 'on', 'ssl', '1'), true);
return \in_array(strtolower($proto[0]), array('https', 'on', 'ssl', '1'), true);
}
$https = $this->server->get('HTTPS');
@@ -1157,10 +1157,10 @@ class Request
throw new SuspiciousOperationException(sprintf('Invalid Host "%s".', $host));
}
if (count(self::$trustedHostPatterns) > 0) {
if (\count(self::$trustedHostPatterns) > 0) {
// to avoid host header injection attacks, you should provide a list of trusted host patterns
if (in_array($host, self::$trustedHosts)) {
if (\in_array($host, self::$trustedHosts)) {
return $host;
}
@@ -1218,7 +1218,10 @@ class Request
if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
$this->method = strtoupper($method);
} elseif (self::$httpMethodParameterOverride) {
$this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
$method = $this->request->get('_method', $this->query->get('_method', 'POST'));
if (\is_string($method)) {
$this->method = strtoupper($method);
}
}
}
}
@@ -1289,10 +1292,10 @@ class Request
}
foreach (static::$formats as $format => $mimeTypes) {
if (in_array($mimeType, (array) $mimeTypes)) {
if (\in_array($mimeType, (array) $mimeTypes)) {
return $format;
}
if (null !== $canonicalMimeType && in_array($canonicalMimeType, (array) $mimeTypes)) {
if (null !== $canonicalMimeType && \in_array($canonicalMimeType, (array) $mimeTypes)) {
return $format;
}
}
@@ -1310,7 +1313,7 @@ class Request
static::initializeFormats();
}
static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
}
/**
@@ -1422,12 +1425,12 @@ class Request
*/
public function isMethodSafe(/* $andCacheable = true */)
{
if (!func_num_args() || func_get_arg(0)) {
if (!\func_num_args() || func_get_arg(0)) {
// setting $andCacheable to false should be deprecated in 4.1
throw new \BadMethodCallException('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is not supported.');
}
return in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
return \in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
}
/**
@@ -1437,7 +1440,7 @@ class Request
*/
public function isMethodIdempotent()
{
return in_array($this->getMethod(), array('HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE'));
return \in_array($this->getMethod(), array('HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE'));
}
/**
@@ -1449,7 +1452,7 @@ class Request
*/
public function isMethodCacheable()
{
return in_array($this->getMethod(), array('GET', 'HEAD'));
return \in_array($this->getMethod(), array('GET', 'HEAD'));
}
/**
@@ -1487,7 +1490,7 @@ class Request
*/
public function getContent($asResource = false)
{
$currentContentIsResource = is_resource($this->content);
$currentContentIsResource = \is_resource($this->content);
if (true === $asResource) {
if ($currentContentIsResource) {
@@ -1497,7 +1500,7 @@ class Request
}
// Content passed in parameter (test)
if (is_string($this->content)) {
if (\is_string($this->content)) {
$resource = fopen('php://temp', 'r+');
fwrite($resource, $this->content);
rewind($resource);
@@ -1565,7 +1568,7 @@ class Request
$extendedPreferredLanguages[] = $language;
if (false !== $position = strpos($language, '_')) {
$superLanguage = substr($language, 0, $position);
if (!in_array($superLanguage, $preferredLanguages)) {
if (!\in_array($superLanguage, $preferredLanguages)) {
$extendedPreferredLanguages[] = $superLanguage;
}
}
@@ -1596,11 +1599,11 @@ class Request
// Language not listed in ISO 639 that are not variants
// of any listed language, which can be registered with the
// i-prefix, such as i-cherokee
if (count($codes) > 1) {
if (\count($codes) > 1) {
$lang = $codes[1];
}
} else {
for ($i = 0, $max = count($codes); $i < $max; ++$i) {
for ($i = 0, $max = \count($codes); $i < $max; ++$i) {
if (0 === $i) {
$lang = strtolower($codes[0]);
} else {
@@ -1685,18 +1688,7 @@ class Request
{
$requestUri = '';
if ($this->headers->has('X_ORIGINAL_URL')) {
// IIS with Microsoft Rewrite Module
$requestUri = $this->headers->get('X_ORIGINAL_URL');
$this->headers->remove('X_ORIGINAL_URL');
$this->server->remove('HTTP_X_ORIGINAL_URL');
$this->server->remove('UNENCODED_URL');
$this->server->remove('IIS_WasUrlRewritten');
} elseif ($this->headers->has('X_REWRITE_URL')) {
// IIS with ISAPI_Rewrite
$requestUri = $this->headers->get('X_REWRITE_URL');
$this->headers->remove('X_REWRITE_URL');
} elseif ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) {
if ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) {
// IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
$requestUri = $this->server->get('UNENCODED_URL');
$this->server->remove('UNENCODED_URL');
@@ -1706,7 +1698,7 @@ class Request
// HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
$schemeAndHttpHost = $this->getSchemeAndHttpHost();
if (0 === strpos($requestUri, $schemeAndHttpHost)) {
$requestUri = substr($requestUri, strlen($schemeAndHttpHost));
$requestUri = substr($requestUri, \strlen($schemeAndHttpHost));
}
} elseif ($this->server->has('ORIG_PATH_INFO')) {
// IIS 5.0, PHP as CGI
@@ -1746,7 +1738,7 @@ class Request
$segs = explode('/', trim($file, '/'));
$segs = array_reverse($segs);
$index = 0;
$last = count($segs);
$last = \count($segs);
$baseUrl = '';
do {
$seg = $segs[$index];
@@ -1766,9 +1758,9 @@ class Request
return $prefix;
}
if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(dirname($baseUrl), '/'.DIRECTORY_SEPARATOR).'/')) {
if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(\dirname($baseUrl), '/'.\DIRECTORY_SEPARATOR).'/')) {
// directory portion of $baseUrl matches
return rtrim($prefix, '/'.DIRECTORY_SEPARATOR);
return rtrim($prefix, '/'.\DIRECTORY_SEPARATOR);
}
$truncatedRequestUri = $requestUri;
@@ -1785,11 +1777,11 @@ class Request
// If using mod_rewrite or ISAPI_Rewrite strip the script filename
// out of baseUrl. $pos !== 0 makes sure it is not matching a value
// from PATH_INFO or QUERY_STRING
if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) {
$baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
if (\strlen($requestUri) >= \strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) {
$baseUrl = substr($requestUri, 0, $pos + \strlen($baseUrl));
}
return rtrim($baseUrl, '/'.DIRECTORY_SEPARATOR);
return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR);
}
/**
@@ -1806,12 +1798,12 @@ class Request
$filename = basename($this->server->get('SCRIPT_FILENAME'));
if (basename($baseUrl) === $filename) {
$basePath = dirname($baseUrl);
$basePath = \dirname($baseUrl);
} else {
$basePath = $baseUrl;
}
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$basePath = str_replace('\\', '/', $basePath);
}
@@ -1841,7 +1833,7 @@ class Request
return $requestUri;
}
$pathInfo = substr($requestUri, strlen($baseUrl));
$pathInfo = substr($requestUri, \strlen($baseUrl));
if (false === $pathInfo || '' === $pathInfo) {
// If substr() returns false then PATH_INFO is set to an empty string
return '/';
@@ -1895,7 +1887,7 @@ class Request
return false;
}
$len = strlen($prefix);
$len = \strlen($prefix);
if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
return $match[0];
@@ -1907,7 +1899,7 @@ class Request
private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
if (self::$requestFactory) {
$request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
$request = \call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
if (!$request instanceof self) {
throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
@@ -1949,10 +1941,16 @@ class Request
$forwardedValues = array();
$param = self::$forwardedParams[$type];
foreach ($parts as $subParts) {
$assoc = HeaderUtils::combine($subParts);
if (isset($assoc[$param])) {
$forwardedValues[] = $assoc[$param];
if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) {
continue;
}
if (self::HEADER_X_FORWARDED_PORT === $type) {
if (']' === substr($v, -1) || false === $v = strrchr($v, ':')) {
$v = $this->isSecure() ? ':443' : ':80';
}
$v = '0.0.0.0'.$v;
}
$forwardedValues[] = $v;
}
}
@@ -1993,7 +1991,7 @@ class Request
if ($i) {
$clientIps[$key] = $clientIp = substr($clientIp, 0, $i);
}
} elseif ('[' == $clientIp[0]) {
} elseif (0 === strpos($clientIp, '[')) {
// Strip brackets and :port from IPv6 addresses.
$i = strpos($clientIp, ']', 1);
$clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1);

View File

@@ -145,11 +145,11 @@ class RequestMatcher implements RequestMatcherInterface
*/
public function matches(Request $request)
{
if ($this->schemes && !in_array($request->getScheme(), $this->schemes, true)) {
if ($this->schemes && !\in_array($request->getScheme(), $this->schemes, true)) {
return false;
}
if ($this->methods && !in_array($request->getMethod(), $this->methods, true)) {
if ($this->methods && !\in_array($request->getMethod(), $this->methods, true)) {
return false;
}
@@ -173,6 +173,6 @@ class RequestMatcher implements RequestMatcherInterface
// Note to future implementors: add additional checks above the
// foreach above or else your check might not be run!
return 0 === count($this->ips);
return 0 === \count($this->ips);
}
}

View File

@@ -92,7 +92,7 @@ class RequestStack
*/
public function getParentRequest()
{
$pos = count($this->requests) - 2;
$pos = \count($this->requests) - 2;
if (!isset($this->requests[$pos])) {
return;

View File

@@ -64,7 +64,12 @@ class Response
const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
const HTTP_LOCKED = 423; // RFC4918
const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
/**
* @deprecated
*/
const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817
const HTTP_TOO_EARLY = 425; // RFC-ietf-httpbis-replay-04
const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
@@ -169,7 +174,7 @@ class Response
422 => 'Unprocessable Entity', // RFC4918
423 => 'Locked', // RFC4918
424 => 'Failed Dependency', // RFC4918
425 => 'Reserved for WebDAV advanced collections expired proposal', // RFC2817
425 => 'Too Early', // RFC-ietf-httpbis-replay-04
426 => 'Upgrade Required', // RFC2817
428 => 'Precondition Required', // RFC6585
429 => 'Too Many Requests', // RFC6585
@@ -324,12 +329,17 @@ class Response
}
// headers
foreach ($this->headers->allPreserveCase() as $name => $values) {
foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
foreach ($values as $value) {
header($name.': '.$value, false, $this->statusCode);
}
}
// cookies
foreach ($this->headers->getCookies() as $cookie) {
header('Set-Cookie: '.$cookie->getName().strstr($cookie, '='), false, $this->statusCode);
}
// status
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
@@ -358,9 +368,9 @@ class Response
$this->sendHeaders();
$this->sendContent();
if (function_exists('fastcgi_finish_request')) {
if (\function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} elseif (!\in_array(PHP_SAPI, array('cli', 'phpdbg'), true)) {
} elseif (!\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true)) {
static::closeOutputBuffers(0, true);
}
@@ -380,8 +390,8 @@ class Response
*/
public function setContent($content)
{
if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content, '__toString'))) {
throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', gettype($content)));
if (null !== $content && !\is_string($content) && !is_numeric($content) && !\is_callable(array($content, '__toString'))) {
throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', \gettype($content)));
}
$this->content = (string) $content;
@@ -512,7 +522,7 @@ class Response
*/
public function isCacheable(): bool
{
if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
if (!\in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
return false;
}
@@ -679,6 +689,7 @@ class Response
{
if ($this->isFresh()) {
$this->headers->set('Age', $this->getMaxAge());
$this->headers->remove('Expires');
}
return $this;
@@ -1057,7 +1068,7 @@ class Response
$modifiedSince = $request->headers->get('If-Modified-Since');
if ($etags = $request->getETags()) {
$notModified = in_array($this->getEtag(), $etags) || in_array('*', $etags);
$notModified = \in_array($this->getEtag(), $etags) || \in_array('*', $etags);
}
if ($modifiedSince && $lastModified) {
@@ -1170,7 +1181,7 @@ class Response
*/
public function isRedirect(string $location = null): bool
{
return in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
return \in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
}
/**
@@ -1180,7 +1191,7 @@ class Response
*/
public function isEmpty(): bool
{
return in_array($this->statusCode, array(204, 304));
return \in_array($this->statusCode, array(204, 304));
}
/**
@@ -1193,7 +1204,7 @@ class Response
public static function closeOutputBuffers(int $targetLevel, bool $flush)
{
$status = ob_get_status(true);
$level = count($status);
$level = \count($status);
$flags = PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE);
while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {

View File

@@ -216,7 +216,7 @@ class ResponseHeaderBag extends HeaderBag
*/
public function getCookies($format = self::COOKIES_FLAT)
{
if (!in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) {
if (!\in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) {
throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY))));
}
@@ -267,7 +267,7 @@ class ResponseHeaderBag extends HeaderBag
*/
public function makeDisposition($disposition, $filename, $filenameFallback = '')
{
if (!in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) {
if (!\in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) {
throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE));
}

View File

@@ -68,7 +68,7 @@ class ServerBag extends ParameterBag
if (0 === stripos($authorizationHeader, 'basic ')) {
// Decode AUTHORIZATION header into PHP_AUTH_USER and PHP_AUTH_PW when authorization header is basic
$exploded = explode(':', base64_decode(substr($authorizationHeader, 6)), 2);
if (2 == count($exploded)) {
if (2 == \count($exploded)) {
list($headers['PHP_AUTH_USER'], $headers['PHP_AUTH_PW']) = $exploded;
}
} elseif (empty($this->parameters['PHP_AUTH_DIGEST']) && (0 === stripos($authorizationHeader, 'digest '))) {

View File

@@ -143,6 +143,6 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta
*/
public function count()
{
return count($this->attributes);
return \count($this->attributes);
}
}

View File

@@ -110,7 +110,7 @@ class NamespacedAttributeBag extends AttributeBag
}
$parts = explode($this->namespaceCharacter, $name);
if (count($parts) < 2) {
if (\count($parts) < 2) {
if (!$writeContext) {
return $array;
}
@@ -120,11 +120,17 @@ class NamespacedAttributeBag extends AttributeBag
return $array;
}
unset($parts[count($parts) - 1]);
unset($parts[\count($parts) - 1]);
foreach ($parts as $part) {
if (null !== $array && !array_key_exists($part, $array)) {
$array[$part] = $writeContext ? array() : null;
if (!$writeContext) {
$null = null;
return $null;
}
$array[$part] = array();
}
$array = &$array[$part];

View File

@@ -24,7 +24,7 @@ interface FlashBagInterface extends SessionBagInterface
* Adds a flash message for type.
*
* @param string $type
* @param string $message
* @param mixed $message
*/
public function add($type, $message);

View File

@@ -11,12 +11,12 @@
namespace Symfony\Component\HttpFoundation\Session;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
@@ -54,8 +54,6 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
*/
public function start()
{
++$this->usageIndex;
return $this->storage->start();
}
@@ -140,7 +138,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
*/
public function count()
{
return count($this->getAttributeBag()->all());
return \count($this->getAttributeBag()->all());
}
/**
@@ -160,7 +158,9 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
*/
public function isEmpty()
{
++$this->usageIndex;
if ($this->isStarted()) {
++$this->usageIndex;
}
foreach ($this->data as &$data) {
if (!empty($data)) {
return false;
@@ -185,8 +185,6 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
*/
public function migrate($destroy = false, $lifetime = null)
{
++$this->usageIndex;
return $this->storage->regenerate($destroy, $lifetime);
}
@@ -195,8 +193,6 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
*/
public function save()
{
++$this->usageIndex;
$this->storage->save();
}

View File

@@ -44,6 +44,9 @@ final class SessionBagProxy implements SessionBagInterface
*/
public function isEmpty()
{
if (!isset($this->data[$this->bag->getStorageKey()])) {
return true;
}
++$this->usageIndex;
return empty($this->data[$this->bag->getStorageKey()]);
@@ -81,8 +84,6 @@ final class SessionBagProxy implements SessionBagInterface
*/
public function clear()
{
++$this->usageIndex;
return $this->bag->clear();
}
}

View File

@@ -119,7 +119,7 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
{
if (!headers_sent() && ini_get('session.use_cookies')) {
if (!$this->sessionName) {
throw new \LogicException(sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', get_class($this)));
throw new \LogicException(sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', \get_class($this)));
}
$sessionCookie = sprintf(' %s=', urlencode($this->sessionName));
$sessionCookieWithId = sprintf('%s%s;', $sessionCookie, urlencode($sessionId));

View File

@@ -24,7 +24,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
private $mongo;
/**
* @var \MongoCollection
* @var \MongoDB\Collection
*/
private $collection;
@@ -143,21 +143,12 @@ class MongoDbSessionHandler extends AbstractSessionHandler
{
$expiry = new \MongoDB\BSON\UTCDateTime((time() + (int) ini_get('session.gc_maxlifetime')) * 1000);
if ($this->mongo instanceof \MongoDB\Client) {
$methodName = 'updateOne';
$options = array();
} else {
$methodName = 'update';
$options = array('multiple' => false);
}
$this->getCollection()->$methodName(
$this->getCollection()->updateOne(
array($this->options['id_field'] => $sessionId),
array('$set' => array(
$this->options['time_field'] => new \MongoDB\BSON\UTCDateTime(),
$this->options['expiry_field'] => $expiry,
)),
$options
))
);
return true;
@@ -181,7 +172,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
}
/**
* @return \MongoCollection
* @return \MongoDB\Collection
*/
private function getCollection()
{

View File

@@ -178,7 +178,7 @@ class PdoSessionHandler extends AbstractSessionHandler
$this->pdo = $pdoOrDsn;
$this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
} elseif (is_string($pdoOrDsn) && false !== strpos($pdoOrDsn, '://')) {
} elseif (\is_string($pdoOrDsn) && false !== strpos($pdoOrDsn, '://')) {
$this->dsn = $this->buildDsnFromUrl($pdoOrDsn);
} else {
$this->dsn = $pdoOrDsn;
@@ -629,7 +629,7 @@ class PdoSessionHandler extends AbstractSessionHandler
return '';
}
return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
return \is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
}
if (null !== $insertStmt) {
@@ -735,11 +735,11 @@ class PdoSessionHandler extends AbstractSessionHandler
private function convertStringToInt(string $string): int
{
if (4 === \PHP_INT_SIZE) {
return (ord($string[3]) << 24) + (ord($string[2]) << 16) + (ord($string[1]) << 8) + ord($string[0]);
return (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
}
$int1 = (ord($string[7]) << 24) + (ord($string[6]) << 16) + (ord($string[5]) << 8) + ord($string[4]);
$int2 = (ord($string[3]) << 24) + (ord($string[2]) << 16) + (ord($string[1]) << 8) + ord($string[0]);
$int1 = (\ord($string[7]) << 24) + (\ord($string[6]) << 16) + (\ord($string[5]) << 8) + \ord($string[4]);
$int2 = (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
return $int2 + ($int1 << 32);
}

View File

@@ -12,6 +12,7 @@
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Predis\Response\ErrorInterface;
use Symfony\Component\Cache\Traits\RedisProxy;
/**
* Redis based session storage handler based on the Redis class
@@ -32,15 +33,21 @@ class RedisSessionHandler extends AbstractSessionHandler
* List of available options:
* * prefix: The prefix to use for the keys in order to avoid collision on the Redis server.
*
* @param \Redis|\RedisArray|\RedisCluster|\Predis\Client $redis
* @param array $options An associative array of options
* @param \Redis|\RedisArray|\RedisCluster|\Predis\Client|RedisProxy $redis
* @param array $options An associative array of options
*
* @throws \InvalidArgumentException When unsupported client or options are passed
*/
public function __construct($redis, array $options = array())
{
if (!$redis instanceof \Redis && !$redis instanceof \RedisArray && !$redis instanceof \Predis\Client && !$redis instanceof RedisProxy) {
throw new \InvalidArgumentException(sprintf('%s() expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\Client, %s given', __METHOD__, is_object($redis) ? get_class($redis) : gettype($redis)));
if (
!$redis instanceof \Redis &&
!$redis instanceof \RedisArray &&
!$redis instanceof \RedisCluster &&
!$redis instanceof \Predis\Client &&
!$redis instanceof RedisProxy
) {
throw new \InvalidArgumentException(sprintf('%s() expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\Client, %s given', __METHOD__, \is_object($redis) ? \get_class($redis) : \gettype($redis)));
}
if ($diff = array_diff(array_keys($options), array('prefix'))) {

View File

@@ -24,7 +24,7 @@ class StrictSessionHandler extends AbstractSessionHandler
public function __construct(\SessionHandlerInterface $handler)
{
if ($handler instanceof \SessionUpdateTimestampHandlerInterface) {
throw new \LogicException(sprintf('"%s" is already an instance of "SessionUpdateTimestampHandlerInterface", you cannot wrap it with "%s".', get_class($handler), self::class));
throw new \LogicException(sprintf('"%s" is already an instance of "SessionUpdateTimestampHandlerInterface", you cannot wrap it with "%s".', \get_class($handler), self::class));
}
$this->handler = $handler;

View File

@@ -248,7 +248,7 @@ class NativeSessionStorage implements SessionStorageInterface
$handler = $handler->getHandler();
}
trigger_error(sprintf('session_write_close(): Failed to write session data with %s handler', get_class($handler)), E_USER_WARNING);
trigger_error(sprintf('session_write_close(): Failed to write session data with %s handler', \get_class($handler)), E_USER_WARNING);
}
$this->closed = true;
@@ -407,8 +407,6 @@ class NativeSessionStorage implements SessionStorageInterface
}
if ($this->saveHandler instanceof SessionHandlerProxy) {
session_set_save_handler($this->saveHandler->getHandler(), false);
} elseif ($this->saveHandler instanceof \SessionHandlerInterface) {
session_set_save_handler($this->saveHandler, false);
}
}

View File

@@ -14,7 +14,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy;
/**
* @author Drak <drak@zikula.org>
*/
class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface
class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
{
protected $handler;
@@ -82,4 +82,20 @@ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterf
{
return (bool) $this->handler->gc($maxlifetime);
}
/**
* {@inheritdoc}
*/
public function validateId($sessionId)
{
return !$this->handler instanceof \SessionUpdateTimestampHandlerInterface || $this->handler->validateId($sessionId);
}
/**
* {@inheritdoc}
*/
public function updateTimestamp($sessionId, $data)
{
return $this->handler instanceof \SessionUpdateTimestampHandlerInterface ? $this->handler->updateTimestamp($sessionId, $data) : $this->write($sessionId, $data);
}
}

View File

@@ -111,7 +111,7 @@ class StreamedResponse extends Response
throw new \LogicException('The Response callback must not be null.');
}
call_user_func($this->callback);
\call_user_func($this->callback);
return $this;
}
@@ -141,4 +141,16 @@ class StreamedResponse extends Response
{
return false;
}
/**
* {@inheritdoc}
*
* @return $this
*/
public function setNotModified()
{
$this->setCallback(function () {});
return parent::setNotModified();
}
}

View File

@@ -208,6 +208,19 @@ class BinaryFileResponseTest extends ResponseTestCase
);
}
public function testUnpreparedResponseSendsFullFile()
{
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200);
$data = file_get_contents(__DIR__.'/File/Fixtures/test.gif');
$this->expectOutputString($data);
$response = clone $response;
$response->sendContent();
$this->assertEquals(200, $response->getStatusCode());
}
/**
* @dataProvider provideInvalidRanges
*/

View File

@@ -154,6 +154,18 @@ class CookieTest extends TestCase
$cookie = new Cookie('foo', 'bar', time() - 20);
$this->assertTrue($cookie->isCleared(), '->isCleared() returns true if the cookie has expired');
$cookie = new Cookie('foo', 'bar');
$this->assertFalse($cookie->isCleared());
$cookie = new Cookie('foo', 'bar', 0);
$this->assertFalse($cookie->isCleared());
$cookie = new Cookie('foo', 'bar', -1);
$this->assertFalse($cookie->isCleared());
}
public function testToString()

View File

@@ -12,8 +12,8 @@
namespace Symfony\Component\HttpFoundation\Tests\File\MimeType;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\FileBinaryMimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
/**
* @requires extension fileinfo
@@ -59,7 +59,7 @@ class MimeTypeTest extends TestCase
public function testGuessWithNonReadablePath()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Can not verify chmod operations on Windows');
}

View File

@@ -53,7 +53,7 @@ class UploadedFileTest extends TestCase
$this->assertEquals('application/octet-stream', $file->getClientMimeType());
if (extension_loaded('fileinfo')) {
if (\extension_loaded('fileinfo')) {
$this->assertEquals('image/gif', $file->getMimeType());
}
}

View File

@@ -4,7 +4,7 @@ Array
[0] => Content-Type: text/plain; charset=utf-8
[1] => Cache-Control: no-cache, private
[2] => Date: Sat, 12 Nov 1955 20:04:00 GMT
[3] => Set-Cookie: %3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/
[3] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/
[4] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/
)
shutdown

View File

@@ -192,7 +192,7 @@ class HeaderBagTest extends TestCase
$this->assertEquals(array($headers[$key]), $val);
}
$this->assertEquals(count($headers), $i);
$this->assertEquals(\count($headers), $i);
}
public function testCount()
@@ -200,6 +200,6 @@ class HeaderBagTest extends TestCase
$headers = array('foo' => 'bar', 'HELLO' => 'WORLD');
$headerBag = new HeaderBag($headers);
$this->assertCount(count($headers), $headerBag);
$this->assertCount(\count($headers), $headerBag);
}
}

View File

@@ -47,7 +47,7 @@ class IpUtilsTest extends TestCase
*/
public function testIpv6($matches, $remoteAddr, $cidr)
{
if (!defined('AF_INET6')) {
if (!\defined('AF_INET6')) {
$this->markTestSkipped('Only works when PHP is compiled without the option "disable-ipv6".');
}
@@ -78,7 +78,7 @@ class IpUtilsTest extends TestCase
*/
public function testAnIpv6WithOptionDisabledIpv6()
{
if (defined('AF_INET6')) {
if (\defined('AF_INET6')) {
$this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".');
}

View File

@@ -171,7 +171,7 @@ class ParameterBagTest extends TestCase
$this->assertEquals($parameters[$key], $val);
}
$this->assertEquals(count($parameters), $i);
$this->assertEquals(\count($parameters), $i);
}
public function testCount()
@@ -179,7 +179,7 @@ class ParameterBagTest extends TestCase
$parameters = array('foo' => 'bar', 'hello' => 'world');
$bag = new ParameterBag($parameters);
$this->assertCount(count($parameters), $bag);
$this->assertCount(\count($parameters), $bag);
}
public function testGetBoolean()

View File

@@ -12,8 +12,8 @@
namespace Symfony\Component\HttpFoundation\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcher;
class RequestMatcherTest extends TestCase
{

View File

@@ -13,9 +13,9 @@ namespace Symfony\Component\HttpFoundation\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
class RequestTest extends TestCase
{
@@ -854,6 +854,11 @@ class RequestTest extends TestCase
$request->setMethod('POST');
$request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete');
$this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override if defined and POST');
$request = new Request();
$request->setMethod('POST');
$request->query->set('_method', array('delete', 'patch'));
$this->assertSame('POST', $request->getMethod(), '->getMethod() returns the request method if invalid type is defined in query');
}
/**
@@ -901,7 +906,7 @@ class RequestTest extends TestCase
public function getClientIpsProvider()
{
// $expected $remoteAddr $httpForwardedFor $trustedProxies
// $expected $remoteAddr $httpForwardedFor $trustedProxies
return array(
// simple IPv4
array(array('88.88.88.88'), '88.88.88.88', null, null),
@@ -915,8 +920,8 @@ class RequestTest extends TestCase
// forwarded for with remote IPv4 addr not trusted
array(array('127.0.0.1'), '127.0.0.1', '88.88.88.88', null),
// forwarded for with remote IPv4 addr trusted
array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88', array('127.0.0.1')),
// forwarded for with remote IPv4 addr trusted + comma
array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88,', array('127.0.0.1')),
// forwarded for with remote IPv4 and all FF addrs trusted
array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88', array('127.0.0.1', '88.88.88.88')),
// forwarded for with remote IPv4 range trusted
@@ -1020,7 +1025,7 @@ class RequestTest extends TestCase
'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor,
);
Request::setTrustedProxies(array('88.88.88.88'), Request::HEADER_X_FORWARDED_ALL);
Request::setTrustedProxies(array('88.88.88.88'), -1);
$request->initialize(array(), array(), array(), array(), array(), $server);
@@ -1831,20 +1836,6 @@ class RequestTest extends TestCase
public function iisRequestUriProvider()
{
return array(
array(
array(
'X_ORIGINAL_URL' => '/foo/bar',
),
array(),
'/foo/bar',
),
array(
array(
'X_REWRITE_URL' => '/foo/bar',
),
array(),
'/foo/bar',
),
array(
array(),
array(
@@ -1853,36 +1844,6 @@ class RequestTest extends TestCase
),
'/foo/bar',
),
array(
array(
'X_ORIGINAL_URL' => '/foo/bar',
),
array(
'HTTP_X_ORIGINAL_URL' => '/foo/bar',
),
'/foo/bar',
),
array(
array(
'X_ORIGINAL_URL' => '/foo/bar',
),
array(
'IIS_WasUrlRewritten' => '1',
'UNENCODED_URL' => '/foo/bar',
),
'/foo/bar',
),
array(
array(
'X_ORIGINAL_URL' => '/foo/bar',
),
array(
'HTTP_X_ORIGINAL_URL' => '/foo/bar',
'IIS_WasUrlRewritten' => '1',
'UNENCODED_URL' => '/foo/bar',
),
'/foo/bar',
),
array(
array(),
array(
@@ -2192,6 +2153,55 @@ class RequestTest extends TestCase
$this->assertEquals($expectedBaseUrl, $request->getBaseUrl());
$this->assertEquals($expectedBasePath, $request->getBasePath());
}
public function testTrustedHost()
{
Request::setTrustedProxies(array('1.1.1.1'), -1);
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('Forwarded', 'host=localhost:8080');
$request->headers->set('X-Forwarded-Host', 'localhost:8080');
$this->assertSame('localhost:8080', $request->getHttpHost());
$this->assertSame(8080, $request->getPort());
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('Forwarded', 'host="[::1]:443"');
$request->headers->set('X-Forwarded-Host', '[::1]:443');
$request->headers->set('X-Forwarded-Port', 443);
$this->assertSame('[::1]:443', $request->getHttpHost());
$this->assertSame(443, $request->getPort());
}
public function testTrustedPort()
{
Request::setTrustedProxies(array('1.1.1.1'), -1);
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('Forwarded', 'host=localhost:8080');
$request->headers->set('X-Forwarded-Port', 8080);
$this->assertSame(8080, $request->getPort());
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('Forwarded', 'host=localhost');
$request->headers->set('X-Forwarded-Port', 80);
$this->assertSame(80, $request->getPort());
$request = Request::create('/');
$request->server->set('REMOTE_ADDR', '1.1.1.1');
$request->headers->set('Forwarded', 'host="[::1]"');
$request->headers->set('X-Forwarded-Proto', 'https');
$request->headers->set('X-Forwarded-Port', 443);
$this->assertSame(443, $request->getPort());
}
}
class RequestContentProxy extends Request

View File

@@ -12,8 +12,8 @@
namespace Symfony\Component\HttpFoundation\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
/**
* @group time-sensitive

View File

@@ -126,7 +126,7 @@ class ResponseTest extends ResponseTestCase
public function testSetNotModified()
{
$response = new Response();
$response = new Response('foo');
$modified = $response->setNotModified();
$this->assertObjectHasAttribute('headers', $modified);
$this->assertObjectHasAttribute('content', $modified);
@@ -135,6 +135,11 @@ class ResponseTest extends ResponseTestCase
$this->assertObjectHasAttribute('statusText', $modified);
$this->assertObjectHasAttribute('charset', $modified);
$this->assertEquals(304, $modified->getStatusCode());
ob_start();
$modified->sendContent();
$string = ob_get_clean();
$this->assertEmpty($string);
}
public function testIsSuccessful()
@@ -357,6 +362,11 @@ class ResponseTest extends ResponseTestCase
$response->headers->set('Expires', -1);
$response->expire();
$this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired');
$response = new Response();
$response->headers->set('Expires', date(DATE_RFC2822, time() + 600));
$response->expire();
$this->assertNull($response->headers->get('Expires'), '->expire() removes the Expires header when the response is fresh');
}
public function testGetTtl()
@@ -969,7 +979,7 @@ class ResponseTest extends ResponseTestCase
*/
public function ianaCodesReasonPhrasesProvider()
{
if (!in_array('https', stream_get_wrappers(), true)) {
if (!\in_array('https', stream_get_wrappers(), true)) {
$this->markTestSkipped('The "https" wrapper is not available');
}
@@ -997,7 +1007,7 @@ class ResponseTest extends ResponseTestCase
$value = $xpath->query('.//ns:value', $record)->item(0)->nodeValue;
$description = $xpath->query('.//ns:description', $record)->item(0)->nodeValue;
if (in_array($description, array('Unassigned', '(Unused)'), true)) {
if (\in_array($description, array('Unassigned', '(Unused)'), true)) {
continue;
}

View File

@@ -176,11 +176,11 @@ class AttributeBagTest extends TestCase
++$i;
}
$this->assertEquals(count($this->array), $i);
$this->assertEquals(\count($this->array), $i);
}
public function testCount()
{
$this->assertCount(count($this->array), $this->bag);
$this->assertCount(\count($this->array), $this->bag);
}
}

View File

@@ -82,6 +82,17 @@ class NamespacedAttributeBagTest extends TestCase
$this->assertEquals($exists, $this->bag->has($key));
}
/**
* @dataProvider attributesProvider
*/
public function testHasNoSideEffect($key, $value, $expected)
{
$expected = json_encode($this->bag->all());
$this->bag->has($key);
$this->assertEquals($expected, json_encode($this->bag->all()));
}
/**
* @dataProvider attributesProvider
*/
@@ -96,6 +107,17 @@ class NamespacedAttributeBagTest extends TestCase
$this->assertEquals('default', $this->bag->get('user2.login', 'default'));
}
/**
* @dataProvider attributesProvider
*/
public function testGetNoSideEffect($key, $value, $expected)
{
$expected = json_encode($this->bag->all());
$this->bag->get($key);
$this->assertEquals($expected, json_encode($this->bag->all()));
}
/**
* @dataProvider attributesProvider
*/

View File

@@ -74,6 +74,18 @@ class FlashBagTest extends TestCase
$this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
}
public function testAdd()
{
$tab = array('bar' => 'baz');
$this->bag->add('string_message', 'lorem');
$this->bag->add('object_message', new \stdClass());
$this->bag->add('array_message', $tab);
$this->assertEquals(array('lorem'), $this->bag->get('string_message'));
$this->assertEquals(array(new \stdClass()), $this->bag->get('object_message'));
$this->assertEquals(array($tab), $this->bag->get('array_message'));
}
public function testGet()
{
$this->assertEquals(array(), $this->bag->get('non_existing'));
@@ -112,6 +124,19 @@ class FlashBagTest extends TestCase
$this->assertEquals(array('notice'), $this->bag->keys());
}
public function testSetAll()
{
$this->bag->add('one_flash', 'Foo');
$this->bag->add('another_flash', 'Bar');
$this->assertTrue($this->bag->has('one_flash'));
$this->assertTrue($this->bag->has('another_flash'));
$this->bag->setAll(array('unique_flash' => 'FooBar'));
$this->assertFalse($this->bag->has('one_flash'));
$this->assertFalse($this->bag->has('another_flash'));
$this->assertSame(array('unique_flash' => 'FooBar'), $this->bag->all());
$this->assertSame(array(), $this->bag->all());
}
public function testPeekAll()
{
$this->bag->set('notice', 'Foo');

View File

@@ -12,9 +12,9 @@
namespace Symfony\Component\HttpFoundation\Tests\Session;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
/**
@@ -206,7 +206,7 @@ class SessionTest extends TestCase
++$i;
}
$this->assertEquals(count($attributes), $i);
$this->assertEquals(\count($attributes), $i);
}
public function testGetCount()

View File

@@ -32,11 +32,6 @@ abstract class AbstractRedisSessionHandlerTestCase extends TestCase
*/
protected $redisClient;
/**
* @var \Redis
*/
protected $validator;
/**
* @return \Redis|\RedisArray|\RedisCluster|\Predis\Client
*/
@@ -46,15 +41,12 @@ abstract class AbstractRedisSessionHandlerTestCase extends TestCase
{
parent::setUp();
if (!extension_loaded('redis')) {
if (!\extension_loaded('redis')) {
self::markTestSkipped('Extension redis required.');
}
$host = getenv('REDIS_HOST') ?: 'localhost';
$this->validator = new \Redis();
$this->validator->connect($host);
$this->redisClient = $this->createRedisClient($host);
$this->storage = new RedisSessionHandler(
$this->redisClient,
@@ -82,8 +74,8 @@ abstract class AbstractRedisSessionHandlerTestCase extends TestCase
public function testReadSession()
{
$this->setFixture(self::PREFIX.'id1', null);
$this->setFixture(self::PREFIX.'id2', 'abc123');
$this->redisClient->set(self::PREFIX.'id1', null);
$this->redisClient->set(self::PREFIX.'id2', 'abc123');
$this->assertEquals('', $this->storage->read('id1'));
$this->assertEquals('abc123', $this->storage->read('id2'));
@@ -93,14 +85,14 @@ abstract class AbstractRedisSessionHandlerTestCase extends TestCase
{
$this->assertTrue($this->storage->write('id', 'data'));
$this->assertTrue($this->hasFixture(self::PREFIX.'id'));
$this->assertEquals('data', $this->getFixture(self::PREFIX.'id'));
$this->assertTrue((bool) $this->redisClient->exists(self::PREFIX.'id'));
$this->assertEquals('data', $this->redisClient->get(self::PREFIX.'id'));
}
public function testUseSessionGcMaxLifetimeAsTimeToLive()
{
$this->storage->write('id', 'data');
$ttl = $this->fixtureTtl(self::PREFIX.'id');
$ttl = $this->redisClient->ttl(self::PREFIX.'id');
$this->assertLessThanOrEqual(ini_get('session.gc_maxlifetime'), $ttl);
$this->assertGreaterThanOrEqual(0, $ttl);
@@ -108,11 +100,11 @@ abstract class AbstractRedisSessionHandlerTestCase extends TestCase
public function testDestroySession()
{
$this->setFixture(self::PREFIX.'id', 'foo');
$this->redisClient->set(self::PREFIX.'id', 'foo');
$this->assertTrue($this->hasFixture(self::PREFIX.'id'));
$this->assertTrue((bool) $this->redisClient->exists(self::PREFIX.'id'));
$this->assertTrue($this->storage->destroy('id'));
$this->assertFalse($this->hasFixture(self::PREFIX.'id'));
$this->assertFalse((bool) $this->redisClient->exists(self::PREFIX.'id'));
}
public function testGcSession()
@@ -122,12 +114,12 @@ abstract class AbstractRedisSessionHandlerTestCase extends TestCase
public function testUpdateTimestamp()
{
$lowTTL = 10;
$lowTtl = 10;
$this->setFixture(self::PREFIX.'id', 'foo', $lowTTL);
$this->redisClient->setex(self::PREFIX.'id', $lowTtl, 'foo');
$this->storage->updateTimestamp('id', array());
$this->assertGreaterThan($lowTTL, $this->fixtureTtl(self::PREFIX.'id'));
$this->assertGreaterThan($lowTtl, $this->redisClient->ttl(self::PREFIX.'id'));
}
/**
@@ -150,28 +142,4 @@ abstract class AbstractRedisSessionHandlerTestCase extends TestCase
array(array('prefix' => 'sfs', 'foo' => 'bar'), false),
);
}
protected function setFixture($key, $value, $ttl = null)
{
if (null !== $ttl) {
$this->validator->setex($key, $ttl, $value);
} else {
$this->validator->set($key, $value);
}
}
protected function getFixture($key)
{
return $this->validator->get($key);
}
protected function hasFixture($key): bool
{
return $this->validator->exists($key);
}
protected function fixtureTtl($key): int
{
return $this->validator->ttl($key);
}
}

View File

@@ -12,9 +12,9 @@
namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Session;
/**
* Test class for NullSessionHandler.

View File

@@ -389,8 +389,8 @@ class MockPdo extends \PDO
public function prepare($statement, $driverOptions = array())
{
return is_callable($this->prepareResult)
? call_user_func($this->prepareResult, $statement, $driverOptions)
return \is_callable($this->prepareResult)
? \call_user_func($this->prepareResult, $statement, $driverOptions)
: $this->prepareResult;
}

View File

@@ -17,6 +17,6 @@ class PredisClusterSessionHandlerTest extends AbstractRedisSessionHandlerTestCas
{
protected function createRedisClient(string $host): Client
{
return new Client(array(array('host' => $host)));
return new Client(array(array('host' => $host)));
}
}

View File

@@ -12,9 +12,9 @@
namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
/**
* Test class for MockArraySessionStorage.

View File

@@ -12,9 +12,9 @@
namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
/**
* Test class for MockFileSessionStorage.

View File

@@ -184,7 +184,7 @@ class NativeSessionStorageTest extends TestCase
public function testSessionOptions()
{
if (defined('HHVM_VERSION')) {
if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('HHVM is not handled in this test case.');
}

View File

@@ -12,8 +12,8 @@
namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
/**
* Test class for PhpSessionStorage.

View File

@@ -121,4 +121,37 @@ class SessionHandlerProxyTest extends TestCase
$this->proxy->gc(86400);
}
/**
* @requires PHPUnit 5.1
*/
public function testValidateId()
{
$mock = $this->getMockBuilder(array('SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'))->getMock();
$mock->expects($this->once())
->method('validateId');
$proxy = new SessionHandlerProxy($mock);
$proxy->validateId('id');
$this->assertTrue($this->proxy->validateId('id'));
}
/**
* @requires PHPUnit 5.1
*/
public function testUpdateTimestamp()
{
$mock = $this->getMockBuilder(array('SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'))->getMock();
$mock->expects($this->once())
->method('updateTimestamp');
$proxy = new SessionHandlerProxy($mock);
$proxy->updateTimestamp('id', 'data');
$this->mock->expects($this->once())
->method('write');
$this->proxy->updateTimestamp('id', 'data');
}
}

View File

@@ -123,4 +123,22 @@ class StreamedResponseTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response->sendHeaders());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response->sendHeaders());
}
public function testSetNotModified()
{
$response = new StreamedResponse(function () { echo 'foo'; });
$modified = $response->setNotModified();
$this->assertObjectHasAttribute('headers', $modified);
$this->assertObjectHasAttribute('content', $modified);
$this->assertObjectHasAttribute('version', $modified);
$this->assertObjectHasAttribute('statusCode', $modified);
$this->assertObjectHasAttribute('statusText', $modified);
$this->assertObjectHasAttribute('charset', $modified);
$this->assertEquals(304, $modified->getStatusCode());
ob_start();
$modified->sendContent();
$string = ob_get_clean();
$this->assertEmpty($string);
}
}