From 3e350889e01242108c40ec54b978b0d4ca288aab Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 17 May 2017 18:21:40 +0200 Subject: [PATCH 001/225] updated version to 3.4 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index dfa25f79e..adf85e0fe 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "3.3-dev" + "dev-master": "3.4-dev" } } } From 5fb9abe5cd4a56dbdaf610ed1df77c1e8a8e00aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Thu, 18 May 2017 08:33:50 +0200 Subject: [PATCH 002/225] Allow individual bridges, bundles and components to be used with 4.0 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index adf85e0fe..7e0994993 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,7 @@ "symfony/polyfill-mbstring": "~1.1" }, "require-dev": { - "symfony/expression-language": "~2.8|~3.0" + "symfony/expression-language": "~2.8|~3.0|~4.0.0" }, "autoload": { "psr-4": { "Symfony\\Component\\HttpFoundation\\": "" }, From 4b277cbc3e305e87325da7b38f650511101c8b51 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 24 May 2017 11:02:43 +0200 Subject: [PATCH 003/225] [3.4] Allow 4.* deps --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 7e0994993..44192dfe1 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,7 @@ "symfony/polyfill-mbstring": "~1.1" }, "require-dev": { - "symfony/expression-language": "~2.8|~3.0|~4.0.0" + "symfony/expression-language": "~2.8|~3.0|~4.0" }, "autoload": { "psr-4": { "Symfony\\Component\\HttpFoundation\\": "" }, From 28209d9e670787ad473ef424ae00ffab442bd51d Mon Sep 17 00:00:00 2001 From: Matthias Pigulla Date: Thu, 23 Mar 2017 10:24:24 +0100 Subject: [PATCH 004/225] Shift responsibility for keeping Date header to ResponseHeaderBag --- Response.php | 19 ------- ResponseHeaderBag.php | 20 ++++++++ Tests/ResponseHeaderBagTest.php | 91 +++++++++++++++++++-------------- 3 files changed, 72 insertions(+), 58 deletions(-) diff --git a/Response.php b/Response.php index 4af1e0bae..3ea4cb617 100644 --- a/Response.php +++ b/Response.php @@ -201,11 +201,6 @@ public function __construct($content = '', $status = 200, $headers = array()) $this->setContent($content); $this->setStatusCode($status); $this->setProtocolVersion('1.0'); - - /* RFC2616 - 14.18 says all Responses need to have a Date */ - if (!$this->headers->has('Date')) { - $this->setDate(\DateTime::createFromFormat('U', time())); - } } /** @@ -334,11 +329,6 @@ public function sendHeaders() return $this; } - /* RFC2616 - 14.18 says all Responses need to have a Date */ - if (!$this->headers->has('Date')) { - $this->setDate(\DateTime::createFromFormat('U', time())); - } - // headers foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) { foreach ($values as $value) { @@ -648,15 +638,6 @@ public function mustRevalidate() */ public function getDate() { - /* - RFC2616 - 14.18 says all Responses need to have a Date. - Make sure we provide one even if it the header - has been removed in the meantime. - */ - if (!$this->headers->has('Date')) { - $this->setDate(\DateTime::createFromFormat('U', time())); - } - return $this->headers->getDate('Date'); } diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index df2931be0..236528de2 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -51,6 +51,11 @@ public function __construct(array $headers = array()) if (!isset($this->headers['cache-control'])) { $this->set('Cache-Control', ''); } + + /* RFC2616 - 14.18 says all Responses need to have a Date */ + if (!isset($this->headers['date'])) { + $this->initDate(); + } } /** @@ -90,6 +95,10 @@ public function replace(array $headers = array()) if (!isset($this->headers['cache-control'])) { $this->set('Cache-Control', ''); } + + if (!isset($this->headers['date'])) { + $this->initDate(); + } } /** @@ -156,6 +165,10 @@ public function remove($key) if ('cache-control' === $uniqueKey) { $this->computedCacheControl = array(); } + + if ('date' === $uniqueKey) { + $this->initDate(); + } } /** @@ -338,4 +351,11 @@ protected function computeCacheControlValue() return $header; } + + private function initDate() + { + $now = \DateTime::createFromFormat('U', time()); + $now->setTimezone(new \DateTimeZone('UTC')); + $this->set('Date', $now->format('D, d M Y H:i:s').' GMT'); + } } diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index 724328ae8..1d7341f33 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -20,48 +20,24 @@ */ class ResponseHeaderBagTest extends TestCase { - /** - * @dataProvider provideAllPreserveCase - */ - public function testAllPreserveCase($headers, $expected) + public function testAllPreserveCase() { + $headers = array( + 'fOo' => 'BAR', + 'ETag' => 'xyzzy', + 'Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ==', + 'P3P' => 'CP="CAO PSA OUR"', + 'WWW-Authenticate' => 'Basic realm="WallyWorld"', + 'X-UA-Compatible' => 'IE=edge,chrome=1', + 'X-XSS-Protection' => '1; mode=block', + ); + $bag = new ResponseHeaderBag($headers); + $allPreservedCase = $bag->allPreserveCase(); - $this->assertEquals($expected, $bag->allPreserveCase(), '->allPreserveCase() gets all input keys in original case'); - } - - public function provideAllPreserveCase() - { - return array( - array( - array('fOo' => 'BAR'), - array('fOo' => array('BAR'), 'Cache-Control' => array('no-cache, private')), - ), - array( - array('ETag' => 'xyzzy'), - array('ETag' => array('xyzzy'), 'Cache-Control' => array('private, must-revalidate')), - ), - array( - array('Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ=='), - array('Content-MD5' => array('Q2hlY2sgSW50ZWdyaXR5IQ=='), 'Cache-Control' => array('no-cache, private')), - ), - array( - array('P3P' => 'CP="CAO PSA OUR"'), - array('P3P' => array('CP="CAO PSA OUR"'), 'Cache-Control' => array('no-cache, private')), - ), - array( - array('WWW-Authenticate' => 'Basic realm="WallyWorld"'), - array('WWW-Authenticate' => array('Basic realm="WallyWorld"'), 'Cache-Control' => array('no-cache, private')), - ), - array( - array('X-UA-Compatible' => 'IE=edge,chrome=1'), - array('X-UA-Compatible' => array('IE=edge,chrome=1'), 'Cache-Control' => array('no-cache, private')), - ), - array( - array('X-XSS-Protection' => '1; mode=block'), - array('X-XSS-Protection' => array('1; mode=block'), 'Cache-Control' => array('no-cache, private')), - ), - ); + foreach (array_keys($headers) as $headerName) { + $this->assertArrayHasKey($headerName, $allPreservedCase, '->allPreserveCase() gets all input keys in original case'); + } } public function testCacheControlHeader() @@ -332,6 +308,43 @@ public function provideMakeDispositionFail() ); } + public function testDateHeaderAddedOnCreation() + { + $now = time(); + + $bag = new ResponseHeaderBag(); + $this->assertTrue($bag->has('Date')); + + $this->assertEquals($now, $bag->getDate('Date')->getTimestamp()); + } + + public function testDateHeaderCanBeSetOnCreation() + { + $someDate = 'Thu, 23 Mar 2017 09:15:12 GMT'; + $bag = new ResponseHeaderBag(array('Date' => $someDate)); + + $this->assertEquals($someDate, $bag->get('Date')); + } + + public function testDateHeaderWillBeRecreatedWhenRemoved() + { + $someDate = 'Thu, 23 Mar 2017 09:15:12 GMT'; + $bag = new ResponseHeaderBag(array('Date' => $someDate)); + $bag->remove('Date'); + + // a (new) Date header is still present + $this->assertTrue($bag->has('Date')); + $this->assertNotEquals($someDate, $bag->get('Date')); + } + + public function testDateHeaderWillBeRecreatedWhenHeadersAreReplaced() + { + $bag = new ResponseHeaderBag(); + $bag->replace(array()); + + $this->assertTrue($bag->has('Date')); + } + private function assertSetCookieHeader($expected, ResponseHeaderBag $actual) { $this->assertRegExp('#^Set-Cookie:\s+'.preg_quote($expected, '#').'$#m', str_replace("\r\n", "\n", (string) $actual)); From 46552dee236cf4c8de2864e6736503b4320b8e30 Mon Sep 17 00:00:00 2001 From: Jaroslav Kuba Date: Sun, 28 May 2017 21:03:49 +0200 Subject: [PATCH 005/225] Added support for the immutable directive in the cache-control header --- Response.php | 34 +++++++++++++++++++++++++++++++++- Tests/ResponseTest.php | 22 ++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/Response.php b/Response.php index 3ea4cb617..8b237d758 100644 --- a/Response.php +++ b/Response.php @@ -610,6 +610,34 @@ public function setPublic() return $this; } + /** + * Marks the response as "immutable". + * + * @param bool $immutable Enables or disables the immutable directive. + * + * @return $this + */ + public function setImmutable($immutable = true) + { + if ($immutable) { + $this->headers->addCacheControlDirective('immutable'); + } else { + $this->headers->removeCacheControlDirective('immutable'); + } + + return $this; + } + + /** + * Returns true if the response is marked as "immutable". + * + * @return bool Returns true if the response is marked as "immutable"; otherwise false. + */ + public function isImmutable() + { + return $this->headers->hasCacheControlDirective('immutable'); + } + /** * Returns true if the response must be revalidated by caches. * @@ -937,7 +965,7 @@ public function setEtag($etag = null, $weak = false) */ public function setCache(array $options) { - if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public'))) { + if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'))) { throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff)))); } @@ -973,6 +1001,10 @@ public function setCache(array $options) } } + if (isset($options['immutable'])) { + $this->setImmutable((bool) $options['immutable']); + } + return $this; } diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 62b8c6525..9c5b34feb 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -610,6 +610,12 @@ public function testSetCache() $response->setCache(array('private' => false)); $this->assertTrue($response->headers->hasCacheControlDirective('public')); $this->assertFalse($response->headers->hasCacheControlDirective('private')); + + $response->setCache(array('immutable' => true)); + $this->assertTrue($response->headers->hasCacheControlDirective('immutable')); + + $response->setCache(array('immutable' => false)); + $this->assertFalse($response->headers->hasCacheControlDirective('immutable')); } public function testSendContent() @@ -631,6 +637,22 @@ public function testSetPublic() $this->assertFalse($response->headers->hasCacheControlDirective('private')); } + public function testSetImmutable() + { + $response = new Response(); + $response->setImmutable(); + + $this->assertTrue($response->headers->hasCacheControlDirective('immutable')); + } + + public function testIsImmutable() + { + $response = new Response(); + $response->setImmutable(); + + $this->assertTrue($response->isImmutable()); + } + public function testSetExpires() { $response = new Response(); From 7880f0918ef41c7a697c9b55f6fbd3007b66d5f5 Mon Sep 17 00:00:00 2001 From: Chris Wilkinson Date: Tue, 31 Jan 2017 08:56:27 +0000 Subject: [PATCH 006/225] [HttpFoundation] Find the original request protocol version --- Request.php | 24 ++++++++++++++++++++++++ Tests/RequestTest.php | 30 ++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/Request.php b/Request.php index 6fd0707b0..6cfee8f4a 100644 --- a/Request.php +++ b/Request.php @@ -1581,6 +1581,30 @@ public function isMethodCacheable() return in_array($this->getMethod(), array('GET', 'HEAD')); } + /** + * Returns the protocol version. + * + * If the application is behind a proxy, the protocol version used in the + * requests between the client and the proxy and between the proxy and the + * server might be different. This returns the former (from the "Via" header) + * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns + * the latter (from the "SERVER_PROTOCOL" server parameter). + * + * @return string + */ + public function getProtocolVersion() + { + if ($this->isFromTrustedProxy()) { + preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via'), $matches); + + if ($matches) { + return 'HTTP/'.$matches[2]; + } + } + + return $this->server->get('SERVER_PROTOCOL'); + } + /** * Returns the request body content. * diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index b36fbb7e9..54c95c431 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -2188,6 +2188,36 @@ public function testGetTrustedHeaderName() Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_FORWARDED_PORT'); Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_FORWARDED_PROTO'); } + + /** + * @dataProvider protocolVersionProvider + */ + public function testProtocolVersion($serverProtocol, $trustedProxy, $via, $expected) + { + if ($trustedProxy) { + Request::setTrustedProxies(array('1.1.1.1')); + } + + $request = new Request(); + $request->server->set('SERVER_PROTOCOL', $serverProtocol); + $request->server->set('REMOTE_ADDR', '1.1.1.1'); + $request->headers->set('Via', $via); + + $this->assertSame($expected, $request->getProtocolVersion()); + } + + public function protocolVersionProvider() + { + return array( + 'untrusted without via' => array('HTTP/2.0', false, '', 'HTTP/2.0'), + 'untrusted with via' => array('HTTP/2.0', false, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/2.0'), + 'trusted without via' => array('HTTP/2.0', true, '', 'HTTP/2.0'), + 'trusted with via' => array('HTTP/2.0', true, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'), + 'trusted with via and protocol name' => array('HTTP/2.0', true, 'HTTP/1.0 fred, HTTP/1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'), + 'trusted with broken via' => array('HTTP/2.0', true, 'HTTP/1^0 foo', 'HTTP/2.0'), + 'trusted with partially-broken via' => array('HTTP/2.0', true, '1.0 fred, foo', 'HTTP/1.0'), + ); + } } class RequestContentProxy extends Request From 220f0bf5b1c48cc99e025c24a1412704443c993c Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 6 Jul 2017 12:58:45 +0300 Subject: [PATCH 007/225] fixed tests --- Tests/RequestTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 54c95c431..47459c79a 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -2195,7 +2195,7 @@ public function testGetTrustedHeaderName() public function testProtocolVersion($serverProtocol, $trustedProxy, $via, $expected) { if ($trustedProxy) { - Request::setTrustedProxies(array('1.1.1.1')); + Request::setTrustedProxies(array('1.1.1.1'), -1); } $request = new Request(); From c00cdd8eb799c02741c0354f5a3cf9f6f633e193 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 2 Aug 2017 14:30:55 +0200 Subject: [PATCH 008/225] Consistently use 7 chars of sha256 for hash-based id generation --- BinaryFileResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 5f18aa930..a950e0cb7 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -141,7 +141,7 @@ public function setAutoLastModified() */ public function setAutoEtag() { - $this->setEtag(sha1_file($this->file->getPathname())); + $this->setEtag(substr(base64_encode(hash_file('sha256', $this->file->getPathname(), true)), 0, 32)); return $this; } From b34cf2f966520a7ee47c092208c3055288ffb882 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 9 Aug 2017 07:21:07 +0200 Subject: [PATCH 009/225] [HttpFoundation] Remove length limit on ETag --- BinaryFileResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 7ffa98401..3c32871c4 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -141,7 +141,7 @@ public function setAutoLastModified() */ public function setAutoEtag() { - $this->setEtag(substr(base64_encode(hash_file('sha256', $this->file->getPathname(), true)), 0, 32)); + $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true))); return $this; } From 9cc8019b5d013f3b0dda7f1ba5596677229562b9 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 20 Aug 2017 09:36:00 +0200 Subject: [PATCH 010/225] removed sf2 references --- Session/Flash/AutoExpireFlashBag.php | 2 +- Session/Flash/FlashBag.php | 2 +- Tests/Session/Flash/AutoExpireFlashBagTest.php | 2 +- Tests/Session/Flash/FlashBagTest.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Session/Flash/AutoExpireFlashBag.php b/Session/Flash/AutoExpireFlashBag.php index ddd603fdd..138565aa3 100644 --- a/Session/Flash/AutoExpireFlashBag.php +++ b/Session/Flash/AutoExpireFlashBag.php @@ -39,7 +39,7 @@ class AutoExpireFlashBag implements FlashBagInterface * * @param string $storageKey The key used to store flashes in the session */ - public function __construct($storageKey = '_sf2_flashes') + public function __construct($storageKey = '_symfony_flashes') { $this->storageKey = $storageKey; } diff --git a/Session/Flash/FlashBag.php b/Session/Flash/FlashBag.php index 85b4f00b0..ee6be434c 100644 --- a/Session/Flash/FlashBag.php +++ b/Session/Flash/FlashBag.php @@ -39,7 +39,7 @@ class FlashBag implements FlashBagInterface * * @param string $storageKey The key used to store flashes in the session */ - public function __construct($storageKey = '_sf2_flashes') + public function __construct($storageKey = '_symfony_flashes') { $this->storageKey = $storageKey; } diff --git a/Tests/Session/Flash/AutoExpireFlashBagTest.php b/Tests/Session/Flash/AutoExpireFlashBagTest.php index 4eb200afa..c25befc4c 100644 --- a/Tests/Session/Flash/AutoExpireFlashBagTest.php +++ b/Tests/Session/Flash/AutoExpireFlashBagTest.php @@ -62,7 +62,7 @@ public function testInitialize() public function testGetStorageKey() { - $this->assertEquals('_sf2_flashes', $this->bag->getStorageKey()); + $this->assertEquals('_symfony_flashes', $this->bag->getStorageKey()); $attributeBag = new FlashBag('test'); $this->assertEquals('test', $attributeBag->getStorageKey()); } diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index f0aa6a615..07d178880 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -57,7 +57,7 @@ public function testInitialize() public function testGetStorageKey() { - $this->assertEquals('_sf2_flashes', $this->bag->getStorageKey()); + $this->assertEquals('_symfony_flashes', $this->bag->getStorageKey()); $attributeBag = new FlashBag('test'); $this->assertEquals('test', $attributeBag->getStorageKey()); } From 654818ba3caa806604e13e9f1e52bbafa0c2ebf1 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 6 Sep 2017 10:30:21 +0200 Subject: [PATCH 011/225] [travis] update to trusty --- JsonResponse.php | 4 ++-- Tests/JsonResponseTest.php | 7 +++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/JsonResponse.php b/JsonResponse.php index c6e0ba654..621c8410c 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -121,7 +121,7 @@ public function setData($data = array()) $data = json_encode($data, $this->encodingOptions); } else { try { - if (\PHP_VERSION_ID < 50400) { + if (!interface_exists('JsonSerializable', false)) { // PHP 5.3 triggers annoying warnings for some // types that can't be serialized as JSON (INF, resources, etc.) // but doesn't provide the JsonSerializable interface. @@ -153,7 +153,7 @@ public function setData($data = array()) if (\PHP_VERSION_ID < 50500) { restore_error_handler(); } - if (\PHP_VERSION_ID >= 50400 && 'Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) { + if (interface_exists('JsonSerializable', false) && 'Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) { throw $e->getPrevious() ?: $e; } throw $e; diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index 8156da069..e15505cc6 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -206,10 +206,13 @@ public function testSetContent() /** * @expectedException \Exception * @expectedExceptionMessage This error is expected - * @requires PHP 5.4 */ public function testSetContentJsonSerializeError() { + if (!interface_exists('JsonSerializable', false)) { + $this->markTestSkipped('JsonSerializable is required.'); + } + $serializable = new JsonSerializableObject(); JsonResponse::create($serializable); @@ -224,7 +227,7 @@ public function testSetComplexCallback() } } -if (interface_exists('JsonSerializable')) { +if (interface_exists('JsonSerializable', false)) { class JsonSerializableObject implements \JsonSerializable { public function jsonSerialize() From 8fa5a600ba74b322408891093fe8981ec38e9545 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 6 Sep 2017 18:53:48 +0200 Subject: [PATCH 012/225] [HttpFoundation] Fix logic when JsonSerializable is missing --- JsonResponse.php | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/JsonResponse.php b/JsonResponse.php index 621c8410c..8837175df 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -127,30 +127,31 @@ public function setData($data = array()) // but doesn't provide the JsonSerializable interface. set_error_handler(function () { return false; }); $data = @json_encode($data, $this->encodingOptions); - } else { + restore_error_handler(); + } elseif (\PHP_VERSION_ID < 50500) { // PHP 5.4 and up wrap exceptions thrown by JsonSerializable // objects in a new exception that needs to be removed. // Fortunately, PHP 5.5 and up do not trigger any warning anymore. - if (\PHP_VERSION_ID < 50500) { - // Clear json_last_error() - json_encode(null); - $errorHandler = set_error_handler('var_dump'); - restore_error_handler(); - set_error_handler(function () use ($errorHandler) { - if (JSON_ERROR_NONE === json_last_error()) { - return $errorHandler && false !== call_user_func_array($errorHandler, func_get_args()); - } - }); - } - + // Clear json_last_error() + json_encode(null); + $errorHandler = set_error_handler('var_dump'); + restore_error_handler(); + set_error_handler(function () use ($errorHandler) { + if (JSON_ERROR_NONE === json_last_error()) { + return $errorHandler && false !== call_user_func_array($errorHandler, func_get_args()); + } + }); + $data = json_encode($data, $this->encodingOptions); + restore_error_handler(); + } else { $data = json_encode($data, $this->encodingOptions); } - - if (\PHP_VERSION_ID < 50500) { + } catch (\Error $e) { + if (\PHP_VERSION_ID < 50500 || !interface_exists('JsonSerializable', false)) { restore_error_handler(); } } catch (\Exception $e) { - if (\PHP_VERSION_ID < 50500) { + if (\PHP_VERSION_ID < 50500 || !interface_exists('JsonSerializable', false)) { restore_error_handler(); } if (interface_exists('JsonSerializable', false) && 'Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) { From fca9d49176558ee1a79f58b89ef7c07c56df1d4c Mon Sep 17 00:00:00 2001 From: Dariusz Date: Mon, 11 Sep 2017 11:28:55 +0200 Subject: [PATCH 013/225] [CS] Apply phpdoc_annotation_without_dot --- Response.php | 6 +++--- Session/SessionInterface.php | 2 +- Session/Storage/SessionStorageInterface.php | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Response.php b/Response.php index f9512d670..074c896ff 100644 --- a/Response.php +++ b/Response.php @@ -441,12 +441,12 @@ public function getProtocolVersion() /** * Sets the response status code. * - * @param int $code HTTP status code - * @param mixed $text HTTP status text - * * If the status text is null it will be automatically populated for the known * status codes and left empty otherwise. * + * @param int $code HTTP status code + * @param mixed $text HTTP status text + * * @return $this * * @throws \InvalidArgumentException When the HTTP status code is not valid diff --git a/Session/SessionInterface.php b/Session/SessionInterface.php index d3fcd2eec..172c9b457 100644 --- a/Session/SessionInterface.php +++ b/Session/SessionInterface.php @@ -25,7 +25,7 @@ interface SessionInterface * * @return bool True if session started * - * @throws \RuntimeException If session fails to start. + * @throws \RuntimeException if session fails to start */ public function start(); diff --git a/Session/Storage/SessionStorageInterface.php b/Session/Storage/SessionStorageInterface.php index 34f6c4633..097583d5a 100644 --- a/Session/Storage/SessionStorageInterface.php +++ b/Session/Storage/SessionStorageInterface.php @@ -26,7 +26,7 @@ interface SessionStorageInterface * * @return bool True if started * - * @throws \RuntimeException If something goes wrong starting the session. + * @throws \RuntimeException if something goes wrong starting the session */ public function start(); @@ -104,8 +104,8 @@ public function regenerate($destroy = false, $lifetime = null); * a real PHP session would interfere with testing, in which case * it should actually persist the session data if required. * - * @throws \RuntimeException If the session is saved without being started, or if the session - * is already closed. + * @throws \RuntimeException if the session is saved without being started, or if the session + * is already closed */ public function save(); From f252f37798654691780c523dd88828eb8a2b7622 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Mon, 11 Sep 2017 14:23:01 -0700 Subject: [PATCH 014/225] fixed CS --- JsonResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JsonResponse.php b/JsonResponse.php index 547a8e487..137ac33c4 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -150,7 +150,7 @@ public function setData($data = array()) try { $data = @json_encode($data, $this->encodingOptions); } finally { - restore_error_handler(); + restore_error_handler(); } } else { try { From eb635edacc95e9be0eaed39d65f7e320efb6f70c Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Mon, 11 Sep 2017 14:34:45 -0700 Subject: [PATCH 015/225] fixed CS --- Response.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Response.php b/Response.php index 15fa56a6b..359143f33 100644 --- a/Response.php +++ b/Response.php @@ -613,7 +613,7 @@ public function setPublic() /** * Marks the response as "immutable". * - * @param bool $immutable Enables or disables the immutable directive. + * @param bool $immutable enables or disables the immutable directive * * @return $this */ @@ -631,7 +631,7 @@ public function setImmutable($immutable = true) /** * Returns true if the response is marked as "immutable". * - * @return bool Returns true if the response is marked as "immutable"; otherwise false. + * @return bool returns true if the response is marked as "immutable"; otherwise false */ public function isImmutable() { From a44813fb7b9f4f5601bdefdf71d302d95d522c6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1chym=20Tou=C5=A1ek?= Date: Thu, 14 Sep 2017 10:24:46 +0200 Subject: [PATCH 016/225] [HttpFoundation] Fix file upload multiple with no files --- FileBag.php | 4 ++-- Tests/FileBagTest.php | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/FileBag.php b/FileBag.php index e17a9057b..1f3a502fb 100644 --- a/FileBag.php +++ b/FileBag.php @@ -69,7 +69,7 @@ public function add(array $files = array()) * * @param array|UploadedFile $file A (multi-dimensional) array of uploaded file information * - * @return UploadedFile|UploadedFile[] A (multi-dimensional) array of UploadedFile instances + * @return UploadedFile[]|UploadedFile|null A (multi-dimensional) array of UploadedFile instances */ protected function convertFileInformation($file) { @@ -89,7 +89,7 @@ protected function convertFileInformation($file) $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']); } } else { - $file = array_map(array($this, 'convertFileInformation'), $file); + $file = array_filter(array_map(array($this, 'convertFileInformation'), $file)); } } diff --git a/Tests/FileBagTest.php b/Tests/FileBagTest.php index e7defa677..7d2902d32 100644 --- a/Tests/FileBagTest.php +++ b/Tests/FileBagTest.php @@ -60,6 +60,19 @@ public function testShouldSetEmptyUploadedFilesToNull() $this->assertNull($bag->get('file')); } + public function testShouldRemoveEmptyUploadedFilesForMultiUpload() + { + $bag = new FileBag(array('file' => array( + 'name' => array(''), + 'type' => array(''), + 'tmp_name' => array(''), + 'error' => array(UPLOAD_ERR_NO_FILE), + 'size' => array(0), + ))); + + $this->assertSame(array(), $bag->get('file')); + } + public function testShouldConvertUploadedFilesWithPhpBug() { $tmpFile = $this->createTempFile(); From 3511cc10e0846c0371afe971f489c52f0b79c6b7 Mon Sep 17 00:00:00 2001 From: SpacePossum Date: Thu, 7 Sep 2017 11:04:22 +0200 Subject: [PATCH 017/225] [CS][2.7] yoda_style, no_unneeded_curly_braces, no_unneeded_final_method, semicolon_after_instruction --- AcceptHeaderItem.php | 4 +-- BinaryFileResponse.php | 6 ++-- File/UploadedFile.php | 4 +-- IpUtils.php | 2 +- Request.php | 28 +++++++++---------- RequestMatcher.php | 2 +- Response.php | 4 +-- ServerBag.php | 2 +- Session/Attribute/NamespacedAttributeBag.php | 2 +- .../Handler/MemcachedSessionHandler.php | 2 +- Tests/File/MimeType/MimeTypeTest.php | 2 +- Tests/RequestTest.php | 2 +- 12 files changed, 30 insertions(+), 30 deletions(-) diff --git a/AcceptHeaderItem.php b/AcceptHeaderItem.php index fb54b4935..06582b677 100644 --- a/AcceptHeaderItem.php +++ b/AcceptHeaderItem.php @@ -67,7 +67,7 @@ public static function fromString($itemValue) $lastNullAttribute = null; foreach ($bits as $bit) { - if (($start = substr($bit, 0, 1)) === ($end = substr($bit, -1)) && ($start === '"' || $start === '\'')) { + 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); @@ -78,7 +78,7 @@ public static function fromString($itemValue) } } - return new self(($start = substr($value, 0, 1)) === ($end = substr($value, -1)) && ($start === '"' || $start === '\'') ? substr($value, 1, -1) : $value, $attributes); + return new self(($start = substr($value, 0, 1)) === ($end = substr($value, -1)) && ('"' === $start || '\'' === $start) ? substr($value, 1, -1) : $value, $attributes); } /** diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 177b708e8..0cac313dd 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -157,7 +157,7 @@ public function setAutoEtag() */ public function setContentDisposition($disposition, $filename = '', $filenameFallback = '') { - if ($filename === '') { + if ('' === $filename) { $filename = $this->file->getFilename(); } @@ -214,7 +214,7 @@ public function prepare(Request $request) if (false === $path) { $path = $this->file->getPathname(); } - if (strtolower($type) === 'x-accel-redirect') { + 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) { @@ -254,7 +254,7 @@ public function prepare(Request $request) if ($start < 0 || $end > $fileSize - 1) { $this->setStatusCode(416); $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize)); - } elseif ($start !== 0 || $end !== $fileSize - 1) { + } elseif (0 !== $start || $end !== $fileSize - 1) { $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1; $this->offset = $start; diff --git a/File/UploadedFile.php b/File/UploadedFile.php index 10837726c..d32ec176c 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -198,7 +198,7 @@ public function getError() */ public function isValid() { - $isOk = $this->error === UPLOAD_ERR_OK; + $isOk = UPLOAD_ERR_OK === $this->error; return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname()); } @@ -285,7 +285,7 @@ public function getErrorMessage() ); $errorCode = $this->error; - $maxFilesize = $errorCode === UPLOAD_ERR_INI_SIZE ? self::getMaxFilesize() / 1024 : 0; + $maxFilesize = UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0; $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.'; return sprintf($message, $this->getClientOriginalName(), $maxFilesize); diff --git a/IpUtils.php b/IpUtils.php index eba603b15..dc6d3ec81 100644 --- a/IpUtils.php +++ b/IpUtils.php @@ -75,7 +75,7 @@ public static function checkIp4($requestIp, $ip) if (false !== strpos($ip, '/')) { list($address, $netmask) = explode('/', $ip, 2); - if ($netmask === '0') { + if ('0' === $netmask) { return self::$checkedIps[$cacheKey] = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); } diff --git a/Request.php b/Request.php index 0c11adab6..f1aff0f87 100644 --- a/Request.php +++ b/Request.php @@ -427,22 +427,22 @@ public static function setFactory($callable) public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null) { $dup = clone $this; - if ($query !== null) { + if (null !== $query) { $dup->query = new ParameterBag($query); } - if ($request !== null) { + if (null !== $request) { $dup->request = new ParameterBag($request); } - if ($attributes !== null) { + if (null !== $attributes) { $dup->attributes = new ParameterBag($attributes); } - if ($cookies !== null) { + if (null !== $cookies) { $dup->cookies = new ParameterBag($cookies); } - if ($files !== null) { + if (null !== $files) { $dup->files = new FileBag($files); } - if ($server !== null) { + if (null !== $server) { $dup->server = new ServerBag($server); $dup->headers = new HeaderBag($dup->server->getHeaders()); } @@ -971,7 +971,7 @@ public function getPort() } if ($host = $this->headers->get('HOST')) { - if ($host[0] === '[') { + if ('[' === $host[0]) { $pos = strpos($host, ':', strrpos($host, ']')); } else { $pos = strrpos($host, ':'); @@ -1036,7 +1036,7 @@ public function getHttpHost() $scheme = $this->getScheme(); $port = $this->getPort(); - if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) { + if (('http' == $scheme && 80 == $port) || ('https' == $scheme && 443 == $port)) { return $this->getHost(); } @@ -1618,7 +1618,7 @@ public function getLanguages() } } else { for ($i = 0, $max = count($codes); $i < $max; ++$i) { - if ($i === 0) { + if (0 === $i) { $lang = strtolower($codes[0]); } else { $lang .= '_'.strtoupper($codes[$i]); @@ -1713,7 +1713,7 @@ protected function prepareRequestUri() // IIS with ISAPI_Rewrite $requestUri = $this->headers->get('X_REWRITE_URL'); $this->headers->remove('X_REWRITE_URL'); - } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') { + } elseif ('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'); @@ -1722,7 +1722,7 @@ protected function prepareRequestUri() $requestUri = $this->server->get('REQUEST_URI'); // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path $schemeAndHttpHost = $this->getSchemeAndHttpHost(); - if (strpos($requestUri, $schemeAndHttpHost) === 0) { + if (0 === strpos($requestUri, $schemeAndHttpHost)) { $requestUri = substr($requestUri, strlen($schemeAndHttpHost)); } } elseif ($this->server->has('ORIG_PATH_INFO')) { @@ -1774,7 +1774,7 @@ protected function prepareBaseUrl() // Does the baseUrl have anything in common with the request_uri? $requestUri = $this->getRequestUri(); - if ($requestUri !== '' && $requestUri[0] !== '/') { + if ('' !== $requestUri && '/' !== $requestUri[0]) { $requestUri = '/'.$requestUri; } @@ -1802,7 +1802,7 @@ protected function prepareBaseUrl() // 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)) && $pos !== 0) { + if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) { $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl)); } @@ -1852,7 +1852,7 @@ protected function preparePathInfo() if (false !== $pos = strpos($requestUri, '?')) { $requestUri = substr($requestUri, 0, $pos); } - if ($requestUri !== '' && $requestUri[0] !== '/') { + if ('' !== $requestUri && '/' !== $requestUri[0]) { $requestUri = '/'.$requestUri; } diff --git a/RequestMatcher.php b/RequestMatcher.php index aa4f67b58..076d077c7 100644 --- a/RequestMatcher.php +++ b/RequestMatcher.php @@ -173,6 +173,6 @@ public function matches(Request $request) // Note to future implementors: add additional checks above the // foreach above or else your check might not be run! - return count($this->ips) === 0; + return 0 === count($this->ips); } } diff --git a/Response.php b/Response.php index 074c896ff..860906c3d 100644 --- a/Response.php +++ b/Response.php @@ -1151,7 +1151,7 @@ public static function closeOutputBuffers($targetLevel, $flush) $level = count($status); $flags = defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1; - while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || $flags === ($s['flags'] & $flags) : $s['del'])) { + while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) { if ($flush) { ob_end_flush(); } else { @@ -1167,7 +1167,7 @@ public static function closeOutputBuffers($targetLevel, $flush) */ protected function ensureIEOverSSLCompatibility(Request $request) { - if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) == 1 && true === $request->isSecure()) { + if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) { if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) { $this->headers->remove('Cache-Control'); } diff --git a/ServerBag.php b/ServerBag.php index 0d38c08ac..19d2022ef 100644 --- a/ServerBag.php +++ b/ServerBag.php @@ -68,7 +68,7 @@ public function getHeaders() 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 (count($exploded) == 2) { + 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 '))) { diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index d797a6f23..7301f9528 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -109,7 +109,7 @@ public function remove($name) protected function &resolveAttributePath($name, $writeContext = false) { $array = &$this->attributes; - $name = (strpos($name, $this->namespaceCharacter) === 0) ? substr($name, 1) : $name; + $name = (0 === strpos($name, $this->namespaceCharacter)) ? substr($name, 1) : $name; // Check if there is anything to do, else return if (!$name) { diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 67a49ad6f..dfe2fee0d 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -103,7 +103,7 @@ public function destroy($sessionId) { $result = $this->memcached->delete($this->prefix.$sessionId); - return $result || $this->memcached->getResultCode() == \Memcached::RES_NOTFOUND; + return $result || \Memcached::RES_NOTFOUND == $this->memcached->getResultCode(); } /** diff --git a/Tests/File/MimeType/MimeTypeTest.php b/Tests/File/MimeType/MimeTypeTest.php index 5a2b7a21c..b3f1f026a 100644 --- a/Tests/File/MimeType/MimeTypeTest.php +++ b/Tests/File/MimeType/MimeTypeTest.php @@ -71,7 +71,7 @@ public function testGuessWithNonReadablePath() touch($path); @chmod($path, 0333); - if (substr(sprintf('%o', fileperms($path)), -4) == '0333') { + if ('0333' == substr(sprintf('%o', fileperms($path)), -4)) { $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException'); MimeTypeGuesser::getInstance()->guess($path); } else { diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index bb7a3f480..ed4224c4f 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1008,7 +1008,7 @@ public function testGetContentReturnsResourceWhenContentSetInConstructor() $req = new Request(array(), array(), array(), array(), array(), array(), 'MyContent'); $resource = $req->getContent(true); - $this->assertTrue(is_resource($resource)); + $this->assertInternalType('resource', $resource); $this->assertEquals('MyContent', stream_get_contents($resource)); } From c339c52246290032ba86806b69cda6f16934f560 Mon Sep 17 00:00:00 2001 From: Dariusz Date: Fri, 15 Sep 2017 12:36:22 +0200 Subject: [PATCH 018/225] CS: recover no_break_comment --- File/UploadedFile.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/File/UploadedFile.php b/File/UploadedFile.php index d32ec176c..9a2d28491 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -259,8 +259,11 @@ public static function getMaxFilesize() switch (substr($iniMax, -1)) { case 't': $max *= 1024; + // no break case 'g': $max *= 1024; + // no break case 'm': $max *= 1024; + // no break case 'k': $max *= 1024; } From 0e3c3100ba98abc0013bb4ddf7ec0f301690b527 Mon Sep 17 00:00:00 2001 From: Alexandru Furculita Date: Sun, 17 Sep 2017 15:54:32 +0300 Subject: [PATCH 019/225] [HttpFoundation] Deprecate compatibility with PHP <5.4 sessions --- CHANGELOG.md | 7 ++++ .../Handler/MemcacheSessionHandler.php | 2 - .../Handler/MemcachedSessionHandler.php | 2 - .../Storage/Handler/MongoDbSessionHandler.php | 2 - .../Handler/NativeFileSessionHandler.php | 5 +-- .../Storage/Handler/NativeSessionHandler.php | 5 ++- .../Storage/Handler/NullSessionHandler.php | 2 - Session/Storage/MetadataBag.php | 2 - Session/Storage/MockArraySessionStorage.php | 2 - Session/Storage/MockFileSessionStorage.php | 2 - Session/Storage/NativeSessionStorage.php | 31 +++++++------- Session/Storage/PhpBridgeSessionStorage.php | 9 +---- Session/Storage/Proxy/AbstractProxy.php | 4 +- Session/Storage/Proxy/NativeProxy.php | 6 ++- Session/Storage/Proxy/SessionHandlerProxy.php | 9 ++--- .../Handler/NativeSessionHandlerTest.php | 1 + .../Storage/Proxy/AbstractProxyTest.php | 40 +++---------------- .../Session/Storage/Proxy/NativeProxyTest.php | 2 + .../Storage/Proxy/SessionHandlerProxyTest.php | 1 + 19 files changed, 48 insertions(+), 86 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1fdf77b9..d60ebdfe8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ CHANGELOG ========= +3.4.0 +----- + + * deprecated the `NativeSessionHandler` class, + * deprecated the `AbstractProxy`, `NativeProxy` and `SessionHandlerProxy` classes, + * deprecated setting session save handlers that do not implement `\SessionHandlerInterface` in `NativeSessionStorage::setSaveHandler()` + 3.3.0 ----- diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index 4e490a05d..26a0a17e9 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * MemcacheSessionHandler. - * * @author Drak */ class MemcacheSessionHandler implements \SessionHandlerInterface diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index dfe2fee0d..5e9ba7103 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * MemcachedSessionHandler. - * * Memcached based session storage handler based on the Memcached class * provided by the PHP memcached extension. * diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index 8408f000c..cfc427bce 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * MongoDB session handler. - * * @author Markus Bachmann */ class MongoDbSessionHandler implements \SessionHandlerInterface diff --git a/Session/Storage/Handler/NativeFileSessionHandler.php b/Session/Storage/Handler/NativeFileSessionHandler.php index 1be0a3983..4e9704bd5 100644 --- a/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/Session/Storage/Handler/NativeFileSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * NativeFileSessionHandler. - * * Native session handler using PHP's built in file storage. * * @author Drak @@ -21,8 +19,6 @@ class NativeFileSessionHandler extends NativeSessionHandler { /** - * Constructor. - * * @param string $savePath Path of directory to save session files * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path @@ -30,6 +26,7 @@ class NativeFileSessionHandler extends NativeSessionHandler * @see http://php.net/session.configuration.php#ini.session.save-path for further details. * * @throws \InvalidArgumentException On invalid $savePath + * @throws \RuntimeException When failing to create the save directory */ public function __construct($savePath = null) { diff --git a/Session/Storage/Handler/NativeSessionHandler.php b/Session/Storage/Handler/NativeSessionHandler.php index 4ae410f9b..daa7dbd15 100644 --- a/Session/Storage/Handler/NativeSessionHandler.php +++ b/Session/Storage/Handler/NativeSessionHandler.php @@ -11,9 +11,10 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; +@trigger_error('The '.__NAMESPACE__.'\NativeSessionHandler class is deprecated since version 3.4 and will be removed in 4.0. Use the \SessionHandler class instead.', E_USER_DEPRECATED); + /** - * Adds SessionHandler functionality if available. - * + * @deprecated since version 3.4, to be removed in 4.0. Use \SessionHandler instead. * @see http://php.net/sessionhandler */ class NativeSessionHandler extends \SessionHandler diff --git a/Session/Storage/Handler/NullSessionHandler.php b/Session/Storage/Handler/NullSessionHandler.php index 1516d4314..981d96d93 100644 --- a/Session/Storage/Handler/NullSessionHandler.php +++ b/Session/Storage/Handler/NullSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * NullSessionHandler. - * * Can be used in unit testing or in a situations where persisted sessions are not desired. * * @author Drak diff --git a/Session/Storage/MetadataBag.php b/Session/Storage/MetadataBag.php index 322dd560f..6f59af486 100644 --- a/Session/Storage/MetadataBag.php +++ b/Session/Storage/MetadataBag.php @@ -54,8 +54,6 @@ class MetadataBag implements SessionBagInterface private $updateThreshold; /** - * Constructor. - * * @param string $storageKey The key used to store bag in the session * @param int $updateThreshold The time to wait between two UPDATED updates */ diff --git a/Session/Storage/MockArraySessionStorage.php b/Session/Storage/MockArraySessionStorage.php index 348fd2301..0349a4336 100644 --- a/Session/Storage/MockArraySessionStorage.php +++ b/Session/Storage/MockArraySessionStorage.php @@ -63,8 +63,6 @@ class MockArraySessionStorage implements SessionStorageInterface protected $bags = array(); /** - * Constructor. - * * @param string $name Session name * @param MetadataBag $metaBag MetadataBag instance */ diff --git a/Session/Storage/MockFileSessionStorage.php b/Session/Storage/MockFileSessionStorage.php index 71f9e5551..8c1bf73ca 100644 --- a/Session/Storage/MockFileSessionStorage.php +++ b/Session/Storage/MockFileSessionStorage.php @@ -30,8 +30,6 @@ class MockFileSessionStorage extends MockArraySessionStorage private $savePath; /** - * Constructor. - * * @param string $savePath Path of directory to save session files * @param string $name Session name * @param MetadataBag $metaBag MetadataBag instance diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 97161b8d0..48bef335b 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -13,7 +13,6 @@ use Symfony\Component\Debug\Exception\ContextErrorException; use Symfony\Component\HttpFoundation\Session\SessionBagInterface; -use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; @@ -25,8 +24,6 @@ class NativeSessionStorage implements SessionStorageInterface { /** - * Array of SessionBagInterface. - * * @var SessionBagInterface[] */ protected $bags; @@ -42,7 +39,7 @@ class NativeSessionStorage implements SessionStorageInterface protected $closed = false; /** - * @var AbstractProxy + * @var AbstractProxy|\SessionHandlerInterface */ protected $saveHandler; @@ -52,8 +49,6 @@ class NativeSessionStorage implements SessionStorageInterface protected $metadataBag; /** - * Constructor. - * * Depending on how you want the storage driver to behave you probably * want to override this constructor entirely. * @@ -97,9 +92,9 @@ class NativeSessionStorage implements SessionStorageInterface * trans_sid_hosts, $_SERVER['HTTP_HOST'] * trans_sid_tags, "a=href,area=href,frame=src,form=" * - * @param array $options Session configuration options - * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $handler - * @param MetadataBag $metaBag MetadataBag + * @param array $options Session configuration options + * @param \SessionHandlerInterface|null $handler + * @param MetadataBag $metaBag MetadataBag */ public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) { @@ -116,7 +111,7 @@ public function __construct(array $options = array(), $handler = null, MetadataB /** * Gets the save handler instance. * - * @return AbstractProxy + * @return AbstractProxy|\SessionHandlerInterface */ public function getSaveHandler() { @@ -276,7 +271,7 @@ public function getBag($name) throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name)); } - if ($this->saveHandler->isActive() && !$this->started) { + if (!$this->started && $this->saveHandler->isActive()) { $this->loadSession(); } elseif (!$this->started) { $this->start(); @@ -358,7 +353,7 @@ public function setOptions(array $options) * ini_set('session.save_handler', 'files'); * ini_set('session.save_path', '/tmp'); * - * or pass in a NativeSessionHandler instance which configures session.save_handler in the + * or pass in a \SessionHandler instance which configures session.save_handler in the * constructor, for a template see NativeFileSessionHandler or use handlers in * composer package drak/native-session * @@ -367,17 +362,23 @@ public function setOptions(array $options) * @see http://php.net/sessionhandler * @see http://github.com/drak/NativeSession * - * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $saveHandler + * @param \SessionHandlerInterface|null $saveHandler * * @throws \InvalidArgumentException */ public function setSaveHandler($saveHandler = null) { if (!$saveHandler instanceof AbstractProxy && - !$saveHandler instanceof NativeSessionHandler && !$saveHandler instanceof \SessionHandlerInterface && null !== $saveHandler) { - throw new \InvalidArgumentException('Must be instance of AbstractProxy or NativeSessionHandler; implement \SessionHandlerInterface; or be null.'); + throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.'); + } + + if ($saveHandler instanceof AbstractProxy) { + @trigger_error( + 'Using session save handlers that are instances of AbstractProxy is deprecated since version 3.4 and will be removed in 4.0.', + E_USER_DEPRECATED + ); } // Wrap $saveHandler in proxy and prevent double wrapping of proxy diff --git a/Session/Storage/PhpBridgeSessionStorage.php b/Session/Storage/PhpBridgeSessionStorage.php index 6f02a7fd7..662ed5015 100644 --- a/Session/Storage/PhpBridgeSessionStorage.php +++ b/Session/Storage/PhpBridgeSessionStorage.php @@ -11,9 +11,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage; -use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; -use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler; - /** * Allows session to be started by PHP and managed by Symfony. * @@ -22,10 +19,8 @@ class PhpBridgeSessionStorage extends NativeSessionStorage { /** - * Constructor. - * - * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $handler - * @param MetadataBag $metaBag MetadataBag + * @param \SessionHandlerInterface|null $handler + * @param MetadataBag $metaBag MetadataBag */ public function __construct($handler = null, MetadataBag $metaBag = null) { diff --git a/Session/Storage/Proxy/AbstractProxy.php b/Session/Storage/Proxy/AbstractProxy.php index a7478656d..c1c8b9b1f 100644 --- a/Session/Storage/Proxy/AbstractProxy.php +++ b/Session/Storage/Proxy/AbstractProxy.php @@ -11,8 +11,10 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; +@trigger_error('The '.__NAMESPACE__.'\AbstractProxy class is deprecated since version 3.4 and will be removed in 4.0. Use your session handler implementation directly.', E_USER_DEPRECATED); + /** - * AbstractProxy. + * @deprecated since version 3.4, to be removed in 4.0. Use your session handler implementation directly. * * @author Drak */ diff --git a/Session/Storage/Proxy/NativeProxy.php b/Session/Storage/Proxy/NativeProxy.php index 0db34aa28..e75497d57 100644 --- a/Session/Storage/Proxy/NativeProxy.php +++ b/Session/Storage/Proxy/NativeProxy.php @@ -11,10 +11,12 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; +@trigger_error('The '.__NAMESPACE__.'\NativeProxy class is deprecated since version 3.4 and will be removed in 4.0. Use your session handler implementation directly.', E_USER_DEPRECATED); + /** - * NativeProxy. + * This proxy is built-in session handlers in PHP 5.3.x. * - * This proxy is built-in session handlers in PHP 5.3.x + * @deprecated since version 3.4, to be removed in 4.0. Use your session handler implementation directly. * * @author Drak */ diff --git a/Session/Storage/Proxy/SessionHandlerProxy.php b/Session/Storage/Proxy/SessionHandlerProxy.php index 68ed713c2..d6adef82d 100644 --- a/Session/Storage/Proxy/SessionHandlerProxy.php +++ b/Session/Storage/Proxy/SessionHandlerProxy.php @@ -11,8 +11,10 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; +@trigger_error('The '.__NAMESPACE__.'\SessionHandlerProxy class is deprecated since version 3.4 and will be removed in 4.0. Use your session handler implementation directly.', E_USER_DEPRECATED); + /** - * SessionHandler proxy. + * @deprecated since version 3.4, to be removed in 4.0. Use your session handler implementation directly. * * @author Drak */ @@ -23,11 +25,6 @@ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterf */ protected $handler; - /** - * Constructor. - * - * @param \SessionHandlerInterface $handler - */ public function __construct(\SessionHandlerInterface $handler) { $this->handler = $handler; diff --git a/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php index 5486b2d65..fe4cc72d2 100644 --- a/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php @@ -21,6 +21,7 @@ * * @runTestsInSeparateProcesses * @preserveGlobalState disabled + * @group legacy */ class NativeSessionHandlerTest extends TestCase { diff --git a/Tests/Session/Storage/Proxy/AbstractProxyTest.php b/Tests/Session/Storage/Proxy/AbstractProxyTest.php index ef1da130a..f2be722c8 100644 --- a/Tests/Session/Storage/Proxy/AbstractProxyTest.php +++ b/Tests/Session/Storage/Proxy/AbstractProxyTest.php @@ -13,43 +13,13 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; - -// Note until PHPUnit_Mock_Objects 1.2 is released you cannot mock abstracts due to -// https://github.com/sebastianbergmann/phpunit-mock-objects/issues/73 -class ConcreteProxy extends AbstractProxy -{ -} - -class ConcreteSessionHandlerInterfaceProxy extends AbstractProxy implements \SessionHandlerInterface -{ - public function open($savePath, $sessionName) - { - } - - public function close() - { - } - - public function read($id) - { - } - - public function write($id, $data) - { - } - - public function destroy($id) - { - } - - public function gc($maxlifetime) - { - } -} +use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; /** * Test class for AbstractProxy. * + * @group legacy + * * @author Drak */ class AbstractProxyTest extends TestCase @@ -61,7 +31,7 @@ class AbstractProxyTest extends TestCase protected function setUp() { - $this->proxy = new ConcreteProxy(); + $this->proxy = $this->getMockForAbstractClass(AbstractProxy::class); } protected function tearDown() @@ -77,7 +47,7 @@ public function testGetSaveHandlerName() public function testIsSessionHandlerInterface() { $this->assertFalse($this->proxy->isSessionHandlerInterface()); - $sh = new ConcreteSessionHandlerInterfaceProxy(); + $sh = new SessionHandlerProxy(new \SessionHandler()); $this->assertTrue($sh->isSessionHandlerInterface()); } diff --git a/Tests/Session/Storage/Proxy/NativeProxyTest.php b/Tests/Session/Storage/Proxy/NativeProxyTest.php index 8ec305344..ed4fee6bf 100644 --- a/Tests/Session/Storage/Proxy/NativeProxyTest.php +++ b/Tests/Session/Storage/Proxy/NativeProxyTest.php @@ -17,6 +17,8 @@ /** * Test class for NativeProxy. * + * @group legacy + * * @author Drak */ class NativeProxyTest extends TestCase diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index 682825356..fdd1dae25 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -21,6 +21,7 @@ * * @runTestsInSeparateProcesses * @preserveGlobalState disabled + * @group legacy */ class SessionHandlerProxyTest extends TestCase { From 23464307fc9fbb8e4038957d9afdbf900a5f2882 Mon Sep 17 00:00:00 2001 From: Tobias Schultze Date: Thu, 28 Sep 2017 20:22:10 +0200 Subject: [PATCH 020/225] PdoSessionHandler: fix advisory lock for pgsql when session.sid_bits_per_character > 4 --- Session/Storage/Handler/PdoSessionHandler.php | 33 +++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 8909a5f40..483e73a11 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -580,11 +580,11 @@ private function doAdvisoryLock($sessionId) return $releaseStmt; case 'pgsql': // Obtaining an exclusive session level advisory lock requires an integer key. - // So we convert the HEX representation of the session id to an integer. - // Since integers are signed, we have to skip one hex char to fit in the range. - if (4 === PHP_INT_SIZE) { - $sessionInt1 = hexdec(substr($sessionId, 0, 7)); - $sessionInt2 = hexdec(substr($sessionId, 7, 7)); + // When session.sid_bits_per_character > 4, the session id can contain non-hex-characters. + // So we cannot just use hexdec(). + if (4 === \PHP_INT_SIZE) { + $sessionInt1 = $this->convertStringToInt($sessionId); + $sessionInt2 = $this->convertStringToInt(substr($sessionId, 4, 4)); $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)'); $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); @@ -595,7 +595,7 @@ private function doAdvisoryLock($sessionId) $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT); } else { - $sessionBigInt = hexdec(substr($sessionId, 0, 15)); + $sessionBigInt = $this->convertStringToInt($sessionId); $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)'); $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT); @@ -613,6 +613,27 @@ private function doAdvisoryLock($sessionId) } } + /** + * Encodes the first 4 (when PHP_INT_SIZE == 4) or 8 characters of the string as an integer. + * + * Keep in mind, PHP integers are signed. + * + * @param string $string + * + * @return int + */ + private function convertStringToInt($string) + { + if (4 === \PHP_INT_SIZE) { + 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]); + + return $int2 + ($int1 << 32); + } + /** * Return a locking or nonlocking SQL query to read session information. * From 372641e1ad07a05aa69687304ee131c74d6b1460 Mon Sep 17 00:00:00 2001 From: Antoine Bellion Date: Fri, 29 Sep 2017 13:45:44 +0200 Subject: [PATCH 021/225] [HttpFoundation] Return instance in StreamedResponse --- StreamedResponse.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/StreamedResponse.php b/StreamedResponse.php index 928531309..cd86be136 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -66,16 +66,22 @@ public static function create($callback = null, $status = 200, $headers = array( * Sets the PHP callback associated with this Response. * * @param callable $callback A valid PHP callback + * + * @return $this */ public function setCallback(callable $callback) { $this->callback = $callback; + + return $this; } /** * {@inheritdoc} * * This method only sends the headers once. + * + * @return $this */ public function sendHeaders() { @@ -85,13 +91,15 @@ public function sendHeaders() $this->headersSent = true; - parent::sendHeaders(); + return parent::sendHeaders(); } /** * {@inheritdoc} * * This method only sends the content once. + * + * @return $this */ public function sendContent() { @@ -106,18 +114,24 @@ public function sendContent() } call_user_func($this->callback); + + return $this; } /** * {@inheritdoc} * * @throws \LogicException when the content is not null + * + * @return $this */ public function setContent($content) { if (null !== $content) { throw new \LogicException('The content cannot be set on a StreamedResponse instance.'); } + + return $this; } /** From 4f5ec33a934e668185726ddb4fd2d053364139ef Mon Sep 17 00:00:00 2001 From: Oskar Stark Date: Thu, 28 Sep 2017 08:42:58 +0200 Subject: [PATCH 022/225] removed useless PHPDoc --- AcceptHeader.php | 2 -- AcceptHeaderItem.php | 2 -- BinaryFileResponse.php | 2 -- Cookie.php | 2 -- File/Exception/AccessDeniedException.php | 2 -- File/Exception/FileNotFoundException.php | 2 -- File/MimeType/FileBinaryMimeTypeGuesser.php | 2 -- File/MimeType/FileinfoMimeTypeGuesser.php | 2 -- FileBag.php | 2 -- HeaderBag.php | 2 -- JsonResponse.php | 2 -- ParameterBag.php | 2 -- Request.php | 2 -- Response.php | 2 -- ResponseHeaderBag.php | 2 -- Session/Attribute/AttributeBag.php | 2 -- Session/Attribute/NamespacedAttributeBag.php | 2 -- Session/Flash/AutoExpireFlashBag.php | 2 -- Session/Flash/FlashBag.php | 2 -- Session/Session.php | 4 ---- Session/Storage/Handler/LegacyPdoSessionHandler.php | 2 -- Session/Storage/Handler/MemcacheSessionHandler.php | 4 ---- Session/Storage/Handler/MemcachedSessionHandler.php | 4 ---- Session/Storage/Handler/MongoDbSessionHandler.php | 4 ---- Session/Storage/Handler/NativeFileSessionHandler.php | 4 ---- Session/Storage/Handler/PdoSessionHandler.php | 2 -- Session/Storage/MetadataBag.php | 2 -- Session/Storage/MockArraySessionStorage.php | 2 -- Session/Storage/MockFileSessionStorage.php | 2 -- Session/Storage/NativeSessionStorage.php | 2 -- Session/Storage/PhpBridgeSessionStorage.php | 2 -- Session/Storage/Proxy/NativeProxy.php | 5 ----- Session/Storage/Proxy/SessionHandlerProxy.php | 4 ---- StreamedResponse.php | 2 -- 34 files changed, 83 deletions(-) diff --git a/AcceptHeader.php b/AcceptHeader.php index 2aa91dc44..99be6768f 100644 --- a/AcceptHeader.php +++ b/AcceptHeader.php @@ -32,8 +32,6 @@ class AcceptHeader private $sorted = true; /** - * Constructor. - * * @param AcceptHeaderItem[] $items */ public function __construct(array $items) diff --git a/AcceptHeaderItem.php b/AcceptHeaderItem.php index fb54b4935..2758f5c40 100644 --- a/AcceptHeaderItem.php +++ b/AcceptHeaderItem.php @@ -39,8 +39,6 @@ class AcceptHeaderItem private $attributes = array(); /** - * Constructor. - * * @param string $value * @param array $attributes */ diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 177b708e8..71823c0f3 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -36,8 +36,6 @@ class BinaryFileResponse extends Response protected $deleteFileAfterSend = false; /** - * Constructor. - * * @param \SplFileInfo|string $file The file to stream * @param int $status The response status code * @param array $headers An array of response headers diff --git a/Cookie.php b/Cookie.php index fb1e7dfd7..93bb099cd 100644 --- a/Cookie.php +++ b/Cookie.php @@ -27,8 +27,6 @@ class Cookie protected $httpOnly; /** - * Constructor. - * * @param string $name The name of the cookie * @param string $value The value of the cookie * @param int|string|\DateTime|\DateTimeInterface $expire The time the cookie expires diff --git a/File/Exception/AccessDeniedException.php b/File/Exception/AccessDeniedException.php index 41f7a4625..3b8e41d4a 100644 --- a/File/Exception/AccessDeniedException.php +++ b/File/Exception/AccessDeniedException.php @@ -19,8 +19,6 @@ class AccessDeniedException extends FileException { /** - * Constructor. - * * @param string $path The path to the accessed file */ public function __construct($path) diff --git a/File/Exception/FileNotFoundException.php b/File/Exception/FileNotFoundException.php index ac90d4035..bfcc37ec6 100644 --- a/File/Exception/FileNotFoundException.php +++ b/File/Exception/FileNotFoundException.php @@ -19,8 +19,6 @@ class FileNotFoundException extends FileException { /** - * Constructor. - * * @param string $path The path to the file that was not found */ public function __construct($path) diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index f917a06d6..c2ac6768c 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -24,8 +24,6 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface private $cmd; /** - * Constructor. - * * The $cmd pattern must contain a "%s" string that will be replaced * with the file name to guess. * diff --git a/File/MimeType/FileinfoMimeTypeGuesser.php b/File/MimeType/FileinfoMimeTypeGuesser.php index 6fee94798..9b42835e4 100644 --- a/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/File/MimeType/FileinfoMimeTypeGuesser.php @@ -24,8 +24,6 @@ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface private $magicFile; /** - * Constructor. - * * @param string $magicFile A magic file to use with the finfo instance * * @see http://www.php.net/manual/en/function.finfo-open.php diff --git a/FileBag.php b/FileBag.php index e17a9057b..0aaf49aa6 100644 --- a/FileBag.php +++ b/FileBag.php @@ -24,8 +24,6 @@ class FileBag extends ParameterBag private static $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type'); /** - * Constructor. - * * @param array $parameters An array of HTTP files */ public function __construct(array $parameters = array()) diff --git a/HeaderBag.php b/HeaderBag.php index 29bac5e51..a824ed864 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -22,8 +22,6 @@ class HeaderBag implements \IteratorAggregate, \Countable protected $cacheControl = array(); /** - * Constructor. - * * @param array $headers An array of HTTP headers */ public function __construct(array $headers = array()) diff --git a/JsonResponse.php b/JsonResponse.php index c6e0ba654..099749084 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -32,8 +32,6 @@ class JsonResponse extends Response protected $encodingOptions = 15; /** - * Constructor. - * * @param mixed $data The response data * @param int $status The response status code * @param array $headers An array of response headers diff --git a/ParameterBag.php b/ParameterBag.php index 3436ee933..77b05a900 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -26,8 +26,6 @@ class ParameterBag implements \IteratorAggregate, \Countable protected $parameters; /** - * Constructor. - * * @param array $parameters An array of parameters */ public function __construct(array $parameters = array()) diff --git a/Request.php b/Request.php index 0c11adab6..8f372d432 100644 --- a/Request.php +++ b/Request.php @@ -207,8 +207,6 @@ class Request protected static $requestFactory; /** - * Constructor. - * * @param array $query The GET parameters * @param array $request The POST parameters * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) diff --git a/Response.php b/Response.php index f9512d670..5e8011160 100644 --- a/Response.php +++ b/Response.php @@ -188,8 +188,6 @@ class Response ); /** - * Constructor. - * * @param mixed $content The response content, see setContent() * @param int $status The response status code * @param array $headers An array of response headers diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index 3223691eb..32e718785 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -40,8 +40,6 @@ class ResponseHeaderBag extends HeaderBag protected $headerNames = array(); /** - * Constructor. - * * @param array $headers An array of HTTP headers */ public function __construct(array $headers = array()) diff --git a/Session/Attribute/AttributeBag.php b/Session/Attribute/AttributeBag.php index af292e37a..57c297197 100644 --- a/Session/Attribute/AttributeBag.php +++ b/Session/Attribute/AttributeBag.php @@ -29,8 +29,6 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta protected $attributes = array(); /** - * Constructor. - * * @param string $storageKey The key used to store attributes in the session */ public function __construct($storageKey = '_sf2_attributes') diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index d797a6f23..7afc6de7c 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -27,8 +27,6 @@ class NamespacedAttributeBag extends AttributeBag private $namespaceCharacter; /** - * Constructor. - * * @param string $storageKey Session storage key * @param string $namespaceCharacter Namespace character to use in keys */ diff --git a/Session/Flash/AutoExpireFlashBag.php b/Session/Flash/AutoExpireFlashBag.php index ddd603fdd..8110aee0c 100644 --- a/Session/Flash/AutoExpireFlashBag.php +++ b/Session/Flash/AutoExpireFlashBag.php @@ -35,8 +35,6 @@ class AutoExpireFlashBag implements FlashBagInterface private $storageKey; /** - * Constructor. - * * @param string $storageKey The key used to store flashes in the session */ public function __construct($storageKey = '_sf2_flashes') diff --git a/Session/Flash/FlashBag.php b/Session/Flash/FlashBag.php index 1516de7fe..a4159cd82 100644 --- a/Session/Flash/FlashBag.php +++ b/Session/Flash/FlashBag.php @@ -37,8 +37,6 @@ class FlashBag implements FlashBagInterface, \IteratorAggregate private $storageKey; /** - * Constructor. - * * @param string $storageKey The key used to store flashes in the session */ public function __construct($storageKey = '_sf2_flashes') diff --git a/Session/Session.php b/Session/Session.php index cdd97375b..5a765654c 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -19,8 +19,6 @@ use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; /** - * Session. - * * @author Fabien Potencier * @author Drak */ @@ -44,8 +42,6 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable private $attributeName; /** - * Constructor. - * * @param SessionStorageInterface $storage A SessionStorageInterface instance * @param AttributeBagInterface $attributes An AttributeBagInterface instance, (defaults null for default AttributeBag) * @param FlashBagInterface $flashes A FlashBagInterface instance (defaults null for default FlashBag) diff --git a/Session/Storage/Handler/LegacyPdoSessionHandler.php b/Session/Storage/Handler/LegacyPdoSessionHandler.php index 111541d92..900fb9f5f 100644 --- a/Session/Storage/Handler/LegacyPdoSessionHandler.php +++ b/Session/Storage/Handler/LegacyPdoSessionHandler.php @@ -57,8 +57,6 @@ class LegacyPdoSessionHandler implements \SessionHandlerInterface private $timeCol; /** - * Constructor. - * * List of available options: * * db_table: The name of the table [required] * * db_id_col: The column where to store the session id [default: sess_id] diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index 4e490a05d..d31aa7667 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * MemcacheSessionHandler. - * * @author Drak */ class MemcacheSessionHandler implements \SessionHandlerInterface @@ -34,8 +32,6 @@ class MemcacheSessionHandler implements \SessionHandlerInterface private $prefix; /** - * Constructor. - * * List of available options: * * prefix: The prefix to use for the memcache keys in order to avoid collision * * expiretime: The time to live in seconds diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 67a49ad6f..68901294e 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * MemcachedSessionHandler. - * * Memcached based session storage handler based on the Memcached class * provided by the PHP memcached extension. * @@ -39,8 +37,6 @@ class MemcachedSessionHandler implements \SessionHandlerInterface private $prefix; /** - * Constructor. - * * List of available options: * * prefix: The prefix to use for the memcached keys in order to avoid collision * * expiretime: The time to live in seconds diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index 8408f000c..80ecc1cc3 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * MongoDB session handler. - * * @author Markus Bachmann */ class MongoDbSessionHandler implements \SessionHandlerInterface @@ -34,8 +32,6 @@ class MongoDbSessionHandler implements \SessionHandlerInterface private $options; /** - * Constructor. - * * List of available options: * * database: The name of the database [required] * * collection: The name of the collection [required] diff --git a/Session/Storage/Handler/NativeFileSessionHandler.php b/Session/Storage/Handler/NativeFileSessionHandler.php index 1be0a3983..d6ad93749 100644 --- a/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/Session/Storage/Handler/NativeFileSessionHandler.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** - * NativeFileSessionHandler. - * * Native session handler using PHP's built in file storage. * * @author Drak @@ -21,8 +19,6 @@ class NativeFileSessionHandler extends NativeSessionHandler { /** - * Constructor. - * * @param string $savePath Path of directory to save session files * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 8909a5f40..66d12aaef 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -148,8 +148,6 @@ class PdoSessionHandler implements \SessionHandlerInterface private $gcCalled = false; /** - * Constructor. - * * You can either pass an existing database connection as PDO instance or * pass a DSN string that will be used to lazy-connect to the database * when the session is actually used. Furthermore it's possible to pass null diff --git a/Session/Storage/MetadataBag.php b/Session/Storage/MetadataBag.php index 322dd560f..6f59af486 100644 --- a/Session/Storage/MetadataBag.php +++ b/Session/Storage/MetadataBag.php @@ -54,8 +54,6 @@ class MetadataBag implements SessionBagInterface private $updateThreshold; /** - * Constructor. - * * @param string $storageKey The key used to store bag in the session * @param int $updateThreshold The time to wait between two UPDATED updates */ diff --git a/Session/Storage/MockArraySessionStorage.php b/Session/Storage/MockArraySessionStorage.php index 348fd2301..0349a4336 100644 --- a/Session/Storage/MockArraySessionStorage.php +++ b/Session/Storage/MockArraySessionStorage.php @@ -63,8 +63,6 @@ class MockArraySessionStorage implements SessionStorageInterface protected $bags = array(); /** - * Constructor. - * * @param string $name Session name * @param MetadataBag $metaBag MetadataBag instance */ diff --git a/Session/Storage/MockFileSessionStorage.php b/Session/Storage/MockFileSessionStorage.php index 71f9e5551..8c1bf73ca 100644 --- a/Session/Storage/MockFileSessionStorage.php +++ b/Session/Storage/MockFileSessionStorage.php @@ -30,8 +30,6 @@ class MockFileSessionStorage extends MockArraySessionStorage private $savePath; /** - * Constructor. - * * @param string $savePath Path of directory to save session files * @param string $name Session name * @param MetadataBag $metaBag MetadataBag instance diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 812f5f2e4..5888323bd 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -52,8 +52,6 @@ class NativeSessionStorage implements SessionStorageInterface protected $metadataBag; /** - * Constructor. - * * Depending on how you want the storage driver to behave you probably * want to override this constructor entirely. * diff --git a/Session/Storage/PhpBridgeSessionStorage.php b/Session/Storage/PhpBridgeSessionStorage.php index ced706f72..3a2391e76 100644 --- a/Session/Storage/PhpBridgeSessionStorage.php +++ b/Session/Storage/PhpBridgeSessionStorage.php @@ -22,8 +22,6 @@ class PhpBridgeSessionStorage extends NativeSessionStorage { /** - * Constructor. - * * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $handler * @param MetadataBag $metaBag MetadataBag */ diff --git a/Session/Storage/Proxy/NativeProxy.php b/Session/Storage/Proxy/NativeProxy.php index 0db34aa28..21ed1ada0 100644 --- a/Session/Storage/Proxy/NativeProxy.php +++ b/Session/Storage/Proxy/NativeProxy.php @@ -12,17 +12,12 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; /** - * NativeProxy. - * * This proxy is built-in session handlers in PHP 5.3.x * * @author Drak */ class NativeProxy extends AbstractProxy { - /** - * Constructor. - */ public function __construct() { // this makes an educated guess as to what the handler is since it should already be set. diff --git a/Session/Storage/Proxy/SessionHandlerProxy.php b/Session/Storage/Proxy/SessionHandlerProxy.php index 81643c74b..8f91f0604 100644 --- a/Session/Storage/Proxy/SessionHandlerProxy.php +++ b/Session/Storage/Proxy/SessionHandlerProxy.php @@ -12,8 +12,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; /** - * SessionHandler proxy. - * * @author Drak */ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface @@ -24,8 +22,6 @@ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterf protected $handler; /** - * Constructor. - * * @param \SessionHandlerInterface $handler */ public function __construct(\SessionHandlerInterface $handler) diff --git a/StreamedResponse.php b/StreamedResponse.php index 8be624436..d6b7b9e53 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -31,8 +31,6 @@ class StreamedResponse extends Response private $headersSent; /** - * Constructor. - * * @param callable|null $callback A valid PHP callback or null to set it later * @param int $status The response status code * @param array $headers An array of response headers From 87a89742570b60fb9014502b1acd11ca064d3551 Mon Sep 17 00:00:00 2001 From: Tobias Schultze Date: Thu, 5 Oct 2017 14:27:30 +0200 Subject: [PATCH 023/225] [HttpFoundation] deprecate using with the legacy mongo extension; use it with the mongodb/mongodb package and ext-mongodb instead --- CHANGELOG.md | 1 + Session/Storage/Handler/MongoDbSessionHandler.php | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d60ebdfe8..608bac2d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ CHANGELOG * deprecated the `NativeSessionHandler` class, * deprecated the `AbstractProxy`, `NativeProxy` and `SessionHandlerProxy` classes, * deprecated setting session save handlers that do not implement `\SessionHandlerInterface` in `NativeSessionStorage::setSaveHandler()` + * deprecated using `MongoDbSessionHandler` with the legacy mongo extension; use it with the mongodb/mongodb package and ext-mongodb instead 3.3.0 ----- diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index 80ecc1cc3..20e1a897e 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -12,7 +12,12 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** + * Session handler using the mongodb/mongodb package and MongoDB driver extension. + * * @author Markus Bachmann + * + * @see https://packagist.org/packages/mongodb/mongodb + * @see http://php.net/manual/en/set.mongodb.php */ class MongoDbSessionHandler implements \SessionHandlerInterface { @@ -57,14 +62,18 @@ class MongoDbSessionHandler implements \SessionHandlerInterface * If you use such an index, you can drop `gc_probability` to 0 since * no garbage-collection is required. * - * @param \Mongo|\MongoClient|\MongoDB\Client $mongo A MongoDB\Client, MongoClient or Mongo instance - * @param array $options An associative array of field options + * @param \MongoDB\Client $mongo A MongoDB\Client instance + * @param array $options An associative array of field options * * @throws \InvalidArgumentException When MongoClient or Mongo instance not provided * @throws \InvalidArgumentException When "database" or "collection" not provided */ public function __construct($mongo, array $options) { + if ($mongo instanceof \MongoClient || $mongo instanceof \Mongo) { + @trigger_error(sprintf('Using %s with the legacy mongo extension is deprecated as of 3.4 and will be removed in 4.0. Use it with the mongodb/mongodb package and ext-mongodb instead.', __CLASS__), E_USER_DEPRECATED); + } + if (!($mongo instanceof \MongoDB\Client || $mongo instanceof \MongoClient || $mongo instanceof \Mongo)) { throw new \InvalidArgumentException('MongoClient or Mongo instance required'); } From ec42e45f4b4158253458382e53beedb8a4149da2 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 3 Oct 2017 11:46:06 +0200 Subject: [PATCH 024/225] [Bridge\Doctrine][FrameworkBundle] Deprecate some remaining uses of ContainerAwareTrait --- Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 74366863f..9b28f066d 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -17,6 +17,7 @@ /** * @author Markus Bachmann * @group time-sensitive + * @group legacy */ class MongoDbSessionHandlerTest extends TestCase { From 6137f3f361817c558d0f2d298e668f386d773532 Mon Sep 17 00:00:00 2001 From: Tobias Schultze Date: Thu, 5 Oct 2017 17:58:33 +0200 Subject: [PATCH 025/225] [Session] deprecate MemcacheSessionHandler memcache extension didn't get a release since 4.5 years and is not compatible with PHP 7 --- CHANGELOG.md | 1 + Session/Storage/Handler/MemcacheSessionHandler.php | 4 ++++ Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php | 1 + 3 files changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 608bac2d6..83a3c8e32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ CHANGELOG * deprecated the `AbstractProxy`, `NativeProxy` and `SessionHandlerProxy` classes, * deprecated setting session save handlers that do not implement `\SessionHandlerInterface` in `NativeSessionStorage::setSaveHandler()` * deprecated using `MongoDbSessionHandler` with the legacy mongo extension; use it with the mongodb/mongodb package and ext-mongodb instead + * deprecated `MemcacheSessionHandler`; use `MemcachedSessionHandler` instead 3.3.0 ----- diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index d31aa7667..2978ef4a2 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -11,8 +11,12 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; +@trigger_error(sprintf('The class %s is deprecated since version 3.4 and will be removed in 4.0. Use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler instead.', MemcacheSessionHandler::class), E_USER_DEPRECATED); + /** * @author Drak + * + * @deprecated since version 3.4, to be removed in 4.0. Use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler instead. */ class MemcacheSessionHandler implements \SessionHandlerInterface { diff --git a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php index 06193c8be..05470ed80 100644 --- a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php @@ -17,6 +17,7 @@ /** * @requires extension memcache * @group time-sensitive + * @group legacy */ class MemcacheSessionHandlerTest extends TestCase { From 867e1eb2a4540d806969224ff458c2d2e7bc7aba Mon Sep 17 00:00:00 2001 From: Tobias Schultze Date: Thu, 5 Oct 2017 21:04:13 +0200 Subject: [PATCH 026/225] [Session] fix MongoDb session handler to gc all expired sessions --- Session/Storage/Handler/MongoDbSessionHandler.php | 2 +- Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index 80ecc1cc3..f140939db 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -118,7 +118,7 @@ public function destroy($sessionId) */ public function gc($maxlifetime) { - $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove'; + $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteMany' : 'remove'; $this->getCollection()->$methodName(array( $this->options['expiry_field'] => array('$lt' => $this->createDateTime()), diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 128b9b52f..8ea0c52a8 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -291,7 +291,7 @@ public function testGc() $that = $this; - $methodName = phpversion('mongodb') ? 'deleteOne' : 'remove'; + $methodName = phpversion('mongodb') ? 'deleteMany' : 'remove'; $collection->expects($this->once()) ->method($methodName) From 70a1183fdd632c9a8856f71b0ce89e0d46aab217 Mon Sep 17 00:00:00 2001 From: Christian Schmidt Date: Sun, 8 Oct 2017 16:27:20 +0200 Subject: [PATCH 027/225] [HttpFoundation] Combine Cache-Control headers --- HeaderBag.php | 2 +- Tests/ResponseHeaderBagTest.php | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/HeaderBag.php b/HeaderBag.php index a824ed864..a797d7a2e 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -146,7 +146,7 @@ public function set($key, $values, $replace = true) } if ('cache-control' === $key) { - $this->cacheControl = $this->parseCacheControl($values[0]); + $this->cacheControl = $this->parseCacheControl(implode(', ', $this->headers[$key])); } } diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index debcdc1fa..c55a7f6a5 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -110,6 +110,17 @@ public function testCacheControlHeader() $bag = new ResponseHeaderBag(); $bag->set('Last-Modified', 'abcde'); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); + + $bag = new ResponseHeaderBag(); + $bag->set('Cache-Control', array('public', 'must-revalidate')); + $this->assertCount(1, $bag->get('Cache-Control', null, false)); + $this->assertEquals('must-revalidate, public', $bag->get('Cache-Control')); + + $bag = new ResponseHeaderBag(); + $bag->set('Cache-Control', 'public'); + $bag->set('Cache-Control', 'must-revalidate', false); + $this->assertCount(1, $bag->get('Cache-Control', null, false)); + $this->assertEquals('must-revalidate, public', $bag->get('Cache-Control')); } public function testToStringIncludesCookieHeaders() From 45f9659d0c1bda1fdfd21fed9b7a72295a02631f Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 9 Oct 2017 11:21:24 +0200 Subject: [PATCH 028/225] [HttpFoundation] Add missing session.lazy_write config option --- Session/Storage/NativeSessionStorage.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 5888323bd..9bf438c15 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -76,6 +76,7 @@ class NativeSessionStorage implements SessionStorageInterface * gc_probability, "1" * hash_bits_per_character, "4" * hash_function, "0" + * lazy_write, "1" * name, "PHPSESSID" * referer_check, "" * serialize_handler, "php" @@ -337,7 +338,7 @@ public function setOptions(array $options) 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'entropy_file', 'entropy_length', 'gc_divisor', 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character', - 'hash_function', 'name', 'referer_check', + 'hash_function', 'lazy_write', 'name', 'referer_check', 'serialize_handler', 'use_strict_mode', 'use_cookies', 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled', 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name', From f50d4c800ed49b685c7a66191a81514b2f265f9a Mon Sep 17 00:00:00 2001 From: Amrouche Hamza Date: Sat, 29 Jul 2017 11:14:02 +0200 Subject: [PATCH 029/225] Fix PHP 7.2 support --- Session/Storage/NativeSessionStorage.php | 18 ++++++--- .../Storage/Handler/PdoSessionHandlerTest.php | 38 +++++++++++++++++++ .../Storage/NativeSessionStorageTest.php | 2 +- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 5888323bd..1ee6d3f34 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -101,8 +101,12 @@ class NativeSessionStorage implements SessionStorageInterface */ public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) { - session_cache_limiter(''); // disable by default because it's managed by HeaderBag (if used) - ini_set('session.use_cookies', 1); + if (empty($options)) { + $options += array('cache_limiter' => 'public'); + } + if (1 !== (int) ini_get('session.use_cookies')) { + ini_set('session.use_cookies', 1); + } if (\PHP_VERSION_ID >= 50400) { session_register_shutdown(); @@ -345,9 +349,11 @@ public function setOptions(array $options) 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags', )); - foreach ($options as $key => $value) { - if (isset($validOptions[$key])) { - ini_set('session.'.$key, $value); + if (PHP_VERSION_ID < 70200 || !headers_sent()) { + foreach ($options as $key => $value) { + if (isset($validOptions[$key])) { + ini_set('session.'.$key, $value); + } } } } @@ -392,7 +398,7 @@ public function setSaveHandler($saveHandler = null) } $this->saveHandler = $saveHandler; - if ($this->saveHandler instanceof \SessionHandlerInterface) { + if ($this->saveHandler instanceof \SessionHandlerInterface && false === headers_sent()) { if (\PHP_VERSION_ID >= 50400) { session_set_save_handler($this->saveHandler, false); } else { diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index a47120f18..88509b11b 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -271,6 +271,10 @@ public function testSessionDestroy() public function testSessionGC() { + if (\PHP_VERSION_ID >= 70200) { + $this->markTestSkipped('PHP version is 7.2'); + } + $previousLifeTime = ini_set('session.gc_maxlifetime', 1000); $pdo = $this->getMemorySqlitePdo(); $storage = new PdoSessionHandler($pdo); @@ -282,10 +286,12 @@ public function testSessionGC() $storage->open('', 'sid'); $storage->read('gc_id'); + // IN 7.2 this does not work ini_set('session.gc_maxlifetime', -1); // test that you can set lifetime of a session after it has been read $storage->write('gc_id', 'data'); $storage->close(); $this->assertEquals(2, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'No session pruned because gc not called'); + $storage->destroy('gc_id'); $storage->open('', 'sid'); $data = $storage->read('gc_id'); @@ -293,7 +299,39 @@ public function testSessionGC() $storage->close(); ini_set('session.gc_maxlifetime', $previousLifeTime); + $this->assertSame('', $data, 'Session already considered garbage, so not returning data even if it is not pruned yet'); + $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'Expired session is pruned'); + } + + public function testSessionGC72() + { + if (\PHP_VERSION_ID <= 70200) { + $this->markTestSkipped('PHP version is not 7.2'); + } + + $previousLifeTime = false === headers_sent() && ini_set('session.gc_maxlifetime', 1000); + $pdo = $this->getMemorySqlitePdo(); + $storage = new PdoSessionHandler($pdo); + + $storage->open('', 'sid'); + $storage->read('id'); + $storage->write('id', 'data'); + $storage->close(); + + $storage->open('', 'sid'); + $storage->read('gc_id'); + false === headers_sent() && ini_set('session.gc_maxlifetime', -1); // test that you can set lifetime of a session after it has been read + $storage->write('gc_id', 'data'); + $storage->close(); + $this->assertEquals(2, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'No session pruned because gc not called'); + true === headers_sent() && $storage->destroy('gc_id'); + + $storage->open('', 'sid'); + $data = $storage->read('gc_id'); + $storage->gc(-1); + $storage->close(); + false === headers_sent() && ini_set('session.gc_maxlifetime', $previousLifeTime); $this->assertSame('', $data, 'Session already considered garbage, so not returning data even if it is not pruned yet'); $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'Expired session is pruned'); } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 20f9ca060..d5281c644 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -152,7 +152,7 @@ public function testDefaultSessionCacheLimiter() { $this->iniSet('session.cache_limiter', 'nocache'); - $storage = new NativeSessionStorage(); + $storage = new NativeSessionStorage(array('cache_limiter' => '')); $this->assertEquals('', ini_get('session.cache_limiter')); } From ef7a168bd5eaea517fb36f60c477a4460f722644 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 9 Oct 2017 12:39:15 +0200 Subject: [PATCH 030/225] Fix 7.2 compat layer --- Session/Storage/NativeSessionStorage.php | 33 +++++++++------ .../Storage/Handler/PdoSessionHandlerTest.php | 41 ++----------------- .../Storage/NativeSessionStorageTest.php | 2 +- 3 files changed, 25 insertions(+), 51 deletions(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 1ee6d3f34..09cb242f9 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -101,12 +101,11 @@ class NativeSessionStorage implements SessionStorageInterface */ public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) { - if (empty($options)) { - $options += array('cache_limiter' => 'public'); - } - if (1 !== (int) ini_get('session.use_cookies')) { - ini_set('session.use_cookies', 1); - } + $options += array( + // disable by default because it's managed by HeaderBag (if used) + 'cache_limiter' => '', + 'use_cookies' => 1, + ); if (\PHP_VERSION_ID >= 50400) { session_register_shutdown(); @@ -212,6 +211,10 @@ public function regenerate($destroy = false, $lifetime = null) return false; } + if (headers_sent()) { + return false; + } + if (null !== $lifetime) { ini_set('session.cookie_lifetime', $lifetime); } @@ -336,6 +339,10 @@ public function isStarted() */ public function setOptions(array $options) { + if (headers_sent()) { + return; + } + $validOptions = array_flip(array( 'cache_limiter', 'cookie_domain', 'cookie_httponly', 'cookie_lifetime', 'cookie_path', 'cookie_secure', @@ -349,11 +356,9 @@ public function setOptions(array $options) 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags', )); - if (PHP_VERSION_ID < 70200 || !headers_sent()) { - foreach ($options as $key => $value) { - if (isset($validOptions[$key])) { - ini_set('session.'.$key, $value); - } + foreach ($options as $key => $value) { + if (isset($validOptions[$key])) { + ini_set('session.'.$key, $value); } } } @@ -389,6 +394,10 @@ public function setSaveHandler($saveHandler = null) throw new \InvalidArgumentException('Must be instance of AbstractProxy or NativeSessionHandler; implement \SessionHandlerInterface; or be null.'); } + if (headers_sent($file, $line)) { + throw new \RuntimeException(sprintf('Failed to set the session handler because headers have already been sent by "%s" at line %d.', $file, $line)); + } + // Wrap $saveHandler in proxy and prevent double wrapping of proxy if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) { $saveHandler = new SessionHandlerProxy($saveHandler); @@ -398,7 +407,7 @@ public function setSaveHandler($saveHandler = null) } $this->saveHandler = $saveHandler; - if ($this->saveHandler instanceof \SessionHandlerInterface && false === headers_sent()) { + if ($this->saveHandler instanceof \SessionHandlerInterface) { if (\PHP_VERSION_ID >= 50400) { session_set_save_handler($this->saveHandler, false); } else { diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 88509b11b..a9884c1c9 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -269,12 +269,11 @@ public function testSessionDestroy() $this->assertSame('', $data, 'Destroyed session returns empty string'); } + /** + * @runInSeparateProcess + */ public function testSessionGC() { - if (\PHP_VERSION_ID >= 70200) { - $this->markTestSkipped('PHP version is 7.2'); - } - $previousLifeTime = ini_set('session.gc_maxlifetime', 1000); $pdo = $this->getMemorySqlitePdo(); $storage = new PdoSessionHandler($pdo); @@ -286,12 +285,10 @@ public function testSessionGC() $storage->open('', 'sid'); $storage->read('gc_id'); - // IN 7.2 this does not work ini_set('session.gc_maxlifetime', -1); // test that you can set lifetime of a session after it has been read $storage->write('gc_id', 'data'); $storage->close(); $this->assertEquals(2, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'No session pruned because gc not called'); - $storage->destroy('gc_id'); $storage->open('', 'sid'); $data = $storage->read('gc_id'); @@ -299,39 +296,7 @@ public function testSessionGC() $storage->close(); ini_set('session.gc_maxlifetime', $previousLifeTime); - $this->assertSame('', $data, 'Session already considered garbage, so not returning data even if it is not pruned yet'); - $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'Expired session is pruned'); - } - - public function testSessionGC72() - { - if (\PHP_VERSION_ID <= 70200) { - $this->markTestSkipped('PHP version is not 7.2'); - } - - $previousLifeTime = false === headers_sent() && ini_set('session.gc_maxlifetime', 1000); - $pdo = $this->getMemorySqlitePdo(); - $storage = new PdoSessionHandler($pdo); - - $storage->open('', 'sid'); - $storage->read('id'); - $storage->write('id', 'data'); - $storage->close(); - - $storage->open('', 'sid'); - $storage->read('gc_id'); - false === headers_sent() && ini_set('session.gc_maxlifetime', -1); // test that you can set lifetime of a session after it has been read - $storage->write('gc_id', 'data'); - $storage->close(); - $this->assertEquals(2, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'No session pruned because gc not called'); - true === headers_sent() && $storage->destroy('gc_id'); - - $storage->open('', 'sid'); - $data = $storage->read('gc_id'); - $storage->gc(-1); - $storage->close(); - false === headers_sent() && ini_set('session.gc_maxlifetime', $previousLifeTime); $this->assertSame('', $data, 'Session already considered garbage, so not returning data even if it is not pruned yet'); $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'Expired session is pruned'); } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index d5281c644..20f9ca060 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -152,7 +152,7 @@ public function testDefaultSessionCacheLimiter() { $this->iniSet('session.cache_limiter', 'nocache'); - $storage = new NativeSessionStorage(array('cache_limiter' => '')); + $storage = new NativeSessionStorage(); $this->assertEquals('', ini_get('session.cache_limiter')); } From 527c072ef5d6443ab823f8c215ea2bb1c4bc505d Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 10 Oct 2017 10:04:23 +0200 Subject: [PATCH 031/225] never match invalid IP addresses --- IpUtils.php | 4 ++++ Tests/IpUtilsTest.php | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/IpUtils.php b/IpUtils.php index dc6d3ec81..3bb33140f 100644 --- a/IpUtils.php +++ b/IpUtils.php @@ -87,6 +87,10 @@ public static function checkIp4($requestIp, $ip) $netmask = 32; } + if (false === ip2long($address)) { + return self::$checkedIps[$cacheKey] = false; + } + return self::$checkedIps[$cacheKey] = 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask); } diff --git a/Tests/IpUtilsTest.php b/Tests/IpUtilsTest.php index 297ee3d8d..54cbb5c20 100644 --- a/Tests/IpUtilsTest.php +++ b/Tests/IpUtilsTest.php @@ -82,4 +82,21 @@ public function testAnIpv6WithOptionDisabledIpv6() IpUtils::checkIp('2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'); } + + /** + * @dataProvider invalidIpAddressData + */ + public function testInvalidIpAddressesDoNotMatch($requestIp, $proxyIp) + { + $this->assertFalse(IpUtils::checkIp4($requestIp, $proxyIp)); + } + + public function invalidIpAddressData() + { + return array( + 'invalid proxy wildcard' => array('192.168.20.13', '*'), + 'invalid proxy missing netmask' => array('192.168.20.13', '0.0.0.0'), + 'invalid request IP with invalid proxy wildcard' => array('0.0.0.0', '*'), + ); + } } From b54ae1fbb0f4efd89905e814fe62e8fe75c2f3a3 Mon Sep 17 00:00:00 2001 From: "Anton A. Sumin" Date: Fri, 10 Mar 2017 23:00:21 +0300 Subject: [PATCH 032/225] Fixed pathinfo calculation for requests starting with a question mark. - fix bad conflict resolving issue - port symfony/symfony#21968 to 3.3+ --- Request.php | 8 +++++- Tests/RequestTest.php | 61 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 28e78c0a2..ac3ec7171 100644 --- a/Request.php +++ b/Request.php @@ -1863,6 +1863,9 @@ protected function prepareBaseUrl() // Does the baseUrl have anything in common with the request_uri? $requestUri = $this->getRequestUri(); + if ($requestUri !== '' && $requestUri[0] !== '/') { + $requestUri = '/'.$requestUri; + } if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { // full $baseUrl matches @@ -1935,9 +1938,12 @@ protected function preparePathInfo() } // Remove the query string from REQUEST_URI - if ($pos = strpos($requestUri, '?')) { + if (false !== $pos = strpos($requestUri, '?')) { $requestUri = substr($requestUri, 0, $pos); } + if ($requestUri !== '' && $requestUri[0] !== '/') { + $requestUri = '/'.$requestUri; + } $pathInfo = substr($requestUri, strlen($baseUrl)); if (null !== $baseUrl && (false === $pathInfo || '' === $pathInfo)) { diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index b36fbb7e9..3c123656c 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1286,6 +1286,12 @@ public function testGetPathInfo() $request->initialize(array(), array(), array(), array(), array(), $server); $this->assertEquals('/path%20test/info', $request->getPathInfo()); + + $server = array(); + $server['REQUEST_URI'] = '?a=b'; + $request->initialize(array(), array(), array(), array(), array(), $server); + + $this->assertEquals('/', $request->getPathInfo()); } public function testGetParameterPrecedence() @@ -2188,6 +2194,61 @@ public function testGetTrustedHeaderName() Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_FORWARDED_PORT'); Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_FORWARDED_PROTO'); } + + public function nonstandardRequestsData() + { + return array( + array('', '', '/', 'http://host:8080/', ''), + array('/', '', '/', 'http://host:8080/', ''), + + array('hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'), + array('/hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'), + + array('', 'a=b', '/', 'http://host:8080/?a=b'), + array('?a=b', 'a=b', '/', 'http://host:8080/?a=b'), + array('/?a=b', 'a=b', '/', 'http://host:8080/?a=b'), + + array('x', 'a=b', '/x', 'http://host:8080/x?a=b'), + array('x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'), + array('/x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'), + + array('hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'), + array('/hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'), + + array('hello/app.php/x', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'), + array('hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'), + array('/hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'), + ); + } + + /** + * @dataProvider nonstandardRequestsData + */ + public function testNonstandardRequests($requestUri, $queryString, $expectedPathInfo, $expectedUri, $expectedBasePath = '', $expectedBaseUrl = null) + { + if (null === $expectedBaseUrl) { + $expectedBaseUrl = $expectedBasePath; + } + + $server = array( + 'HTTP_HOST' => 'host:8080', + 'SERVER_PORT' => '8080', + 'QUERY_STRING' => $queryString, + 'PHP_SELF' => '/hello/app.php', + 'SCRIPT_FILENAME' => '/some/path/app.php', + 'REQUEST_URI' => $requestUri, + ); + + $request = new Request(array(), array(), array(), array(), array(), $server); + + $this->assertEquals($expectedPathInfo, $request->getPathInfo()); + $this->assertEquals($expectedUri, $request->getUri()); + $this->assertEquals($queryString, $request->getQueryString()); + $this->assertEquals(8080, $request->getPort()); + $this->assertEquals('host:8080', $request->getHttpHost()); + $this->assertEquals($expectedBaseUrl, $request->getBaseUrl()); + $this->assertEquals($expectedBasePath, $request->getBasePath()); + } } class RequestContentProxy extends Request From eafa4959f2fde1c9a94a35e4d51d6b7705bf4a15 Mon Sep 17 00:00:00 2001 From: Yuriy Potemkin Date: Mon, 16 Oct 2017 20:34:10 +0300 Subject: [PATCH 033/225] pdo session fix --- Session/Storage/Handler/PdoSessionHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 5cdac6393..daabbc21f 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -387,7 +387,7 @@ public function close() $this->gcCalled = false; // delete the session records that have expired - $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time"; + $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time - $this->timeCol"; $stmt = $this->pdo->prepare($sql); $stmt->bindValue(':time', time(), \PDO::PARAM_INT); From 55ca8d885e7e0790a24ad8b2c9253bdb68035e89 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 10 Oct 2017 11:13:08 +0200 Subject: [PATCH 034/225] [HttpFoundation] Make sessions secure and lazy --- CHANGELOG.md | 5 +- .../Handler/AbstractSessionHandler.php | 165 +++++++++++++++ .../Handler/MemcachedSessionHandler.php | 18 +- .../Storage/Handler/MongoDbSessionHandler.php | 45 +++-- .../Storage/Handler/NativeSessionHandler.php | 6 +- .../Storage/Handler/NullSessionHandler.php | 20 +- Session/Storage/Handler/PdoSessionHandler.php | 44 +++- .../Storage/Handler/StrictSessionHandler.php | 89 +++++++++ .../Handler/WriteCheckSessionHandler.php | 4 + Session/Storage/NativeSessionStorage.php | 44 ++-- Session/Storage/Proxy/AbstractProxy.php | 4 - Session/Storage/Proxy/SessionHandlerProxy.php | 4 - .../Handler/AbstractSessionHandlerTest.php | 61 ++++++ .../Storage/Handler/Fixtures/common.inc | 152 ++++++++++++++ .../Handler/Fixtures/empty_destroys.expected | 17 ++ .../Handler/Fixtures/empty_destroys.php | 8 + .../Handler/Fixtures/read_only.expected | 14 ++ .../Storage/Handler/Fixtures/read_only.php | 8 + .../Handler/Fixtures/regenerate.expected | 24 +++ .../Storage/Handler/Fixtures/regenerate.php | 10 + .../Storage/Handler/Fixtures/storage.expected | 20 ++ .../Storage/Handler/Fixtures/storage.php | 24 +++ .../Handler/Fixtures/with_cookie.expected | 15 ++ .../Storage/Handler/Fixtures/with_cookie.php | 8 + .../Handler/NativeSessionHandlerTest.php | 3 + .../Storage/Handler/PdoSessionHandlerTest.php | 3 + .../Handler/StrictSessionHandlerTest.php | 189 ++++++++++++++++++ .../Handler/WriteCheckSessionHandlerTest.php | 2 + .../Storage/NativeSessionStorageTest.php | 8 +- .../Storage/Proxy/AbstractProxyTest.php | 2 - .../Storage/Proxy/SessionHandlerProxyTest.php | 1 - composer.json | 3 +- 32 files changed, 946 insertions(+), 74 deletions(-) create mode 100644 Session/Storage/Handler/AbstractSessionHandler.php create mode 100644 Session/Storage/Handler/StrictSessionHandler.php create mode 100644 Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php create mode 100644 Tests/Session/Storage/Handler/Fixtures/common.inc create mode 100644 Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected create mode 100644 Tests/Session/Storage/Handler/Fixtures/empty_destroys.php create mode 100644 Tests/Session/Storage/Handler/Fixtures/read_only.expected create mode 100644 Tests/Session/Storage/Handler/Fixtures/read_only.php create mode 100644 Tests/Session/Storage/Handler/Fixtures/regenerate.expected create mode 100644 Tests/Session/Storage/Handler/Fixtures/regenerate.php create mode 100644 Tests/Session/Storage/Handler/Fixtures/storage.expected create mode 100644 Tests/Session/Storage/Handler/Fixtures/storage.php create mode 100644 Tests/Session/Storage/Handler/Fixtures/with_cookie.expected create mode 100644 Tests/Session/Storage/Handler/Fixtures/with_cookie.php create mode 100644 Tests/Session/Storage/Handler/StrictSessionHandlerTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 83a3c8e32..ee5b6cecf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,9 @@ CHANGELOG 3.4.0 ----- - * deprecated the `NativeSessionHandler` class, - * deprecated the `AbstractProxy`, `NativeProxy` and `SessionHandlerProxy` classes, + * implemented PHP 7.0's `SessionUpdateTimestampHandlerInterface` with a new + `AbstractSessionHandler` base class and a new `StrictSessionHandler` wrapper + * deprecated the `WriteCheckSessionHandler`, `NativeSessionHandler` and `NativeProxy` classes * deprecated setting session save handlers that do not implement `\SessionHandlerInterface` in `NativeSessionStorage::setSaveHandler()` * deprecated using `MongoDbSessionHandler` with the legacy mongo extension; use it with the mongodb/mongodb package and ext-mongodb instead * deprecated `MemcacheSessionHandler`; use `MemcachedSessionHandler` instead diff --git a/Session/Storage/Handler/AbstractSessionHandler.php b/Session/Storage/Handler/AbstractSessionHandler.php new file mode 100644 index 000000000..c20a23b20 --- /dev/null +++ b/Session/Storage/Handler/AbstractSessionHandler.php @@ -0,0 +1,165 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * This abstract session handler provides a generic implementation + * of the PHP 7.0 SessionUpdateTimestampHandlerInterface, + * enabling strict and lazy session handling. + * + * @author Nicolas Grekas + */ +abstract class AbstractSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface +{ + private $sessionName; + private $prefetchId; + private $prefetchData; + private $newSessionId; + private $igbinaryEmptyData; + + /** + * {@inheritdoc} + */ + public function open($savePath, $sessionName) + { + $this->sessionName = $sessionName; + + return true; + } + + /** + * @param string $sessionId + * + * @return string + */ + abstract protected function doRead($sessionId); + + /** + * @param string $sessionId + * @param string $data + * + * @return bool + */ + abstract protected function doWrite($sessionId, $data); + + /** + * @param string $sessionId + * + * @return bool + */ + abstract protected function doDestroy($sessionId); + + /** + * {@inheritdoc} + */ + public function validateId($sessionId) + { + $this->prefetchData = $this->read($sessionId); + $this->prefetchId = $sessionId; + + return '' !== $this->prefetchData; + } + + /** + * {@inheritdoc} + */ + public function read($sessionId) + { + if (null !== $this->prefetchId) { + $prefetchId = $this->prefetchId; + $prefetchData = $this->prefetchData; + $this->prefetchId = $this->prefetchData = null; + + if ($prefetchId === $sessionId || '' === $prefetchData) { + $this->newSessionId = '' === $prefetchData ? $sessionId : null; + + return $prefetchData; + } + } + + $data = $this->doRead($sessionId); + $this->newSessionId = '' === $data ? $sessionId : null; + if (\PHP_VERSION_ID < 70000) { + $this->prefetchData = $data; + } + + return $data; + } + + /** + * {@inheritdoc} + */ + public function write($sessionId, $data) + { + if (\PHP_VERSION_ID < 70000 && $this->prefetchData) { + $readData = $this->prefetchData; + $this->prefetchData = null; + + if ($readData === $data) { + return $this->updateTimestamp($sessionId, $data); + } + } + if (null === $this->igbinaryEmptyData) { + // see https://github.com/igbinary/igbinary/issues/146 + $this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize(array()) : ''; + } + if ('' === $data || $this->igbinaryEmptyData === $data) { + return $this->destroy($sessionId); + } + $this->newSessionId = null; + + return $this->doWrite($sessionId, $data); + } + + /** + * {@inheritdoc} + */ + public function destroy($sessionId) + { + if (\PHP_VERSION_ID < 70000) { + $this->prefetchData = null; + } + 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))); + } + $sessionCookie = sprintf(' %s=', urlencode($this->sessionName)); + $sessionCookieWithId = sprintf('%s%s;', $sessionCookie, urlencode($sessionId)); + $sessionCookieFound = false; + $otherCookies = array(); + foreach (headers_list() as $h) { + if (0 !== stripos($h, 'Set-Cookie:')) { + continue; + } + if (11 === strpos($h, $sessionCookie, 11)) { + $sessionCookieFound = true; + + if (11 !== strpos($h, $sessionCookieWithId, 11)) { + $otherCookies[] = $h; + } + } else { + $otherCookies[] = $h; + } + } + if ($sessionCookieFound) { + header_remove('Set-Cookie'); + foreach ($otherCookies as $h) { + header('Set-Cookie:'.$h, false); + } + } else { + setcookie($this->sessionName, '', 0, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly')); + } + } + + return $this->newSessionId === $sessionId || $this->doDestroy($sessionId); + } +} diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 3bbde5420..a31642cc8 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -19,7 +19,7 @@ * * @author Drak */ -class MemcachedSessionHandler implements \SessionHandlerInterface +class MemcachedSessionHandler extends AbstractSessionHandler { /** * @var \Memcached Memcached driver @@ -39,7 +39,7 @@ class MemcachedSessionHandler implements \SessionHandlerInterface /** * List of available options: * * prefix: The prefix to use for the memcached keys in order to avoid collision - * * expiretime: The time to live in seconds + * * expiretime: The time to live in seconds. * * @param \Memcached $memcached A \Memcached instance * @param array $options An associative array of Memcached options @@ -63,7 +63,7 @@ public function __construct(\Memcached $memcached, array $options = array()) /** * {@inheritdoc} */ - public function open($savePath, $sessionName) + public function close() { return true; } @@ -71,23 +71,23 @@ public function open($savePath, $sessionName) /** * {@inheritdoc} */ - public function close() + protected function doRead($sessionId) { - return true; + return $this->memcached->get($this->prefix.$sessionId) ?: ''; } /** * {@inheritdoc} */ - public function read($sessionId) + public function updateTimestamp($sessionId, $data) { - return $this->memcached->get($this->prefix.$sessionId) ?: ''; + return $this->memcached->touch($this->prefix.$sessionId, time() + $this->ttl); } /** * {@inheritdoc} */ - public function write($sessionId, $data) + protected function doWrite($sessionId, $data) { return $this->memcached->set($this->prefix.$sessionId, $data, time() + $this->ttl); } @@ -95,7 +95,7 @@ public function write($sessionId, $data) /** * {@inheritdoc} */ - public function destroy($sessionId) + protected function doDestroy($sessionId) { $result = $this->memcached->delete($this->prefix.$sessionId); diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index d532fb92c..7d770421c 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -19,7 +19,7 @@ * @see https://packagist.org/packages/mongodb/mongodb * @see http://php.net/manual/en/set.mongodb.php */ -class MongoDbSessionHandler implements \SessionHandlerInterface +class MongoDbSessionHandler extends AbstractSessionHandler { /** * @var \Mongo|\MongoClient|\MongoDB\Client @@ -43,7 +43,7 @@ class MongoDbSessionHandler implements \SessionHandlerInterface * * id_field: The field name for storing the session id [default: _id] * * data_field: The field name for storing the session data [default: data] * * time_field: The field name for storing the timestamp [default: time] - * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at] + * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]. * * It is strongly recommended to put an index on the `expiry_field` for * garbage-collection. Alternatively it's possible to automatically expire @@ -92,14 +92,6 @@ public function __construct($mongo, array $options) ), $options); } - /** - * {@inheritdoc} - */ - public function open($savePath, $sessionName) - { - return true; - } - /** * {@inheritdoc} */ @@ -111,7 +103,7 @@ public function close() /** * {@inheritdoc} */ - public function destroy($sessionId) + protected function doDestroy($sessionId) { $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove'; @@ -139,7 +131,7 @@ public function gc($maxlifetime) /** * {@inheritdoc} */ - public function write($sessionId, $data) + protected function doWrite($sessionId, $data) { $expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime')); @@ -171,7 +163,34 @@ public function write($sessionId, $data) /** * {@inheritdoc} */ - public function read($sessionId) + public function updateTimestamp($sessionId, $data) + { + $expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime')); + + if ($this->mongo instanceof \MongoDB\Client) { + $methodName = 'updateOne'; + $options = array(); + } else { + $methodName = 'update'; + $options = array('multiple' => false); + } + + $this->getCollection()->$methodName( + array($this->options['id_field'] => $sessionId), + array('$set' => array( + $this->options['time_field'] => $this->createDateTime(), + $this->options['expiry_field'] => $expiry, + )), + $options + ); + + return true; + } + + /** + * {@inheritdoc} + */ + protected function doRead($sessionId) { $dbData = $this->getCollection()->findOne(array( $this->options['id_field'] => $sessionId, diff --git a/Session/Storage/Handler/NativeSessionHandler.php b/Session/Storage/Handler/NativeSessionHandler.php index daa7dbd15..9ea4629ca 100644 --- a/Session/Storage/Handler/NativeSessionHandler.php +++ b/Session/Storage/Handler/NativeSessionHandler.php @@ -11,12 +11,14 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; -@trigger_error('The '.__NAMESPACE__.'\NativeSessionHandler class is deprecated since version 3.4 and will be removed in 4.0. Use the \SessionHandler class instead.', E_USER_DEPRECATED); - /** * @deprecated since version 3.4, to be removed in 4.0. Use \SessionHandler instead. * @see http://php.net/sessionhandler */ class NativeSessionHandler extends \SessionHandler { + public function __construct() + { + @trigger_error('The '.__NAMESPACE__.'\NativeSessionHandler class is deprecated since version 3.4 and will be removed in 4.0. Use the \SessionHandler class instead.', E_USER_DEPRECATED); + } } diff --git a/Session/Storage/Handler/NullSessionHandler.php b/Session/Storage/Handler/NullSessionHandler.php index 981d96d93..8d193155b 100644 --- a/Session/Storage/Handler/NullSessionHandler.php +++ b/Session/Storage/Handler/NullSessionHandler.php @@ -16,12 +16,12 @@ * * @author Drak */ -class NullSessionHandler implements \SessionHandlerInterface +class NullSessionHandler extends AbstractSessionHandler { /** * {@inheritdoc} */ - public function open($savePath, $sessionName) + public function close() { return true; } @@ -29,7 +29,7 @@ public function open($savePath, $sessionName) /** * {@inheritdoc} */ - public function close() + public function validateId($sessionId) { return true; } @@ -37,7 +37,7 @@ public function close() /** * {@inheritdoc} */ - public function read($sessionId) + protected function doRead($sessionId) { return ''; } @@ -45,7 +45,15 @@ public function read($sessionId) /** * {@inheritdoc} */ - public function write($sessionId, $data) + public function updateTimestamp($sessionId, $data) + { + return true; + } + + /** + * {@inheritdoc} + */ + protected function doWrite($sessionId, $data) { return true; } @@ -53,7 +61,7 @@ public function write($sessionId, $data) /** * {@inheritdoc} */ - public function destroy($sessionId) + protected function doDestroy($sessionId) { return true; } diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 5cdac6393..19bf6e9bc 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -38,7 +38,7 @@ * @author Michael Williams * @author Tobias Schultze */ -class PdoSessionHandler implements \SessionHandlerInterface +class PdoSessionHandler extends AbstractSessionHandler { /** * No locking is done. This means sessions are prone to loss of data due to @@ -260,11 +260,13 @@ public function isSessionExpired() */ public function open($savePath, $sessionName) { + $this->sessionExpired = false; + if (null === $this->pdo) { $this->connect($this->dsn ?: $savePath); } - return true; + return parent::open($savePath, $sessionName); } /** @@ -273,7 +275,7 @@ public function open($savePath, $sessionName) public function read($sessionId) { try { - return $this->doRead($sessionId); + return parent::read($sessionId); } catch (\PDOException $e) { $this->rollback(); @@ -296,7 +298,7 @@ public function gc($maxlifetime) /** * {@inheritdoc} */ - public function destroy($sessionId) + protected function doDestroy($sessionId) { // delete the record associated with this id $sql = "DELETE FROM $this->table WHERE $this->idCol = :id"; @@ -317,7 +319,7 @@ public function destroy($sessionId) /** * {@inheritdoc} */ - public function write($sessionId, $data) + protected function doWrite($sessionId, $data) { $maxlifetime = (int) ini_get('session.gc_maxlifetime'); @@ -372,6 +374,30 @@ public function write($sessionId, $data) return true; } + /** + * {@inheritdoc} + */ + public function updateTimestamp($sessionId, $data) + { + $maxlifetime = (int) ini_get('session.gc_maxlifetime'); + + try { + $updateStmt = $this->pdo->prepare( + "UPDATE $this->table SET $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id" + ); + $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); + $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT); + $updateStmt->execute(); + } catch (\PDOException $e) { + $this->rollback(); + + throw $e; + } + + return true; + } + /** * {@inheritdoc} */ @@ -491,10 +517,8 @@ private function rollback() * * @return string The session data */ - private function doRead($sessionId) + protected function doRead($sessionId) { - $this->sessionExpired = false; - if (self::LOCK_ADVISORY === $this->lockMode) { $this->unlockStatements[] = $this->doAdvisoryLock($sessionId); } @@ -517,7 +541,9 @@ private function doRead($sessionId) return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; } - if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { + if (!ini_get('session.use_strict_mode') && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { + // In strict mode, session fixation is not possible: new sessions always start with a unique + // random id, so that concurrency is not possible and this code path can be skipped. // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block // until other connections to the session are committed. try { diff --git a/Session/Storage/Handler/StrictSessionHandler.php b/Session/Storage/Handler/StrictSessionHandler.php new file mode 100644 index 000000000..1bad0641e --- /dev/null +++ b/Session/Storage/Handler/StrictSessionHandler.php @@ -0,0 +1,89 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; + +/** + * Adds basic `SessionUpdateTimestampHandlerInterface` behaviors to another `SessionHandlerInterface`. + * + * @author Nicolas Grekas + */ +class StrictSessionHandler extends AbstractSessionHandler +{ + private $handler; + + 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)); + } + + $this->handler = $handler; + } + + /** + * {@inheritdoc} + */ + public function open($savePath, $sessionName) + { + parent::open($savePath, $sessionName); + + return $this->handler->open($savePath, $sessionName); + } + + /** + * {@inheritdoc} + */ + protected function doRead($sessionId) + { + return $this->handler->read($sessionId); + } + + /** + * {@inheritdoc} + */ + public function updateTimestamp($sessionId, $data) + { + return $this->write($sessionId, $data); + } + + /** + * {@inheritdoc} + */ + protected function doWrite($sessionId, $data) + { + return $this->handler->write($sessionId, $data); + } + + /** + * {@inheritdoc} + */ + protected function doDestroy($sessionId) + { + return $this->handler->destroy($sessionId); + } + + /** + * {@inheritdoc} + */ + public function close() + { + return $this->handler->close(); + } + + /** + * {@inheritdoc} + */ + public function gc($maxlifetime) + { + return $this->handler->gc($maxlifetime); + } +} diff --git a/Session/Storage/Handler/WriteCheckSessionHandler.php b/Session/Storage/Handler/WriteCheckSessionHandler.php index d49c36cae..638a63307 100644 --- a/Session/Storage/Handler/WriteCheckSessionHandler.php +++ b/Session/Storage/Handler/WriteCheckSessionHandler.php @@ -11,10 +11,14 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; +@trigger_error(sprintf('The %s class is deprecated since version 3.4 and will be removed in 4.0. Implement `SessionUpdateTimestampHandlerInterface` or extend `AbstractSessionHandler` instead.', WriteCheckSessionHandler::class), E_USER_DEPRECATED); + /** * Wraps another SessionHandlerInterface to only write the session when it has been modified. * * @author Adrien Brault + * + * @deprecated since version 3.4, to be removed in 4.0. Implement `SessionUpdateTimestampHandlerInterface` or extend `AbstractSessionHandler` instead. */ class WriteCheckSessionHandler implements \SessionHandlerInterface { diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 623d38721..092d21830 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -11,8 +11,8 @@ namespace Symfony\Component\HttpFoundation\Session\Storage; -use Symfony\Component\Debug\Exception\ContextErrorException; use Symfony\Component\HttpFoundation\Session\SessionBagInterface; +use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; @@ -26,7 +26,7 @@ class NativeSessionStorage implements SessionStorageInterface /** * @var SessionBagInterface[] */ - protected $bags; + protected $bags = array(); /** * @var bool @@ -100,9 +100,9 @@ class NativeSessionStorage implements SessionStorageInterface public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) { $options += array( - // disable by default because it's managed by HeaderBag (if used) - 'cache_limiter' => '', + 'cache_limiter' => 'private_no_expire', 'use_cookies' => 1, + 'lazy_write' => 1, ); session_register_shutdown(); @@ -217,15 +217,31 @@ public function regenerate($destroy = false, $lifetime = null) */ public function save() { + $session = $_SESSION; + + foreach ($this->bags as $bag) { + if (empty($_SESSION[$key = $bag->getStorageKey()])) { + unset($_SESSION[$key]); + } + } + if (array($key = $this->metadataBag->getStorageKey()) === array_keys($_SESSION)) { + unset($_SESSION[$key]); + } + // Register custom error handler to catch a possible failure warning during session write - set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { - throw new ContextErrorException($errstr, $errno, E_WARNING, $errfile, $errline, $errcontext); + set_error_handler(function ($errno, $errstr, $errfile, $errline) { + throw new \ErrorException($errstr, $errno, E_WARNING, $errfile, $errline); }, E_WARNING); try { + $e = null; session_write_close(); + } catch (\ErrorException $e) { + } finally { restore_error_handler(); - } catch (ContextErrorException $e) { + $_SESSION = $session; + } + if (null !== $e) { // The default PHP error message is not very helpful, as it does not give any information on the current save handler. // Therefore, we catch this error and trigger a warning with a better error message $handler = $this->getSaveHandler(); @@ -233,7 +249,6 @@ public function save() $handler = $handler->getHandler(); } - restore_error_handler(); trigger_error(sprintf('session_write_close(): Failed to write session data with %s handler', get_class($handler)), E_USER_WARNING); } @@ -386,13 +401,6 @@ public function setSaveHandler($saveHandler = null) throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.'); } - if ($saveHandler instanceof AbstractProxy) { - @trigger_error( - 'Using session save handlers that are instances of AbstractProxy is deprecated since version 3.4 and will be removed in 4.0.', - E_USER_DEPRECATED - ); - } - if (headers_sent($file, $line)) { throw new \RuntimeException(sprintf('Failed to set the session handler because headers have already been sent by "%s" at line %d.', $file, $line)); } @@ -401,11 +409,13 @@ public function setSaveHandler($saveHandler = null) if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) { $saveHandler = new SessionHandlerProxy($saveHandler); } elseif (!$saveHandler instanceof AbstractProxy) { - $saveHandler = new SessionHandlerProxy(new \SessionHandler()); + $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler())); } $this->saveHandler = $saveHandler; - if ($this->saveHandler instanceof \SessionHandlerInterface) { + 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); } } diff --git a/Session/Storage/Proxy/AbstractProxy.php b/Session/Storage/Proxy/AbstractProxy.php index c1c8b9b1f..09c92483c 100644 --- a/Session/Storage/Proxy/AbstractProxy.php +++ b/Session/Storage/Proxy/AbstractProxy.php @@ -11,11 +11,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; -@trigger_error('The '.__NAMESPACE__.'\AbstractProxy class is deprecated since version 3.4 and will be removed in 4.0. Use your session handler implementation directly.', E_USER_DEPRECATED); - /** - * @deprecated since version 3.4, to be removed in 4.0. Use your session handler implementation directly. - * * @author Drak */ abstract class AbstractProxy diff --git a/Session/Storage/Proxy/SessionHandlerProxy.php b/Session/Storage/Proxy/SessionHandlerProxy.php index d6adef82d..359bb877b 100644 --- a/Session/Storage/Proxy/SessionHandlerProxy.php +++ b/Session/Storage/Proxy/SessionHandlerProxy.php @@ -11,11 +11,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; -@trigger_error('The '.__NAMESPACE__.'\SessionHandlerProxy class is deprecated since version 3.4 and will be removed in 4.0. Use your session handler implementation directly.', E_USER_DEPRECATED); - /** - * @deprecated since version 3.4, to be removed in 4.0. Use your session handler implementation directly. - * * @author Drak */ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface diff --git a/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php new file mode 100644 index 000000000..3ac081e38 --- /dev/null +++ b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; + +use PHPUnit\Framework\TestCase; + +/** + * @requires PHP 7.0 + */ +class AbstractSessionHandlerTest extends TestCase +{ + private static $server; + + public static function setUpBeforeClass() + { + $spec = array( + 1 => array('file', '/dev/null', 'w'), + 2 => array('file', '/dev/null', 'w'), + ); + if (!self::$server = @proc_open('exec php -S localhost:8053', $spec, $pipes, __DIR__.'/Fixtures')) { + self::markTestSkipped('PHP server unable to start.'); + } + sleep(1); + } + + public static function tearDownAfterClass() + { + if (self::$server) { + proc_terminate(self::$server); + proc_close(self::$server); + } + } + + /** + * @dataProvider provideSession + */ + public function testSession($fixture) + { + $context = array('http' => array('header' => "Cookie: sid=123abc\r\n")); + $context = stream_context_create($context); + $result = file_get_contents(sprintf('http://localhost:8053/%s.php', $fixture), false, $context); + + $this->assertStringEqualsFile(__DIR__.sprintf('/Fixtures/%s.expected', $fixture), $result); + } + + public function provideSession() + { + foreach (glob(__DIR__.'/Fixtures/*.php') as $file) { + yield array(pathinfo($file, PATHINFO_FILENAME)); + } + } +} diff --git a/Tests/Session/Storage/Handler/Fixtures/common.inc b/Tests/Session/Storage/Handler/Fixtures/common.inc new file mode 100644 index 000000000..5c183acff --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/common.inc @@ -0,0 +1,152 @@ +data = $data; + } + + public function open($path, $name) + { + echo __FUNCTION__, "\n"; + + return parent::open($path, $name); + } + + public function validateId($sessionId) + { + echo __FUNCTION__, "\n"; + + return parent::validateId($sessionId); + } + + /** + * {@inheritdoc} + */ + public function read($sessionId) + { + echo __FUNCTION__, "\n"; + + return parent::read($sessionId); + } + + /** + * {@inheritdoc} + */ + public function updateTimestamp($sessionId, $data) + { + echo __FUNCTION__, "\n"; + + return true; + } + + /** + * {@inheritdoc} + */ + public function write($sessionId, $data) + { + echo __FUNCTION__, "\n"; + + return parent::write($sessionId, $data); + } + + /** + * {@inheritdoc} + */ + public function destroy($sessionId) + { + echo __FUNCTION__, "\n"; + + return parent::destroy($sessionId); + } + + public function close() + { + echo __FUNCTION__, "\n"; + + return true; + } + + public function gc($maxLifetime) + { + echo __FUNCTION__, "\n"; + + return true; + } + + protected function doRead($sessionId) + { + echo __FUNCTION__.': ', $this->data, "\n"; + + return $this->data; + } + + protected function doWrite($sessionId, $data) + { + echo __FUNCTION__.': ', $data, "\n"; + + return true; + } + + protected function doDestroy($sessionId) + { + echo __FUNCTION__, "\n"; + + return true; + } +} diff --git a/Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected b/Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected new file mode 100644 index 000000000..1720bf055 --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected @@ -0,0 +1,17 @@ +open +validateId +read +doRead: abc|i:123; +read + +write +destroy +doDestroy +close +Array +( + [0] => Content-Type: text/plain; charset=utf-8 + [1] => Cache-Control: private, max-age=10800 + [2] => Set-Cookie: sid=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; secure; HttpOnly +) +shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/empty_destroys.php b/Tests/Session/Storage/Handler/Fixtures/empty_destroys.php new file mode 100644 index 000000000..3cfc1250a --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/empty_destroys.php @@ -0,0 +1,8 @@ + Content-Type: text/plain; charset=utf-8 + [1] => Cache-Control: private, max-age=10800 +) +shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/read_only.php b/Tests/Session/Storage/Handler/Fixtures/read_only.php new file mode 100644 index 000000000..3e62fb9ec --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/read_only.php @@ -0,0 +1,8 @@ + Content-Type: text/plain; charset=utf-8 + [1] => Cache-Control: private, max-age=10800 + [2] => Set-Cookie: sid=random_session_id; path=/; secure; HttpOnly +) +shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/regenerate.php b/Tests/Session/Storage/Handler/Fixtures/regenerate.php new file mode 100644 index 000000000..a0f635c87 --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/regenerate.php @@ -0,0 +1,10 @@ + bar +) +$_SESSION is not empty +write +destroy +close +$_SESSION is not empty +Array +( + [0] => Content-Type: text/plain; charset=utf-8 + [1] => Cache-Control: private, max-age=10800 +) +shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/storage.php b/Tests/Session/Storage/Handler/Fixtures/storage.php new file mode 100644 index 000000000..96dca3c2c --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/storage.php @@ -0,0 +1,24 @@ +setSaveHandler(new TestSessionHandler()); +$flash = new FlashBag(); +$storage->registerBag($flash); +$storage->start(); + +$flash->add('foo', 'bar'); + +print_r($flash->get('foo')); +echo empty($_SESSION) ? '$_SESSION is empty' : '$_SESSION is not empty'; +echo "\n"; + +$storage->save(); + +echo empty($_SESSION) ? '$_SESSION is empty' : '$_SESSION is not empty'; + +ob_start(function ($buffer) { return str_replace(session_id(), 'random_session_id', $buffer); }); diff --git a/Tests/Session/Storage/Handler/Fixtures/with_cookie.expected b/Tests/Session/Storage/Handler/Fixtures/with_cookie.expected new file mode 100644 index 000000000..47ae4da82 --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/with_cookie.expected @@ -0,0 +1,15 @@ +open +validateId +read +doRead: abc|i:123; +read + +updateTimestamp +close +Array +( + [0] => Content-Type: text/plain; charset=utf-8 + [1] => Cache-Control: private, max-age=10800 + [2] => Set-Cookie: abc=def +) +shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/with_cookie.php b/Tests/Session/Storage/Handler/Fixtures/with_cookie.php new file mode 100644 index 000000000..ffb5b20a3 --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/with_cookie.php @@ -0,0 +1,8 @@ +markTestSkipped('PHPUnit_MockObject cannot mock the PDOStatement class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); } + if (ini_get('session.use_strict_mode')) { + $this->markTestSkipped('Strict mode needs no locking for new sessions.'); + } $pdo = new MockPdo('pgsql'); $selectStmt = $this->getMockBuilder('PDOStatement')->getMock(); diff --git a/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php b/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php new file mode 100644 index 000000000..9d2c1949f --- /dev/null +++ b/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php @@ -0,0 +1,189 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpFoundation\Session\Storage\Handler\AbstractSessionHandler; +use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler; + +class StrictSessionHandlerTest extends TestCase +{ + public function testOpen() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('open') + ->with('path', 'name')->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertInstanceof('SessionUpdateTimestampHandlerInterface', $proxy); + $this->assertInstanceof(AbstractSessionHandler::class, $proxy); + $this->assertTrue($proxy->open('path', 'name')); + } + + public function testCloseSession() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('close') + ->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->close()); + } + + public function testValidateIdOK() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn('data'); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->validateId('id')); + } + + public function testValidateIdKO() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn(''); + $proxy = new StrictSessionHandler($handler); + + $this->assertFalse($proxy->validateId('id')); + } + + public function testRead() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn('data'); + $proxy = new StrictSessionHandler($handler); + + $this->assertSame('data', $proxy->read('id')); + } + + public function testReadWithValidateIdOK() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn('data'); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->validateId('id')); + $this->assertSame('data', $proxy->read('id')); + } + + public function testReadWithValidateIdMismatch() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->exactly(2))->method('read') + ->withConsecutive(array('id1'), array('id2')) + ->will($this->onConsecutiveCalls('data1', 'data2')); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->validateId('id1')); + $this->assertSame('data2', $proxy->read('id2')); + } + + public function testUpdateTimestamp() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('write') + ->with('id', 'data')->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->updateTimestamp('id', 'data')); + } + + public function testWrite() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('write') + ->with('id', 'data')->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->write('id', 'data')); + } + + public function testWriteEmptyNewSession() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn(''); + $handler->expects($this->never())->method('write'); + $handler->expects($this->never())->method('destroy'); + $proxy = new StrictSessionHandler($handler); + + $this->assertFalse($proxy->validateId('id')); + $this->assertSame('', $proxy->read('id')); + $this->assertTrue($proxy->write('id', '')); + } + + public function testWriteEmptyExistingSession() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn('data'); + $handler->expects($this->never())->method('write'); + $handler->expects($this->once())->method('destroy')->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertSame('data', $proxy->read('id')); + $this->assertTrue($proxy->write('id', '')); + } + + public function testDestroy() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('destroy') + ->with('id')->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->destroy('id')); + } + + public function testDestroyNewSession() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn(''); + $handler->expects($this->never())->method('destroy'); + $proxy = new StrictSessionHandler($handler); + + $this->assertSame('', $proxy->read('id')); + $this->assertTrue($proxy->destroy('id')); + } + + public function testDestroyNonEmptyNewSession() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('read') + ->with('id')->willReturn(''); + $handler->expects($this->once())->method('write') + ->with('id', 'data')->willReturn(true); + $handler->expects($this->once())->method('destroy') + ->with('id')->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertSame('', $proxy->read('id')); + $this->assertTrue($proxy->write('id', 'data')); + $this->assertTrue($proxy->destroy('id')); + } + + public function testGc() + { + $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); + $handler->expects($this->once())->method('gc') + ->with(123)->willReturn(true); + $proxy = new StrictSessionHandler($handler); + + $this->assertTrue($proxy->gc(123)); + } +} diff --git a/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php b/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php index 5e41a4743..898a7d11a 100644 --- a/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php @@ -16,6 +16,8 @@ /** * @author Adrien Brault + * + * @group legacy */ class WriteCheckSessionHandlerTest extends TestCase { diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 818c63a9d..93de175fd 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -14,7 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; -use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler; +use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; @@ -152,7 +152,7 @@ public function testDefaultSessionCacheLimiter() $this->iniSet('session.cache_limiter', 'nocache'); $storage = new NativeSessionStorage(); - $this->assertEquals('', ini_get('session.cache_limiter')); + $this->assertEquals('private_no_expire', ini_get('session.cache_limiter')); } public function testExplicitSessionCacheLimiter() @@ -201,9 +201,9 @@ public function testSetSaveHandler() $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); $storage->setSaveHandler(null); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); - $storage->setSaveHandler(new SessionHandlerProxy(new NativeSessionHandler())); + $storage->setSaveHandler(new SessionHandlerProxy(new NativeFileSessionHandler())); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); - $storage->setSaveHandler(new NativeSessionHandler()); + $storage->setSaveHandler(new NativeFileSessionHandler()); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); $storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler())); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); diff --git a/Tests/Session/Storage/Proxy/AbstractProxyTest.php b/Tests/Session/Storage/Proxy/AbstractProxyTest.php index f2be722c8..cbb291f19 100644 --- a/Tests/Session/Storage/Proxy/AbstractProxyTest.php +++ b/Tests/Session/Storage/Proxy/AbstractProxyTest.php @@ -18,8 +18,6 @@ /** * Test class for AbstractProxy. * - * @group legacy - * * @author Drak */ class AbstractProxyTest extends TestCase diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index fdd1dae25..682825356 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -21,7 +21,6 @@ * * @runTestsInSeparateProcesses * @preserveGlobalState disabled - * @group legacy */ class SessionHandlerProxyTest extends TestCase { diff --git a/composer.json b/composer.json index 4f13511e9..f6c6f2e62 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ ], "require": { "php": "^5.5.9|>=7.0.8", - "symfony/polyfill-mbstring": "~1.1" + "symfony/polyfill-mbstring": "~1.1", + "symfony/polyfill-php70": "~1.6" }, "require-dev": { "symfony/expression-language": "~2.8|~3.0|~4.0" From d8aad9b7460a1368e017c5d8efb275b119664fd5 Mon Sep 17 00:00:00 2001 From: DQNEO Date: Thu, 19 Oct 2017 20:55:56 +0900 Subject: [PATCH 035/225] content can be a resource --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index f9d7895db..b987c5b90 100644 --- a/Request.php +++ b/Request.php @@ -130,7 +130,7 @@ class Request public $headers; /** - * @var string + * @var string|resource */ protected $content; From 933e5778b051cfeac8be681f474e827749e4ea44 Mon Sep 17 00:00:00 2001 From: DQNEO Date: Thu, 19 Oct 2017 20:43:06 +0900 Subject: [PATCH 036/225] $isClientIpsVali is not used --- Request.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Request.php b/Request.php index ac3ec7171..494790477 100644 --- a/Request.php +++ b/Request.php @@ -221,7 +221,6 @@ class Request protected static $requestFactory; private $isHostValid = true; - private $isClientIpsValid = true; private $isForwardedValid = true; private static $trustedHeaderSet = -1; From 0f15654825f2f60f0b96329836114c0dee2092d2 Mon Sep 17 00:00:00 2001 From: DQNEO Date: Thu, 19 Oct 2017 22:42:56 +0900 Subject: [PATCH 037/225] streamed response should return $this --- StreamedResponse.php | 8 +++++--- Tests/StreamedResponseTest.php | 11 +++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/StreamedResponse.php b/StreamedResponse.php index d6b7b9e53..01e8cf8c3 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -83,12 +83,12 @@ public function setCallback($callback) public function sendHeaders() { if ($this->headersSent) { - return; + return $this; } $this->headersSent = true; - parent::sendHeaders(); + return parent::sendHeaders(); } /** @@ -99,7 +99,7 @@ public function sendHeaders() public function sendContent() { if ($this->streamed) { - return; + return $this; } $this->streamed = true; @@ -109,6 +109,8 @@ public function sendContent() } call_user_func($this->callback); + + return $this; } /** diff --git a/Tests/StreamedResponseTest.php b/Tests/StreamedResponseTest.php index 587414534..2ccb6841a 100644 --- a/Tests/StreamedResponseTest.php +++ b/Tests/StreamedResponseTest.php @@ -121,4 +121,15 @@ public function testCreate() $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response); $this->assertEquals(204, $response->getStatusCode()); } + + public function testReturnThis() + { + $response = new StreamedResponse(function () {}); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response->sendContent()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response->sendContent()); + + $response = new StreamedResponse(function () {}); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response->sendHeaders()); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response->sendHeaders()); + } } From 8d5978cd55aedab286aee527363a69faf9d7c2f5 Mon Sep 17 00:00:00 2001 From: DQNEO Date: Thu, 19 Oct 2017 21:29:08 +0900 Subject: [PATCH 038/225] declare argument type --- AcceptHeader.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AcceptHeader.php b/AcceptHeader.php index 99be6768f..c6fd85f94 100644 --- a/AcceptHeader.php +++ b/AcceptHeader.php @@ -153,7 +153,7 @@ public function first() private function sort() { if (!$this->sorted) { - uasort($this->items, function ($a, $b) { + uasort($this->items, function (AcceptHeaderItem $a, AcceptHeaderItem $b) { $qA = $a->getQuality(); $qB = $b->getQuality(); From 6985cabd9e8ab4c7ab3b4a8143f316eb4013f5e1 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sun, 22 Oct 2017 09:42:21 -0700 Subject: [PATCH 039/225] [DI] minor docblock fixes --- AcceptHeader.php | 2 -- File/MimeType/ExtensionGuesser.php | 2 -- File/MimeType/MimeTypeExtensionGuesser.php | 2 -- File/MimeType/MimeTypeGuesser.php | 2 -- FileBag.php | 2 -- ParameterBag.php | 2 -- RequestMatcherInterface.php | 2 -- Response.php | 6 ------ ResponseHeaderBag.php | 19 ------------------- Session/Attribute/AttributeBag.php | 7 ------- Session/Flash/AutoExpireFlashBag.php | 12 ------------ Session/Flash/FlashBag.php | 12 ------------ Session/Flash/FlashBagInterface.php | 2 -- Session/SessionBagInterface.php | 2 -- Session/SessionInterface.php | 2 -- Session/Storage/MockArraySessionStorage.php | 10 ---------- Session/Storage/NativeSessionStorage.php | 7 ------- Session/Storage/SessionStorageInterface.php | 2 -- Tests/Session/Attribute/AttributeBagTest.php | 5 +---- .../Attribute/NamespacedAttributeBagTest.php | 5 +---- .../Session/Flash/AutoExpireFlashBagTest.php | 3 --- Tests/Session/Flash/FlashBagTest.php | 3 --- Tests/Session/Storage/MetadataBagTest.php | 3 --- .../Storage/NativeSessionStorageTest.php | 2 -- 24 files changed, 2 insertions(+), 114 deletions(-) diff --git a/AcceptHeader.php b/AcceptHeader.php index c6fd85f94..d1740266b 100644 --- a/AcceptHeader.php +++ b/AcceptHeader.php @@ -97,8 +97,6 @@ public function get($value) /** * Adds an item. * - * @param AcceptHeaderItem $item - * * @return $this */ public function add(AcceptHeaderItem $item) diff --git a/File/MimeType/ExtensionGuesser.php b/File/MimeType/ExtensionGuesser.php index 921751f6b..263fb321c 100644 --- a/File/MimeType/ExtensionGuesser.php +++ b/File/MimeType/ExtensionGuesser.php @@ -65,8 +65,6 @@ private function __construct() * Registers a new extension guesser. * * When guessing, this guesser is preferred over previously registered ones. - * - * @param ExtensionGuesserInterface $guesser */ public function register(ExtensionGuesserInterface $guesser) { diff --git a/File/MimeType/MimeTypeExtensionGuesser.php b/File/MimeType/MimeTypeExtensionGuesser.php index 17fd344b8..49c323c1f 100644 --- a/File/MimeType/MimeTypeExtensionGuesser.php +++ b/File/MimeType/MimeTypeExtensionGuesser.php @@ -23,8 +23,6 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface * This list has been updated from upstream on 2013-04-23. * * @see http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - * - * @var array */ protected $defaultExtensions = array( 'application/andrew-inset' => 'ez', diff --git a/File/MimeType/MimeTypeGuesser.php b/File/MimeType/MimeTypeGuesser.php index 69c803b49..e3ef45ef6 100644 --- a/File/MimeType/MimeTypeGuesser.php +++ b/File/MimeType/MimeTypeGuesser.php @@ -93,8 +93,6 @@ private function __construct() * Registers a new mime type guesser. * * When guessing, this guesser is preferred over previously registered ones. - * - * @param MimeTypeGuesserInterface $guesser */ public function register(MimeTypeGuesserInterface $guesser) { diff --git a/FileBag.php b/FileBag.php index 722ec2a9c..a43ea1476 100644 --- a/FileBag.php +++ b/FileBag.php @@ -106,8 +106,6 @@ protected function convertFileInformation($file) * It's safe to pass an already converted array, in which case this method * just returns the original array unmodified. * - * @param array $data - * * @return array */ protected function fixPhpFilesArray($data) diff --git a/ParameterBag.php b/ParameterBag.php index 77b05a900..4b58d1c37 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -20,8 +20,6 @@ class ParameterBag implements \IteratorAggregate, \Countable { /** * Parameter storage. - * - * @var array */ protected $parameters; diff --git a/RequestMatcherInterface.php b/RequestMatcherInterface.php index 066e7e8bf..c26db3e6f 100644 --- a/RequestMatcherInterface.php +++ b/RequestMatcherInterface.php @@ -21,8 +21,6 @@ interface RequestMatcherInterface /** * Decides whether the rule(s) implemented by the strategy matches the supplied request. * - * @param Request $request The request to check for a match - * * @return bool true if the request matches, false otherwise */ public function matches(Request $request); diff --git a/Response.php b/Response.php index 4c94ea2e3..a98a37723 100644 --- a/Response.php +++ b/Response.php @@ -258,8 +258,6 @@ public function __clone() * compliant with RFC 2616. Most of the changes are based on * the Request that is "associated" with this Response. * - * @param Request $request A Request instance - * * @return $this */ public function prepare(Request $request) @@ -616,8 +614,6 @@ public function getDate() /** * Sets the Date header. * - * @param \DateTime $date A \DateTime instance - * * @return $this */ public function setDate(\DateTime $date) @@ -992,8 +988,6 @@ public function setVary($headers, $replace = true) * If the Response is not modified, it sets the status code to 304 and * removes the actual content by calling the setNotModified() method. * - * @param Request $request A Request instance - * * @return bool true if the Response validators match the Request, false otherwise */ public function isNotModified(Request $request) diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index 32e718785..a042328ca 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -24,24 +24,10 @@ class ResponseHeaderBag extends HeaderBag const DISPOSITION_ATTACHMENT = 'attachment'; const DISPOSITION_INLINE = 'inline'; - /** - * @var array - */ protected $computedCacheControl = array(); - - /** - * @var array - */ protected $cookies = array(); - - /** - * @var array - */ protected $headerNames = array(); - /** - * @param array $headers An array of HTTP headers - */ public function __construct(array $headers = array()) { parent::__construct($headers); @@ -140,11 +126,6 @@ public function getCacheControlDirective($key) return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null; } - /** - * Sets a cookie. - * - * @param Cookie $cookie - */ public function setCookie(Cookie $cookie) { $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie; diff --git a/Session/Attribute/AttributeBag.php b/Session/Attribute/AttributeBag.php index 57c297197..ea1fda290 100644 --- a/Session/Attribute/AttributeBag.php +++ b/Session/Attribute/AttributeBag.php @@ -17,15 +17,8 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Countable { private $name = 'attributes'; - - /** - * @var string - */ private $storageKey; - /** - * @var array - */ protected $attributes = array(); /** diff --git a/Session/Flash/AutoExpireFlashBag.php b/Session/Flash/AutoExpireFlashBag.php index 8110aee0c..59ba30900 100644 --- a/Session/Flash/AutoExpireFlashBag.php +++ b/Session/Flash/AutoExpireFlashBag.php @@ -19,19 +19,7 @@ class AutoExpireFlashBag implements FlashBagInterface { private $name = 'flashes'; - - /** - * Flash messages. - * - * @var array - */ private $flashes = array('display' => array(), 'new' => array()); - - /** - * The storage key for flashes in the session. - * - * @var string - */ private $storageKey; /** diff --git a/Session/Flash/FlashBag.php b/Session/Flash/FlashBag.php index a4159cd82..f533a755d 100644 --- a/Session/Flash/FlashBag.php +++ b/Session/Flash/FlashBag.php @@ -21,19 +21,7 @@ class FlashBag implements FlashBagInterface, \IteratorAggregate { private $name = 'flashes'; - - /** - * Flash messages. - * - * @var array - */ private $flashes = array(); - - /** - * The storage key for flashes in the session. - * - * @var string - */ private $storageKey; /** diff --git a/Session/Flash/FlashBagInterface.php b/Session/Flash/FlashBagInterface.php index 25f3d57b5..80e97f17c 100644 --- a/Session/Flash/FlashBagInterface.php +++ b/Session/Flash/FlashBagInterface.php @@ -72,8 +72,6 @@ public function all(); /** * Sets all flash messages. - * - * @param array $messages */ public function setAll(array $messages); diff --git a/Session/SessionBagInterface.php b/Session/SessionBagInterface.php index aca18aacb..8e37d06d6 100644 --- a/Session/SessionBagInterface.php +++ b/Session/SessionBagInterface.php @@ -27,8 +27,6 @@ public function getName(); /** * Initializes the Bag. - * - * @param array $array */ public function initialize(array &$array); diff --git a/Session/SessionInterface.php b/Session/SessionInterface.php index 172c9b457..95fca857e 100644 --- a/Session/SessionInterface.php +++ b/Session/SessionInterface.php @@ -159,8 +159,6 @@ public function isStarted(); /** * Registers a SessionBagInterface with the session. - * - * @param SessionBagInterface $bag */ public function registerBag(SessionBagInterface $bag); diff --git a/Session/Storage/MockArraySessionStorage.php b/Session/Storage/MockArraySessionStorage.php index 0349a4336..027f4efff 100644 --- a/Session/Storage/MockArraySessionStorage.php +++ b/Session/Storage/MockArraySessionStorage.php @@ -72,11 +72,6 @@ public function __construct($name = 'MOCKSESSID', MetadataBag $metaBag = null) $this->setMetadataBag($metaBag); } - /** - * Sets the session data. - * - * @param array $array - */ public function setSessionData(array $array) { $this->data = $array; @@ -213,11 +208,6 @@ public function isStarted() return $this->started; } - /** - * Sets the MetadataBag. - * - * @param MetadataBag $bag - */ public function setMetadataBag(MetadataBag $bag = null) { if (null === $bag) { diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 93c223436..76654d26f 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -296,11 +296,6 @@ public function getBag($name) return $this->bags[$name]; } - /** - * Sets the MetadataBag. - * - * @param MetadataBag $metaBag - */ public function setMetadataBag(MetadataBag $metaBag = null) { if (null === $metaBag) { @@ -431,8 +426,6 @@ public function setSaveHandler($saveHandler = null) * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()). * PHP takes the return value from the read() handler, unserializes it * and populates $_SESSION with the result automatically. - * - * @param array|null $session */ protected function loadSession(array &$session = null) { diff --git a/Session/Storage/SessionStorageInterface.php b/Session/Storage/SessionStorageInterface.php index 097583d5a..66e8b33dd 100644 --- a/Session/Storage/SessionStorageInterface.php +++ b/Session/Storage/SessionStorageInterface.php @@ -127,8 +127,6 @@ public function getBag($name); /** * Registers a SessionBagInterface for use. - * - * @param SessionBagInterface $bag */ public function registerBag(SessionBagInterface $bag); diff --git a/Tests/Session/Attribute/AttributeBagTest.php b/Tests/Session/Attribute/AttributeBagTest.php index 8c148b58f..655c26a9c 100644 --- a/Tests/Session/Attribute/AttributeBagTest.php +++ b/Tests/Session/Attribute/AttributeBagTest.php @@ -21,10 +21,7 @@ */ class AttributeBagTest extends TestCase { - /** - * @var array - */ - private $array; + private $array = array(); /** * @var AttributeBag diff --git a/Tests/Session/Attribute/NamespacedAttributeBagTest.php b/Tests/Session/Attribute/NamespacedAttributeBagTest.php index d9d9eb7fb..f074ce1b2 100644 --- a/Tests/Session/Attribute/NamespacedAttributeBagTest.php +++ b/Tests/Session/Attribute/NamespacedAttributeBagTest.php @@ -21,10 +21,7 @@ */ class NamespacedAttributeBagTest extends TestCase { - /** - * @var array - */ - private $array; + private $array = array(); /** * @var NamespacedAttributeBag diff --git a/Tests/Session/Flash/AutoExpireFlashBagTest.php b/Tests/Session/Flash/AutoExpireFlashBagTest.php index 4eb200afa..18b71a502 100644 --- a/Tests/Session/Flash/AutoExpireFlashBagTest.php +++ b/Tests/Session/Flash/AutoExpireFlashBagTest.php @@ -26,9 +26,6 @@ class AutoExpireFlashBagTest extends TestCase */ private $bag; - /** - * @var array - */ protected $array = array(); protected function setUp() diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index 3de224603..b44429d89 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -26,9 +26,6 @@ class FlashBagTest extends TestCase */ private $bag; - /** - * @var array - */ protected $array = array(); protected function setUp() diff --git a/Tests/Session/Storage/MetadataBagTest.php b/Tests/Session/Storage/MetadataBagTest.php index 159e62114..69cf6163c 100644 --- a/Tests/Session/Storage/MetadataBagTest.php +++ b/Tests/Session/Storage/MetadataBagTest.php @@ -26,9 +26,6 @@ class MetadataBagTest extends TestCase */ protected $bag; - /** - * @var array - */ protected $array = array(); protected function setUp() diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 20f9ca060..7eda5b3a3 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -55,8 +55,6 @@ protected function tearDown() } /** - * @param array $options - * * @return NativeSessionStorage */ protected function getStorage(array $options = array()) From 821c834650e5f699377d599c76d24d3778119ed6 Mon Sep 17 00:00:00 2001 From: Rudy Onfroy Date: Tue, 24 Oct 2017 20:35:27 +0200 Subject: [PATCH 040/225] fix the phpdoc that is not really inherited from response --- RedirectResponse.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/RedirectResponse.php b/RedirectResponse.php index 4118fff24..23eb04a19 100644 --- a/RedirectResponse.php +++ b/RedirectResponse.php @@ -44,7 +44,13 @@ public function __construct($url, $status = 302, $headers = array()) } /** - * {@inheritdoc} + * Factory method for chainability. + * + * @param string $url The url to redirect to + * @param int $status The response status code + * @param array $headers An array of response headers + * + * @return static */ public static function create($url = '', $status = 302, $headers = array()) { From f70dc2c910c722aeeb2c988e8b337bb9726e32fb Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 25 Oct 2017 18:42:56 +0200 Subject: [PATCH 041/225] [HttpFoundation] Fix caching of session-enabled pages --- Session/Storage/NativeSessionStorage.php | 6 ++++-- Tests/Session/Storage/Handler/Fixtures/storage.expected | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index de7700847..2975e4104 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -60,7 +60,8 @@ class NativeSessionStorage implements SessionStorageInterface * ("auto_start", is not supported as it tells PHP to start a session before * PHP starts to execute user-land code. Setting during runtime has no effect). * - * cache_limiter, "" (use "0" to prevent headers from being sent entirely). + * cache_limiter, "private_no_expire" (use "0" to prevent headers from being sent entirely). + * cache_expire, "0" * cookie_domain, "" * cookie_httponly, "" * cookie_lifetime, "0" @@ -101,6 +102,7 @@ public function __construct(array $options = array(), $handler = null, MetadataB { $options += array( 'cache_limiter' => 'private_no_expire', + 'cache_expire' => 0, 'use_cookies' => 1, 'lazy_write' => 1, ); @@ -347,7 +349,7 @@ public function setOptions(array $options) } $validOptions = array_flip(array( - 'cache_limiter', 'cookie_domain', 'cookie_httponly', + 'cache_limiter', 'cache_expire', 'cookie_domain', 'cookie_httponly', 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'entropy_file', 'entropy_length', 'gc_divisor', 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character', diff --git a/Tests/Session/Storage/Handler/Fixtures/storage.expected b/Tests/Session/Storage/Handler/Fixtures/storage.expected index 5e8deb557..3bc9beeb7 100644 --- a/Tests/Session/Storage/Handler/Fixtures/storage.expected +++ b/Tests/Session/Storage/Handler/Fixtures/storage.expected @@ -15,6 +15,6 @@ $_SESSION is not empty Array ( [0] => Content-Type: text/plain; charset=utf-8 - [1] => Cache-Control: private, max-age=10800 + [1] => Cache-Control: private, max-age=0 ) shutdown From 1d098b2958372b883b22e9dfc1b180f4217b7056 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1chym=20Tou=C5=A1ek?= Date: Wed, 18 Oct 2017 17:59:47 +0200 Subject: [PATCH 042/225] [HttpFoundation] Fix FileBag issue with associative arrays --- FileBag.php | 5 ++++- Tests/FileBagTest.php | 17 +++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/FileBag.php b/FileBag.php index 722ec2a9c..41f8c9269 100644 --- a/FileBag.php +++ b/FileBag.php @@ -87,7 +87,10 @@ protected function convertFileInformation($file) $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']); } } else { - $file = array_filter(array_map(array($this, 'convertFileInformation'), $file)); + $file = array_map(array($this, 'convertFileInformation'), $file); + if (array_keys($keys) === $keys) { + $file = array_filter($file); + } } } diff --git a/Tests/FileBagTest.php b/Tests/FileBagTest.php index 7d2902d32..b1bbba0d3 100644 --- a/Tests/FileBagTest.php +++ b/Tests/FileBagTest.php @@ -62,7 +62,7 @@ public function testShouldSetEmptyUploadedFilesToNull() public function testShouldRemoveEmptyUploadedFilesForMultiUpload() { - $bag = new FileBag(array('file' => array( + $bag = new FileBag(array('files' => array( 'name' => array(''), 'type' => array(''), 'tmp_name' => array(''), @@ -70,7 +70,20 @@ public function testShouldRemoveEmptyUploadedFilesForMultiUpload() 'size' => array(0), ))); - $this->assertSame(array(), $bag->get('file')); + $this->assertSame(array(), $bag->get('files')); + } + + public function testShouldNotRemoveEmptyUploadedFilesForAssociativeArray() + { + $bag = new FileBag(array('files' => array( + 'name' => array('file1' => ''), + 'type' => array('file1' => ''), + 'tmp_name' => array('file1' => ''), + 'error' => array('file1' => UPLOAD_ERR_NO_FILE), + 'size' => array('file1' => 0), + ))); + + $this->assertSame(array('file1' => null), $bag->get('files')); } public function testShouldConvertUploadedFilesWithPhpBug() From e2a7d6576339822a4a35f00a99d600b1d8c11f10 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 28 Oct 2017 20:22:29 +0200 Subject: [PATCH 043/225] [HttpFoundation] Mark new methods on Response as final --- Response.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Response.php b/Response.php index 765e38852..9c9820314 100644 --- a/Response.php +++ b/Response.php @@ -612,6 +612,8 @@ public function setPublic() * @param bool $immutable enables or disables the immutable directive * * @return $this + * + * @final */ public function setImmutable($immutable = true) { @@ -628,6 +630,8 @@ public function setImmutable($immutable = true) * Returns true if the response is marked as "immutable". * * @return bool returns true if the response is marked as "immutable"; otherwise false + * + * @final */ public function isImmutable() { From 2a307c15443c9c457a81f316342d8e07911bbba6 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 28 Oct 2017 20:51:46 +0200 Subject: [PATCH 044/225] Remove useless docblocks --- AcceptHeaderItem.php | 15 -------- File/UploadedFile.php | 36 ++----------------- Request.php | 6 ++-- Session/Attribute/NamespacedAttributeBag.php | 5 --- Session/Session.php | 12 ------- .../Handler/LegacyPdoSessionHandler.php | 3 -- .../Handler/MemcacheSessionHandler.php | 3 -- .../Handler/MemcachedSessionHandler.php | 3 -- .../Storage/Handler/MongoDbSessionHandler.php | 3 -- .../Handler/WriteCheckSessionHandler.php | 3 -- Session/Storage/MockFileSessionStorage.php | 3 -- Session/Storage/Proxy/NativeProxy.php | 2 +- Session/Storage/Proxy/SessionHandlerProxy.php | 3 -- .../Handler/MemcacheSessionHandlerTest.php | 1 + 14 files changed, 8 insertions(+), 90 deletions(-) diff --git a/AcceptHeaderItem.php b/AcceptHeaderItem.php index e07a48aa9..c69dbbba3 100644 --- a/AcceptHeaderItem.php +++ b/AcceptHeaderItem.php @@ -18,24 +18,9 @@ */ class AcceptHeaderItem { - /** - * @var string - */ private $value; - - /** - * @var float - */ private $quality = 1.0; - - /** - * @var int - */ private $index = 0; - - /** - * @var array - */ private $attributes = array(); /** diff --git a/File/UploadedFile.php b/File/UploadedFile.php index 9a2d28491..082d8d534 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -24,41 +24,10 @@ */ class UploadedFile extends File { - /** - * Whether the test mode is activated. - * - * Local files are used in test mode hence the code should not enforce HTTP uploads. - * - * @var bool - */ private $test = false; - - /** - * The original name of the uploaded file. - * - * @var string - */ private $originalName; - - /** - * The mime type provided by the uploader. - * - * @var string - */ private $mimeType; - - /** - * The file size provided by the uploader. - * - * @var int|null - */ private $size; - - /** - * The UPLOAD_ERR_XXX constant provided by the uploader. - * - * @var int - */ private $error; /** @@ -76,11 +45,12 @@ class UploadedFile extends File * Calling any other method on an non-valid instance will cause an unpredictable result. * * @param string $path The full temporary path to the file - * @param string $originalName The original file name + * @param string $originalName The original file name of the uploaded file * @param string|null $mimeType The type of the file as provided by PHP; null defaults to application/octet-stream - * @param int|null $size The file size + * @param int|null $size The file size provided by the uploader * @param int|null $error The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK * @param bool $test Whether the test mode is active + * Local files are used in test mode hence the code should not enforce HTTP uploads * * @throws FileException If file_uploads is disabled * @throws FileNotFoundException If the file does not exist diff --git a/Request.php b/Request.php index b987c5b90..83b62142c 100644 --- a/Request.php +++ b/Request.php @@ -714,9 +714,9 @@ public static function getHttpMethodParameterOverride() * It is better to explicitly get request parameters from the appropriate * public property instead (query, attributes, request). * - * @param string $key the key - * @param mixed $default the default value if the parameter key does not exist - * @param bool $deep is parameter deep in multidimensional array + * @param string $key The key + * @param mixed $default The default value if the parameter key does not exist + * @param bool $deep Is parameter deep in multidimensional array * * @return mixed */ diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index e149801aa..abbf37ee7 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -19,11 +19,6 @@ */ class NamespacedAttributeBag extends AttributeBag { - /** - * Namespace character. - * - * @var string - */ private $namespaceCharacter; /** diff --git a/Session/Session.php b/Session/Session.php index 5a765654c..d20a4daff 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -24,21 +24,9 @@ */ class Session implements SessionInterface, \IteratorAggregate, \Countable { - /** - * Storage driver. - * - * @var SessionStorageInterface - */ protected $storage; - /** - * @var string - */ private $flashName; - - /** - * @var string - */ private $attributeName; /** diff --git a/Session/Storage/Handler/LegacyPdoSessionHandler.php b/Session/Storage/Handler/LegacyPdoSessionHandler.php index 900fb9f5f..458bb73b3 100644 --- a/Session/Storage/Handler/LegacyPdoSessionHandler.php +++ b/Session/Storage/Handler/LegacyPdoSessionHandler.php @@ -31,9 +31,6 @@ */ class LegacyPdoSessionHandler implements \SessionHandlerInterface { - /** - * @var \PDO PDO instance - */ private $pdo; /** diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index d31aa7667..89b4dac2c 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -16,9 +16,6 @@ */ class MemcacheSessionHandler implements \SessionHandlerInterface { - /** - * @var \Memcache Memcache driver - */ private $memcache; /** diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 3bbde5420..6e2c2ee30 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -21,9 +21,6 @@ */ class MemcachedSessionHandler implements \SessionHandlerInterface { - /** - * @var \Memcached Memcached driver - */ private $memcached; /** diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index f140939db..29fc3f529 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -16,9 +16,6 @@ */ class MongoDbSessionHandler implements \SessionHandlerInterface { - /** - * @var \Mongo|\MongoClient|\MongoDB\Client - */ private $mongo; /** diff --git a/Session/Storage/Handler/WriteCheckSessionHandler.php b/Session/Storage/Handler/WriteCheckSessionHandler.php index d49c36cae..7f4b6bc03 100644 --- a/Session/Storage/Handler/WriteCheckSessionHandler.php +++ b/Session/Storage/Handler/WriteCheckSessionHandler.php @@ -18,9 +18,6 @@ */ class WriteCheckSessionHandler implements \SessionHandlerInterface { - /** - * @var \SessionHandlerInterface - */ private $wrappedSessionHandler; /** diff --git a/Session/Storage/MockFileSessionStorage.php b/Session/Storage/MockFileSessionStorage.php index 8c1bf73ca..0a580d602 100644 --- a/Session/Storage/MockFileSessionStorage.php +++ b/Session/Storage/MockFileSessionStorage.php @@ -24,9 +24,6 @@ */ class MockFileSessionStorage extends MockArraySessionStorage { - /** - * @var string - */ private $savePath; /** diff --git a/Session/Storage/Proxy/NativeProxy.php b/Session/Storage/Proxy/NativeProxy.php index 21ed1ada0..a0f48c1e2 100644 --- a/Session/Storage/Proxy/NativeProxy.php +++ b/Session/Storage/Proxy/NativeProxy.php @@ -12,7 +12,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; /** - * This proxy is built-in session handlers in PHP 5.3.x + * This proxy is built-in session handlers in PHP 5.3.x. * * @author Drak */ diff --git a/Session/Storage/Proxy/SessionHandlerProxy.php b/Session/Storage/Proxy/SessionHandlerProxy.php index 8f91f0604..6190d3ed1 100644 --- a/Session/Storage/Proxy/SessionHandlerProxy.php +++ b/Session/Storage/Proxy/SessionHandlerProxy.php @@ -16,9 +16,6 @@ */ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface { - /** - * @var \SessionHandlerInterface - */ protected $handler; /** diff --git a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php index 06193c8be..75be18bef 100644 --- a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php @@ -22,6 +22,7 @@ class MemcacheSessionHandlerTest extends TestCase { const PREFIX = 'prefix_'; const TTL = 1000; + /** * @var MemcacheSessionHandler */ From 96c8d6a69be6d757284c82d784b1c5c203ecf893 Mon Sep 17 00:00:00 2001 From: Amrouche Hamza Date: Tue, 31 Oct 2017 07:14:14 +0100 Subject: [PATCH 045/225] [HttpFoundation] add Early Hints in Reponse to fix test --- Response.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Response.php b/Response.php index a98a37723..4aabc0da2 100644 --- a/Response.php +++ b/Response.php @@ -126,6 +126,7 @@ class Response 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', // RFC2518 + 103 => 'Early Hints', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', From b3896ecc1d5560f270aa93052ae8d5b8d85baee1 Mon Sep 17 00:00:00 2001 From: ReenExe Date: Sun, 29 Oct 2017 13:17:42 +0200 Subject: [PATCH 046/225] [HttpFoundation] refactoring: calculate when need --- Request.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Request.php b/Request.php index 06144543d..a2ee7970b 100644 --- a/Request.php +++ b/Request.php @@ -1928,12 +1928,12 @@ protected function prepareBaseUrl() */ protected function prepareBasePath() { - $filename = basename($this->server->get('SCRIPT_FILENAME')); $baseUrl = $this->getBaseUrl(); if (empty($baseUrl)) { return ''; } + $filename = basename($this->server->get('SCRIPT_FILENAME')); if (basename($baseUrl) === $filename) { $basePath = dirname($baseUrl); } else { @@ -1954,8 +1954,6 @@ protected function prepareBasePath() */ protected function preparePathInfo() { - $baseUrl = $this->getBaseUrl(); - if (null === ($requestUri = $this->getRequestUri())) { return '/'; } @@ -1968,12 +1966,14 @@ protected function preparePathInfo() $requestUri = '/'.$requestUri; } + if (null === ($baseUrl = $this->getBaseUrl())) { + return $requestUri; + } + $pathInfo = substr($requestUri, strlen($baseUrl)); - if (null !== $baseUrl && (false === $pathInfo || '' === $pathInfo)) { + if (false === $pathInfo || '' === $pathInfo) { // If substr() returns false then PATH_INFO is set to an empty string return '/'; - } elseif (null === $baseUrl) { - return $requestUri; } return (string) $pathInfo; From 0d84932805d93dccc3a2ef1174d92548fac6c9d6 Mon Sep 17 00:00:00 2001 From: Samuel ROZE Date: Thu, 12 Oct 2017 11:48:23 +0100 Subject: [PATCH 047/225] [HttpFoundation] Fix forward-compat of NativeSessionStorage with PHP 7.2 --- Session/Storage/NativeSessionStorage.php | 7 ++++- .../Storage/NativeSessionStorageTest.php | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 76654d26f..e35af4e29 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -102,6 +102,12 @@ class NativeSessionStorage implements SessionStorageInterface */ public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) { + $this->setMetadataBag($metaBag); + + if (\PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE === session_status()) { + return; + } + $options += array( // disable by default because it's managed by HeaderBag (if used) 'cache_limiter' => '', @@ -114,7 +120,6 @@ public function __construct(array $options = array(), $handler = null, MetadataB register_shutdown_function('session_write_close'); } - $this->setMetadataBag($metaBag); $this->setOptions($options); $this->setSaveHandler($handler); } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 7eda5b3a3..673cd386b 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -270,4 +270,30 @@ public function testRestart() $this->assertSame($id, $storage->getId(), 'Same session ID after restarting'); $this->assertSame(7, $storage->getBag('attributes')->get('lucky'), 'Data still available'); } + + /** + * @requires PHP 5.4 + */ + public function testCanCreateNativeSessionStorageWhenSessionAlreadyStarted() + { + session_start(); + $this->getStorage(); + + // Assert no exception has been thrown by `getStorage()` + $this->addToAssertionCount(1); + } + + /** + * @requires PHP 5.4 + */ + public function testSetSessionOptionsOnceSessionStartedIsIgnored() + { + session_start(); + $this->getStorage(array( + 'name' => 'something-else', + )); + + // Assert no exception has been thrown by `getStorage()` + $this->addToAssertionCount(1); + } } From 478eef0e538fd5a73a31004cf4e00deac6ac621c Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 7 Nov 2017 21:33:43 +0100 Subject: [PATCH 048/225] Micro optim using explicit root namespaces --- HeaderBag.php | 18 +++++++++++++----- ResponseHeaderBag.php | 2 +- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/HeaderBag.php b/HeaderBag.php index e06713f39..a73f345a7 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -121,7 +121,7 @@ public function get($key, $default = null, $first = true) } if ($first) { - return count($headers[$key]) ? $headers[$key][0] : $default; + return \count($headers[$key]) ? $headers[$key][0] : $default; } return $headers[$key]; @@ -138,12 +138,20 @@ public function set($key, $values, $replace = true) { $key = str_replace('_', '-', strtolower($key)); - $values = array_values((array) $values); + if (\is_array($values)) { + $values = array_values($values); - if (true === $replace || !isset($this->headers[$key])) { - $this->headers[$key] = $values; + if (true === $replace || !isset($this->headers[$key])) { + $this->headers[$key] = $values; + } else { + $this->headers[$key] = array_merge($this->headers[$key], $values); + } } else { - $this->headers[$key] = array_merge($this->headers[$key], $values); + if (true === $replace || !isset($this->headers[$key])) { + $this->headers[$key] = array($values); + } else { + $this->headers[$key][] = $values; + } } if ('cache-control' === $key) { diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index df995cf74..11a859326 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -122,7 +122,7 @@ public function set($key, $values, $replace = true) parent::set($key, $values, $replace); // ensure the cache-control header has sensible defaults - if (in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'))) { + if (\in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'), true)) { $computed = $this->computeCacheControlValue(); $this->headers['cache-control'] = array($computed); $this->headerNames['cache-control'] = 'Cache-Control'; From 896b2df6e4bfa2f1ce229dc794936f2c2a4892bf Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 9 Nov 2017 11:49:37 +0100 Subject: [PATCH 049/225] [HttpFoundation] Prevent PHP from sending Last-Modified on session start --- Session/Storage/Handler/AbstractSessionHandler.php | 3 +++ Session/Storage/NativeSessionStorage.php | 2 +- Tests/Session/Storage/Handler/Fixtures/common.inc | 3 +-- Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected | 2 +- Tests/Session/Storage/Handler/Fixtures/read_only.expected | 2 +- Tests/Session/Storage/Handler/Fixtures/regenerate.expected | 2 +- Tests/Session/Storage/Handler/Fixtures/storage.expected | 2 +- Tests/Session/Storage/Handler/Fixtures/with_cookie.expected | 2 +- Tests/Session/Storage/NativeSessionStorageTest.php | 2 +- 9 files changed, 11 insertions(+), 9 deletions(-) diff --git a/Session/Storage/Handler/AbstractSessionHandler.php b/Session/Storage/Handler/AbstractSessionHandler.php index c20a23b20..ced5b4895 100644 --- a/Session/Storage/Handler/AbstractSessionHandler.php +++ b/Session/Storage/Handler/AbstractSessionHandler.php @@ -32,6 +32,9 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess public function open($savePath, $sessionName) { $this->sessionName = $sessionName; + if (!headers_sent() && !ini_get('session.cache_limiter')) { + header(sprintf('Cache-Control: max-age=%d, private, must-revalidate', 60 * (int) ini_get('session.cache_expire'))); + } return true; } diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index c034c5903..050325898 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -107,7 +107,7 @@ public function __construct(array $options = array(), $handler = null, MetadataB } $options += array( - 'cache_limiter' => 'private_no_expire', + 'cache_limiter' => '', 'cache_expire' => 0, 'use_cookies' => 1, 'lazy_write' => 1, diff --git a/Tests/Session/Storage/Handler/Fixtures/common.inc b/Tests/Session/Storage/Handler/Fixtures/common.inc index 5c183acff..7a064c7f3 100644 --- a/Tests/Session/Storage/Handler/Fixtures/common.inc +++ b/Tests/Session/Storage/Handler/Fixtures/common.inc @@ -38,14 +38,13 @@ ini_set('session.use_strict_mode', 1); ini_set('session.lazy_write', 1); ini_set('session.name', 'sid'); ini_set('session.save_path', __DIR__); -ini_set('session.cache_limiter', 'private_no_expire'); +ini_set('session.cache_limiter', ''); header_remove('X-Powered-By'); header('Content-Type: text/plain; charset=utf-8'); register_shutdown_function(function () { echo "\n"; - header_remove('Last-Modified'); session_write_close(); print_r(headers_list()); echo "shutdown\n"; diff --git a/Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected b/Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected index 1720bf055..820371474 100644 --- a/Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected +++ b/Tests/Session/Storage/Handler/Fixtures/empty_destroys.expected @@ -11,7 +11,7 @@ close Array ( [0] => Content-Type: text/plain; charset=utf-8 - [1] => Cache-Control: private, max-age=10800 + [1] => Cache-Control: max-age=10800, private, must-revalidate [2] => Set-Cookie: sid=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; secure; HttpOnly ) shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/read_only.expected b/Tests/Session/Storage/Handler/Fixtures/read_only.expected index 307b6c322..587adaf15 100644 --- a/Tests/Session/Storage/Handler/Fixtures/read_only.expected +++ b/Tests/Session/Storage/Handler/Fixtures/read_only.expected @@ -9,6 +9,6 @@ close Array ( [0] => Content-Type: text/plain; charset=utf-8 - [1] => Cache-Control: private, max-age=10800 + [1] => Cache-Control: max-age=10800, private, must-revalidate ) shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/regenerate.expected b/Tests/Session/Storage/Handler/Fixtures/regenerate.expected index 33f3892e2..baa5f2f6f 100644 --- a/Tests/Session/Storage/Handler/Fixtures/regenerate.expected +++ b/Tests/Session/Storage/Handler/Fixtures/regenerate.expected @@ -18,7 +18,7 @@ close Array ( [0] => Content-Type: text/plain; charset=utf-8 - [1] => Cache-Control: private, max-age=10800 + [1] => Cache-Control: max-age=10800, private, must-revalidate [2] => Set-Cookie: sid=random_session_id; path=/; secure; HttpOnly ) shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/storage.expected b/Tests/Session/Storage/Handler/Fixtures/storage.expected index 3bc9beeb7..4533a10a1 100644 --- a/Tests/Session/Storage/Handler/Fixtures/storage.expected +++ b/Tests/Session/Storage/Handler/Fixtures/storage.expected @@ -15,6 +15,6 @@ $_SESSION is not empty Array ( [0] => Content-Type: text/plain; charset=utf-8 - [1] => Cache-Control: private, max-age=0 + [1] => Cache-Control: max-age=0, private, must-revalidate ) shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/with_cookie.expected b/Tests/Session/Storage/Handler/Fixtures/with_cookie.expected index 47ae4da82..33da0a5be 100644 --- a/Tests/Session/Storage/Handler/Fixtures/with_cookie.expected +++ b/Tests/Session/Storage/Handler/Fixtures/with_cookie.expected @@ -9,7 +9,7 @@ close Array ( [0] => Content-Type: text/plain; charset=utf-8 - [1] => Cache-Control: private, max-age=10800 + [1] => Cache-Control: max-age=10800, private, must-revalidate [2] => Set-Cookie: abc=def ) shutdown diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 8864bb706..ec094a616 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -150,7 +150,7 @@ public function testDefaultSessionCacheLimiter() $this->iniSet('session.cache_limiter', 'nocache'); $storage = new NativeSessionStorage(); - $this->assertEquals('private_no_expire', ini_get('session.cache_limiter')); + $this->assertEquals('', ini_get('session.cache_limiter')); } public function testExplicitSessionCacheLimiter() From ce3c40e528a2786453fa4154c85480ee6e9b8500 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 10 Nov 2017 08:36:14 +0100 Subject: [PATCH 050/225] [HttpFoundation] minor session-related fix --- Session/Storage/Handler/AbstractSessionHandler.php | 2 +- Session/Storage/NativeSessionStorage.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Session/Storage/Handler/AbstractSessionHandler.php b/Session/Storage/Handler/AbstractSessionHandler.php index ced5b4895..7c6c476aa 100644 --- a/Session/Storage/Handler/AbstractSessionHandler.php +++ b/Session/Storage/Handler/AbstractSessionHandler.php @@ -32,7 +32,7 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess public function open($savePath, $sessionName) { $this->sessionName = $sessionName; - if (!headers_sent() && !ini_get('session.cache_limiter')) { + if (!headers_sent() && !ini_get('session.cache_limiter') && '0' !== ini_get('session.cache_limiter')) { header(sprintf('Cache-Control: max-age=%d, private, must-revalidate', 60 * (int) ini_get('session.cache_expire'))); } diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 050325898..612b6bd3e 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -60,7 +60,7 @@ class NativeSessionStorage implements SessionStorageInterface * ("auto_start", is not supported as it tells PHP to start a session before * PHP starts to execute user-land code. Setting during runtime has no effect). * - * cache_limiter, "private_no_expire" (use "0" to prevent headers from being sent entirely). + * cache_limiter, "" (use "0" to prevent headers from being sent entirely). * cache_expire, "0" * cookie_domain, "" * cookie_httponly, "" From fed42ecaef65bbac5c6db4f006a78b85fcb8a022 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 13 Nov 2017 16:41:44 +0100 Subject: [PATCH 051/225] [HttpFoundation] Fix session-related BC break --- Session/Storage/NativeSessionStorage.php | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index e35af4e29..f03cdf343 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -102,12 +102,6 @@ class NativeSessionStorage implements SessionStorageInterface */ public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) { - $this->setMetadataBag($metaBag); - - if (\PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE === session_status()) { - return; - } - $options += array( // disable by default because it's managed by HeaderBag (if used) 'cache_limiter' => '', @@ -120,6 +114,7 @@ public function __construct(array $options = array(), $handler = null, MetadataB register_shutdown_function('session_write_close'); } + $this->setMetadataBag($metaBag); $this->setOptions($options); $this->setSaveHandler($handler); } @@ -292,7 +287,7 @@ public function getBag($name) throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name)); } - if ($this->saveHandler->isActive() && !$this->started) { + if (!$this->started && $this->saveHandler->isActive()) { $this->loadSession(); } elseif (!$this->started) { $this->start(); @@ -340,7 +335,7 @@ public function isStarted() */ public function setOptions(array $options) { - if (headers_sent()) { + if (headers_sent() || (\PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE === session_status())) { return; } @@ -395,10 +390,6 @@ public function setSaveHandler($saveHandler = null) throw new \InvalidArgumentException('Must be instance of AbstractProxy or NativeSessionHandler; implement \SessionHandlerInterface; or be null.'); } - if (headers_sent($file, $line)) { - throw new \RuntimeException(sprintf('Failed to set the session handler because headers have already been sent by "%s" at line %d.', $file, $line)); - } - // Wrap $saveHandler in proxy and prevent double wrapping of proxy if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) { $saveHandler = new SessionHandlerProxy($saveHandler); @@ -408,6 +399,10 @@ public function setSaveHandler($saveHandler = null) } $this->saveHandler = $saveHandler; + if (headers_sent() || (\PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE === session_status())) { + return; + } + if ($this->saveHandler instanceof \SessionHandlerInterface) { if (\PHP_VERSION_ID >= 50400) { session_set_save_handler($this->saveHandler, false); From 332e85cee2a7376a67124c7512fb48ae1689fe8c Mon Sep 17 00:00:00 2001 From: Samuel ROZE Date: Mon, 13 Nov 2017 13:14:59 +0000 Subject: [PATCH 052/225] [HttpFoundation] Add test --- .../Session/Storage/NativeSessionStorageTest.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 673cd386b..7eb7e5647 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -296,4 +296,19 @@ public function testSetSessionOptionsOnceSessionStartedIsIgnored() // Assert no exception has been thrown by `getStorage()` $this->addToAssertionCount(1); } + + /** + * @requires PHP 5.4 + */ + public function testGetBagsOnceSessionStartedIsIgnored() + { + session_start(); + $bag = new AttributeBag(); + $bag->setName('flashes'); + + $storage = $this->getStorage(); + $storage->registerBag($bag); + + $this->assertEquals($storage->getBag('flashes'), $bag); + } } From 72e1a53fd10fea4a3d3e1d4ea74ec951cc569071 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 21 Nov 2017 10:41:52 +0100 Subject: [PATCH 053/225] [HttpFoundation] Fix bad merge in NativeSessionStorage --- Session/Storage/NativeSessionStorage.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 6f60a5c76..f03cdf343 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -108,7 +108,11 @@ public function __construct(array $options = array(), $handler = null, MetadataB 'use_cookies' => 1, ); - session_register_shutdown(); + if (\PHP_VERSION_ID >= 50400) { + session_register_shutdown(); + } else { + register_shutdown_function('session_write_close'); + } $this->setMetadataBag($metaBag); $this->setOptions($options); From c91ca579ed2e1a1953d8963a9ab62179bf1d8c15 Mon Sep 17 00:00:00 2001 From: Amrouche Hamza Date: Tue, 28 Nov 2017 06:31:17 +0100 Subject: [PATCH 054/225] [HttpFoundation] AutExpireFlashBag should not clear new flashes --- Session/Flash/AutoExpireFlashBag.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Flash/AutoExpireFlashBag.php b/Session/Flash/AutoExpireFlashBag.php index 59ba30900..0ed660097 100644 --- a/Session/Flash/AutoExpireFlashBag.php +++ b/Session/Flash/AutoExpireFlashBag.php @@ -106,7 +106,7 @@ public function get($type, array $default = array()) public function all() { $return = $this->flashes['display']; - $this->flashes = array('new' => array(), 'display' => array()); + $this->flashes['display'] = array(); return $return; } From 45a228eaab08b9d927d8ec896b377028ab235906 Mon Sep 17 00:00:00 2001 From: Samuel ROZE Date: Tue, 28 Nov 2017 08:49:55 +0000 Subject: [PATCH 055/225] Test that it do not remove the new flashes when displaying the existing ones --- Tests/Session/Flash/AutoExpireFlashBagTest.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Tests/Session/Flash/AutoExpireFlashBagTest.php b/Tests/Session/Flash/AutoExpireFlashBagTest.php index 18b71a502..0e0724a32 100644 --- a/Tests/Session/Flash/AutoExpireFlashBagTest.php +++ b/Tests/Session/Flash/AutoExpireFlashBagTest.php @@ -150,4 +150,12 @@ public function testClear() { $this->assertEquals(array('notice' => array('A previous flash message')), $this->bag->clear()); } + + public function testDoNotRemoveTheNewFlashesWhenDisplayingTheExistingOnes() + { + $this->bag->add('success', 'Something'); + $this->bag->all(); + + $this->assertEquals(array('new' => array('success' => array('Something')), 'display' => array()), $this->array); + } } From d9625c8abb907e0ca2d7506afd7a719a572c766f Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 30 Nov 2017 11:09:16 +0100 Subject: [PATCH 056/225] [HttpFoundation] Add Session::isEmpty(), fix MockFileSessionStorage to behave like the native one --- Session/Session.php | 25 +++++-- Session/SessionBagProxy.php | 79 ++++++++++++++++++++++ Session/Storage/MockFileSessionStorage.php | 21 +++++- Tests/Session/SessionTest.php | 18 +++++ 4 files changed, 138 insertions(+), 5 deletions(-) create mode 100644 Session/SessionBagProxy.php diff --git a/Session/Session.php b/Session/Session.php index 09caa3442..0c3371fab 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -28,6 +28,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable private $flashName; private $attributeName; + private $data = array(); /** * @param SessionStorageInterface $storage A SessionStorageInterface instance @@ -108,7 +109,7 @@ public function remove($name) */ public function clear() { - $this->storage->getBag($this->attributeName)->clear(); + $this->getAttributeBag()->clear(); } /** @@ -139,6 +140,22 @@ public function count() return count($this->getAttributeBag()->all()); } + /** + * @return bool + * + * @internal + */ + public function isEmpty() + { + foreach ($this->data as &$data) { + if (!empty($data)) { + return false; + } + } + + return true; + } + /** * {@inheritdoc} */ @@ -210,7 +227,7 @@ public function getMetadataBag() */ public function registerBag(SessionBagInterface $bag) { - $this->storage->registerBag($bag); + $this->storage->registerBag(new SessionBagProxy($bag, $this->data)); } /** @@ -218,7 +235,7 @@ public function registerBag(SessionBagInterface $bag) */ public function getBag($name) { - return $this->storage->getBag($name); + return $this->storage->getBag($name)->getBag(); } /** @@ -240,6 +257,6 @@ public function getFlashBag() */ private function getAttributeBag() { - return $this->storage->getBag($this->attributeName); + return $this->storage->getBag($this->attributeName)->getBag(); } } diff --git a/Session/SessionBagProxy.php b/Session/SessionBagProxy.php new file mode 100644 index 000000000..6c4cab671 --- /dev/null +++ b/Session/SessionBagProxy.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Session; + +/** + * @author Nicolas Grekas + * + * @internal + */ +final class SessionBagProxy implements SessionBagInterface +{ + private $bag; + private $data; + + public function __construct(SessionBagInterface $bag, array &$data) + { + $this->bag = $bag; + $this->data = &$data; + } + + /** + * @return SessionBagInterface + */ + public function getBag() + { + return $this->bag; + } + + /** + * @return bool + */ + public function isEmpty() + { + return empty($this->data[$this->bag->getStorageKey()]); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->bag->getName(); + } + + /** + * {@inheritdoc} + */ + public function initialize(array &$array) + { + $this->data[$this->bag->getStorageKey()] = &$array; + + $this->bag->initialize($array); + } + + /** + * {@inheritdoc} + */ + public function getStorageKey() + { + return $this->bag->getStorageKey(); + } + + /** + * {@inheritdoc} + */ + public function clear() + { + return $this->bag->clear(); + } +} diff --git a/Session/Storage/MockFileSessionStorage.php b/Session/Storage/MockFileSessionStorage.php index 0a580d602..14f427007 100644 --- a/Session/Storage/MockFileSessionStorage.php +++ b/Session/Storage/MockFileSessionStorage.php @@ -91,7 +91,26 @@ public function save() throw new \RuntimeException('Trying to save a session that was not started yet or was already closed'); } - file_put_contents($this->getFilePath(), serialize($this->data)); + $data = $this->data; + + foreach ($this->bags as $bag) { + if (empty($data[$key = $bag->getStorageKey()])) { + unset($data[$key]); + } + } + if (array($key = $this->metadataBag->getStorageKey()) === array_keys($data)) { + unset($data[$key]); + } + + try { + if ($data) { + file_put_contents($this->getFilePath(), serialize($data)); + } else { + $this->destroy(); + } + } finally { + $this->data = $data; + } // this is needed for Silex, where the session object is re-used across requests // in functional tests. In Symfony, the container is rebooted, so we don't have diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index fa93507a4..41720e4b6 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -221,4 +221,22 @@ public function testGetMeta() { $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\MetadataBag', $this->session->getMetadataBag()); } + + public function testIsEmpty() + { + $this->assertTrue($this->session->isEmpty()); + + $this->session->set('hello', 'world'); + $this->assertFalse($this->session->isEmpty()); + + $this->session->remove('hello'); + $this->assertTrue($this->session->isEmpty()); + + $flash = $this->session->getFlashBag(); + $flash->set('hello', 'world'); + $this->assertFalse($this->session->isEmpty()); + + $flash->get('hello'); + $this->assertTrue($this->session->isEmpty()); + } } From e59304000cec121f886d87a684a4574adf397e38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pablo=20Schl=C3=A4pfer?= Date: Fri, 8 Dec 2017 14:05:42 +0100 Subject: [PATCH 057/225] [HttpFoundation] don't prefix cookies with "Set-Cookie:" See symfony/symfony#25393 --- .../Handler/AbstractSessionHandler.php | 2 +- .../Fixtures/with_cookie_and_session.expected | 24 +++++++++++++++++++ .../Fixtures/with_cookie_and_session.php | 13 ++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.expected create mode 100644 Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.php diff --git a/Session/Storage/Handler/AbstractSessionHandler.php b/Session/Storage/Handler/AbstractSessionHandler.php index 7c6c476aa..6ae135581 100644 --- a/Session/Storage/Handler/AbstractSessionHandler.php +++ b/Session/Storage/Handler/AbstractSessionHandler.php @@ -156,7 +156,7 @@ public function destroy($sessionId) if ($sessionCookieFound) { header_remove('Set-Cookie'); foreach ($otherCookies as $h) { - header('Set-Cookie:'.$h, false); + header($h, false); } } else { setcookie($this->sessionName, '', 0, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly')); diff --git a/Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.expected b/Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.expected new file mode 100644 index 000000000..5de2d9e39 --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.expected @@ -0,0 +1,24 @@ +open +validateId +read +doRead: abc|i:123; +read +updateTimestamp +close +open +validateId +read +doRead: abc|i:123; +read + +write +destroy +doDestroy +close +Array +( + [0] => Content-Type: text/plain; charset=utf-8 + [1] => Cache-Control: max-age=10800, private, must-revalidate + [2] => Set-Cookie: abc=def +) +shutdown diff --git a/Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.php b/Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.php new file mode 100644 index 000000000..ec5119323 --- /dev/null +++ b/Tests/Session/Storage/Handler/Fixtures/with_cookie_and_session.php @@ -0,0 +1,13 @@ + Date: Fri, 8 Dec 2017 16:50:58 +0100 Subject: [PATCH 058/225] fix cs --- Request.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Request.php b/Request.php index e8412b50e..63b917a75 100644 --- a/Request.php +++ b/Request.php @@ -1862,7 +1862,7 @@ protected function prepareBaseUrl() // Does the baseUrl have anything in common with the request_uri? $requestUri = $this->getRequestUri(); - if ($requestUri !== '' && $requestUri[0] !== '/') { + if ('' !== $requestUri && '/' !== $requestUri[0]) { $requestUri = '/'.$requestUri; } @@ -1940,7 +1940,7 @@ protected function preparePathInfo() if (false !== $pos = strpos($requestUri, '?')) { $requestUri = substr($requestUri, 0, $pos); } - if ($requestUri !== '' && $requestUri[0] !== '/') { + if ('' !== $requestUri && '/' !== $requestUri[0]) { $requestUri = '/'.$requestUri; } From e1c4807c73cfd9d1068ec36c6b3ccbb04dcb1ba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phan=20Kochen?= Date: Tue, 5 Dec 2017 09:56:13 +0100 Subject: [PATCH 059/225] [HttpFoundation] Support 0 bit netmask in IPv6 () --- IpUtils.php | 4 ++++ Tests/IpUtilsTest.php | 2 ++ 2 files changed, 6 insertions(+) diff --git a/IpUtils.php b/IpUtils.php index 3bb33140f..86d135b2d 100644 --- a/IpUtils.php +++ b/IpUtils.php @@ -123,6 +123,10 @@ public static function checkIp6($requestIp, $ip) if (false !== strpos($ip, '/')) { list($address, $netmask) = explode('/', $ip, 2); + if ('0' === $netmask) { + return (bool) unpack('n*', @inet_pton($address)); + } + if ($netmask < 1 || $netmask > 128) { return self::$checkedIps[$cacheKey] = false; } diff --git a/Tests/IpUtilsTest.php b/Tests/IpUtilsTest.php index 54cbb5c20..7a93f9947 100644 --- a/Tests/IpUtilsTest.php +++ b/Tests/IpUtilsTest.php @@ -62,6 +62,8 @@ public function getIpv6Data() array(false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'), array(true, '0:0:0:0:0:0:0:1', '::1'), array(false, '0:0:603:0:396e:4789:8e99:0001', '::1'), + array(true, '0:0:603:0:396e:4789:8e99:0001', '::/0'), + array(true, '0:0:603:0:396e:4789:8e99:0001', '2a01:198:603:0::/0'), array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '2a01:198:603:0::/65')), array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('2a01:198:603:0::/65', '::1')), array(false, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '1a01:198:603:0::/65')), From 8bf9a56b84d2e15808e27efd9d606bd11ecabe39 Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Mon, 11 Dec 2017 19:55:31 -0200 Subject: [PATCH 060/225] Refactoring tests. --- Tests/HeaderBagTest.php | 2 +- Tests/ParameterBagTest.php | 2 +- Tests/ResponseHeaderBagTest.php | 18 +++++++++--------- Tests/ServerBagTest.php | 8 ++++---- Tests/Session/Attribute/AttributeBagTest.php | 2 +- .../Storage/NativeSessionStorageTest.php | 2 +- .../Storage/PhpBridgeSessionStorageTest.php | 8 ++++---- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/Tests/HeaderBagTest.php b/Tests/HeaderBagTest.php index e5b1b38fd..683ef47b2 100644 --- a/Tests/HeaderBagTest.php +++ b/Tests/HeaderBagTest.php @@ -191,6 +191,6 @@ public function testCount() $headers = array('foo' => 'bar', 'HELLO' => 'WORLD'); $headerBag = new HeaderBag($headers); - $this->assertEquals(count($headers), count($headerBag)); + $this->assertCount(count($headers), $headerBag); } } diff --git a/Tests/ParameterBagTest.php b/Tests/ParameterBagTest.php index 5ee2954db..83f49f695 100644 --- a/Tests/ParameterBagTest.php +++ b/Tests/ParameterBagTest.php @@ -210,7 +210,7 @@ public function testCount() $parameters = array('foo' => 'bar', 'hello' => 'world'); $bag = new ParameterBag($parameters); - $this->assertEquals(count($parameters), count($bag)); + $this->assertCount(count($parameters), $bag); } public function testGetBoolean() diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index c55a7f6a5..48be57296 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -183,10 +183,10 @@ public function testCookiesWithSameNames() $this->assertSetCookieHeader('foo=bar; path=/; httponly', $bag); $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); - $this->assertTrue(isset($cookies['foo.bar']['/path/foo']['foo'])); - $this->assertTrue(isset($cookies['foo.bar']['/path/bar']['foo'])); - $this->assertTrue(isset($cookies['bar.foo']['/path/bar']['foo'])); - $this->assertTrue(isset($cookies['']['/']['foo'])); + $this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/foo']); + $this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/bar']); + $this->assertArrayHasKey('foo', $cookies['bar.foo']['/path/bar']); + $this->assertArrayHasKey('foo', $cookies['']['/']); } public function testRemoveCookie() @@ -196,17 +196,17 @@ public function testRemoveCookie() $bag->setCookie(new Cookie('bar', 'foo', 0, '/path/bar', 'foo.bar')); $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); - $this->assertTrue(isset($cookies['foo.bar']['/path/foo'])); + $this->assertArrayHasKey('/path/foo', $cookies['foo.bar']); $bag->removeCookie('foo', '/path/foo', 'foo.bar'); $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); - $this->assertFalse(isset($cookies['foo.bar']['/path/foo'])); + $this->assertArrayNotHasKey('/path/foo', $cookies['foo.bar']); $bag->removeCookie('bar', '/path/bar', 'foo.bar'); $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); - $this->assertFalse(isset($cookies['foo.bar'])); + $this->assertArrayNotHasKey('foo.bar', $cookies); } public function testRemoveCookieWithNullRemove() @@ -216,11 +216,11 @@ public function testRemoveCookieWithNullRemove() $bag->setCookie(new Cookie('bar', 'foo', 0)); $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); - $this->assertTrue(isset($cookies['']['/'])); + $this->assertArrayHasKey('/', $cookies['']); $bag->removeCookie('foo', null); $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); - $this->assertFalse(isset($cookies['']['/']['foo'])); + $this->assertArrayNotHasKey('foo', $cookies['']['/']); $bag->removeCookie('bar', null); $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); diff --git a/Tests/ServerBagTest.php b/Tests/ServerBagTest.php index c1d9d12a6..f8becec5a 100644 --- a/Tests/ServerBagTest.php +++ b/Tests/ServerBagTest.php @@ -74,8 +74,8 @@ public function testHttpBasicAuthWithPhpCgiBogus() // Username and passwords should not be set as the header is bogus $headers = $bag->getHeaders(); - $this->assertFalse(isset($headers['PHP_AUTH_USER'])); - $this->assertFalse(isset($headers['PHP_AUTH_PW'])); + $this->assertArrayNotHasKey('PHP_AUTH_USER', $headers); + $this->assertArrayNotHasKey('PHP_AUTH_PW', $headers); } public function testHttpBasicAuthWithPhpCgiRedirect() @@ -118,8 +118,8 @@ public function testHttpDigestAuthWithPhpCgiBogus() // Username and passwords should not be set as the header is bogus $headers = $bag->getHeaders(); - $this->assertFalse(isset($headers['PHP_AUTH_USER'])); - $this->assertFalse(isset($headers['PHP_AUTH_PW'])); + $this->assertArrayNotHasKey('PHP_AUTH_USER', $headers); + $this->assertArrayNotHasKey('PHP_AUTH_PW', $headers); } public function testHttpDigestAuthWithPhpCgiRedirect() diff --git a/Tests/Session/Attribute/AttributeBagTest.php b/Tests/Session/Attribute/AttributeBagTest.php index 655c26a9c..724a0b984 100644 --- a/Tests/Session/Attribute/AttributeBagTest.php +++ b/Tests/Session/Attribute/AttributeBagTest.php @@ -181,6 +181,6 @@ public function testGetIterator() public function testCount() { - $this->assertEquals(count($this->array), count($this->bag)); + $this->assertCount(count($this->array), $this->bag); } } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 7eb7e5647..3501f7478 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -255,7 +255,7 @@ public function testStartedOutside() $this->assertFalse($storage->isStarted()); $key = $storage->getMetadataBag()->getStorageKey(); - $this->assertFalse(isset($_SESSION[$key])); + $this->assertArrayNotHasKey($key, $_SESSION); $storage->start(); } diff --git a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php index 5cfb328d3..384ad7b03 100644 --- a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php +++ b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php @@ -79,9 +79,9 @@ public function testPhpSession53() $this->assertFalse($storage->isStarted()); $key = $storage->getMetadataBag()->getStorageKey(); - $this->assertFalse(isset($_SESSION[$key])); + $this->assertArrayNotHasKey($key, $_SESSION); $storage->start(); - $this->assertTrue(isset($_SESSION[$key])); + $this->assertArrayHasKey($key, $_SESSION); } /** @@ -102,9 +102,9 @@ public function testPhpSession54() $this->assertFalse($storage->isStarted()); $key = $storage->getMetadataBag()->getStorageKey(); - $this->assertFalse(isset($_SESSION[$key])); + $this->assertArrayNotHasKey($key, $_SESSION); $storage->start(); - $this->assertTrue(isset($_SESSION[$key])); + $this->assertArrayHasKey($key, $_SESSION); } public function testClear() From 3d7c40a290b8086149389f520c8d3f6f0742a98a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Tue, 12 Dec 2017 09:38:51 +0100 Subject: [PATCH 061/225] [HttpFoundation] Add immutable to setCache's PHPDoc --- Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Response.php b/Response.php index e079ae2e9..cf1325afe 100644 --- a/Response.php +++ b/Response.php @@ -952,7 +952,7 @@ public function setEtag($etag = null, $weak = false) /** * Sets the response's cache headers (validation and/or expiration). * - * Available options are: etag, last_modified, max_age, s_maxage, private, and public. + * Available options are: etag, last_modified, max_age, s_maxage, private, public and immutable. * * @param array $options An array of cache options * From d528e5958488e61ded7db838ad422eebeb278302 Mon Sep 17 00:00:00 2001 From: Robin Chalas Date: Tue, 12 Dec 2017 12:55:28 +0100 Subject: [PATCH 062/225] Fix tests --- Tests/ResponseHeaderBagTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index 922093e54..d15e49ebd 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -199,10 +199,10 @@ public function testCookiesWithSameNames() $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY); - $this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/foo'])); - $this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/bar'])); - $this->assertArrayHasKey('foo', $cookies['bar.foo']['/path/bar'])); - $this->assertArrayHasKey('foo', $cookies['']['/'])); + $this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/foo']); + $this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/bar']); + $this->assertArrayHasKey('foo', $cookies['bar.foo']['/path/bar']); + $this->assertArrayHasKey('foo', $cookies['']['/']); } public function testRemoveCookie() From 1473645d83dc0855434a9ef3da2e23f1506a6c53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Karlovi=C4=87?= Date: Mon, 18 Dec 2017 12:23:20 +0100 Subject: [PATCH 063/225] [2.7] Fix issues found by PHPStan --- Tests/ResponseTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 8043ee45c..5f69735fc 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -912,7 +912,7 @@ public function ianaCodesReasonPhrasesProvider() $ianaCodesReasonPhrases = array(); - $xpath = new \DomXPath($ianaHttpStatusCodes); + $xpath = new \DOMXPath($ianaHttpStatusCodes); $xpath->registerNamespace('ns', 'http://www.iana.org/assignments'); $records = $xpath->query('//ns:record'); From c9c20fc7becdd800b548e2f6eb32b8c626fd1237 Mon Sep 17 00:00:00 2001 From: Romain Neutron Date: Wed, 20 Dec 2017 15:36:51 +0100 Subject: [PATCH 064/225] [2.7][DX] Use constant message contextualisation for deprecations --- Session/Flash/FlashBag.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Flash/FlashBag.php b/Session/Flash/FlashBag.php index f533a755d..bc1f8f69b 100644 --- a/Session/Flash/FlashBag.php +++ b/Session/Flash/FlashBag.php @@ -161,7 +161,7 @@ public function clear() */ public function getIterator() { - @trigger_error('The '.__METHOD__.' method is deprecated since version 2.4 and will be removed in 3.0.', E_USER_DEPRECATED); + @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0.', E_USER_DEPRECATED); return new \ArrayIterator($this->all()); } From f9ccd584dea3d501ae59ee2fff19ad07a20a5517 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 28 Dec 2017 18:49:57 +0100 Subject: [PATCH 065/225] Error handlers' $context should be optional as it's deprecated --- Session/Storage/NativeSessionStorage.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 5620aae3c..3d8c9bc06 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -221,7 +221,7 @@ public function regenerate($destroy = false, $lifetime = null) public function save() { // Register custom error handler to catch a possible failure warning during session write - set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { + set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext = array()) { throw new ContextErrorException($errstr, $errno, E_WARNING, $errfile, $errline, $errcontext); }, E_WARNING); From 5ee275070905232ee2acbf0df958d1ba9fbe0f47 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 29 Dec 2017 10:49:16 +0100 Subject: [PATCH 066/225] [HttpFoundation] Fix false-positive ConflictingHeadersException --- Tests/RequestTest.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 3c123656c..dbd10293d 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -968,6 +968,26 @@ public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXFor $request->getClientIps(); } + /** + * @dataProvider getClientIpsWithConflictingHeadersProvider + */ + public function testGetClientIpsOnlyXHttpForwardedForTrusted($httpForwarded, $httpXForwardedFor) + { + $request = new Request(); + + $server = array( + 'REMOTE_ADDR' => '88.88.88.88', + 'HTTP_FORWARDED' => $httpForwarded, + 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor, + ); + + Request::setTrustedProxies(array('88.88.88.88'), Request::HEADER_X_FORWARDED_FOR); + + $request->initialize(array(), array(), array(), array(), array(), $server); + + $this->assertSame(array_reverse(explode(',', $httpXForwardedFor)), $request->getClientIps()); + } + public function getClientIpsWithConflictingHeadersProvider() { // $httpForwarded $httpXForwardedFor From 0e518f4d7aab8b5008aa84d482ae434a1bcf8ab5 Mon Sep 17 00:00:00 2001 From: Vincent CHALAMON Date: Sun, 24 Dec 2017 21:43:35 +0100 Subject: [PATCH 067/225] Add application/ld+json format associated to json --- Request.php | 1 + Tests/RequestTest.php | 1 + 2 files changed, 2 insertions(+) diff --git a/Request.php b/Request.php index 83b62142c..7a24f1cf8 100644 --- a/Request.php +++ b/Request.php @@ -1876,6 +1876,7 @@ protected static function initializeFormats() 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'), 'css' => array('text/css'), 'json' => array('application/json', 'application/x-json'), + 'jsonld' => array('application/ld+json'), 'xml' => array('text/xml', 'application/xml', 'application/x-xml'), 'rdf' => array('application/rdf+xml'), 'atom' => array('application/atom+xml'), diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index ed4224c4f..4524f8b23 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -334,6 +334,7 @@ public function getFormatToMimeTypeMapProvider() array('js', array('application/javascript', 'application/x-javascript', 'text/javascript')), array('css', array('text/css')), array('json', array('application/json', 'application/x-json')), + array('jsonld', array('application/ld+json')), array('xml', array('text/xml', 'application/xml', 'application/x-xml')), array('rdf', array('application/rdf+xml')), array('atom', array('application/atom+xml')), From e83c070caa59c1812db972e83ec33c4c0a654592 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 31 Dec 2017 05:55:05 +0100 Subject: [PATCH 068/225] fixed some deprecation messages --- Session/Storage/Handler/LegacyPdoSessionHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/Handler/LegacyPdoSessionHandler.php b/Session/Storage/Handler/LegacyPdoSessionHandler.php index 458bb73b3..d8af869f6 100644 --- a/Session/Storage/Handler/LegacyPdoSessionHandler.php +++ b/Session/Storage/Handler/LegacyPdoSessionHandler.php @@ -11,7 +11,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; -@trigger_error('The '.__NAMESPACE__.'\LegacyPdoSessionHandler class is deprecated since version 2.6 and will be removed in 3.0. Use the Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler class instead.', E_USER_DEPRECATED); +@trigger_error('The '.__NAMESPACE__.'\LegacyPdoSessionHandler class is deprecated since Symfony 2.6 and will be removed in 3.0. Use the Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler class instead.', E_USER_DEPRECATED); /** * Session handler using a PDO connection to read and write data. From 643f3425622ab228ee05fcf3c212c29db80922e7 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 31 Dec 2017 05:48:26 +0100 Subject: [PATCH 069/225] fixed some deprecation messages --- ParameterBag.php | 4 ++-- Request.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ParameterBag.php b/ParameterBag.php index dc8effe09..b524c27e5 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -87,7 +87,7 @@ public function add(array $parameters = array()) public function get($key, $default = null, $deep = false) { if ($deep) { - @trigger_error('Using paths to find deeper items in '.__METHOD__.' is deprecated since version 2.8 and will be removed in 3.0. Filter the returned value in your own code instead.', E_USER_DEPRECATED); + @trigger_error('Using paths to find deeper items in '.__METHOD__.' is deprecated since Symfony 2.8 and will be removed in 3.0. Filter the returned value in your own code instead.', E_USER_DEPRECATED); } if (!$deep || false === $pos = strpos($key, '[')) { @@ -264,7 +264,7 @@ public function filter($key, $default = null, $filter = FILTER_DEFAULT, $options } } if (is_bool($filter) || !isset($filters[$filter]) || is_array($deep)) { - @trigger_error('Passing the $deep boolean as 3rd argument to the '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Remove it altogether as the $deep argument will be removed in 3.0.', E_USER_DEPRECATED); + @trigger_error('Passing the $deep boolean as 3rd argument to the '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0. Remove it altogether as the $deep argument will be removed in 3.0.', E_USER_DEPRECATED); $tmp = $deep; $deep = $filter; $filter = $options; diff --git a/Request.php b/Request.php index 987e58118..38b4c56c0 100644 --- a/Request.php +++ b/Request.php @@ -734,7 +734,7 @@ public static function getHttpMethodParameterOverride() public function get($key, $default = null, $deep = false) { if ($deep) { - @trigger_error('Using paths to find deeper items in '.__METHOD__.' is deprecated since version 2.8 and will be removed in 3.0. Filter the returned value in your own code instead.', E_USER_DEPRECATED); + @trigger_error('Using paths to find deeper items in '.__METHOD__.' is deprecated since Symfony 2.8 and will be removed in 3.0. Filter the returned value in your own code instead.', E_USER_DEPRECATED); } if ($this !== $result = $this->query->get($key, $this, $deep)) { From 1cce1abb646331efee8558f214692e37b89e7eb4 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 31 Dec 2017 06:33:21 +0100 Subject: [PATCH 070/225] fixed some deprecation messages --- Request.php | 8 ++++---- Tests/RequestTest.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Request.php b/Request.php index 351e5d3ce..7b47948c6 100644 --- a/Request.php +++ b/Request.php @@ -587,7 +587,7 @@ public static function setTrustedProxies(array $proxies/*, int $trustedHeaderSet self::$trustedProxies = $proxies; if (2 > func_num_args()) { - @trigger_error(sprintf('The %s() method expects a bit field of Request::HEADER_* as second argument since version 3.3. Defining it will be required in 4.0. ', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('The %s() method expects a bit field of Request::HEADER_* as second argument since Symfony 3.3. Defining it will be required in 4.0. ', __METHOD__), E_USER_DEPRECATED); return; } @@ -667,7 +667,7 @@ public static function getTrustedHosts() */ public static function setTrustedHeaderName($key, $value) { - @trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED); if ('forwarded' === $key) { $key = self::HEADER_FORWARDED; @@ -707,7 +707,7 @@ public static function setTrustedHeaderName($key, $value) public static function getTrustedHeaderName($key) { if (2 > func_num_args() || func_get_arg(1)) { - @trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.', __METHOD__), E_USER_DEPRECATED); } if (!array_key_exists($key, self::$trustedHeaders)) { @@ -1548,7 +1548,7 @@ public function isMethodSafe(/* $andCacheable = true */) if (!func_num_args() || func_get_arg(0)) { // This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature) // then setting $andCacheable to false should be deprecated in 4.1 - @trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since version 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.', E_USER_DEPRECATED); + @trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since Symfony 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.', E_USER_DEPRECATED); return in_array($this->getMethod(), array('GET', 'HEAD')); } diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 60b5aa1de..444b98820 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1756,7 +1756,7 @@ public function testTrustedProxiesXForwardedFor() /** * @group legacy - * @expectedDeprecation The "Symfony\Component\HttpFoundation\Request::setTrustedHeaderName()" method is deprecated since version 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. + * @expectedDeprecation The "Symfony\Component\HttpFoundation\Request::setTrustedHeaderName()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. */ public function testLegacyTrustedProxies() { @@ -2126,7 +2126,7 @@ public function methodSafeProvider() /** * @group legacy - * @expectedDeprecation Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since version 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead. + * @expectedDeprecation Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since Symfony 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead. */ public function testMethodSafeChecksCacheable() { From 56308dfe68bceb3b9626c08814083e765c8d2ac0 Mon Sep 17 00:00:00 2001 From: Guido Donnari Date: Mon, 11 Dec 2017 01:18:02 -0300 Subject: [PATCH 071/225] Fixes for Oracle in PdoSessionHandler --- Session/Storage/Handler/PdoSessionHandler.php | 138 ++++++++++++------ 1 file changed, 90 insertions(+), 48 deletions(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index daabbc21f..1f2a7dea4 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -330,13 +330,7 @@ public function write($sessionId, $data) return true; } - $updateStmt = $this->pdo->prepare( - "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id" - ); - $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); - $updateStmt->bindParam(':data', $data, \PDO::PARAM_LOB); - $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); - $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT); + $updateStmt = $this->getUpdateStatement($sessionId, $data, $maxlifetime); $updateStmt->execute(); // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in @@ -346,13 +340,7 @@ public function write($sessionId, $data) // false positives due to longer gap locking. if (!$updateStmt->rowCount()) { try { - $insertStmt = $this->pdo->prepare( - "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)" - ); - $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); - $insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB); - $insertStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); - $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT); + $insertStmt = $this->getInsertStatement($sessionId, $data, $maxlifetime); $insertStmt->execute(); } catch (\PDOException $e) { // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys @@ -521,13 +509,7 @@ private function doRead($sessionId) // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block // until other connections to the session are committed. try { - $insertStmt = $this->pdo->prepare( - "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)" - ); - $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); - $insertStmt->bindValue(':data', '', \PDO::PARAM_LOB); - $insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT); - $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT); + $insertStmt = $this->getInsertStatement($sessionId, '', 0); $insertStmt->execute(); } catch (\PDOException $e) { // Catch duplicate key error because other connection created the session already. @@ -662,6 +644,72 @@ private function getSelectSql() return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id"; } + /** + * Returns a insert statement supported by the database for writing session data. + * + * @param string $sessionId Session ID + * @param string $sessionData Encoded session data + * @param int $maxlifetime session.gc_maxlifetime + * + * @return \PDOStatement The insert statement + */ + private function getInsertStatement($sessionId, $sessionData, $maxlifetime) + { + switch ($this->driver) { + case 'oci': + $data = fopen('php://memory', 'r+'); + fwrite($data, $sessionData); + rewind($data); + $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, EMPTY_BLOB(), :lifetime, :time) RETURNING $this->dataCol into :data"; + break; + default: + $data = $sessionData; + $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"; + break; + } + + $stmt = $this->pdo->prepare($sql); + $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $stmt->bindParam(':data', $data, \PDO::PARAM_LOB); + $stmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); + $stmt->bindValue(':time', time(), \PDO::PARAM_INT); + + return $stmt; + } + + /** + * Returns a update statement supported by the database for writing session data. + * + * @param string $sessionId Session ID + * @param string $sessionData Encoded session data + * @param int $maxlifetime session.gc_maxlifetime + * + * @return \PDOStatement The update statement + */ + private function getUpdateStatement($sessionId, $sessionData, $maxlifetime) + { + switch ($this->driver) { + case 'oci': + $data = fopen('php://memory', 'r+'); + fwrite($data, $sessionData); + rewind($data); + $sql = "UPDATE $this->table SET $this->dataCol = EMPTY_BLOB(), $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id RETURNING $this->dataCol into :data"; + break; + default: + $data = $sessionData; + $sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id"; + break; + } + + $stmt = $this->pdo->prepare($sql); + $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $stmt->bindParam(':data', $data, \PDO::PARAM_LOB); + $stmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); + $stmt->bindValue(':time', time(), \PDO::PARAM_INT); + + return $stmt; + } + /** * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data. * @@ -673,18 +721,11 @@ private function getSelectSql() */ private function getMergeStatement($sessionId, $data, $maxlifetime) { - $mergeSql = null; switch (true) { case 'mysql' === $this->driver: $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)"; break; - case 'oci' === $this->driver: - // DUAL is Oracle specific dummy table - $mergeSql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ". - "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". - "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?"; - break; case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='): // MERGE is only available since SQL Server 2008 and must be terminated by semicolon // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx @@ -699,29 +740,30 @@ private function getMergeStatement($sessionId, $data, $maxlifetime) $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)"; break; + default: + // MERGE is not supported with LOBs: http://www.oracle.com/technetwork/articles/fuecks-lobs-095315.html + return null; } - if (null !== $mergeSql) { - $mergeStmt = $this->pdo->prepare($mergeSql); - - if ('sqlsrv' === $this->driver || 'oci' === $this->driver) { - $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR); - $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR); - $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB); - $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT); - $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT); - $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB); - $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT); - $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT); - } else { - $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); - $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB); - $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); - $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT); - } - - return $mergeStmt; + $mergeStmt = $this->pdo->prepare($mergeSql); + + if ('sqlsrv' === $this->driver) { + $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB); + $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT); + $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB); + $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT); + } else { + $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB); + $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); + $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT); } + + return $mergeStmt; } /** From cbec781184468398e46537c20f30ba328beaefeb Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 31 Dec 2017 07:02:56 +0100 Subject: [PATCH 072/225] fixed CS --- Session/Storage/Handler/PdoSessionHandler.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 1f2a7dea4..15945644a 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -645,7 +645,7 @@ private function getSelectSql() } /** - * Returns a insert statement supported by the database for writing session data. + * Returns an insert statement supported by the database for writing session data. * * @param string $sessionId Session ID * @param string $sessionData Encoded session data @@ -678,7 +678,7 @@ private function getInsertStatement($sessionId, $sessionData, $maxlifetime) } /** - * Returns a update statement supported by the database for writing session data. + * Returns an update statement supported by the database for writing session data. * * @param string $sessionId Session ID * @param string $sessionData Encoded session data From 5cdd7522d0dedd86cd712233d8452277f85d2581 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 31 Dec 2017 07:25:36 +0100 Subject: [PATCH 073/225] fixed some deprecation messages --- Session/Storage/Handler/MemcacheSessionHandler.php | 2 +- Session/Storage/Handler/NativeSessionHandler.php | 2 +- Session/Storage/Handler/WriteCheckSessionHandler.php | 2 +- Session/Storage/Proxy/NativeProxy.php | 2 +- Tests/Session/Storage/Handler/NativeSessionHandlerTest.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index 84f4357b1..cf728648a 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -11,7 +11,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; -@trigger_error(sprintf('The class %s is deprecated since version 3.4 and will be removed in 4.0. Use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler instead.', MemcacheSessionHandler::class), E_USER_DEPRECATED); +@trigger_error(sprintf('The class %s is deprecated since Symfony 3.4 and will be removed in 4.0. Use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler instead.', MemcacheSessionHandler::class), E_USER_DEPRECATED); /** * @author Drak diff --git a/Session/Storage/Handler/NativeSessionHandler.php b/Session/Storage/Handler/NativeSessionHandler.php index 9ea4629ca..9be4528ae 100644 --- a/Session/Storage/Handler/NativeSessionHandler.php +++ b/Session/Storage/Handler/NativeSessionHandler.php @@ -19,6 +19,6 @@ class NativeSessionHandler extends \SessionHandler { public function __construct() { - @trigger_error('The '.__NAMESPACE__.'\NativeSessionHandler class is deprecated since version 3.4 and will be removed in 4.0. Use the \SessionHandler class instead.', E_USER_DEPRECATED); + @trigger_error('The '.__NAMESPACE__.'\NativeSessionHandler class is deprecated since Symfony 3.4 and will be removed in 4.0. Use the \SessionHandler class instead.', E_USER_DEPRECATED); } } diff --git a/Session/Storage/Handler/WriteCheckSessionHandler.php b/Session/Storage/Handler/WriteCheckSessionHandler.php index 2fc7e0919..1541ec4e0 100644 --- a/Session/Storage/Handler/WriteCheckSessionHandler.php +++ b/Session/Storage/Handler/WriteCheckSessionHandler.php @@ -11,7 +11,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; -@trigger_error(sprintf('The %s class is deprecated since version 3.4 and will be removed in 4.0. Implement `SessionUpdateTimestampHandlerInterface` or extend `AbstractSessionHandler` instead.', WriteCheckSessionHandler::class), E_USER_DEPRECATED); +@trigger_error(sprintf('The %s class is deprecated since Symfony 3.4 and will be removed in 4.0. Implement `SessionUpdateTimestampHandlerInterface` or extend `AbstractSessionHandler` instead.', WriteCheckSessionHandler::class), E_USER_DEPRECATED); /** * Wraps another SessionHandlerInterface to only write the session when it has been modified. diff --git a/Session/Storage/Proxy/NativeProxy.php b/Session/Storage/Proxy/NativeProxy.php index 460abe15c..082eed143 100644 --- a/Session/Storage/Proxy/NativeProxy.php +++ b/Session/Storage/Proxy/NativeProxy.php @@ -11,7 +11,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Proxy; -@trigger_error('The '.__NAMESPACE__.'\NativeProxy class is deprecated since version 3.4 and will be removed in 4.0. Use your session handler implementation directly.', E_USER_DEPRECATED); +@trigger_error('The '.__NAMESPACE__.'\NativeProxy class is deprecated since Symfony 3.4 and will be removed in 4.0. Use your session handler implementation directly.', E_USER_DEPRECATED); /** * This proxy is built-in session handlers in PHP 5.3.x. diff --git a/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php index b5af1df36..1a68d575e 100644 --- a/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php @@ -26,7 +26,7 @@ class NativeSessionHandlerTest extends TestCase { /** - * @expectedDeprecation The Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler class is deprecated since version 3.4 and will be removed in 4.0. Use the \SessionHandler class instead. + * @expectedDeprecation The Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler class is deprecated since Symfony 3.4 and will be removed in 4.0. Use the \SessionHandler class instead. */ public function testConstruct() { From fbcfca04c69b2f037b09780daa1486dac5ed1515 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Sun, 31 Dec 2017 13:09:44 +0100 Subject: [PATCH 074/225] Update LICENSE year... forever --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 17d16a133..0138f8f07 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2017 Fabien Potencier +Copyright (c) 2004-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 86f9cca18c0ee150c1d1003cfcdddbb7b0dee18b Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 3 Jan 2018 08:23:28 +0100 Subject: [PATCH 075/225] fixed years in copyright --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 0138f8f07..21d7fb9e2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-present Fabien Potencier +Copyright (c) 2004-2018 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 6ee886faed2df4808ea5db3e43f2cbcdece9b6d4 Mon Sep 17 00:00:00 2001 From: Dariusz Date: Mon, 1 Jan 2018 23:05:14 +0100 Subject: [PATCH 076/225] PHP CS Fixer: clean up repo and adjust config --- Session/Storage/Handler/LegacyPdoSessionHandler.php | 2 ++ Session/Storage/Handler/MemcacheSessionHandler.php | 2 ++ Session/Storage/Handler/MemcachedSessionHandler.php | 2 ++ Session/Storage/Handler/MongoDbSessionHandler.php | 2 ++ 4 files changed, 8 insertions(+) diff --git a/Session/Storage/Handler/LegacyPdoSessionHandler.php b/Session/Storage/Handler/LegacyPdoSessionHandler.php index d8af869f6..194c9cd77 100644 --- a/Session/Storage/Handler/LegacyPdoSessionHandler.php +++ b/Session/Storage/Handler/LegacyPdoSessionHandler.php @@ -54,6 +54,8 @@ class LegacyPdoSessionHandler implements \SessionHandlerInterface private $timeCol; /** + * Construct new legacy PDO session handler. + * * List of available options: * * db_table: The name of the table [required] * * db_id_col: The column where to store the session id [default: sess_id] diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index 89b4dac2c..9575e4e9a 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -29,6 +29,8 @@ class MemcacheSessionHandler implements \SessionHandlerInterface private $prefix; /** + * Constructor. + * * List of available options: * * prefix: The prefix to use for the memcache keys in order to avoid collision * * expiretime: The time to live in seconds diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 6e2c2ee30..2c45face4 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -34,6 +34,8 @@ class MemcachedSessionHandler implements \SessionHandlerInterface private $prefix; /** + * Constructor. + * * List of available options: * * prefix: The prefix to use for the memcached keys in order to avoid collision * * expiretime: The time to live in seconds diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index 29fc3f529..0d8e2dd0a 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -29,6 +29,8 @@ class MongoDbSessionHandler implements \SessionHandlerInterface private $options; /** + * Constructor. + * * List of available options: * * database: The name of the database [required] * * collection: The name of the collection [required] From be1ef1f305bb56f6526c868fc93996a9c5789faf Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 9 Jan 2018 14:54:39 +0100 Subject: [PATCH 077/225] [HttpFoundation] Always call proxied handler::destroy() in StrictSessionHandler --- Session/Storage/Handler/StrictSessionHandler.php | 14 ++++++++++++++ .../Storage/Handler/StrictSessionHandlerTest.php | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Session/Storage/Handler/StrictSessionHandler.php b/Session/Storage/Handler/StrictSessionHandler.php index 1bad0641e..228119297 100644 --- a/Session/Storage/Handler/StrictSessionHandler.php +++ b/Session/Storage/Handler/StrictSessionHandler.php @@ -19,6 +19,7 @@ class StrictSessionHandler extends AbstractSessionHandler { private $handler; + private $doDestroy; public function __construct(\SessionHandlerInterface $handler) { @@ -63,11 +64,24 @@ protected function doWrite($sessionId, $data) return $this->handler->write($sessionId, $data); } + /** + * {@inheritdoc} + */ + public function destroy($sessionId) + { + $this->doDestroy = true; + $destroyed = parent::destroy($sessionId); + + return $this->doDestroy ? $this->doDestroy($sessionId) : $destroyed; + } + /** * {@inheritdoc} */ protected function doDestroy($sessionId) { + $this->doDestroy = false; + return $this->handler->destroy($sessionId); } diff --git a/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php b/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php index 8e9784876..b02c41ae8 100644 --- a/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php @@ -118,7 +118,7 @@ public function testWriteEmptyNewSession() $handler->expects($this->once())->method('read') ->with('id')->willReturn(''); $handler->expects($this->never())->method('write'); - $handler->expects($this->never())->method('destroy'); + $handler->expects($this->once())->method('destroy')->willReturn(true); $proxy = new StrictSessionHandler($handler); $this->assertFalse($proxy->validateId('id')); @@ -154,7 +154,7 @@ public function testDestroyNewSession() $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); $handler->expects($this->once())->method('read') ->with('id')->willReturn(''); - $handler->expects($this->never())->method('destroy'); + $handler->expects($this->once())->method('destroy')->willReturn(true); $proxy = new StrictSessionHandler($handler); $this->assertSame('', $proxy->read('id')); From a55274fbd4cfa7eb33289bb448e37636982d9388 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 6 Jan 2018 08:55:13 +0100 Subject: [PATCH 078/225] [HttpKernel] Fix session handling: decouple "save" from setting response "private" --- Session/Session.php | 15 +++++++++++++-- Session/SessionBagProxy.php | 5 ++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Session/Session.php b/Session/Session.php index 0c3371fab..a46cffbb8 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -29,6 +29,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable private $flashName; private $attributeName; private $data = array(); + private $hasBeenStarted; /** * @param SessionStorageInterface $storage A SessionStorageInterface instance @@ -140,6 +141,16 @@ public function count() return count($this->getAttributeBag()->all()); } + /** + * @return bool + * + * @internal + */ + public function hasBeenStarted() + { + return $this->hasBeenStarted; + } + /** * @return bool * @@ -227,7 +238,7 @@ public function getMetadataBag() */ public function registerBag(SessionBagInterface $bag) { - $this->storage->registerBag(new SessionBagProxy($bag, $this->data)); + $this->storage->registerBag(new SessionBagProxy($bag, $this->data, $this->hasBeenStarted)); } /** @@ -257,6 +268,6 @@ public function getFlashBag() */ private function getAttributeBag() { - return $this->storage->getBag($this->attributeName)->getBag(); + return $this->getBag($this->attributeName); } } diff --git a/Session/SessionBagProxy.php b/Session/SessionBagProxy.php index 6c4cab671..307836d5f 100644 --- a/Session/SessionBagProxy.php +++ b/Session/SessionBagProxy.php @@ -20,11 +20,13 @@ final class SessionBagProxy implements SessionBagInterface { private $bag; private $data; + private $hasBeenStarted; - public function __construct(SessionBagInterface $bag, array &$data) + public function __construct(SessionBagInterface $bag, array &$data, &$hasBeenStarted) { $this->bag = $bag; $this->data = &$data; + $this->hasBeenStarted = &$hasBeenStarted; } /** @@ -56,6 +58,7 @@ public function getName() */ public function initialize(array &$array) { + $this->hasBeenStarted = true; $this->data[$this->bag->getStorageKey()] = &$array; $this->bag->initialize($array); From 0451bae531b17b2fe4edf29dc1371722f62704f5 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 15 Jan 2018 13:27:55 +0100 Subject: [PATCH 079/225] fix HHVM tests --- Tests/RequestTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 4524f8b23..1b6426ae9 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -45,18 +45,18 @@ public function testGetLocale() public function testGetUser() { - $request = Request::create('http://user_test:password_test@test.com/'); + $request = Request::create('http://user:password@test.com'); $user = $request->getUser(); - $this->assertEquals('user_test', $user); + $this->assertEquals('user', $user); } public function testGetPassword() { - $request = Request::create('http://user_test:password_test@test.com/'); + $request = Request::create('http://user:password@test.com'); $password = $request->getPassword(); - $this->assertEquals('password_test', $password); + $this->assertEquals('password', $password); } public function testIsNoCache() From 6031e98163f6e9020d477787e64d0a022efd176c Mon Sep 17 00:00:00 2001 From: Yanick Witschi Date: Mon, 15 Jan 2018 16:19:42 +0100 Subject: [PATCH 080/225] Fixed Request::__toString ignoring cookies --- Request.php | 14 +++++++++++++- Tests/RequestTest.php | 12 +++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/Request.php b/Request.php index 7a24f1cf8..ce7258acd 100644 --- a/Request.php +++ b/Request.php @@ -496,9 +496,21 @@ public function __toString() return trigger_error($e, E_USER_ERROR); } + $cookieHeader = ''; + $cookies = array(); + + foreach ($this->cookies as $k => $v) { + $cookies[] = $k.'='.$v; + } + + if (!empty($cookies)) { + $cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n"; + } + return sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n". - $this->headers."\r\n". + $this->headers. + $cookieHeader."\r\n". $content; } diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 1b6426ae9..5dad40576 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1454,8 +1454,18 @@ public function testToString() $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); + $request->cookies->set('Foo', 'Bar'); - $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $request->__toString()); + $asString = (string) $request; + + $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $asString); + $this->assertContains('Cookie: Foo=Bar', $asString); + + $request->cookies->set('Another', 'Cookie'); + + $asString = (string) $request; + + $this->assertContains('Cookie: Foo=Bar; Another=Cookie', $asString); } public function testIsMethod() From fd93ef99328eadeaec380480d046c07cae083b03 Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 10 Nov 2017 11:21:24 +0000 Subject: [PATCH 081/225] [HttpFoundation] Added "resource" type on Request::create docblock --- Request.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Request.php b/Request.php index ce7258acd..297f036a2 100644 --- a/Request.php +++ b/Request.php @@ -294,13 +294,13 @@ public static function createFromGlobals() * The information contained in the URI always take precedence * over the other information (server and parameters). * - * @param string $uri The URI - * @param string $method The HTTP method - * @param array $parameters The query (GET) or request (POST) parameters - * @param array $cookies The request cookies ($_COOKIE) - * @param array $files The request files ($_FILES) - * @param array $server The server parameters ($_SERVER) - * @param string $content The raw body data + * @param string $uri The URI + * @param string $method The HTTP method + * @param array $parameters The query (GET) or request (POST) parameters + * @param array $cookies The request cookies ($_COOKIE) + * @param array $files The request files ($_FILES) + * @param array $server The server parameters ($_SERVER) + * @param string|resource $content The raw body data * * @return static */ From 38cd54aa32820a00e7411f28b8db0dea9451cdbe Mon Sep 17 00:00:00 2001 From: AmsTaFFix Date: Wed, 15 Nov 2017 15:24:59 +0300 Subject: [PATCH 082/225] [HttpFoundation] fixed return type of method HeaderBag::get --- HeaderBag.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/HeaderBag.php b/HeaderBag.php index a797d7a2e..d1065e797 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -101,11 +101,11 @@ public function add(array $headers) /** * Returns a header value by name. * - * @param string $key The header name - * @param mixed $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[] $default The default value + * @param bool $first Whether to return the first value or all header values * - * @return string|array The first header value if $first is true, an array of values otherwise + * @return string|string[] The first header value or default value if $first is true, an array of values otherwise */ public function get($key, $default = null, $first = true) { @@ -129,9 +129,9 @@ public function get($key, $default = null, $first = true) /** * Sets a header by name. * - * @param string $key The key - * @param string|array $values The value or an array of values - * @param bool $replace Whether to replace the actual value or not (true by default) + * @param string $key The key + * @param string|string[] $values The value or an array of values + * @param bool $replace Whether to replace the actual value or not (true by default) */ public function set($key, $values, $replace = true) { From db68fd060456056aa28b3bc07ab984a3e65c51b0 Mon Sep 17 00:00:00 2001 From: Cosmin-Romeo TANASE Date: Thu, 25 Jan 2018 06:29:19 +0000 Subject: [PATCH 083/225] [HttpFoundation] Use the correct syntax for session gc based on Pdo driver --- Session/Storage/Handler/PdoSessionHandler.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 15945644a..dfd665160 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -375,7 +375,11 @@ public function close() $this->gcCalled = false; // delete the session records that have expired - $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time - $this->timeCol"; + if ('mysql' === $this->driver) { + $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time"; + } else { + $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time - $this->timeCol"; + } $stmt = $this->pdo->prepare($sql); $stmt->bindValue(':time', time(), \PDO::PARAM_INT); From 78e80bb932b1088f593a74aa272fc800c1968eeb Mon Sep 17 00:00:00 2001 From: Dariusz Date: Sun, 21 Jan 2018 19:35:11 +0100 Subject: [PATCH 084/225] [HttpFoundation] Added "null" type on Request::create docblock --- Request.php | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Request.php b/Request.php index 297f036a2..fe7080ab8 100644 --- a/Request.php +++ b/Request.php @@ -130,7 +130,7 @@ class Request public $headers; /** - * @var string|resource + * @var string|resource|false|null */ protected $content; @@ -207,13 +207,13 @@ class Request protected static $requestFactory; /** - * @param array $query The GET parameters - * @param array $request The POST parameters - * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) - * @param array $cookies The COOKIE parameters - * @param array $files The FILES parameters - * @param array $server The SERVER parameters - * @param string|resource $content The raw body data + * @param array $query The GET parameters + * @param array $request The POST parameters + * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) + * @param array $cookies The COOKIE parameters + * @param array $files The FILES parameters + * @param array $server The SERVER parameters + * @param string|resource|null $content The raw body data */ public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) { @@ -225,13 +225,13 @@ public function __construct(array $query = array(), array $request = array(), ar * * This method also re-initializes all properties. * - * @param array $query The GET parameters - * @param array $request The POST parameters - * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) - * @param array $cookies The COOKIE parameters - * @param array $files The FILES parameters - * @param array $server The SERVER parameters - * @param string|resource $content The raw body data + * @param array $query The GET parameters + * @param array $request The POST parameters + * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) + * @param array $cookies The COOKIE parameters + * @param array $files The FILES parameters + * @param array $server The SERVER parameters + * @param string|resource|null $content The raw body data */ public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) { @@ -294,13 +294,13 @@ public static function createFromGlobals() * The information contained in the URI always take precedence * over the other information (server and parameters). * - * @param string $uri The URI - * @param string $method The HTTP method - * @param array $parameters The query (GET) or request (POST) parameters - * @param array $cookies The request cookies ($_COOKIE) - * @param array $files The request files ($_FILES) - * @param array $server The server parameters ($_SERVER) - * @param string|resource $content The raw body data + * @param string $uri The URI + * @param string $method The HTTP method + * @param array $parameters The query (GET) or request (POST) parameters + * @param array $cookies The request cookies ($_COOKIE) + * @param array $files The request files ($_FILES) + * @param array $server The server parameters ($_SERVER) + * @param string|resource|null $content The raw body data * * @return static */ From 7878b34bd20bf8633b42b9c9866d2c7e45206186 Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Thu, 1 Feb 2018 03:55:42 -0200 Subject: [PATCH 085/225] Improve assertions --- Tests/Session/Storage/Handler/NativeSessionHandlerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php index 1a68d575e..4a9fb600d 100644 --- a/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeSessionHandlerTest.php @@ -32,7 +32,7 @@ public function testConstruct() { $handler = new NativeSessionHandler(); - $this->assertTrue($handler instanceof \SessionHandler); + $this->assertInstanceOf('SessionHandler', $handler); $this->assertTrue($handler instanceof NativeSessionHandler); } } From fce0fd78a84429e107b09826423e3e16859a7280 Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Tue, 6 Feb 2018 07:47:25 -0200 Subject: [PATCH 086/225] Fix misspelling variable --- Tests/RequestTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 5dad40576..96f87958e 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1982,11 +1982,11 @@ public function testMethodSafeChecksCacheable() /** * @dataProvider methodCacheableProvider */ - public function testMethodCacheable($method, $chacheable) + public function testMethodCacheable($method, $cacheable) { $request = new Request(); $request->setMethod($method); - $this->assertEquals($chacheable, $request->isMethodCacheable()); + $this->assertEquals($cacheable, $request->isMethodCacheable()); } public function methodCacheableProvider() From 0557e1241590c922d6664d0d0f087ec5b9a35afc Mon Sep 17 00:00:00 2001 From: Ian Jenkins Date: Thu, 15 Feb 2018 15:19:03 +0000 Subject: [PATCH 087/225] [HttpFoundation] Add x-zip-compressed to MimeTypeExtensionGuesser. Zip files uploaded on Windows often have a mime type of `x-zip-compressed`. This patch adds support for this mime type to `MimeTypeExtensionGuesser`. The mime type seems to be a valid mime type for zip files according to http://filext.com/file-extension/ZIP --- File/MimeType/MimeTypeExtensionGuesser.php | 1 + 1 file changed, 1 insertion(+) diff --git a/File/MimeType/MimeTypeExtensionGuesser.php b/File/MimeType/MimeTypeExtensionGuesser.php index 49c323c1f..36271afe4 100644 --- a/File/MimeType/MimeTypeExtensionGuesser.php +++ b/File/MimeType/MimeTypeExtensionGuesser.php @@ -599,6 +599,7 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'application/x-xliff+xml' => 'xlf', 'application/x-xpinstall' => 'xpi', 'application/x-xz' => 'xz', + 'application/x-zip-compressed' => 'zip', 'application/x-zmachine' => 'z1', 'application/xaml+xml' => 'xaml', 'application/xcap-diff+xml' => 'xdf', From 0b384aa088e17a283c2ffebcd0bce19458840a20 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 19 Feb 2018 12:59:32 +0100 Subject: [PATCH 088/225] [HttpFoundation] Fix missing "throw" in JsonResponse --- JsonResponse.php | 1 + 1 file changed, 1 insertion(+) diff --git a/JsonResponse.php b/JsonResponse.php index 4ec2fa19a..51852443c 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -148,6 +148,7 @@ public function setData($data = array()) if (\PHP_VERSION_ID < 50500 || !interface_exists('JsonSerializable', false)) { restore_error_handler(); } + throw $e; } catch (\Exception $e) { if (\PHP_VERSION_ID < 50500 || !interface_exists('JsonSerializable', false)) { restore_error_handler(); From 4cdc08cab8c6514a33faf9fd4282a52e8d75d342 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Mon, 19 Feb 2018 12:14:59 +0100 Subject: [PATCH 089/225] Add support for URL-like DSNs for the PdoSessionHandler This allows migrating away from the deprecated DbalSessionHandler when DBAL was used for its ability to be configured through a URL (which is what is provided on Heroku and some other PaaS). --- Session/Storage/Handler/PdoSessionHandler.php | 100 +++++++++++++++++- .../Storage/Handler/PdoSessionHandlerTest.php | 35 ++++++ 2 files changed, 134 insertions(+), 1 deletion(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 2e1692b6f..c8737be18 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -164,7 +164,7 @@ class PdoSessionHandler extends AbstractSessionHandler * * db_connection_options: An array of driver-specific connection options [default: array()] * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL] * - * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or null + * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null * @param array $options An associative array of options * * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION @@ -178,6 +178,8 @@ public function __construct($pdoOrDsn = null, array $options = array()) $this->pdo = $pdoOrDsn; $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); + } elseif (is_string($pdoOrDsn) && false !== strpos($pdoOrDsn, '://')) { + $this->dsn = $this->buildDsnFromUrl($pdoOrDsn); } else { $this->dsn = $pdoOrDsn; } @@ -431,6 +433,102 @@ private function connect($dsn) $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); } + /** + * Builds a PDO DSN from a URL-like connection string. + * + * @param string $dsnOrUrl + * + * @return string + * + * @todo implement missing support for oci DSN (which look totally different from other PDO ones) + */ + private function buildDsnFromUrl($dsnOrUrl) + { + // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid + $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl); + + $params = parse_url($url); + + if (false === $params) { + return $dsnOrUrl; // If the URL is not valid, let's assume it might be a DSN already. + } + + $params = array_map('rawurldecode', $params); + + // Override the default username and password. Values passed through options will still win over these in the constructor. + if (isset($params['user'])) { + $this->username = $params['user']; + } + + if (isset($params['pass'])) { + $this->password = $params['pass']; + } + + if (!isset($params['scheme'])) { + throw new \InvalidArgumentException('URLs without scheme are not supported to configure the PdoSessionHandler'); + } + + $driverAliasMap = array( + 'mssql' => 'sqlsrv', + 'mysql2' => 'mysql', // Amazon RDS, for some weird reason + 'postgres' => 'pgsql', + 'postgresql' => 'pgsql', + 'sqlite3' => 'sqlite', + ); + + $driver = isset($driverAliasMap[$params['scheme']]) ? $driverAliasMap[$params['scheme']] : $params['scheme']; + + // Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here. + if (0 === strpos($driver, 'pdo_') || 0 === strpos($driver, 'pdo-')) { + $driver = substr($driver, 4); + } + + switch ($driver) { + case 'mysql': + case 'pgsql': + $dsn = $driver.':'; + + if (isset($params['host']) && '' !== $params['host']) { + $dsn .= 'host='.$params['host'].';'; + } + + if (isset($params['port']) && '' !== $params['port']) { + $dsn .= 'port='.$params['port'].';'; + } + + if (isset($params['path'])) { + $dbName = substr($params['path'], 1); // Remove the leading slash + $dsn .= 'dbname='.$dbName.';'; + } + + return $dsn; + + case 'sqlite': + return 'sqlite:'.substr($params['path'], 1); + + case 'sqlsrv': + $dsn = 'sqlsrv:server='; + + if (isset($params['host'])) { + $dsn .= $params['host']; + } + + if (isset($params['port']) && '' !== $params['port']) { + $dsn .= ','.$params['port']; + } + + if (isset($params['path'])) { + $dbName = substr($params['path'], 1); // Remove the leading slash + $dsn .= ';Database='.$dbName; + } + + return $dsn; + + default: + throw new \InvalidArgumentException(sprintf('The scheme "%s" is not supported by the PdoSessionHandler URL configuration. Pass a PDO DSN directly.', $params['scheme'])); + } + } + /** * Helper method to begin a transaction. * diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index a0d7529f0..0a0e44905 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -324,6 +324,41 @@ public function testGetConnectionConnectsIfNeeded() $this->assertInstanceOf('\PDO', $method->invoke($storage)); } + /** + * @dataProvider provideUrlDsnPairs + */ + public function testUrlDsn($url, $expectedDsn, $expectedUser = null, $expectedPassword = null) + { + $storage = new PdoSessionHandler($url); + + $this->assertAttributeEquals($expectedDsn, 'dsn', $storage); + + if (null !== $expectedUser) { + $this->assertAttributeEquals($expectedUser, 'username', $storage); + } + + if (null !== $expectedPassword) { + $this->assertAttributeEquals($expectedPassword, 'password', $storage); + } + } + + public function provideUrlDsnPairs() + { + yield array('mysql://localhost/test', 'mysql:host=localhost;dbname=test;'); + yield array('mysql://localhost:56/test', 'mysql:host=localhost;port=56;dbname=test;'); + yield array('mysql2://root:pwd@localhost/test', 'mysql:host=localhost;dbname=test;', 'root', 'pwd'); + yield array('postgres://localhost/test', 'pgsql:host=localhost;dbname=test;'); + yield array('postgresql://localhost:5634/test', 'pgsql:host=localhost;port=5634;dbname=test;'); + yield array('postgres://root:pwd@localhost/test', 'pgsql:host=localhost;dbname=test;', 'root', 'pwd'); + yield 'sqlite relative path' => array('sqlite://localhost/tmp/test', 'sqlite:tmp/test'); + yield 'sqlite absolute path' => array('sqlite://localhost//tmp/test', 'sqlite:/tmp/test'); + yield 'sqlite relative path without host' => array('sqlite:///tmp/test', 'sqlite:tmp/test'); + yield 'sqlite absolute path without host' => array('sqlite3:////tmp/test', 'sqlite:/tmp/test'); + yield array('sqlite://localhost/:memory:', 'sqlite::memory:'); + yield array('mssql://localhost/test', 'sqlsrv:server=localhost;Database=test'); + yield array('mssql://localhost:56/test', 'sqlsrv:server=localhost,56;Database=test'); + } + private function createStream($content) { $stream = tmpfile(); From fe8ef850635f26d32884605141ef2f2730be61f3 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 19 Feb 2018 15:59:04 +0100 Subject: [PATCH 090/225] Clean calls to http_build_query() --- Request.php | 2 +- Tests/RequestTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Request.php b/Request.php index fe7080ab8..ecdcdbc25 100644 --- a/Request.php +++ b/Request.php @@ -522,7 +522,7 @@ public function __toString() */ public function overrideGlobals() { - $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), null, '&'))); + $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&'))); $_GET = $this->query->all(); $_POST = $this->request->all(); diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 96f87958e..0c5451dfd 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -2065,7 +2065,7 @@ class RequestContentProxy extends Request { public function getContent($asResource = false) { - return http_build_query(array('_method' => 'PUT', 'content' => 'mycontent')); + return http_build_query(array('_method' => 'PUT', 'content' => 'mycontent'), '', '&'); } } From e37263b485bdd82cfca21fe9b9b66ed0795bca7e Mon Sep 17 00:00:00 2001 From: Alessandro Loffredo Date: Wed, 7 Mar 2018 14:52:09 +0100 Subject: [PATCH 091/225] fix the updating of timestamp in the MemcachedSessionHandler --- Session/Storage/Handler/MemcachedSessionHandler.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 9f4ef7028..dd37eae14 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -80,7 +80,9 @@ protected function doRead($sessionId) */ public function updateTimestamp($sessionId, $data) { - return $this->memcached->touch($this->prefix.$sessionId, time() + $this->ttl); + $this->memcached->touch($this->prefix.$sessionId, time() + $this->ttl); + + return true; } /** From 920c757a503643cff395b0ffc2c88c66029616a7 Mon Sep 17 00:00:00 2001 From: Haralan Dobrev Date: Tue, 3 Apr 2018 01:34:16 +0300 Subject: [PATCH 092/225] Add PHPDbg support to HTTP components --- Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Response.php b/Response.php index 4aabc0da2..a7459224c 100644 --- a/Response.php +++ b/Response.php @@ -372,7 +372,7 @@ public function send() if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); - } elseif ('cli' !== PHP_SAPI) { + } elseif (!\in_array(PHP_SAPI, array('cli', 'phpdbg'), true)) { static::closeOutputBuffers(0, true); } From 4b15446b894d0dca1d7f03a54734ae9121942420 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 6 Dec 2017 10:31:46 +0100 Subject: [PATCH 093/225] [HttpFoundation] Send cookies using header() to fix "SameSite" ones --- Response.php | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/Response.php b/Response.php index 6f8a62395..f3e45b57c 100644 --- a/Response.php +++ b/Response.php @@ -327,7 +327,7 @@ public function sendHeaders() } // headers - foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) { + foreach ($this->headers->allPreserveCase() as $name => $values) { foreach ($values as $value) { header($name.': '.$value, false, $this->statusCode); } @@ -336,15 +336,6 @@ public function sendHeaders() // status header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode); - // cookies - foreach ($this->headers->getCookies() as $cookie) { - if ($cookie->isRaw()) { - setrawcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); - } else { - setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); - } - } - return $this; } From 68bd4bc61fd272d5f14404f683bc6e95095e6a54 Mon Sep 17 00:00:00 2001 From: Matthias Pigulla Date: Thu, 22 Mar 2018 20:40:31 +0100 Subject: [PATCH 094/225] Fix that ESI/SSI processing can turn a \"private\" response \"public\" --- Response.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Response.php b/Response.php index 4aabc0da2..cbeaf2762 100644 --- a/Response.php +++ b/Response.php @@ -507,13 +507,19 @@ public function getCharset() } /** - * Returns true if the response is worth caching under any circumstance. + * Returns true if the response may safely be kept in a shared (surrogate) cache. * * Responses marked "private" with an explicit Cache-Control directive are * considered uncacheable. * * Responses with neither a freshness lifetime (Expires, max-age) nor cache - * validator (Last-Modified, ETag) are considered uncacheable. + * validator (Last-Modified, ETag) are considered uncacheable because there is + * no way to tell when or how to remove them from the cache. + * + * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation, + * for example "status codes that are defined as cacheable by default [...] + * can be reused by a cache with heuristic expiration unless otherwise indicated" + * (https://tools.ietf.org/html/rfc7231#section-6.1) * * @return bool true if the response is worth caching, false otherwise */ From 02ef4f383de873a73939683e81b074941f1fd167 Mon Sep 17 00:00:00 2001 From: Teoh Han Hui Date: Wed, 11 Apr 2018 14:53:24 +0200 Subject: [PATCH 095/225] Don't assume that file binary exists on *nix OS Certain lightweight distributions such as Alpine Linux (popular for smaller Docker images) do not include it by default. --- File/MimeType/FileBinaryMimeTypeGuesser.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index c2ac6768c..3c3581046 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -43,7 +43,21 @@ public function __construct($cmd = 'file -b --mime %s 2>/dev/null') */ public static function isSupported() { - return '\\' !== DIRECTORY_SEPARATOR && function_exists('passthru') && function_exists('escapeshellarg'); + static $supported = null; + + if (null !== $supported) { + return $supported; + } + + if ('\\' === DIRECTORY_SEPARATOR || !function_exists('passthru') || !function_exists('escapeshellarg')) { + return $supported = false; + } + + ob_start(); + passthru('command -v file', $exitStatus); + $binPath = trim(ob_get_clean()); + + return $supported = 0 === $exitStatus && '' !== $binPath; } /** From b79dcc54c464a09b5b34dd4641c6ba26ae78fecf Mon Sep 17 00:00:00 2001 From: cvilleger Date: Thu, 5 Apr 2018 14:19:22 +0200 Subject: [PATCH 096/225] [HttpFoundation] Add functional tests for Response::sendHeaders() --- Cookie.php | 8 ++- Tests/CookieTest.php | 8 +-- Tests/Fixtures/response-functional/common.inc | 39 +++++++++++++ .../cookie_max_age.expected | 11 ++++ .../response-functional/cookie_max_age.php | 10 ++++ .../cookie_raw_urlencode.expected | 10 ++++ .../cookie_raw_urlencode.php | 12 ++++ .../cookie_samesite_lax.expected | 9 +++ .../cookie_samesite_lax.php | 8 +++ .../cookie_samesite_strict.expected | 9 +++ .../cookie_samesite_strict.php | 8 +++ .../cookie_urlencode.expected | 10 ++++ .../response-functional/cookie_urlencode.php | 12 ++++ .../invalid_cookie_name.expected | 6 ++ .../invalid_cookie_name.php | 11 ++++ Tests/ResponseFunctionalTest.php | 58 +++++++++++++++++++ Tests/ResponseHeaderBagTest.php | 4 +- 17 files changed, 224 insertions(+), 9 deletions(-) create mode 100644 Tests/Fixtures/response-functional/common.inc create mode 100644 Tests/Fixtures/response-functional/cookie_max_age.expected create mode 100644 Tests/Fixtures/response-functional/cookie_max_age.php create mode 100644 Tests/Fixtures/response-functional/cookie_raw_urlencode.expected create mode 100644 Tests/Fixtures/response-functional/cookie_raw_urlencode.php create mode 100644 Tests/Fixtures/response-functional/cookie_samesite_lax.expected create mode 100644 Tests/Fixtures/response-functional/cookie_samesite_lax.php create mode 100644 Tests/Fixtures/response-functional/cookie_samesite_strict.expected create mode 100644 Tests/Fixtures/response-functional/cookie_samesite_strict.php create mode 100644 Tests/Fixtures/response-functional/cookie_urlencode.expected create mode 100644 Tests/Fixtures/response-functional/cookie_urlencode.php create mode 100644 Tests/Fixtures/response-functional/invalid_cookie_name.expected create mode 100644 Tests/Fixtures/response-functional/invalid_cookie_name.php create mode 100644 Tests/ResponseFunctionalTest.php diff --git a/Cookie.php b/Cookie.php index 4519a6ada..d202dc6c1 100644 --- a/Cookie.php +++ b/Cookie.php @@ -145,12 +145,12 @@ public function __toString() $str = ($this->isRaw() ? $this->getName() : urlencode($this->getName())).'='; if ('' === (string) $this->getValue()) { - $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; max-age=-31536001'; + $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0'; } else { $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue()); if (0 !== $this->getExpiresTime()) { - $str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; max-age='.$this->getMaxAge(); + $str .= '; expires='.gmdate('D, d-M-Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge(); } } @@ -224,7 +224,9 @@ public function getExpiresTime() */ public function getMaxAge() { - return 0 !== $this->expire ? $this->expire - time() : 0; + $maxAge = $this->expire - time(); + + return 0 >= $maxAge ? 0 : $maxAge; } /** diff --git a/Tests/CookieTest.php b/Tests/CookieTest.php index 070b7dd42..a47b71e1d 100644 --- a/Tests/CookieTest.php +++ b/Tests/CookieTest.php @@ -162,13 +162,13 @@ public function testCookieIsCleared() public function testToString() { $cookie = new Cookie('foo', 'bar', $expire = strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true); - $this->assertEquals('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; max-age='.($expire - time()).'; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() returns string representation of the cookie'); + $this->assertEquals('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; Max-Age=0; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() returns string representation of the cookie'); $cookie = new Cookie('foo', 'bar with white spaces', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true); - $this->assertEquals('foo=bar%20with%20white%20spaces; expires=Fri, 20-May-2011 15:25:52 GMT; max-age='.($expire - time()).'; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() encodes the value of the cookie according to RFC 3986 (white space = %20)'); + $this->assertEquals('foo=bar%20with%20white%20spaces; expires=Fri, 20-May-2011 15:25:52 GMT; Max-Age=0; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() encodes the value of the cookie according to RFC 3986 (white space = %20)'); $cookie = new Cookie('foo', null, 1, '/admin/', '.myfoodomain.com'); - $this->assertEquals('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', $expire = time() - 31536001).'; max-age='.($expire - time()).'; path=/admin/; domain=.myfoodomain.com; httponly', (string) $cookie, '->__toString() returns string representation of a cleared cookie if value is NULL'); + $this->assertEquals('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', $expire = time() - 31536001).'; Max-Age=0; path=/admin/; domain=.myfoodomain.com; httponly', (string) $cookie, '->__toString() returns string representation of a cleared cookie if value is NULL'); $cookie = new Cookie('foo', 'bar', 0, '/', ''); $this->assertEquals('foo=bar; path=/; httponly', (string) $cookie); @@ -194,7 +194,7 @@ public function testGetMaxAge() $this->assertEquals($expire - time(), $cookie->getMaxAge()); $cookie = new Cookie('foo', 'bar', $expire = time() - 100); - $this->assertEquals($expire - time(), $cookie->getMaxAge()); + $this->assertEquals(0, $cookie->getMaxAge()); } public function testFromString() diff --git a/Tests/Fixtures/response-functional/common.inc b/Tests/Fixtures/response-functional/common.inc new file mode 100644 index 000000000..ba101d357 --- /dev/null +++ b/Tests/Fixtures/response-functional/common.inc @@ -0,0 +1,39 @@ +headers->set('Date', 'Sat, 12 Nov 1955 20:04:00 GMT'); + +return $r; diff --git a/Tests/Fixtures/response-functional/cookie_max_age.expected b/Tests/Fixtures/response-functional/cookie_max_age.expected new file mode 100644 index 000000000..bdb9d023f --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_max_age.expected @@ -0,0 +1,11 @@ + +Warning: Expiry date cannot have a year greater than 9999 in %scookie_max_age.php on line 10 + +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: foo=bar; expires=Sat, 01-Jan-10000 02:46:40 GMT; Max-Age=%d; path=/ +) +shutdown diff --git a/Tests/Fixtures/response-functional/cookie_max_age.php b/Tests/Fixtures/response-functional/cookie_max_age.php new file mode 100644 index 000000000..8775a5cce --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_max_age.php @@ -0,0 +1,10 @@ +headers->setCookie(new Cookie('foo', 'bar', 253402310800, '', null, false, false)); +$r->sendHeaders(); + +setcookie('foo2', 'bar', 253402310800, '/'); diff --git a/Tests/Fixtures/response-functional/cookie_raw_urlencode.expected b/Tests/Fixtures/response-functional/cookie_raw_urlencode.expected new file mode 100644 index 000000000..0c097972e --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_raw_urlencode.expected @@ -0,0 +1,10 @@ + +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: ?*():@&+$/%#[]=?*():@&+$/%#[]; path=/ + [4] => Set-Cookie: ?*():@&+$/%#[]=?*():@&+$/%#[]; path=/ +) +shutdown diff --git a/Tests/Fixtures/response-functional/cookie_raw_urlencode.php b/Tests/Fixtures/response-functional/cookie_raw_urlencode.php new file mode 100644 index 000000000..2ca5b59f1 --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_raw_urlencode.php @@ -0,0 +1,12 @@ +headers->setCookie(new Cookie($str, $str, 0, '/', null, false, false, true)); +$r->sendHeaders(); + +setrawcookie($str, $str, 0, '/', null, false, false); diff --git a/Tests/Fixtures/response-functional/cookie_samesite_lax.expected b/Tests/Fixtures/response-functional/cookie_samesite_lax.expected new file mode 100644 index 000000000..cbde2cbfe --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_samesite_lax.expected @@ -0,0 +1,9 @@ + +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: CookieSamesiteLaxTest=LaxValue; path=/; httponly; samesite=lax +) +shutdown diff --git a/Tests/Fixtures/response-functional/cookie_samesite_lax.php b/Tests/Fixtures/response-functional/cookie_samesite_lax.php new file mode 100644 index 000000000..9a476f1d2 --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_samesite_lax.php @@ -0,0 +1,8 @@ +headers->setCookie(new Cookie('CookieSamesiteLaxTest', 'LaxValue', 0, '/', null, false, true, false, Cookie::SAMESITE_LAX)); +$r->sendHeaders(); diff --git a/Tests/Fixtures/response-functional/cookie_samesite_strict.expected b/Tests/Fixtures/response-functional/cookie_samesite_strict.expected new file mode 100644 index 000000000..adc491fd2 --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_samesite_strict.expected @@ -0,0 +1,9 @@ + +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: CookieSamesiteStrictTest=StrictValue; path=/; httponly; samesite=strict +) +shutdown diff --git a/Tests/Fixtures/response-functional/cookie_samesite_strict.php b/Tests/Fixtures/response-functional/cookie_samesite_strict.php new file mode 100644 index 000000000..3bcb41f8f --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_samesite_strict.php @@ -0,0 +1,8 @@ +headers->setCookie(new Cookie('CookieSamesiteStrictTest', 'StrictValue', 0, '/', null, false, true, false, Cookie::SAMESITE_STRICT)); +$r->sendHeaders(); diff --git a/Tests/Fixtures/response-functional/cookie_urlencode.expected b/Tests/Fixtures/response-functional/cookie_urlencode.expected new file mode 100644 index 000000000..4e9c4c075 --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_urlencode.expected @@ -0,0 +1,10 @@ + +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=/ + [4] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/ +) +shutdown diff --git a/Tests/Fixtures/response-functional/cookie_urlencode.php b/Tests/Fixtures/response-functional/cookie_urlencode.php new file mode 100644 index 000000000..05b9af30d --- /dev/null +++ b/Tests/Fixtures/response-functional/cookie_urlencode.php @@ -0,0 +1,12 @@ +headers->setCookie(new Cookie($str, $str, 0, '', null, false, false)); +$r->sendHeaders(); + +setcookie($str, $str, 0, '/'); diff --git a/Tests/Fixtures/response-functional/invalid_cookie_name.expected b/Tests/Fixtures/response-functional/invalid_cookie_name.expected new file mode 100644 index 000000000..2b560f0bd --- /dev/null +++ b/Tests/Fixtures/response-functional/invalid_cookie_name.expected @@ -0,0 +1,6 @@ +The cookie name "Hello + world" contains invalid characters. +Array +( + [0] => Content-Type: text/plain; charset=utf-8 +) +shutdown diff --git a/Tests/Fixtures/response-functional/invalid_cookie_name.php b/Tests/Fixtures/response-functional/invalid_cookie_name.php new file mode 100644 index 000000000..3fe157184 --- /dev/null +++ b/Tests/Fixtures/response-functional/invalid_cookie_name.php @@ -0,0 +1,11 @@ +headers->setCookie(new Cookie('Hello + world', 'hodor')); +} catch (\InvalidArgumentException $e) { + echo $e->getMessage(); +} diff --git a/Tests/ResponseFunctionalTest.php b/Tests/ResponseFunctionalTest.php new file mode 100644 index 000000000..22f25e978 --- /dev/null +++ b/Tests/ResponseFunctionalTest.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpFoundation\Tests; + +use PHPUnit\Framework\TestCase; + +/** + * @requires PHP 7.0 + */ +class ResponseFunctionalTest extends TestCase +{ + private static $server; + + public static function setUpBeforeClass() + { + $spec = array( + 1 => array('file', '/dev/null', 'w'), + 2 => array('file', '/dev/null', 'w'), + ); + if (!self::$server = @proc_open('exec php -S localhost:8054', $spec, $pipes, __DIR__.'/Fixtures/response-functional')) { + self::markTestSkipped('PHP server unable to start.'); + } + sleep(1); + } + + public static function tearDownAfterClass() + { + if (self::$server) { + proc_terminate(self::$server); + proc_close(self::$server); + } + } + + /** + * @dataProvider provideCookie + */ + public function testCookie($fixture) + { + $result = file_get_contents(sprintf('http://localhost:8054/%s.php', $fixture)); + $this->assertStringMatchesFormatFile(__DIR__.sprintf('/Fixtures/response-functional/%s.expected', $fixture), $result); + } + + public function provideCookie() + { + foreach (glob(__DIR__.'/Fixtures/response-functional/*.php') as $file) { + yield array(pathinfo($file, PATHINFO_FILENAME)); + } + } +} diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index ce8553590..7b5e720af 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -116,7 +116,7 @@ public function testToStringIncludesCookieHeaders() $bag->clearCookie('foo'); - $this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; max-age=-31536001; path=/; httponly', $bag); + $this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0; path=/; httponly', $bag); } public function testClearCookieSecureNotHttpOnly() @@ -125,7 +125,7 @@ public function testClearCookieSecureNotHttpOnly() $bag->clearCookie('foo', '/', null, true, false); - $this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; max-age=-31536001; path=/; secure', $bag); + $this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0; path=/; secure', $bag); } public function testReplace() From 1d170f9114695ed0026f6d8ff46cdd4ca5e1d5c2 Mon Sep 17 00:00:00 2001 From: Ahmad Mayahi Date: Mon, 23 Apr 2018 10:51:32 +0200 Subject: [PATCH 097/225] [HttpFoundation] Add HTTP_EARLY_HINTS const --- Response.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Response.php b/Response.php index ad551a85b..13b85b15d 100644 --- a/Response.php +++ b/Response.php @@ -21,6 +21,7 @@ class Response const HTTP_CONTINUE = 100; const HTTP_SWITCHING_PROTOCOLS = 101; const HTTP_PROCESSING = 102; // RFC2518 + const HTTP_EARLY_HINTS = 103; // RFC8297 const HTTP_OK = 200; const HTTP_CREATED = 201; const HTTP_ACCEPTED = 202; From 7a61d311eb3d224e46edf6d726bbb1a28caea7c9 Mon Sep 17 00:00:00 2001 From: Nikolay Labinskiy Date: Thu, 26 Apr 2018 17:44:59 +0300 Subject: [PATCH 098/225] Fix #27011: Session ini_set bug --- Session/Storage/NativeSessionStorage.php | 6 +++--- .../Storage/NativeSessionStorageTest.php | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index f03cdf343..34d94c55b 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -340,7 +340,7 @@ public function setOptions(array $options) } $validOptions = array_flip(array( - 'cache_limiter', 'cookie_domain', 'cookie_httponly', + 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly', 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'entropy_file', 'entropy_length', 'gc_divisor', 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character', @@ -348,13 +348,13 @@ public function setOptions(array $options) 'serialize_handler', 'use_strict_mode', 'use_cookies', 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled', 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name', - 'upload_progress.freq', 'upload_progress.min-freq', 'url_rewriter.tags', + 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags', 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags', )); foreach ($options as $key => $value) { if (isset($validOptions[$key])) { - ini_set('session.'.$key, $value); + ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value); } } } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 3501f7478..529583c01 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -183,6 +183,23 @@ public function testCookieOptions() $this->assertEquals($options, $gco); } + public function testSessionOptions() + { + if (defined('HHVM_VERSION')) { + $this->markTestSkipped('HHVM is not handled in this test case.'); + } + + $options = array( + 'url_rewriter.tags' => 'a=href', + 'cache_expire' => '200', + ); + + $this->getStorage($options); + + $this->assertSame('a=href', ini_get('url_rewriter.tags')); + $this->assertSame('200', ini_get('session.cache_expire')); + } + /** * @expectedException \InvalidArgumentException */ From 2d671296c6d25011c0690c074e9c4b104eddda32 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Thu, 3 May 2018 14:15:36 +0200 Subject: [PATCH 099/225] use brace-style regex delimiters --- Request.php | 2 +- Tests/RequestTest.php | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Request.php b/Request.php index ecdcdbc25..e1309d477 100644 --- a/Request.php +++ b/Request.php @@ -581,7 +581,7 @@ public static function getTrustedProxies() public static function setTrustedHosts(array $hostPatterns) { self::$trustedHostPatterns = array_map(function ($hostPattern) { - return sprintf('#%s#i', $hostPattern); + return sprintf('{%s}i', $hostPattern); }, $hostPatterns); // we need to reset trusted hosts on trusted host patterns change self::$trustedHosts = array(); diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 0c5451dfd..688a7c714 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -18,6 +18,11 @@ class RequestTest extends TestCase { + protected function tearDown() + { + Request::setTrustedHosts(array()); + } + public function testInitialize() { $request = new Request(); @@ -1871,9 +1876,15 @@ public function testTrustedHosts() $request->headers->set('host', 'subdomain.trusted.com'); $this->assertEquals('subdomain.trusted.com', $request->getHost()); + } - // reset request for following tests - Request::setTrustedHosts(array()); + public function testSetTrustedHostsDoesNotBreakOnSpecialCharacters() + { + Request::setTrustedHosts(array('localhost(\.local){0,1}#,example.com', 'localhost')); + + $request = Request::create('/'); + $request->headers->set('host', 'localhost'); + $this->assertSame('localhost', $request->getHost()); } public function testFactory() From 9f01f9b8c53b5ee454d3cd63540187ac0ec6432b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tarmo=20Lepp=C3=A4nen?= Date: Mon, 7 May 2018 19:50:17 +0300 Subject: [PATCH 100/225] Fixed return type --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index e1309d477..7e8e075a8 100644 --- a/Request.php +++ b/Request.php @@ -1322,7 +1322,7 @@ public function getRealMethod() * * @param string $format The format * - * @return string The associated mime type (null if not found) + * @return string|null The associated mime type (null if not found) */ public function getMimeType($format) { From da48c2113675b38233245d16f73dd9238fb87a62 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 10 May 2018 19:25:00 -0700 Subject: [PATCH 101/225] [Filesystem] Fix usages of error_get_last() --- File/File.php | 8 +++++--- File/UploadedFile.php | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/File/File.php b/File/File.php index e2a67684f..65ece9837 100644 --- a/File/File.php +++ b/File/File.php @@ -93,9 +93,11 @@ public function move($directory, $name = null) { $target = $this->getTargetFile($directory, $name); - if (!@rename($this->getPathname(), $target)) { - $error = error_get_last(); - throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message']))); + set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; }); + $renamed = rename($this->getPathname(), $target); + restore_error_handler(); + if (!$renamed) { + throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error))); } @chmod($target, 0666 & ~umask()); diff --git a/File/UploadedFile.php b/File/UploadedFile.php index 082d8d534..39b29775c 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -192,9 +192,11 @@ public function move($directory, $name = null) $target = $this->getTargetFile($directory, $name); - if (!@move_uploaded_file($this->getPathname(), $target)) { - $error = error_get_last(); - throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message']))); + set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; }); + $moved = move_uploaded_file($this->getPathname(), $target); + restore_error_handler(); + if (!$moved) { + throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error))); } @chmod($target, 0666 & ~umask()); From eff0bf432903ed8c2d6e31584ae4e64063a1fda8 Mon Sep 17 00:00:00 2001 From: Oleg Andreyev Date: Mon, 14 May 2018 20:26:58 +0300 Subject: [PATCH 102/225] #27250 limiting GET_LOCK key up to 64 char due to changes in MySQL 5.7.5 and later --- Session/Storage/Handler/PdoSessionHandler.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index dfd665160..0825ee6ea 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -552,14 +552,16 @@ private function doAdvisoryLock($sessionId) { switch ($this->driver) { case 'mysql': + // MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced. + $lockId = \substr($sessionId, 0, 64); // should we handle the return value? 0 on timeout, null on error // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)'); - $stmt->bindValue(':key', $sessionId, \PDO::PARAM_STR); + $stmt->bindValue(':key', $lockId, \PDO::PARAM_STR); $stmt->execute(); $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)'); - $releaseStmt->bindValue(':key', $sessionId, \PDO::PARAM_STR); + $releaseStmt->bindValue(':key', $lockId, \PDO::PARAM_STR); return $releaseStmt; case 'pgsql': From 59d936ebdd878d7e6b68145ce4725cf040a8f791 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 18 May 2018 09:42:46 +0200 Subject: [PATCH 103/225] [HttpFoundation] Break infinite loop in PdoSessionHandler when MySQL is in loose mode --- Session/Storage/Handler/PdoSessionHandler.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 0825ee6ea..bb000f5c9 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -494,6 +494,7 @@ private function doRead($sessionId) $selectSql = $this->getSelectSql(); $selectStmt = $this->pdo->prepare($selectSql); $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); + $insertStmt = null; do { $selectStmt->execute(); @@ -509,6 +510,11 @@ private function doRead($sessionId) return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; } + if (null !== $insertStmt) { + $this->rollback(); + throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.'); + } + if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block // until other connections to the session are committed. From 92f35ae81546a7cf9935c07bbac868fa713a5d9c Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 23 May 2018 23:20:28 +0200 Subject: [PATCH 104/225] [HttpFoundation] Fix perf issue during MimeTypeGuesser intialization --- File/MimeType/MimeTypeGuesser.php | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/File/MimeType/MimeTypeGuesser.php b/File/MimeType/MimeTypeGuesser.php index e3ef45ef6..d78c76068 100644 --- a/File/MimeType/MimeTypeGuesser.php +++ b/File/MimeType/MimeTypeGuesser.php @@ -80,13 +80,8 @@ public static function reset() */ private function __construct() { - if (FileBinaryMimeTypeGuesser::isSupported()) { - $this->register(new FileBinaryMimeTypeGuesser()); - } - - if (FileinfoMimeTypeGuesser::isSupported()) { - $this->register(new FileinfoMimeTypeGuesser()); - } + $this->register(new FileBinaryMimeTypeGuesser()); + $this->register(new FileinfoMimeTypeGuesser()); } /** @@ -125,18 +120,14 @@ public function guess($path) throw new AccessDeniedException($path); } - if (!$this->guessers) { - $msg = 'Unable to guess the mime type as no guessers are available'; - if (!FileinfoMimeTypeGuesser::isSupported()) { - $msg .= ' (Did you enable the php_fileinfo extension?)'; - } - throw new \LogicException($msg); - } - foreach ($this->guessers as $guesser) { if (null !== $mimeType = $guesser->guess($path)) { return $mimeType; } } + + if (2 === \count($this->guessers) && !FileBinaryMimeTypeGuesser::isSupported() && !FileinfoMimeTypeGuesser::isSupported()) { + throw new \LogicException('Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)'); + } } } From af20b8dff66bb5f1cff90a374a7c29f5d44ffd08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Ostroluck=C3=BD?= Date: Thu, 24 May 2018 22:59:06 +0200 Subject: [PATCH 105/225] [HttpFoundation] Fix cookie test with xdebug Here's the failure without this patch: ``` Testing Symfony\Component\HttpFoundation\Tests\ResponseFunctionalTest F..... 6 / 6 (100%) Time: 1.07 seconds, Memory: 4.00MB There was 1 failure: 1) Symfony\Component\HttpFoundation\Tests\ResponseFunctionalTest::testCookie with data set #0 ('cookie_max_age') Failed asserting that string matches format description. --- Expected +++ Actual @@ @@ Warning: Expiry date cannot have a year greater than 9999 in /home/gadelat/PhpstormProjects/symfony/src/Symfony/Component/HttpFoundation/Tests/Fixtures/response-functional/cookie_max_age.php on line 10 +Call Stack: + 0.0004 390392 1. {main}() /home/gadelat/PhpstormProjects/symfony/src/Symfony/Component/HttpFoundation/Tests/Fixtures/response-functional/cookie_max_age.php:0 + 0.0178 500960 2. setcookie() /home/gadelat/PhpstormProjects/symfony/src/Symfony/Component/HttpFoundation/Tests/Fixtures/response-functional/cookie_max_age.php:10 + + 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: foo=bar; expires=Sat, 01-Jan-10000 02:46:40 GMT; Max-Age=%d; path=/ + [3] => Set-Cookie: foo=bar; expires=Sat, 01-Jan-10000 02:46:40 GMT; Max-Age=251875115405; path=/ ) shutdown /home/gadelat/PhpstormProjects/symfony/src/Symfony/Component/HttpFoundation/Tests/ResponseFunctionalTest.php:49 ``` --- Tests/Fixtures/response-functional/common.inc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Tests/Fixtures/response-functional/common.inc b/Tests/Fixtures/response-functional/common.inc index ba101d357..f9c40a9a3 100644 --- a/Tests/Fixtures/response-functional/common.inc +++ b/Tests/Fixtures/response-functional/common.inc @@ -22,6 +22,10 @@ error_reporting(-1); ini_set('html_errors', 0); ini_set('display_errors', 1); +if (ini_get('xdebug.default_enable')) { + xdebug_disable(); +} + header_remove('X-Powered-By'); header('Content-Type: text/plain; charset=utf-8'); From 41328109b0ef0677d3052e01d4d952cd15acad4c Mon Sep 17 00:00:00 2001 From: Davide Borsatto Date: Tue, 29 May 2018 10:57:40 +0200 Subject: [PATCH 106/225] Change PHPDoc in ResponseHeaderBag::getCookies() to help IDEs --- ResponseHeaderBag.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index a042328ca..c299c3692 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -160,7 +160,7 @@ public function removeCookie($name, $path = '/', $domain = null) * * @param string $format * - * @return array + * @return Cookie[] * * @throws \InvalidArgumentException When the $format is invalid */ From c449dc770db96ee48976f7892f0f1391884ed19c Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 31 May 2018 12:02:37 +0200 Subject: [PATCH 107/225] [HttpKernel] Fix restoring trusted proxies in tests --- Tests/RequestTest.php | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 0080cf8ac..3b65bcc99 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -20,6 +20,7 @@ class RequestTest extends TestCase { protected function tearDown() { + Request::setTrustedProxies(array()); Request::setTrustedHosts(array()); } @@ -750,8 +751,6 @@ public function testGetPort() )); $port = $request->getPort(); $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.'); - - Request::setTrustedProxies(array()); } /** @@ -827,8 +826,6 @@ public function testGetClientIp($expected, $remoteAddr, $httpForwardedFor, $trus $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies); $this->assertEquals($expected[0], $request->getClientIp()); - - Request::setTrustedProxies(array()); } /** @@ -839,8 +836,6 @@ public function testGetClientIps($expected, $remoteAddr, $httpForwardedFor, $tru $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies); $this->assertEquals($expected, $request->getClientIps()); - - Request::setTrustedProxies(array()); } /** @@ -851,8 +846,6 @@ public function testGetClientIpsForwarded($expected, $remoteAddr, $httpForwarded $request = $this->getRequestInstanceForClientIpsForwardedTests($remoteAddr, $httpForwarded, $trustedProxies); $this->assertEquals($expected, $request->getClientIps()); - - Request::setTrustedProxies(array()); } public function getClientIpsForwardedProvider() @@ -975,8 +968,6 @@ public function testGetClientIpsWithAgreeingHeaders($httpForwarded, $httpXForwar $clientIps = $request->getClientIps(); - Request::setTrustedProxies(array()); - $this->assertSame($expectedIps, $clientIps); } From 11fc09ddcd33aa338d7d25da8e7d47948131144a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 1 Jun 2018 14:37:16 +0200 Subject: [PATCH 108/225] [HttpKernel] fix session tracking in surrogate master requests --- Session/Session.php | 19 ++++++++++++++----- Session/SessionBagProxy.php | 14 ++++++++++---- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/Session/Session.php b/Session/Session.php index a46cffbb8..f0379c169 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -29,7 +29,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable private $flashName; private $attributeName; private $data = array(); - private $hasBeenStarted; + private $usageIndex = 0; /** * @param SessionStorageInterface $storage A SessionStorageInterface instance @@ -54,6 +54,8 @@ public function __construct(SessionStorageInterface $storage = null, AttributeBa */ public function start() { + ++$this->usageIndex; + return $this->storage->start(); } @@ -142,13 +144,13 @@ public function count() } /** - * @return bool + * @return int * * @internal */ - public function hasBeenStarted() + public function getUsageIndex() { - return $this->hasBeenStarted; + return $this->usageIndex; } /** @@ -158,6 +160,7 @@ public function hasBeenStarted() */ public function isEmpty() { + ++$this->usageIndex; foreach ($this->data as &$data) { if (!empty($data)) { return false; @@ -182,6 +185,8 @@ public function invalidate($lifetime = null) */ public function migrate($destroy = false, $lifetime = null) { + ++$this->usageIndex; + return $this->storage->regenerate($destroy, $lifetime); } @@ -190,6 +195,8 @@ public function migrate($destroy = false, $lifetime = null) */ public function save() { + ++$this->usageIndex; + $this->storage->save(); } @@ -230,6 +237,8 @@ public function setName($name) */ public function getMetadataBag() { + ++$this->usageIndex; + return $this->storage->getMetadataBag(); } @@ -238,7 +247,7 @@ public function getMetadataBag() */ public function registerBag(SessionBagInterface $bag) { - $this->storage->registerBag(new SessionBagProxy($bag, $this->data, $this->hasBeenStarted)); + $this->storage->registerBag(new SessionBagProxy($bag, $this->data, $this->usageIndex)); } /** diff --git a/Session/SessionBagProxy.php b/Session/SessionBagProxy.php index 307836d5f..88005ee09 100644 --- a/Session/SessionBagProxy.php +++ b/Session/SessionBagProxy.php @@ -20,13 +20,13 @@ final class SessionBagProxy implements SessionBagInterface { private $bag; private $data; - private $hasBeenStarted; + private $usageIndex; - public function __construct(SessionBagInterface $bag, array &$data, &$hasBeenStarted) + public function __construct(SessionBagInterface $bag, array &$data, &$usageIndex) { $this->bag = $bag; $this->data = &$data; - $this->hasBeenStarted = &$hasBeenStarted; + $this->usageIndex = &$usageIndex; } /** @@ -34,6 +34,8 @@ public function __construct(SessionBagInterface $bag, array &$data, &$hasBeenSta */ public function getBag() { + ++$this->usageIndex; + return $this->bag; } @@ -42,6 +44,8 @@ public function getBag() */ public function isEmpty() { + ++$this->usageIndex; + return empty($this->data[$this->bag->getStorageKey()]); } @@ -58,7 +62,7 @@ public function getName() */ public function initialize(array &$array) { - $this->hasBeenStarted = true; + ++$this->usageIndex; $this->data[$this->bag->getStorageKey()] = &$array; $this->bag->initialize($array); @@ -77,6 +81,8 @@ public function getStorageKey() */ public function clear() { + ++$this->usageIndex; + return $this->bag->clear(); } } From f0332229bfecb3c3d3c983f2139f39dd73d2723a Mon Sep 17 00:00:00 2001 From: Michael Moravec Date: Tue, 19 Jun 2018 13:59:09 +0200 Subject: [PATCH 109/225] Set serialize_precision explicitly to avoid fancy float rounding --- Tests/JsonResponseTest.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index e15505cc6..0559b5ba0 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -16,6 +16,15 @@ class JsonResponseTest extends TestCase { + protected function setUp() + { + parent::setUp(); + + if (!defined('HHVM_VERSION')) { + $this->iniSet('serialize_precision', 14); + } + } + public function testConstructorEmptyCreatesJsonObject() { $response = new JsonResponse(); From 36d52fc5d6bcb0bd2e48b19a7937e610fa665d75 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 27 Jun 2018 13:18:14 +0200 Subject: [PATCH 110/225] [HttpFoundation] fix session tracking counter --- Session/Session.php | 8 +++----- Session/SessionBagProxy.php | 4 ---- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/Session/Session.php b/Session/Session.php index f0379c169..31da54c73 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -160,7 +160,9 @@ public function getUsageIndex() */ public function isEmpty() { - ++$this->usageIndex; + if ($this->isStarted()) { + ++$this->usageIndex; + } foreach ($this->data as &$data) { if (!empty($data)) { return false; @@ -185,8 +187,6 @@ public function invalidate($lifetime = null) */ public function migrate($destroy = false, $lifetime = null) { - ++$this->usageIndex; - return $this->storage->regenerate($destroy, $lifetime); } @@ -195,8 +195,6 @@ public function migrate($destroy = false, $lifetime = null) */ public function save() { - ++$this->usageIndex; - $this->storage->save(); } diff --git a/Session/SessionBagProxy.php b/Session/SessionBagProxy.php index 88005ee09..d6b242d4e 100644 --- a/Session/SessionBagProxy.php +++ b/Session/SessionBagProxy.php @@ -44,8 +44,6 @@ public function getBag() */ public function isEmpty() { - ++$this->usageIndex; - return empty($this->data[$this->bag->getStorageKey()]); } @@ -81,8 +79,6 @@ public function getStorageKey() */ public function clear() { - ++$this->usageIndex; - return $this->bag->clear(); } } From d3a318f0fbb0d1fcbb55cf6c91e5958acc3370cd Mon Sep 17 00:00:00 2001 From: David Maicher Date: Mon, 25 Jun 2018 20:31:52 +0200 Subject: [PATCH 111/225] failing test to reproduce session problem --- Session/Session.php | 2 -- Session/SessionBagProxy.php | 5 +++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Session/Session.php b/Session/Session.php index 31da54c73..c0978d552 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -54,8 +54,6 @@ public function __construct(SessionStorageInterface $storage = null, AttributeBa */ public function start() { - ++$this->usageIndex; - return $this->storage->start(); } diff --git a/Session/SessionBagProxy.php b/Session/SessionBagProxy.php index d6b242d4e..3504bdfe7 100644 --- a/Session/SessionBagProxy.php +++ b/Session/SessionBagProxy.php @@ -44,6 +44,11 @@ public function getBag() */ public function isEmpty() { + if (!isset($this->data[$this->bag->getStorageKey()])) { + return true; + } + ++$this->usageIndex; + return empty($this->data[$this->bag->getStorageKey()]); } From c38f23518f03ab1f4ab3b6f04964c2b692847971 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 27 Jun 2018 17:17:35 +0200 Subject: [PATCH 112/225] [HttpFoundation] fix registration of session proxies --- Session/Storage/NativeSessionStorage.php | 2 -- Session/Storage/Proxy/SessionHandlerProxy.php | 18 +++++++++- .../Storage/Proxy/SessionHandlerProxyTest.php | 33 +++++++++++++++++++ 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 6416a03fd..41410bd32 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -411,8 +411,6 @@ public function setSaveHandler($saveHandler = null) } 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); } } diff --git a/Session/Storage/Proxy/SessionHandlerProxy.php b/Session/Storage/Proxy/SessionHandlerProxy.php index 53c1209a1..b11cc397a 100644 --- a/Session/Storage/Proxy/SessionHandlerProxy.php +++ b/Session/Storage/Proxy/SessionHandlerProxy.php @@ -14,7 +14,7 @@ /** * @author Drak */ -class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface +class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface { protected $handler; @@ -82,4 +82,20 @@ public function gc($maxlifetime) { 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); + } } diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index 682825356..0b48250e0 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -121,4 +121,37 @@ public function testGc() $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'); + } } From a45626ac24e227f72ec77caf98b0fb1f7141832d Mon Sep 17 00:00:00 2001 From: Sir Kane Date: Thu, 28 Jun 2018 18:39:54 +0000 Subject: [PATCH 113/225] [HttpFoundation] update phpdoc of FlashBagInterface::add() --- Session/Flash/FlashBagInterface.php | 2 +- Tests/Session/Flash/FlashBagTest.php | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Session/Flash/FlashBagInterface.php b/Session/Flash/FlashBagInterface.php index 80e97f17c..f53c9dae6 100644 --- a/Session/Flash/FlashBagInterface.php +++ b/Session/Flash/FlashBagInterface.php @@ -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); diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index b44429d89..3ceb12477 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -74,6 +74,18 @@ public function testPeek() $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')); From 3cb12ef5954ff67341ea517f689732452a2215b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Mon, 2 Jul 2018 23:12:41 +0200 Subject: [PATCH 114/225] [HttpFoundation] Fix tests: new message for status 425 --- Response.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Response.php b/Response.php index 9b4bb4cc5..3a1b5ca8f 100644 --- a/Response.php +++ b/Response.php @@ -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 From 8c33870a6d94a00b4b002f8a0503848e1aa8a189 Mon Sep 17 00:00:00 2001 From: Sir Kane Date: Tue, 3 Jul 2018 19:59:59 +0000 Subject: [PATCH 115/225] [HttpFoundation] add tests for FlashBagInterface::setAll() --- Tests/Session/Flash/FlashBagTest.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index 3ceb12477..3fe0122f4 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -124,6 +124,19 @@ public function testKeys() $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'); From 2654436303aaa591161a1befaa82b4c1ec9222d8 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 7 Jul 2018 11:30:05 +0200 Subject: [PATCH 116/225] [HttpFoundation] don't encode cookie name for BC --- Response.php | 7 ++++++- .../Fixtures/response-functional/cookie_urlencode.expected | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Response.php b/Response.php index ba2ebbb11..7c1edd5a5 100644 --- a/Response.php +++ b/Response.php @@ -333,12 +333,17 @@ public function sendHeaders() } // 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); diff --git a/Tests/Fixtures/response-functional/cookie_urlencode.expected b/Tests/Fixtures/response-functional/cookie_urlencode.expected index 4e9c4c075..14e44a398 100644 --- a/Tests/Fixtures/response-functional/cookie_urlencode.expected +++ b/Tests/Fixtures/response-functional/cookie_urlencode.expected @@ -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 From 4887f53a3cd36f79a213613db27397f4ee95870e Mon Sep 17 00:00:00 2001 From: Jan Hort Date: Wed, 11 Jul 2018 16:52:26 +0200 Subject: [PATCH 117/225] [HttpFoundation] Fixed phpdoc for get method of HeaderBag --- HeaderBag.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/HeaderBag.php b/HeaderBag.php index d1065e797..890dabd13 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -101,11 +101,11 @@ public function add(array $headers) /** * 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) { From 3045ecb254eeadddcff1e24f652282f6920d8847 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Calvo?= Date: Fri, 13 Jul 2018 08:54:27 +0200 Subject: [PATCH 118/225] [HttpFoundation] reset callback on StreamedResponse when setNotModified() is called --- StreamedResponse.php | 12 ++++++++++++ Tests/ResponseTest.php | 7 ++++++- Tests/StreamedResponseTest.php | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/StreamedResponse.php b/StreamedResponse.php index 01e8cf8c3..41ba4dc4e 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -134,4 +134,16 @@ public function getContent() { return false; } + + /** + * {@inheritdoc} + * + * @return $this + */ + public function setNotModified() + { + $this->setCallback(function () {}); + + return parent::setNotModified(); + } } diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 46fcc5f3e..ffd8eb354 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -126,7 +126,7 @@ public function testMustRevalidateWithProxyRevalidateCacheControlHeader() 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 @@ public function testSetNotModified() $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() diff --git a/Tests/StreamedResponseTest.php b/Tests/StreamedResponseTest.php index 2ccb6841a..66effe595 100644 --- a/Tests/StreamedResponseTest.php +++ b/Tests/StreamedResponseTest.php @@ -132,4 +132,22 @@ public function testReturnThis() $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); + } } From 9c69e10d1b094531a72959a0902deac0b2e8d616 Mon Sep 17 00:00:00 2001 From: Webnet team Date: Wed, 11 Jul 2018 15:26:07 +0200 Subject: [PATCH 119/225] suppress side effects in 'get' or 'has' methods of NamespacedAttributeBag --- Session/Attribute/NamespacedAttributeBag.php | 8 ++++++- .../Attribute/NamespacedAttributeBagTest.php | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index abbf37ee7..f9df69e90 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -124,7 +124,13 @@ protected function &resolveAttributePath($name, $writeContext = false) 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]; diff --git a/Tests/Session/Attribute/NamespacedAttributeBagTest.php b/Tests/Session/Attribute/NamespacedAttributeBagTest.php index f074ce1b2..ec4cd5ad1 100644 --- a/Tests/Session/Attribute/NamespacedAttributeBagTest.php +++ b/Tests/Session/Attribute/NamespacedAttributeBagTest.php @@ -82,6 +82,17 @@ public function testHas($key, $value, $exists) $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 @@ public function testGetDefaults() $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 */ From 818a42b36985dd0501b3281601c9c4d9c3a489c4 Mon Sep 17 00:00:00 2001 From: Andreas Date: Fri, 16 Feb 2018 06:32:23 +0100 Subject: [PATCH 120/225] Fix false-positive deprecation notices for TranslationLoader and WriteCheckSessionHandler --- Session/Storage/Handler/WriteCheckSessionHandler.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Session/Storage/Handler/WriteCheckSessionHandler.php b/Session/Storage/Handler/WriteCheckSessionHandler.php index 1541ec4e0..127e47f21 100644 --- a/Session/Storage/Handler/WriteCheckSessionHandler.php +++ b/Session/Storage/Handler/WriteCheckSessionHandler.php @@ -11,8 +11,6 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; -@trigger_error(sprintf('The %s class is deprecated since Symfony 3.4 and will be removed in 4.0. Implement `SessionUpdateTimestampHandlerInterface` or extend `AbstractSessionHandler` instead.', WriteCheckSessionHandler::class), E_USER_DEPRECATED); - /** * Wraps another SessionHandlerInterface to only write the session when it has been modified. * @@ -31,6 +29,8 @@ class WriteCheckSessionHandler implements \SessionHandlerInterface public function __construct(\SessionHandlerInterface $wrappedSessionHandler) { + @trigger_error(sprintf('The %s class is deprecated since Symfony 3.4 and will be removed in 4.0. Implement `SessionUpdateTimestampHandlerInterface` or extend `AbstractSessionHandler` instead.', self::class), E_USER_DEPRECATED); + $this->wrappedSessionHandler = $wrappedSessionHandler; } From f750415afa24a8b3c0dcef9330af9fa281bd9103 Mon Sep 17 00:00:00 2001 From: Roland Franssen Date: Mon, 23 Jul 2018 20:55:22 +0200 Subject: [PATCH 121/225] [HttpFoundation] Fix Cookie::isCleared --- Cookie.php | 2 +- Tests/CookieTest.php | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Cookie.php b/Cookie.php index 93bb099cd..d31f08770 100644 --- a/Cookie.php +++ b/Cookie.php @@ -183,6 +183,6 @@ public function isHttpOnly() */ public function isCleared() { - return $this->expire < time(); + return 0 !== $this->expire && $this->expire < time(); } } diff --git a/Tests/CookieTest.php b/Tests/CookieTest.php index 2d9fb09d3..e10ee18c2 100644 --- a/Tests/CookieTest.php +++ b/Tests/CookieTest.php @@ -153,6 +153,18 @@ public function testCookieIsCleared() $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() From 19fd2d388e760db021e1b3d3e4146fbb2f1fb6b0 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Thu, 5 Jul 2018 13:24:53 +0200 Subject: [PATCH 122/225] Enable the fixer enforcing fully-qualified calls for compiler-optimized functions --- AcceptHeaderItem.php | 4 +- ApacheRequest.php | 2 +- BinaryFileResponse.php | 8 +-- File/Exception/UnexpectedTypeException.php | 2 +- File/MimeType/FileBinaryMimeTypeGuesser.php | 2 +- File/MimeType/FileinfoMimeTypeGuesser.php | 2 +- File/UploadedFile.php | 4 +- FileBag.php | 8 +-- HeaderBag.php | 6 +-- IpUtils.php | 4 +- JsonResponse.php | 8 +-- ParameterBag.php | 12 ++--- Request.php | 50 +++++++++---------- RequestMatcher.php | 6 +-- RequestStack.php | 2 +- Response.php | 18 +++---- ResponseHeaderBag.php | 6 +-- ServerBag.php | 2 +- Session/Attribute/AttributeBag.php | 2 +- Session/Attribute/NamespacedAttributeBag.php | 4 +- Session/Session.php | 2 +- Session/Storage/Handler/PdoSessionHandler.php | 8 +-- StreamedResponse.php | 4 +- Tests/File/UploadedFileTest.php | 2 +- Tests/HeaderBagTest.php | 4 +- Tests/IpUtilsTest.php | 4 +- Tests/JsonResponseTest.php | 2 +- Tests/ParameterBagTest.php | 4 +- Tests/ResponseTest.php | 4 +- Tests/Session/Attribute/AttributeBagTest.php | 4 +- Tests/Session/Flash/FlashBagTest.php | 2 +- Tests/Session/SessionTest.php | 2 +- .../Handler/MemcacheSessionHandlerTest.php | 2 +- .../Handler/MemcachedSessionHandlerTest.php | 2 +- .../Handler/MongoDbSessionHandlerTest.php | 4 +- .../Storage/Handler/PdoSessionHandlerTest.php | 8 +-- .../Storage/NativeSessionStorageTest.php | 2 +- 37 files changed, 106 insertions(+), 106 deletions(-) diff --git a/AcceptHeaderItem.php b/AcceptHeaderItem.php index c69dbbba3..fe7b08bca 100644 --- a/AcceptHeaderItem.php +++ b/AcceptHeaderItem.php @@ -57,7 +57,7 @@ public static function fromString($itemValue) $attributes[$bit] = null; } else { $parts = explode('=', $bit); - $attributes[$parts[0]] = isset($parts[1]) && strlen($parts[1]) > 0 ? $parts[1] : ''; + $attributes[$parts[0]] = isset($parts[1]) && \strlen($parts[1]) > 0 ? $parts[1] : ''; } } @@ -72,7 +72,7 @@ public static function fromString($itemValue) public function __toString() { $string = $this->value.($this->quality < 1 ? ';q='.$this->quality : ''); - if (count($this->attributes) > 0) { + 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)); diff --git a/ApacheRequest.php b/ApacheRequest.php index 84803ebae..4e99186dc 100644 --- a/ApacheRequest.php +++ b/ApacheRequest.php @@ -35,7 +35,7 @@ protected function prepareBaseUrl() if (false === strpos($this->server->get('REQUEST_URI'), $baseUrl)) { // assume mod_rewrite - return rtrim(dirname($baseUrl), '/\\'); + return rtrim(\dirname($baseUrl), '/\\'); } return $baseUrl; diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 7f1f7ed7e..7e8e145db 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -165,7 +165,7 @@ public function setContentDisposition($disposition, $filename = '', $filenameFal 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; @@ -218,12 +218,12 @@ public function prepare(Request $request) foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) { $mapping = explode('=', $mapping, 2); - if (2 === count($mapping)) { + 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)); + if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) { + $path = $location.substr($path, \strlen($pathPrefix)); break; } } diff --git a/File/Exception/UnexpectedTypeException.php b/File/Exception/UnexpectedTypeException.php index 0444b8778..62005d3b6 100644 --- a/File/Exception/UnexpectedTypeException.php +++ b/File/Exception/UnexpectedTypeException.php @@ -15,6 +15,6 @@ class UnexpectedTypeException extends FileException { public function __construct($value, $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))); } } diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index 3c3581046..8181c44e2 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -49,7 +49,7 @@ public static function isSupported() return $supported; } - if ('\\' === DIRECTORY_SEPARATOR || !function_exists('passthru') || !function_exists('escapeshellarg')) { + if ('\\' === DIRECTORY_SEPARATOR || !\function_exists('passthru') || !\function_exists('escapeshellarg')) { return $supported = false; } diff --git a/File/MimeType/FileinfoMimeTypeGuesser.php b/File/MimeType/FileinfoMimeTypeGuesser.php index 9b42835e4..d185af358 100644 --- a/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/File/MimeType/FileinfoMimeTypeGuesser.php @@ -40,7 +40,7 @@ public function __construct($magicFile = null) */ public static function isSupported() { - return function_exists('finfo_open'); + return \function_exists('finfo_open'); } /** diff --git a/File/UploadedFile.php b/File/UploadedFile.php index 39b29775c..de6ce75cc 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -222,9 +222,9 @@ public static function getMaxFilesize() $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; } diff --git a/FileBag.php b/FileBag.php index 5edd0e621..c135ad641 100644 --- a/FileBag.php +++ b/FileBag.php @@ -45,7 +45,7 @@ public function replace(array $files = array()) */ 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 @@ protected function convertFileInformation($file) } $file = $this->fixPhpFilesArray($file); - if (is_array($file)) { + if (\is_array($file)) { $keys = array_keys($file); sort($keys); @@ -113,14 +113,14 @@ protected function convertFileInformation($file) */ 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; } diff --git a/HeaderBag.php b/HeaderBag.php index 890dabd13..06c9e9a0c 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -120,7 +120,7 @@ public function get($key, $default = null, $first = true) } if ($first) { - return count($this->headers[$key]) ? $this->headers[$key][0] : $default; + return \count($this->headers[$key]) ? $this->headers[$key][0] : $default; } return $this->headers[$key]; @@ -172,7 +172,7 @@ public function has($key) */ public function contains($key, $value) { - return in_array($value, $this->get($key, null, false)); + return \in_array($value, $this->get($key, null, false)); } /** @@ -280,7 +280,7 @@ public function getIterator() */ public function count() { - return count($this->headers); + return \count($this->headers); } protected function getCacheControlHeader() diff --git a/IpUtils.php b/IpUtils.php index 86d135b2d..a1bfa9088 100644 --- a/IpUtils.php +++ b/IpUtils.php @@ -37,7 +37,7 @@ private function __construct() */ public static function checkIp($requestIp, $ips) { - if (!is_array($ips)) { + if (!\is_array($ips)) { $ips = array($ips); } @@ -116,7 +116,7 @@ public static function checkIp6($requestIp, $ip) 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".'); } diff --git a/JsonResponse.php b/JsonResponse.php index d3695d153..5a9e75586 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -90,7 +90,7 @@ public function setCallback($callback = null) ); $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.'); } } @@ -112,7 +112,7 @@ public function setCallback($callback = null) */ public function setData($data = array()) { - if (defined('HHVM_VERSION')) { + if (\defined('HHVM_VERSION')) { // HHVM does not trigger any warnings and let exceptions // thrown from a JsonSerializable object pass through. // If only PHP did the same... @@ -136,7 +136,7 @@ public function setData($data = array()) restore_error_handler(); set_error_handler(function () use ($errorHandler) { if (JSON_ERROR_NONE === json_last_error()) { - return $errorHandler && false !== call_user_func_array($errorHandler, func_get_args()); + return $errorHandler && false !== \call_user_func_array($errorHandler, \func_get_args()); } }); $data = json_encode($data, $this->encodingOptions); @@ -153,7 +153,7 @@ public function setData($data = array()) if (\PHP_VERSION_ID < 50500 || !interface_exists('JsonSerializable', false)) { restore_error_handler(); } - if (interface_exists('JsonSerializable', false) && 'Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) { + if (interface_exists('JsonSerializable', false) && 'Exception' === \get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) { throw $e->getPrevious() ?: $e; } throw $e; diff --git a/ParameterBag.php b/ParameterBag.php index b524c27e5..fdf60e56e 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -101,7 +101,7 @@ public function get($key, $default = null, $deep = false) $value = $this->parameters[$root]; $currentKey = null; - for ($i = $pos, $c = strlen($key); $i < $c; ++$i) { + for ($i = $pos, $c = \strlen($key); $i < $c; ++$i) { $char = $key[$i]; if ('[' === $char) { @@ -115,7 +115,7 @@ public function get($key, $default = null, $deep = false) throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "]" at position %d.', $i)); } - if (!is_array($value) || !array_key_exists($currentKey, $value)) { + if (!\is_array($value) || !array_key_exists($currentKey, $value)) { return $default; } @@ -263,7 +263,7 @@ public function filter($key, $default = null, $filter = FILTER_DEFAULT, $options $filters[filter_id($tmp)] = 1; } } - if (is_bool($filter) || !isset($filters[$filter]) || is_array($deep)) { + if (\is_bool($filter) || !isset($filters[$filter]) || \is_array($deep)) { @trigger_error('Passing the $deep boolean as 3rd argument to the '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0. Remove it altogether as the $deep argument will be removed in 3.0.', E_USER_DEPRECATED); $tmp = $deep; $deep = $filter; @@ -274,12 +274,12 @@ public function filter($key, $default = null, $filter = FILTER_DEFAULT, $options $value = $this->get($key, $default, $deep); // 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; } @@ -303,6 +303,6 @@ public function getIterator() */ public function count() { - return count($this->parameters); + return \count($this->parameters); } } diff --git a/Request.php b/Request.php index 60a7c47ad..f055201df 100644 --- a/Request.php +++ b/Request.php @@ -288,7 +288,7 @@ public static function createFromGlobals() $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); @@ -540,7 +540,7 @@ public function overrideGlobals() 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); @@ -1133,7 +1133,7 @@ public function getRelativeUriForPath($path) } $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 @@ -1176,7 +1176,7 @@ public function getQueryString() public function isSecure() { if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_CLIENT_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'); @@ -1220,10 +1220,10 @@ public function getHost() throw new \UnexpectedValueException(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; } @@ -1331,10 +1331,10 @@ public function getFormat($mimeType) } 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; } } @@ -1352,7 +1352,7 @@ public function setFormat($format, $mimeTypes) static::initializeFormats(); } - static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes); + static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : array($mimeTypes); } /** @@ -1464,7 +1464,7 @@ public function isMethod($method) */ public function isMethodSafe(/* $andCacheable = true */) { - return in_array($this->getMethod(), 0 < func_num_args() && !func_get_arg(0) ? array('GET', 'HEAD', 'OPTIONS', 'TRACE') : array('GET', 'HEAD')); + return \in_array($this->getMethod(), 0 < \func_num_args() && !func_get_arg(0) ? array('GET', 'HEAD', 'OPTIONS', 'TRACE') : array('GET', 'HEAD')); } /** @@ -1476,7 +1476,7 @@ public function isMethodSafe(/* $andCacheable = true */) */ public function isMethodCacheable() { - return in_array($this->getMethod(), array('GET', 'HEAD')); + return \in_array($this->getMethod(), array('GET', 'HEAD')); } /** @@ -1490,7 +1490,7 @@ public function isMethodCacheable() */ public function getContent($asResource = false) { - $currentContentIsResource = is_resource($this->content); + $currentContentIsResource = \is_resource($this->content); if (\PHP_VERSION_ID < 50600 && false === $this->content) { throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.'); } @@ -1503,7 +1503,7 @@ public function getContent($asResource = false) } // 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); @@ -1571,7 +1571,7 @@ public function getPreferredLanguage(array $locales = null) $extendedPreferredLanguages[] = $language; if (false !== $position = strpos($language, '_')) { $superLanguage = substr($language, 0, $position); - if (!in_array($superLanguage, $preferredLanguages)) { + if (!\in_array($superLanguage, $preferredLanguages)) { $extendedPreferredLanguages[] = $superLanguage; } } @@ -1602,11 +1602,11 @@ public function getLanguages() // 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 { @@ -1712,7 +1712,7 @@ protected function prepareRequestUri() // 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 @@ -1752,7 +1752,7 @@ protected function prepareBaseUrl() $segs = explode('/', trim($file, '/')); $segs = array_reverse($segs); $index = 0; - $last = count($segs); + $last = \count($segs); $baseUrl = ''; do { $seg = $segs[$index]; @@ -1772,7 +1772,7 @@ protected function prepareBaseUrl() 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); } @@ -1791,8 +1791,8 @@ protected function prepareBaseUrl() // 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); @@ -1812,7 +1812,7 @@ protected function prepareBasePath() } if (basename($baseUrl) === $filename) { - $basePath = dirname($baseUrl); + $basePath = \dirname($baseUrl); } else { $basePath = $baseUrl; } @@ -1845,7 +1845,7 @@ protected function preparePathInfo() $requestUri = '/'.$requestUri; } - $pathInfo = substr($requestUri, strlen($baseUrl)); + $pathInfo = substr($requestUri, \strlen($baseUrl)); if (null !== $baseUrl && (false === $pathInfo || '' === $pathInfo)) { // If substr() returns false then PATH_INFO is set to an empty string return '/'; @@ -1909,7 +1909,7 @@ private function getUrlencodedPrefix($string, $prefix) return false; } - $len = strlen($prefix); + $len = \strlen($prefix); if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) { return $match[0]; @@ -1921,7 +1921,7 @@ private function getUrlencodedPrefix($string, $prefix) 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.'); diff --git a/RequestMatcher.php b/RequestMatcher.php index 076d077c7..6b4cef147 100644 --- a/RequestMatcher.php +++ b/RequestMatcher.php @@ -145,11 +145,11 @@ public function matchAttribute($key, $regexp) */ 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 @@ public function matches(Request $request) // 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); } } diff --git a/RequestStack.php b/RequestStack.php index 3d9cfd0c6..40123f66f 100644 --- a/RequestStack.php +++ b/RequestStack.php @@ -92,7 +92,7 @@ public function getMasterRequest() */ public function getParentRequest() { - $pos = count($this->requests) - 2; + $pos = \count($this->requests) - 2; if (!isset($this->requests[$pos])) { return; diff --git a/Response.php b/Response.php index 3a1b5ca8f..220992139 100644 --- a/Response.php +++ b/Response.php @@ -382,7 +382,7 @@ public function send() $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)) { static::closeOutputBuffers(0, true); @@ -404,8 +404,8 @@ public function send() */ 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; @@ -537,7 +537,7 @@ public function getCharset() */ public function isCacheable() { - 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; } @@ -1029,7 +1029,7 @@ public function isNotModified(Request $request) $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) { @@ -1144,7 +1144,7 @@ public function isNotFound() */ public function isRedirect($location = null) { - 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')); } /** @@ -1154,7 +1154,7 @@ public function isRedirect($location = null) */ public function isEmpty() { - return in_array($this->statusCode, array(204, 304)); + return \in_array($this->statusCode, array(204, 304)); } /** @@ -1168,8 +1168,8 @@ public function isEmpty() public static function closeOutputBuffers($targetLevel, $flush) { $status = ob_get_status(true); - $level = count($status); - $flags = defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1; + $level = \count($status); + $flags = \defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1; while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) { if ($flush) { diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index c299c3692..e97eefc44 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -87,7 +87,7 @@ public function set($key, $values, $replace = true) $this->headerNames[$uniqueKey] = $key; // ensure the cache-control header has sensible defaults - if (in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'))) { + if (\in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'))) { $computed = $this->computeCacheControlValue(); $this->headers['cache-control'] = array($computed); $this->headerNames['cache-control'] = 'Cache-Control'; @@ -166,7 +166,7 @@ public function removeCookie($name, $path = '/', $domain = null) */ 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)))); } @@ -217,7 +217,7 @@ public function clearCookie($name, $path = '/', $domain = null, $secure = false, */ 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)); } diff --git a/ServerBag.php b/ServerBag.php index 19d2022ef..d8ab561aa 100644 --- a/ServerBag.php +++ b/ServerBag.php @@ -68,7 +68,7 @@ public function getHeaders() 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 '))) { diff --git a/Session/Attribute/AttributeBag.php b/Session/Attribute/AttributeBag.php index ea1fda290..fc5fb1410 100644 --- a/Session/Attribute/AttributeBag.php +++ b/Session/Attribute/AttributeBag.php @@ -143,6 +143,6 @@ public function getIterator() */ public function count() { - return count($this->attributes); + return \count($this->attributes); } } diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index f9df69e90..2f1e01a97 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -110,7 +110,7 @@ protected function &resolveAttributePath($name, $writeContext = false) } $parts = explode($this->namespaceCharacter, $name); - if (count($parts) < 2) { + if (\count($parts) < 2) { if (!$writeContext) { return $array; } @@ -120,7 +120,7 @@ protected function &resolveAttributePath($name, $writeContext = false) return $array; } - unset($parts[count($parts) - 1]); + unset($parts[\count($parts) - 1]); foreach ($parts as $part) { if (null !== $array && !array_key_exists($part, $array)) { diff --git a/Session/Session.php b/Session/Session.php index d20a4daff..e3ad5b95a 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -136,7 +136,7 @@ public function getIterator() */ public function count() { - return count($this->storage->getBag($this->attributeName)->all()); + return \count($this->storage->getBag($this->attributeName)->all()); } /** diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index bb000f5c9..1756ae564 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -507,7 +507,7 @@ private function doRead($sessionId) 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) { @@ -617,11 +617,11 @@ private function doAdvisoryLock($sessionId) private function convertStringToInt($string) { 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); } diff --git a/StreamedResponse.php b/StreamedResponse.php index 41ba4dc4e..8552d7130 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -69,7 +69,7 @@ public static function create($callback = null, $status = 200, $headers = array( */ public function setCallback($callback) { - if (!is_callable($callback)) { + if (!\is_callable($callback)) { throw new \LogicException('The Response callback must be a valid PHP callable.'); } $this->callback = $callback; @@ -108,7 +108,7 @@ public function sendContent() throw new \LogicException('The Response callback must not be null.'); } - call_user_func($this->callback); + \call_user_func($this->callback); return $this; } diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 36f122fe7..1a88d4835 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -46,7 +46,7 @@ public function testFileUploadsWithNoMimeType() $this->assertEquals('application/octet-stream', $file->getClientMimeType()); - if (extension_loaded('fileinfo')) { + if (\extension_loaded('fileinfo')) { $this->assertEquals('image/gif', $file->getMimeType()); } } diff --git a/Tests/HeaderBagTest.php b/Tests/HeaderBagTest.php index 683ef47b2..dc1d83f18 100644 --- a/Tests/HeaderBagTest.php +++ b/Tests/HeaderBagTest.php @@ -183,7 +183,7 @@ public function testGetIterator() $this->assertEquals(array($headers[$key]), $val); } - $this->assertEquals(count($headers), $i); + $this->assertEquals(\count($headers), $i); } public function testCount() @@ -191,6 +191,6 @@ public function testCount() $headers = array('foo' => 'bar', 'HELLO' => 'WORLD'); $headerBag = new HeaderBag($headers); - $this->assertCount(count($headers), $headerBag); + $this->assertCount(\count($headers), $headerBag); } } diff --git a/Tests/IpUtilsTest.php b/Tests/IpUtilsTest.php index 7a93f9947..232a2040f 100644 --- a/Tests/IpUtilsTest.php +++ b/Tests/IpUtilsTest.php @@ -47,7 +47,7 @@ public function getIpv4Data() */ 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 @@ public function getIpv6Data() */ public function testAnIpv6WithOptionDisabledIpv6() { - if (defined('AF_INET6')) { + if (\defined('AF_INET6')) { $this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".'); } diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index 0559b5ba0..03411166f 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -20,7 +20,7 @@ protected function setUp() { parent::setUp(); - if (!defined('HHVM_VERSION')) { + if (!\defined('HHVM_VERSION')) { $this->iniSet('serialize_precision', 14); } } diff --git a/Tests/ParameterBagTest.php b/Tests/ParameterBagTest.php index 87806b3f5..fca221c34 100644 --- a/Tests/ParameterBagTest.php +++ b/Tests/ParameterBagTest.php @@ -206,7 +206,7 @@ public function testGetIterator() $this->assertEquals($parameters[$key], $val); } - $this->assertEquals(count($parameters), $i); + $this->assertEquals(\count($parameters), $i); } public function testCount() @@ -214,7 +214,7 @@ public function testCount() $parameters = array('foo' => 'bar', 'hello' => 'world'); $bag = new ParameterBag($parameters); - $this->assertCount(count($parameters), $bag); + $this->assertCount(\count($parameters), $bag); } public function testGetBoolean() diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index ffd8eb354..881a68e98 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -899,7 +899,7 @@ protected function provideResponse() */ 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'); } @@ -927,7 +927,7 @@ public function ianaCodesReasonPhrasesProvider() $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; } diff --git a/Tests/Session/Attribute/AttributeBagTest.php b/Tests/Session/Attribute/AttributeBagTest.php index 724a0b984..43644e23e 100644 --- a/Tests/Session/Attribute/AttributeBagTest.php +++ b/Tests/Session/Attribute/AttributeBagTest.php @@ -176,11 +176,11 @@ public function testGetIterator() ++$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); } } diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index 3fe0122f4..577ff1c4e 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -171,7 +171,7 @@ public function testLegacyGetIterator() ++$i; } - $this->assertEquals(count($flashes), $i); + $this->assertEquals(\count($flashes), $i); $this->assertCount(0, $this->bag->all()); } } diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index fa93507a4..50a4129d6 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -206,7 +206,7 @@ public function testGetIterator() ++$i; } - $this->assertEquals(count($attributes), $i); + $this->assertEquals(\count($attributes), $i); } public function testGetCount() diff --git a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php index 75be18bef..0a6e26ee3 100644 --- a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php @@ -32,7 +32,7 @@ class MemcacheSessionHandlerTest extends TestCase protected function setUp() { - if (defined('HHVM_VERSION')) { + if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcache class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); } diff --git a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php index 2e7be359e..2a1148010 100644 --- a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php @@ -32,7 +32,7 @@ class MemcachedSessionHandlerTest extends TestCase protected function setUp() { - if (defined('HHVM_VERSION')) { + if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcached class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); } diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 8ea0c52a8..7fa516871 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -31,11 +31,11 @@ protected function setUp() { parent::setUp(); - if (extension_loaded('mongodb')) { + if (\extension_loaded('mongodb')) { if (!class_exists('MongoDB\Client')) { $this->markTestSkipped('The mongodb/mongodb package is required.'); } - } elseif (!extension_loaded('mongo')) { + } elseif (!\extension_loaded('mongo')) { $this->markTestSkipped('The Mongo or MongoDB extension is required.'); } diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index a9884c1c9..a34c2b2c7 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -136,7 +136,7 @@ public function testReadWriteReadWithNullByte() public function testReadConvertsStreamToString() { - if (defined('HHVM_VERSION')) { + if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the PDOStatement class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); } @@ -157,7 +157,7 @@ public function testReadConvertsStreamToString() public function testReadLockedConvertsStreamToString() { - if (defined('HHVM_VERSION')) { + if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the PDOStatement class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); } @@ -358,8 +358,8 @@ public function getAttribute($attribute) 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; } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 529583c01..c1e3db461 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -185,7 +185,7 @@ public function testCookieOptions() public function testSessionOptions() { - if (defined('HHVM_VERSION')) { + if (\defined('HHVM_VERSION')) { $this->markTestSkipped('HHVM is not handled in this test case.'); } From 94bbf07cc414700d251fc162cf0eff4c1849d6fa Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 26 Jul 2018 11:03:18 +0200 Subject: [PATCH 123/225] Alpha-ordering for "use" statements --- BinaryFileResponse.php | 2 +- File/File.php | 2 +- File/MimeType/FileBinaryMimeTypeGuesser.php | 2 +- File/MimeType/FileinfoMimeTypeGuesser.php | 2 +- File/MimeType/MimeTypeGuesser.php | 2 +- File/MimeType/MimeTypeGuesserInterface.php | 2 +- Session/Session.php | 2 +- Session/Storage/NativeSessionStorage.php | 2 +- Session/Storage/PhpBridgeSessionStorage.php | 2 +- Tests/File/MimeType/MimeTypeTest.php | 2 +- Tests/RequestMatcherTest.php | 2 +- Tests/RequestTest.php | 4 ++-- Tests/ResponseHeaderBagTest.php | 2 +- Tests/Session/SessionTest.php | 4 ++-- Tests/Session/Storage/Handler/NullSessionHandlerTest.php | 2 +- Tests/Session/Storage/MockArraySessionStorageTest.php | 2 +- Tests/Session/Storage/MockFileSessionStorageTest.php | 4 ++-- Tests/Session/Storage/PhpBridgeSessionStorageTest.php | 2 +- 18 files changed, 21 insertions(+), 21 deletions(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 7e8e145db..b18a3ecbd 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -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. diff --git a/File/File.php b/File/File.php index 65ece9837..b237f9dde 100644 --- a/File/File.php +++ b/File/File.php @@ -13,8 +13,8 @@ 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. diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index 8181c44e2..7db745879 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -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). diff --git a/File/MimeType/FileinfoMimeTypeGuesser.php b/File/MimeType/FileinfoMimeTypeGuesser.php index d185af358..bf1ee9f5d 100644 --- a/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/File/MimeType/FileinfoMimeTypeGuesser.php @@ -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. diff --git a/File/MimeType/MimeTypeGuesser.php b/File/MimeType/MimeTypeGuesser.php index d78c76068..dae47a7c0 100644 --- a/File/MimeType/MimeTypeGuesser.php +++ b/File/MimeType/MimeTypeGuesser.php @@ -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. diff --git a/File/MimeType/MimeTypeGuesserInterface.php b/File/MimeType/MimeTypeGuesserInterface.php index f8c3ad228..5ac1acb82 100644 --- a/File/MimeType/MimeTypeGuesserInterface.php +++ b/File/MimeType/MimeTypeGuesserInterface.php @@ -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. diff --git a/Session/Session.php b/Session/Session.php index e3ad5b95a..725b97ea4 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -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 diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 34d94c55b..8dd39121c 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -13,8 +13,8 @@ use Symfony\Component\HttpFoundation\Session\SessionBagInterface; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler; -use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; +use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; /** diff --git a/Session/Storage/PhpBridgeSessionStorage.php b/Session/Storage/PhpBridgeSessionStorage.php index 3a2391e76..78098fbd6 100644 --- a/Session/Storage/PhpBridgeSessionStorage.php +++ b/Session/Storage/PhpBridgeSessionStorage.php @@ -11,8 +11,8 @@ namespace Symfony\Component\HttpFoundation\Session\Storage; -use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler; +use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; /** * Allows session to be started by PHP and managed by Symfony. diff --git a/Tests/File/MimeType/MimeTypeTest.php b/Tests/File/MimeType/MimeTypeTest.php index b3f1f026a..4faaff740 100644 --- a/Tests/File/MimeType/MimeTypeTest.php +++ b/Tests/File/MimeType/MimeTypeTest.php @@ -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 diff --git a/Tests/RequestMatcherTest.php b/Tests/RequestMatcherTest.php index b5d80048f..10d764a77 100644 --- a/Tests/RequestMatcherTest.php +++ b/Tests/RequestMatcherTest.php @@ -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 { diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 3b65bcc99..eca3048f9 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -12,9 +12,9 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -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 { diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index 48be57296..0d8242517 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -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 diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index 50a4129d6..8e3d55ecb 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -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; /** diff --git a/Tests/Session/Storage/Handler/NullSessionHandlerTest.php b/Tests/Session/Storage/Handler/NullSessionHandlerTest.php index 718fd0f83..9a2212b8b 100644 --- a/Tests/Session/Storage/Handler/NullSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NullSessionHandlerTest.php @@ -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. diff --git a/Tests/Session/Storage/MockArraySessionStorageTest.php b/Tests/Session/Storage/MockArraySessionStorageTest.php index 82df5543e..0c182e0b0 100644 --- a/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -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. diff --git a/Tests/Session/Storage/MockFileSessionStorageTest.php b/Tests/Session/Storage/MockFileSessionStorageTest.php index 53accd384..169579817 100644 --- a/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -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. diff --git a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php index 384ad7b03..3cb6d6622 100644 --- a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php +++ b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php @@ -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. From ab526963b4ca4d9dfad9c39283c6c50fdbd5d34a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 26 Jul 2018 13:13:39 +0200 Subject: [PATCH 124/225] Enable native_constant_invocation CS fixer --- File/File.php | 2 +- File/MimeType/FileBinaryMimeTypeGuesser.php | 2 +- Request.php | 10 +++++----- Response.php | 2 +- Tests/File/MimeType/MimeTypeTest.php | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/File/File.php b/File/File.php index b237f9dde..34220588a 100644 --- a/File/File.php +++ b/File/File.php @@ -115,7 +115,7 @@ protected function getTargetFile($directory, $name = null) 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); } diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index 7db745879..34e015ee5 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -49,7 +49,7 @@ public static function isSupported() return $supported; } - if ('\\' === DIRECTORY_SEPARATOR || !\function_exists('passthru') || !\function_exists('escapeshellarg')) { + if ('\\' === \DIRECTORY_SEPARATOR || !\function_exists('passthru') || !\function_exists('escapeshellarg')) { return $supported = false; } diff --git a/Request.php b/Request.php index f055201df..e8dfa452c 100644 --- a/Request.php +++ b/Request.php @@ -276,7 +276,7 @@ public static function createFromGlobals() // stores the Content-Type and Content-Length header values in // HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields. $server = $_SERVER; - if ('cli-server' === PHP_SAPI) { + if ('cli-server' === \PHP_SAPI) { if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) { $server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH']; } @@ -1772,9 +1772,9 @@ protected function prepareBaseUrl() 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; @@ -1795,7 +1795,7 @@ protected function prepareBaseUrl() $baseUrl = substr($requestUri, 0, $pos + \strlen($baseUrl)); } - return rtrim($baseUrl, '/'.DIRECTORY_SEPARATOR); + return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR); } /** @@ -1817,7 +1817,7 @@ protected function prepareBasePath() $basePath = $baseUrl; } - if ('\\' === DIRECTORY_SEPARATOR) { + if ('\\' === \DIRECTORY_SEPARATOR) { $basePath = str_replace('\\', '/', $basePath); } diff --git a/Response.php b/Response.php index 220992139..10581146f 100644 --- a/Response.php +++ b/Response.php @@ -384,7 +384,7 @@ public function send() 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); } diff --git a/Tests/File/MimeType/MimeTypeTest.php b/Tests/File/MimeType/MimeTypeTest.php index 4faaff740..bb88807ab 100644 --- a/Tests/File/MimeType/MimeTypeTest.php +++ b/Tests/File/MimeType/MimeTypeTest.php @@ -59,7 +59,7 @@ public function testGuessWithIncorrectPath() public function testGuessWithNonReadablePath() { - if ('\\' === DIRECTORY_SEPARATOR) { + if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('Can not verify chmod operations on Windows'); } From 10ba2fb33973711c12bec6c7b9b64404838046d7 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz Date: Fri, 27 Jul 2018 17:20:18 +0200 Subject: [PATCH 125/225] Remove the Expires header when calling Response::expire() --- Response.php | 1 + Tests/ResponseTest.php | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/Response.php b/Response.php index 10581146f..6b6308e36 100644 --- a/Response.php +++ b/Response.php @@ -675,6 +675,7 @@ public function expire() { if ($this->isFresh()) { $this->headers->set('Age', $this->getMaxAge()); + $this->headers->remove('Expires'); } return $this; diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 881a68e98..fa3a40539 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -362,6 +362,11 @@ public function testExpire() $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() From 68ce705629d1638fbcb321feb142e9e8252346e3 Mon Sep 17 00:00:00 2001 From: Phobetor Date: Fri, 27 Jul 2018 16:18:31 +0200 Subject: [PATCH 126/225] [HttpFoundation] fixed using _method parameter with invalid type --- Request.php | 5 ++++- Tests/RequestTest.php | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Request.php b/Request.php index e8dfa452c..4e9f99a05 100644 --- a/Request.php +++ b/Request.php @@ -1276,7 +1276,10 @@ public function getMethod() 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); + } } } } diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index eca3048f9..65687cf39 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -816,6 +816,11 @@ public function testGetSetMethod() $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'); } /** From 5097611b32e20a686a53ed701aeb8d5a43340c35 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 14 Jul 2018 21:56:04 +0200 Subject: [PATCH 127/225] [HttpFoundation] Remove support for legacy and risky HTTP headers --- CHANGELOG.md | 6 ++++++ Request.php | 13 +------------ Tests/RequestTest.php | 44 ------------------------------------------- 3 files changed, 7 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f48e8252..f8b043384 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ CHANGELOG ========= +2.8.44 +------ + + * [BC BREAK] Support for the IIS-only `X_ORIGINAL_URL` and `X_REWRITE_URL` + HTTP headers has been dropped for security reasons. + 2.8.0 ----- diff --git a/Request.php b/Request.php index 60a7c47ad..f8d43c514 100644 --- a/Request.php +++ b/Request.php @@ -1691,18 +1691,7 @@ protected function prepareRequestUri() { $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'); diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 3b65bcc99..e57bf62b5 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1809,52 +1809,8 @@ 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( - 'IIS_WasUrlRewritten' => '1', - 'UNENCODED_URL' => '/foo/bar', - ), - '/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', ), From 10f660d43087b2198c3789bebbd587d20ec6e956 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 31 Jul 2018 14:39:31 +0200 Subject: [PATCH 128/225] [HttpKernel] fix trusted headers management in HttpCache and InlineFragmentRenderer --- Request.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Request.php b/Request.php index 7f3426049..9cc6a9773 100644 --- a/Request.php +++ b/Request.php @@ -1944,6 +1944,11 @@ private function getTrustedValues($type, $ip = null) if (self::$trustedHeaders[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(); + if (self::HEADER_CLIENT_PORT === $type) { + foreach ($forwardedValues as $k => $v) { + $forwardedValues[$k] = substr_replace($v, '0.0.0.0', 0, strrpos($v, ':')); + } + } } if (null !== $ip) { From ee945de5ff903110368db8868d00b1481e74dbde Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 6 Aug 2018 17:30:25 +0200 Subject: [PATCH 129/225] [HttpFoundation] fix false-positive ConflictingHeadersException --- Request.php | 21 +++++++++++++----- Tests/RequestTest.php | 51 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/Request.php b/Request.php index 9cc6a9773..6dc9bbe81 100644 --- a/Request.php +++ b/Request.php @@ -1943,10 +1943,13 @@ private function getTrustedValues($type, $ip = null) if (self::$trustedHeaders[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(); + $forwardedValues = preg_match_all(sprintf('{(?:%s)="?([a-zA-Z0-9\.:_\-/\[\]]*+)}', self::$forwardedParams[$type]), $forwardedValues, $matches) ? $matches[1] : array(); if (self::HEADER_CLIENT_PORT === $type) { foreach ($forwardedValues as $k => $v) { - $forwardedValues[$k] = substr_replace($v, '0.0.0.0', 0, strrpos($v, ':')); + if (']' === substr($v, -1) || false === $v = strrchr($v, ':')) { + $v = $this->isSecure() ? ':443' : ':80'; + } + $forwardedValues[$k] = '0.0.0.0'.$v; } } } @@ -1981,9 +1984,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)) { diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index b7eceef9b..0ee92aab1 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -967,7 +967,7 @@ public function testGetClientIpsWithAgreeingHeaders($httpForwarded, $httpXForwar 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor, ); - Request::setTrustedProxies(array('88.88.88.88')); + Request::setTrustedProxies(array('88.88.88.88'), -1); $request->initialize(array(), array(), array(), array(), array(), $server); @@ -2071,6 +2071,55 @@ public function testNonstandardRequests($requestUri, $queryString, $expectedPath $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 From fadbccc550b10c9bfb37c37e30779d4224e3b9ce Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 22 Aug 2018 17:17:35 +0200 Subject: [PATCH 130/225] [HttpKernel] fix forwarding trusted headers as server parameters --- Request.php | 2 +- Tests/RequestTest.php | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Request.php b/Request.php index 6dc9bbe81..a29037279 100644 --- a/Request.php +++ b/Request.php @@ -1991,7 +1991,7 @@ private function normalizeAndFilterClientIps(array $clientIps, $ip) 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); diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 0ee92aab1..26335db90 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -868,7 +868,7 @@ public function getClientIpsForwardedProvider() 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), @@ -882,8 +882,8 @@ public function getClientIpsProvider() // 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 From 447eecd531a3ecab0d2ccb29d1269feb39b124fd Mon Sep 17 00:00:00 2001 From: Justin Date: Sun, 26 Aug 2018 12:16:17 -0400 Subject: [PATCH 131/225] Instantiate $offset and $maxlen at definition --- BinaryFileResponse.php | 4 ++-- Tests/BinaryFileResponseTest.php | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index b18a3ecbd..c0fd95ea6 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -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; /** diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index e41a2372b..031c9bbca 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -206,6 +206,19 @@ public function provideFullFileRanges() ); } + 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 */ From 2908f2a3b8e705ea01aa7f54f1b534f16a88300c Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 8 Sep 2018 14:44:02 +0200 Subject: [PATCH 132/225] Consistently throw exceptions on a single line --- Session/Storage/Handler/MemcacheSessionHandler.php | 4 +--- Session/Storage/Handler/MemcachedSessionHandler.php | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index 9575e4e9a..ad54b6c4b 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -43,9 +43,7 @@ class MemcacheSessionHandler implements \SessionHandlerInterface public function __construct(\Memcache $memcache, array $options = array()) { if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) { - throw new \InvalidArgumentException(sprintf( - 'The following options are not supported "%s"', implode(', ', $diff) - )); + throw new \InvalidArgumentException(sprintf('The following options are not supported "%s"', implode(', ', $diff))); } $this->memcache = $memcache; diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 2c45face4..1191a411d 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -50,9 +50,7 @@ public function __construct(\Memcached $memcached, array $options = array()) $this->memcached = $memcached; if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) { - throw new \InvalidArgumentException(sprintf( - 'The following options are not supported "%s"', implode(', ', $diff) - )); + throw new \InvalidArgumentException(sprintf('The following options are not supported "%s"', implode(', ', $diff))); } $this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400; From 4a45c6ae6cde4b0243523fa52ec697d3c927fbf3 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sun, 16 Sep 2018 21:41:33 +0200 Subject: [PATCH 133/225] [HttpFoundation] don't override StreamedResponse::setNotModified() --- StreamedResponse.php | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/StreamedResponse.php b/StreamedResponse.php index 8552d7130..ed1c5ff3e 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -123,6 +123,8 @@ public function setContent($content) if (null !== $content) { throw new \LogicException('The content cannot be set on a StreamedResponse instance.'); } + + $this->streamed = true; } /** @@ -134,16 +136,4 @@ public function getContent() { return false; } - - /** - * {@inheritdoc} - * - * @return $this - */ - public function setNotModified() - { - $this->setCallback(function () {}); - - return parent::setNotModified(); - } } From 0b05600f2371a407ba5a3b8cdefb5a2238bf76fc Mon Sep 17 00:00:00 2001 From: Titouan Galopin Date: Mon, 10 Sep 2018 21:53:03 +0200 Subject: [PATCH 134/225] Allow reuse of Session between requests --- Session/Session.php | 4 +++- Tests/Session/SessionTest.php | 21 +++++++++++++++++++ .../Storage/MockArraySessionStorageTest.php | 2 +- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Session/Session.php b/Session/Session.php index 725b97ea4..8293cf287 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -178,7 +178,9 @@ public function getId() */ public function setId($id) { - $this->storage->setId($id); + if ($this->storage->getId() !== $id) { + $this->storage->setId($id); + } } /** diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index 8e3d55ecb..acd551389 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -70,6 +70,27 @@ public function testSetId() $this->assertEquals('0123456789abcdef', $this->session->getId()); } + public function testSetIdAfterStart() + { + $this->session->start(); + $id = $this->session->getId(); + + $e = null; + try { + $this->session->setId($id); + } catch (\Exception $e) { + } + + $this->assertNull($e); + + try { + $this->session->setId('different'); + } catch (\Exception $e) { + } + + $this->assertInstanceOf('\LogicException', $e); + } + public function testSetName() { $this->assertEquals('MOCKSESSID', $this->session->getName()); diff --git a/Tests/Session/Storage/MockArraySessionStorageTest.php b/Tests/Session/Storage/MockArraySessionStorageTest.php index 0c182e0b0..893e120ce 100644 --- a/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -48,7 +48,7 @@ protected function setUp() $this->data = array( $this->attributes->getStorageKey() => array('foo' => 'bar'), $this->flashes->getStorageKey() => array('notice' => 'hello'), - ); + ); $this->storage = new MockArraySessionStorage(); $this->storage->registerBag($this->flashes); From 9b6e18e077ccf58aaa44085003e1891e27bcccaf Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sun, 23 Sep 2018 10:13:20 +0200 Subject: [PATCH 135/225] [HttpFoundation] fix hidding warnings from session handlers --- Session/Storage/NativeSessionStorage.php | 25 +++++++++--------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index a9a54b49d..1ec5c7ff4 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -230,29 +230,22 @@ public function save() unset($_SESSION[$key]); } - // Register custom error handler to catch a possible failure warning during session write - set_error_handler(function ($errno, $errstr, $errfile, $errline) { - throw new \ErrorException($errstr, $errno, E_WARNING, $errfile, $errline); - }, E_WARNING); + // Register error handler to add information about the current save handler + $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) { + if (E_WARNING === $type && 0 === strpos($msg, 'session_write_close():')) { + $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler; + $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler)); + } + + return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false; + }); try { - $e = null; session_write_close(); - } catch (\ErrorException $e) { } finally { restore_error_handler(); $_SESSION = $session; } - if (null !== $e) { - // The default PHP error message is not very helpful, as it does not give any information on the current save handler. - // Therefore, we catch this error and trigger a warning with a better error message - $handler = $this->getSaveHandler(); - if ($handler instanceof SessionHandlerProxy) { - $handler = $handler->getHandler(); - } - - trigger_error(sprintf('session_write_close(): Failed to write session data with %s handler', \get_class($handler)), E_USER_WARNING); - } $this->closed = true; $this->started = false; From 9fcce5f0b6896a135d192cc9fd5394fd46f74eff Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sun, 23 Sep 2018 16:32:19 +0200 Subject: [PATCH 136/225] [HttpFoundation][Security] forward locale and format to subrequests --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index a29037279..85b5a53f4 100644 --- a/Request.php +++ b/Request.php @@ -1367,7 +1367,7 @@ public function setFormat($format, $mimeTypes) * * _format request parameter * * $default * - * @param string $default The default format + * @param string|null $default The default format * * @return string The request format */ From 5d8d0ec9acfa949254b1dfcebbf66d342b54100d Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Mon, 1 Oct 2018 23:42:26 -0300 Subject: [PATCH 137/225] [CS] Use combined assignment operators when possible --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 85b5a53f4..f202d19f4 100644 --- a/Request.php +++ b/Request.php @@ -351,7 +351,7 @@ public static function create($uri, $method = 'GET', $parameters = array(), $coo if (isset($components['port'])) { $server['SERVER_PORT'] = $components['port']; - $server['HTTP_HOST'] = $server['HTTP_HOST'].':'.$components['port']; + $server['HTTP_HOST'] .= ':'.$components['port']; } if (isset($components['user'])) { From 639cb359951b7a3f2f72199a545a0f6254a9ae7b Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Tue, 2 Oct 2018 00:12:00 -0300 Subject: [PATCH 138/225] [CS] Enforces null type hint on last position in phpDocs --- BinaryFileResponse.php | 4 ++-- HeaderBag.php | 2 +- Session/Storage/Handler/PdoSessionHandler.php | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index c0fd95ea6..f11515969 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -40,7 +40,7 @@ class BinaryFileResponse extends Response * @param int $status The response status code * @param array $headers An array of response headers * @param bool $public Files are public by default - * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename + * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename * @param bool $autoEtag Whether the ETag header should be automatically set * @param bool $autoLastModified Whether the Last-Modified header should be automatically set */ @@ -60,7 +60,7 @@ public function __construct($file, $status = 200, $headers = array(), $public = * @param int $status The response status code * @param array $headers An array of response headers * @param bool $public Files are public by default - * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename + * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename * @param bool $autoEtag Whether the ETag header should be automatically set * @param bool $autoLastModified Whether the Last-Modified header should be automatically set * diff --git a/HeaderBag.php b/HeaderBag.php index 06c9e9a0c..0ef742825 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -197,7 +197,7 @@ public function remove($key) * @param string $key The parameter key * @param \DateTime $default The default value * - * @return null|\DateTime The parsed DateTime or the default value if the header does not exist + * @return \DateTime|null The parsed DateTime or the default value if the header does not exist * * @throws \RuntimeException When the HTTP header is not parseable */ diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 1756ae564..aed690377 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -71,7 +71,7 @@ class PdoSessionHandler implements \SessionHandlerInterface private $pdo; /** - * @var string|null|false DSN string or null for session.save_path or false when lazy connection disabled + * @var string|false|null DSN string or null for session.save_path or false when lazy connection disabled */ private $dsn = false; From b36e10094d027f408ca67acceb33494c9353df27 Mon Sep 17 00:00:00 2001 From: Colin O'Dell Date: Tue, 2 Oct 2018 08:07:35 -0400 Subject: [PATCH 139/225] Remove redundant path check The first `if` statement in this method already performs this same check, so the expression here always evaluated to `true`. --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 85b5a53f4..212722ed1 100644 --- a/Request.php +++ b/Request.php @@ -1120,7 +1120,7 @@ public function getRelativeUriForPath($path) } $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath); - $targetDirs = explode('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path); + $targetDirs = explode('/', substr($path, 1)); array_pop($sourceDirs); $targetFile = array_pop($targetDirs); From a8cb1404385c806536afe2ce22e8aeda68a260d1 Mon Sep 17 00:00:00 2001 From: Florent Viel Date: Mon, 8 Oct 2018 15:32:18 +0200 Subject: [PATCH 140/225] Fix class documentation The phpdoc references the PHP flush function, neither a method of this class nor its parent. --- StreamedResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/StreamedResponse.php b/StreamedResponse.php index ed1c5ff3e..44f654aef 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -17,7 +17,7 @@ * A StreamedResponse uses a callback for its content. * * The callback should use the standard PHP functions like echo - * to stream the response back to the client. The flush() method + * to stream the response back to the client. The flush() function * can also be used if needed. * * @see flush() From c787cd0d6c2377aa3ad6bddc0bfa47b180ed6e72 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 11 Oct 2018 04:32:54 -0700 Subject: [PATCH 141/225] fixed CS --- Session/Storage/Handler/NativeFileSessionHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/Handler/NativeFileSessionHandler.php b/Session/Storage/Handler/NativeFileSessionHandler.php index d6ad93749..b645ac2c2 100644 --- a/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/Session/Storage/Handler/NativeFileSessionHandler.php @@ -19,7 +19,7 @@ class NativeFileSessionHandler extends NativeSessionHandler { /** - * @param string $savePath Path of directory to save session files + * @param string $savePath path of directory to save session files * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path * From 0b647277173a60b74c5883840cd808ad0ffb1fac Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Sun, 21 Oct 2018 01:16:31 +0200 Subject: [PATCH 142/225] Revert "fixed CS" This reverts commit d48a3776fe0b425d41e3fa9f3ef8b14315c02a1f. --- Session/Storage/Handler/NativeFileSessionHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/Handler/NativeFileSessionHandler.php b/Session/Storage/Handler/NativeFileSessionHandler.php index b645ac2c2..d6ad93749 100644 --- a/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/Session/Storage/Handler/NativeFileSessionHandler.php @@ -19,7 +19,7 @@ class NativeFileSessionHandler extends NativeSessionHandler { /** - * @param string $savePath path of directory to save session files + * @param string $savePath Path of directory to save session files * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path * From f5dbb2ee6407e216e45fad13ac6bb7542256b807 Mon Sep 17 00:00:00 2001 From: "vladimir.reznichenko" Date: Fri, 26 Oct 2018 15:40:38 +0200 Subject: [PATCH 143/225] SCA: minor code tweaks --- Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Response.php b/Response.php index 3070aed61..832260a51 100644 --- a/Response.php +++ b/Response.php @@ -974,7 +974,7 @@ public function setEtag($etag = null, $weak = false) public function setCache(array $options) { if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'))) { - throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff)))); + throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff))); } if (isset($options['etag'])) { From ad760ac390fa7f115e462361541e1cd1184f778a Mon Sep 17 00:00:00 2001 From: Smaine Milianni Date: Mon, 29 Oct 2018 08:56:04 +0100 Subject: [PATCH 144/225] fix useless space in docblock --- AcceptHeaderItem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AcceptHeaderItem.php b/AcceptHeaderItem.php index c69dbbba3..b9287a0b4 100644 --- a/AcceptHeaderItem.php +++ b/AcceptHeaderItem.php @@ -65,7 +65,7 @@ public static function fromString($itemValue) } /** - * Returns header value's string representation. + * Returns header value's string representation. * * @return string */ From 2eb00ea3ad1aa4a82b3c4610004209d185ddea8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois-Xavier=20de=20Guillebon?= Date: Wed, 31 Oct 2018 10:30:08 +0100 Subject: [PATCH 145/225] Fix ini_get() for boolean values --- Session/Storage/Handler/AbstractSessionHandler.php | 4 ++-- Session/Storage/Handler/PdoSessionHandler.php | 2 +- Session/Storage/NativeSessionStorage.php | 2 +- Tests/Fixtures/response-functional/common.inc | 2 +- Tests/Session/Storage/Handler/PdoSessionHandlerTest.php | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Session/Storage/Handler/AbstractSessionHandler.php b/Session/Storage/Handler/AbstractSessionHandler.php index 5b5c1d817..0d119498d 100644 --- a/Session/Storage/Handler/AbstractSessionHandler.php +++ b/Session/Storage/Handler/AbstractSessionHandler.php @@ -131,7 +131,7 @@ public function destroy($sessionId) if (\PHP_VERSION_ID < 70000) { $this->prefetchData = null; } - if (!headers_sent() && ini_get('session.use_cookies')) { + if (!headers_sent() && filter_var(ini_get('session.use_cookies'), FILTER_VALIDATE_BOOLEAN)) { if (!$this->sessionName) { throw new \LogicException(sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', \get_class($this))); } @@ -159,7 +159,7 @@ public function destroy($sessionId) header($h, false); } } else { - setcookie($this->sessionName, '', 0, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly')); + setcookie($this->sessionName, '', 0, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), filter_var(ini_get('session.cookie_secure'), FILTER_VALIDATE_BOOLEAN), filter_var(ini_get('session.cookie_httponly'), FILTER_VALIDATE_BOOLEAN)); } } diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index c5f0527f9..8c0c42fd2 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -637,7 +637,7 @@ protected function doRead($sessionId) throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.'); } - if (!ini_get('session.use_strict_mode') && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { + if (!filter_var(ini_get('session.use_strict_mode'), FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { // In strict mode, session fixation is not possible: new sessions always start with a unique // random id, so that concurrency is not possible and this code path can be skipped. // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 1ec5c7ff4..a18f812d5 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -137,7 +137,7 @@ public function start() throw new \RuntimeException('Failed to start the session: already started by PHP.'); } - if (ini_get('session.use_cookies') && headers_sent($file, $line)) { + if (filter_var(ini_get('session.use_cookies'), FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) { throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line)); } diff --git a/Tests/Fixtures/response-functional/common.inc b/Tests/Fixtures/response-functional/common.inc index f9c40a9a3..0bdf9e4b7 100644 --- a/Tests/Fixtures/response-functional/common.inc +++ b/Tests/Fixtures/response-functional/common.inc @@ -22,7 +22,7 @@ error_reporting(-1); ini_set('html_errors', 0); ini_set('display_errors', 1); -if (ini_get('xdebug.default_enable')) { +if (filter_var(ini_get('xdebug.default_enable'), FILTER_VALIDATE_BOOLEAN)) { xdebug_disable(); } diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 3060452e9..853e96d28 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -160,7 +160,7 @@ public function testReadLockedConvertsStreamToString() if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the PDOStatement class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); } - if (ini_get('session.use_strict_mode')) { + if (filter_var(ini_get('session.use_strict_mode'), FILTER_VALIDATE_BOOLEAN)) { $this->markTestSkipped('Strict mode needs no locking for new sessions.'); } From 50c6a4359f475e48055fdcba379b06f538c31328 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 1 Nov 2018 18:15:47 +0100 Subject: [PATCH 146/225] [HttpFoundation] replace any preexisting Content-Type headers --- Response.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Response.php b/Response.php index 6b6308e36..a4ad0e66a 100644 --- a/Response.php +++ b/Response.php @@ -344,8 +344,9 @@ public function sendHeaders() // headers foreach ($this->headers->allPreserveCase() as $name => $values) { + $replace = 0 === strcasecmp($name, 'Content-Type'); foreach ($values as $value) { - header($name.': '.$value, false, $this->statusCode); + header($name.': '.$value, $replace, $this->statusCode); } } From b99c30bd0a51973ff005277bbce3d6151340d3a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Pineau?= Date: Tue, 6 Nov 2018 18:42:22 +0100 Subject: [PATCH 147/225] [HttpFoundation] Fixed PHP doc of ParameterBag::getBoolean Since the method should return a bool, then the default value should be a bool too --- ParameterBag.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ParameterBag.php b/ParameterBag.php index fdf60e56e..6141b1bf6 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -231,7 +231,7 @@ public function getInt($key, $default = 0, $deep = false) * Returns the parameter value converted to boolean. * * @param string $key The parameter key - * @param mixed $default The default value if the parameter key does not exist + * @param bool $default The default value if the parameter key does not exist * @param bool $deep If true, a path like foo[bar] will find deeper items * * @return bool The filtered value From f54b7effcbd92adde391cd791087f16fee583491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Sun, 11 Nov 2018 12:11:22 +0100 Subject: [PATCH 148/225] Bump phpunit XSD version to 5.2 Some attributes being used in the phpunit configuration files, namely failOnRisky and failOnWarning were introduced in phpunit 5.2.0. The Composer configuration shows that tests should run with old versions of phpunit, but phpunit only validates the configuration against the XSD since phpunit 7.2.0. These changes can be tested as follows: wget http://schema.phpunit.de/5.2/phpunit.xsd xargs xmllint --schema phpunit.xsd 1>/dev/null find src -name phpunit.xml.dist| xargs xmllint --schema phpunit.xsd 1>/dev/null See https://github.com/sebastianbergmann/phpunit/commit/7e06a82806be004cbfd30a02d92162e9ed4abc7c See https://github.com/symfony/symfony/blob/46e3745a03e199e64cc0fcf3284a96b5a25dcee9/composer.json#L98 --- phpunit.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index c1d61f8bf..f57bc9e62 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,7 +1,7 @@ Date: Sun, 18 Nov 2018 23:17:01 +0100 Subject: [PATCH 149/225] =?UTF-8?q?[HttpFoundation]=C2=A0Fixed=20absolute?= =?UTF-8?q?=20Request=20URI=20with=20default=20port?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Request.php | 12 ++++++++--- Tests/RequestTest.php | 49 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/Request.php b/Request.php index e84e0ba6e..422944ce4 100644 --- a/Request.php +++ b/Request.php @@ -1836,10 +1836,16 @@ protected function prepareRequestUri() $this->server->remove('IIS_WasUrlRewritten'); } elseif ($this->server->has('REQUEST_URI')) { $requestUri = $this->server->get('REQUEST_URI'); + // 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)); + $uriComponents = parse_url($requestUri); + + if (isset($uriComponents['path'])) { + $requestUri = $uriComponents['path']; + } + + if (isset($uriComponents['query'])) { + $requestUri .= '?'.$uriComponents['query']; } } elseif ($this->server->has('ORIG_PATH_INFO')) { // IIS 5.0, PHP as CGI diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index ff4dd67b3..97cc8a9ab 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -232,6 +232,55 @@ public function testCreate() $this->assertEquals(80, $request->getPort()); $this->assertEquals('test.com', $request->getHttpHost()); $this->assertFalse($request->isSecure()); + + // Fragment should not be included in the URI + $request = Request::create('http://test.com/foo#bar'); + $this->assertEquals('http://test.com/foo', $request->getUri()); + } + + public function testCreateWithRequestUri() + { + $request = Request::create('http://test.com:80/foo'); + $request->server->set('REQUEST_URI', 'http://test.com:80/foo'); + $this->assertEquals('http://test.com/foo', $request->getUri()); + $this->assertEquals('/foo', $request->getPathInfo()); + $this->assertEquals('test.com', $request->getHost()); + $this->assertEquals('test.com', $request->getHttpHost()); + $this->assertEquals(80, $request->getPort()); + $this->assertFalse($request->isSecure()); + + $request = Request::create('http://test.com:8080/foo'); + $request->server->set('REQUEST_URI', 'http://test.com:8080/foo'); + $this->assertEquals('http://test.com:8080/foo', $request->getUri()); + $this->assertEquals('/foo', $request->getPathInfo()); + $this->assertEquals('test.com', $request->getHost()); + $this->assertEquals('test.com:8080', $request->getHttpHost()); + $this->assertEquals(8080, $request->getPort()); + $this->assertFalse($request->isSecure()); + + $request = Request::create('http://test.com/foo?bar=foo', 'GET', array('bar' => 'baz')); + $request->server->set('REQUEST_URI', 'http://test.com/foo?bar=foo'); + $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri()); + $this->assertEquals('/foo', $request->getPathInfo()); + $this->assertEquals('bar=baz', $request->getQueryString()); + $this->assertEquals('test.com', $request->getHost()); + $this->assertEquals('test.com', $request->getHttpHost()); + $this->assertEquals(80, $request->getPort()); + $this->assertFalse($request->isSecure()); + + $request = Request::create('https://test.com:443/foo'); + $request->server->set('REQUEST_URI', 'https://test.com:443/foo'); + $this->assertEquals('https://test.com/foo', $request->getUri()); + $this->assertEquals('/foo', $request->getPathInfo()); + $this->assertEquals('test.com', $request->getHost()); + $this->assertEquals('test.com', $request->getHttpHost()); + $this->assertEquals(443, $request->getPort()); + $this->assertTrue($request->isSecure()); + + // Fragment should not be included in the URI + $request = Request::create('http://test.com/foo#bar'); + $request->server->set('REQUEST_URI', 'http://test.com/foo#bar'); + $this->assertEquals('http://test.com/foo', $request->getUri()); } public function testCreateCheckPrecedence() From fdc6033ac228bb844b14ae48410a991265d2d1f6 Mon Sep 17 00:00:00 2001 From: Sascha Dens Date: Wed, 21 Nov 2018 13:53:33 +0100 Subject: [PATCH 150/225] [HttpFoundation] Fix trailing space for mime-type with parameters --- Request.php | 2 +- Tests/RequestTest.php | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 49121d465..51187d855 100644 --- a/Request.php +++ b/Request.php @@ -1326,7 +1326,7 @@ public function getFormat($mimeType) { $canonicalMimeType = null; if (false !== $pos = strpos($mimeType, ';')) { - $canonicalMimeType = substr($mimeType, 0, $pos); + $canonicalMimeType = trim(substr($mimeType, 0, $pos)); } if (null === static::$formats) { diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 26335db90..ac6f1a74e 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -323,6 +323,9 @@ public function testGetFormatFromMimeTypeWithParameters() { $request = new Request(); $this->assertEquals('json', $request->getFormat('application/json; charset=utf-8')); + $this->assertEquals('json', $request->getFormat('application/json;charset=utf-8')); + $this->assertEquals('json', $request->getFormat('application/json ; charset=utf-8')); + $this->assertEquals('json', $request->getFormat('application/json ;charset=utf-8')); } public function testGetFormatWithCustomMimeType() From d0ab719bedc9fc6748a95b2dcb04137292a27b92 Mon Sep 17 00:00:00 2001 From: Tom Counsell Date: Fri, 23 Nov 2018 15:43:18 +0000 Subject: [PATCH 151/225] Doc fix: clarify isMethodCacheable() returns true only for GET & HEAD The current documentation points to https://tools.ietf.org/html/rfc7231#section-4.2.3. The spec says: "this specification defines GET, HEAD, and POST as cacheable, although the overwhelming majority of cache implementations only support GET and HEAD.". This fix to the documentation clarifies that Symfony follows majority (excluding POST) rather than the spec (including POST). --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 51187d855..e025993c6 100644 --- a/Request.php +++ b/Request.php @@ -1475,7 +1475,7 @@ public function isMethodSafe(/* $andCacheable = true */) * * @see https://tools.ietf.org/html/rfc7231#section-4.2.3 * - * @return bool + * @return bool True for GET and HEAD, false otherwise */ public function isMethodCacheable() { From deda9ea8c47b13d2a51e8a9ab40f6c9db67282ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Vasseur?= Date: Mon, 3 Dec 2018 11:41:13 +0100 Subject: [PATCH 152/225] Fix HeaderBag::get phpdoc When setting $first to false, the default value is wrapped into an array meaning you need to pass a string as the default value instead of an array of strings. --- HeaderBag.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/HeaderBag.php b/HeaderBag.php index 5445e80c8..230253663 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -101,9 +101,9 @@ public function add(array $headers) /** * Returns a header value by name. * - * @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 + * @param string $key The header name + * @param string|null $default The default value + * @param bool $first Whether to return the first value or all header values * * @return string|string[]|null The first header value or default value if $first is true, an array of values otherwise */ From 1e28e9ba74b01ce6156b5d4a3163f26e34c18b4a Mon Sep 17 00:00:00 2001 From: Alexandre Quercia Date: Thu, 6 Dec 2018 19:19:56 +0100 Subject: [PATCH 153/225] [HttpFoundation] Fix request uri when it starts with double slashes --- Request.php | 22 ++++++++++++------- Tests/RequestTest.php | 49 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/Request.php b/Request.php index 89611660a..10687e35c 100644 --- a/Request.php +++ b/Request.php @@ -1837,15 +1837,23 @@ protected function prepareRequestUri() } elseif ($this->server->has('REQUEST_URI')) { $requestUri = $this->server->get('REQUEST_URI'); - // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path - $uriComponents = parse_url($requestUri); + if ('' !== $requestUri && '/' === $requestUri[0]) { + // To only use path and query remove the fragment. + if (false !== $pos = strpos($requestUri, '#')) { + $requestUri = substr($requestUri, 0, $pos); + } + } else { + // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, + // only use URL path. + $uriComponents = parse_url($requestUri); - if (isset($uriComponents['path'])) { - $requestUri = $uriComponents['path']; - } + if (isset($uriComponents['path'])) { + $requestUri = $uriComponents['path']; + } - if (isset($uriComponents['query'])) { - $requestUri .= '?'.$uriComponents['query']; + if (isset($uriComponents['query'])) { + $requestUri .= '?'.$uriComponents['query']; + } } } elseif ($this->server->has('ORIG_PATH_INFO')) { // IIS 5.0, PHP as CGI diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 539bb69cf..f2c8f94f7 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -283,6 +283,55 @@ public function testCreateWithRequestUri() $this->assertEquals('http://test.com/foo', $request->getUri()); } + /** + * @dataProvider getRequestUriData + */ + public function testGetRequestUri($serverRequestUri, $expected, $message) + { + $request = new Request(); + $request->server->add(array( + 'REQUEST_URI' => $serverRequestUri, + + // For having http://test.com + 'SERVER_NAME' => 'test.com', + 'SERVER_PORT' => 80, + )); + + $this->assertSame($expected, $request->getRequestUri(), $message); + $this->assertSame($expected, $request->server->get('REQUEST_URI'), 'Normalize the request URI.'); + } + + public function getRequestUriData() + { + $message = 'Do not modify the path.'; + yield array('/foo', '/foo', $message); + yield array('//bar/foo', '//bar/foo', $message); + yield array('///bar/foo', '///bar/foo', $message); + + $message = 'Handle when the scheme, host are on REQUEST_URI.'; + yield array('http://test.com/foo?bar=baz', '/foo?bar=baz', $message); + + $message = 'Handle when the scheme, host and port are on REQUEST_URI.'; + yield array('http://test.com:80/foo', '/foo', $message); + yield array('https://test.com:8080/foo', '/foo', $message); + yield array('https://test.com:443/foo', '/foo', $message); + + $message = 'Fragment should not be included in the URI'; + yield array('http://test.com/foo#bar', '/foo', $message); + yield array('/foo#bar', '/foo', $message); + } + + public function testGetRequestUriWithoutRequiredHeader() + { + $expected = ''; + + $request = new Request(); + + $message = 'Fallback to empty URI when headers are missing.'; + $this->assertSame($expected, $request->getRequestUri(), $message); + $this->assertSame($expected, $request->server->get('REQUEST_URI'), 'Normalize the request URI.'); + } + public function testCreateCheckPrecedence() { // server is used by default From 199ff2578bac307f03d4b3291ee71dfecef5ab4f Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 1 Jan 2019 14:42:07 +0100 Subject: [PATCH 154/225] update year in license files --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 21d7fb9e2..a677f4376 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2018 Fabien Potencier +Copyright (c) 2004-2019 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 9f47e47fe71ddce4ecf2fa31c035c8afb5d18fa9 Mon Sep 17 00:00:00 2001 From: Konstantin Grachev Date: Sat, 5 Jan 2019 00:04:29 +0300 Subject: [PATCH 155/225] [Bugfix] MemcachedSessionHandler::close() must close connection --- Session/Storage/Handler/MemcachedSessionHandler.php | 2 +- .../Session/Storage/Handler/MemcachedSessionHandlerTest.php | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 61a7afd90..8bcd75cc6 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -62,7 +62,7 @@ public function __construct(\Memcached $memcached, array $options = array()) */ public function close() { - return true; + return $this->memcached->quit(); } /** diff --git a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php index 2a1148010..422293084 100644 --- a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php @@ -63,6 +63,12 @@ public function testOpenSession() public function testCloseSession() { + $this->memcached + ->expects($this->once()) + ->method('quit') + ->will($this->returnValue(true)) + ; + $this->assertTrue($this->storage->close()); } From c1493871165d41cfabafc10869ed1327daf27eef Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Mon, 14 Jan 2019 18:38:02 +0100 Subject: [PATCH 156/225] updated MimeType extensions --- File/MimeType/MimeTypeExtensionGuesser.php | 23 +++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/File/MimeType/MimeTypeExtensionGuesser.php b/File/MimeType/MimeTypeExtensionGuesser.php index 77bf51b1e..d5acb3409 100644 --- a/File/MimeType/MimeTypeExtensionGuesser.php +++ b/File/MimeType/MimeTypeExtensionGuesser.php @@ -20,11 +20,11 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface * A map of mime types and their default extensions. * * This list has been placed under the public domain by the Apache HTTPD project. - * This list has been updated from upstream on 2013-04-23. + * This list has been updated from upstream on 2019-01-14. * - * @see http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types + * @see https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types */ - protected $defaultExtensions = array( + protected $defaultExtensions = [ 'application/andrew-inset' => 'ez', 'application/applixware' => 'aw', 'application/atom+xml' => 'atom', @@ -618,7 +618,7 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'audio/adpcm' => 'adp', 'audio/basic' => 'au', 'audio/midi' => 'mid', - 'audio/mp4' => 'mp4a', + 'audio/mp4' => 'm4a', 'audio/mpeg' => 'mpga', 'audio/ogg' => 'oga', 'audio/s3m' => 's3m', @@ -653,6 +653,11 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'chemical/x-cml' => 'cml', 'chemical/x-csml' => 'csml', 'chemical/x-xyz' => 'xyz', + 'font/collection' => 'ttc', + 'font/otf' => 'otf', + 'font/ttf' => 'ttf', + 'font/woff' => 'woff', + 'font/woff2' => 'woff2', 'image/bmp' => 'bmp', 'image/x-ms-bmp' => 'bmp', 'image/cgm' => 'cgm', @@ -669,8 +674,8 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'image/tiff' => 'tiff', 'image/vnd.adobe.photoshop' => 'psd', 'image/vnd.dece.graphic' => 'uvi', - 'image/vnd.dvb.subtitle' => 'sub', 'image/vnd.djvu' => 'djvu', + 'image/vnd.dvb.subtitle' => 'sub', 'image/vnd.dwg' => 'dwg', 'image/vnd.dxf' => 'dxf', 'image/vnd.fastbidsheet' => 'fbs', @@ -732,8 +737,8 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'text/vcard' => 'vcard', 'text/vnd.curl' => 'curl', 'text/vnd.curl.dcurl' => 'dcurl', - 'text/vnd.curl.scurl' => 'scurl', 'text/vnd.curl.mcurl' => 'mcurl', + 'text/vnd.curl.scurl' => 'scurl', 'text/vnd.dvb.subtitle' => 'sub', 'text/vnd.fly' => 'fly', 'text/vnd.fmi.flexstor' => 'flx', @@ -747,10 +752,10 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'text/x-asm' => 's', 'text/x-c' => 'c', 'text/x-fortran' => 'f', - 'text/x-pascal' => 'p', 'text/x-java-source' => 'java', - 'text/x-opml' => 'opml', 'text/x-nfo' => 'nfo', + 'text/x-opml' => 'opml', + 'text/x-pascal' => 'p', 'text/x-setext' => 'etx', 'text/x-sfv' => 'sfv', 'text/x-uuencode' => 'uu', @@ -796,7 +801,7 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface 'video/x-sgi-movie' => 'movie', 'video/x-smv' => 'smv', 'x-conference/x-cooltalk' => 'ice', - ); + ]; /** * {@inheritdoc} From 3ce4d61ff2c4fd6175ee1f4922a85586f953699f Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 16 Jan 2019 10:39:14 +0100 Subject: [PATCH 157/225] switched array() to [] --- AcceptHeader.php | 2 +- AcceptHeaderItem.php | 6 +- BinaryFileResponse.php | 6 +- Cookie.php | 6 +- ExpressionRequestMatcher.php | 4 +- File/MimeType/ExtensionGuesser.php | 2 +- File/MimeType/MimeTypeGuesser.php | 2 +- File/UploadedFile.php | 4 +- FileBag.php | 16 +- HeaderBag.php | 22 +- IpUtils.php | 4 +- JsonResponse.php | 12 +- ParameterBag.php | 12 +- RedirectResponse.php | 4 +- Request.php | 114 +-- RequestMatcher.php | 16 +- RequestStack.php | 2 +- Response.php | 26 +- ResponseHeaderBag.php | 32 +- ServerBag.php | 4 +- Session/Attribute/AttributeBag.php | 6 +- Session/Attribute/NamespacedAttributeBag.php | 4 +- Session/Flash/AutoExpireFlashBag.php | 14 +- Session/Flash/FlashBag.php | 8 +- Session/Flash/FlashBagInterface.php | 4 +- Session/Session.php | 2 +- .../Handler/AbstractSessionHandler.php | 4 +- .../Handler/MemcacheSessionHandler.php | 4 +- .../Handler/MemcachedSessionHandler.php | 4 +- .../Storage/Handler/MongoDbSessionHandler.php | 40 +- Session/Storage/Handler/PdoSessionHandler.php | 10 +- Session/Storage/MetadataBag.php | 2 +- Session/Storage/MockArraySessionStorage.php | 10 +- Session/Storage/MockFileSessionStorage.php | 4 +- Session/Storage/NativeSessionStorage.php | 20 +- StreamedResponse.php | 4 +- Tests/AcceptHeaderItemTest.php | 54 +- Tests/AcceptHeaderTest.php | 42 +- Tests/ApacheRequestTest.php | 52 +- Tests/BinaryFileResponseTest.php | 82 +- Tests/CookieTest.php | 22 +- Tests/ExpressionRequestMatcherTest.php | 20 +- Tests/File/FileTest.php | 16 +- Tests/File/UploadedFileTest.php | 14 +- Tests/FileBagTest.php | 114 +-- Tests/HeaderBagTest.php | 54 +- Tests/IpUtilsTest.php | 66 +- Tests/JsonResponseTest.php | 38 +- Tests/ParameterBagTest.php | 72 +- Tests/RedirectResponseTest.php | 4 +- Tests/RequestMatcherTest.php | 40 +- Tests/RequestTest.php | 850 +++++++++--------- Tests/ResponseFunctionalTest.php | 10 +- Tests/ResponseHeaderBagTest.php | 98 +- Tests/ResponseTest.php | 114 +-- Tests/ServerBagTest.php | 66 +- Tests/Session/Attribute/AttributeBagTest.php | 48 +- .../Attribute/NamespacedAttributeBagTest.php | 62 +- .../Session/Flash/AutoExpireFlashBagTest.php | 70 +- Tests/Session/Flash/FlashBagTest.php | 64 +- Tests/Session/SessionTest.php | 26 +- .../Handler/AbstractSessionHandlerTest.php | 12 +- .../Handler/MemcacheSessionHandlerTest.php | 14 +- .../Handler/MemcachedSessionHandlerTest.php | 14 +- .../Handler/MongoDbSessionHandlerTest.php | 34 +- .../Handler/NativeFileSessionHandlerTest.php | 14 +- .../Handler/NullSessionHandlerTest.php | 2 +- .../Storage/Handler/PdoSessionHandlerTest.php | 34 +- .../Handler/StrictSessionHandlerTest.php | 2 +- Tests/Session/Storage/MetadataBagTest.php | 18 +- .../Storage/MockArraySessionStorageTest.php | 20 +- .../Storage/MockFileSessionStorageTest.php | 2 +- .../Storage/NativeSessionStorageTest.php | 18 +- .../Storage/PhpBridgeSessionStorageTest.php | 4 +- .../Storage/Proxy/SessionHandlerProxyTest.php | 4 +- Tests/StreamedResponseTest.php | 6 +- 76 files changed, 1366 insertions(+), 1366 deletions(-) diff --git a/AcceptHeader.php b/AcceptHeader.php index d1740266b..968b71f5d 100644 --- a/AcceptHeader.php +++ b/AcceptHeader.php @@ -24,7 +24,7 @@ class AcceptHeader /** * @var AcceptHeaderItem[] */ - private $items = array(); + private $items = []; /** * @var bool diff --git a/AcceptHeaderItem.php b/AcceptHeaderItem.php index c9506574d..f6e896874 100644 --- a/AcceptHeaderItem.php +++ b/AcceptHeaderItem.php @@ -21,13 +21,13 @@ class AcceptHeaderItem private $value; private $quality = 1.0; private $index = 0; - private $attributes = array(); + private $attributes = []; /** * @param string $value * @param array $attributes */ - public function __construct($value, array $attributes = array()) + public function __construct($value, array $attributes = []) { $this->value = $value; foreach ($attributes as $name => $value) { @@ -46,7 +46,7 @@ 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(); + $attributes = []; $lastNullAttribute = null; foreach ($bits as $bit) { diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 97023278e..557577a1e 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -44,7 +44,7 @@ class BinaryFileResponse extends Response * @param bool $autoEtag Whether the ETag header should be automatically set * @param bool $autoLastModified Whether the Last-Modified header should be automatically set */ - public function __construct($file, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) + public function __construct($file, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) { parent::__construct(null, $status, $headers); @@ -66,7 +66,7 @@ public function __construct($file, $status = 200, $headers = array(), $public = * * @return static */ - public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) + public static function create($file = null, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) { return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified); } @@ -239,7 +239,7 @@ public function prepare(Request $request) if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) { $range = $request->headers->get('Range'); - list($start, $end) = explode('-', substr($range, 6), 2) + array(0); + list($start, $end) = explode('-', substr($range, 6), 2) + [0]; $end = ('' === $end) ? $fileSize - 1 : (int) $end; diff --git a/Cookie.php b/Cookie.php index c38aa409d..e61619aa6 100644 --- a/Cookie.php +++ b/Cookie.php @@ -41,7 +41,7 @@ class Cookie */ public static function fromString($cookie, $decode = false) { - $data = array( + $data = [ 'expires' => 0, 'path' => '/', 'domain' => null, @@ -49,7 +49,7 @@ public static function fromString($cookie, $decode = false) 'httponly' => false, 'raw' => !$decode, 'samesite' => null, - ); + ]; foreach (explode(';', $cookie) as $part) { if (false === strpos($part, '=')) { $key = trim($part); @@ -128,7 +128,7 @@ public function __construct($name, $value = null, $expire = 0, $path = '/', $dom $sameSite = strtolower($sameSite); } - if (!\in_array($sameSite, array(self::SAMESITE_LAX, self::SAMESITE_STRICT, null), true)) { + if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, null], true)) { throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.'); } diff --git a/ExpressionRequestMatcher.php b/ExpressionRequestMatcher.php index e9c8441ce..26bed7d37 100644 --- a/ExpressionRequestMatcher.php +++ b/ExpressionRequestMatcher.php @@ -35,13 +35,13 @@ public function matches(Request $request) throw new \LogicException('Unable to match the request as the expression language is not available.'); } - return $this->language->evaluate($this->expression, array( + return $this->language->evaluate($this->expression, [ 'request' => $request, 'method' => $request->getMethod(), 'path' => rawurldecode($request->getPathInfo()), 'host' => $request->getHost(), 'ip' => $request->getClientIp(), 'attributes' => $request->attributes->all(), - )) && parent::matches($request); + ]) && parent::matches($request); } } diff --git a/File/MimeType/ExtensionGuesser.php b/File/MimeType/ExtensionGuesser.php index 263fb321c..80f4d47f7 100644 --- a/File/MimeType/ExtensionGuesser.php +++ b/File/MimeType/ExtensionGuesser.php @@ -37,7 +37,7 @@ class ExtensionGuesser implements ExtensionGuesserInterface * * @var array */ - protected $guessers = array(); + protected $guessers = []; /** * Returns the singleton instance. diff --git a/File/MimeType/MimeTypeGuesser.php b/File/MimeType/MimeTypeGuesser.php index dae47a7c0..95d1ee267 100644 --- a/File/MimeType/MimeTypeGuesser.php +++ b/File/MimeType/MimeTypeGuesser.php @@ -51,7 +51,7 @@ class MimeTypeGuesser implements MimeTypeGuesserInterface * * @var array */ - protected $guessers = array(); + protected $guessers = []; /** * Returns the singleton instance. diff --git a/File/UploadedFile.php b/File/UploadedFile.php index de6ce75cc..a44c664b4 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -249,7 +249,7 @@ public static function getMaxFilesize() */ public function getErrorMessage() { - static $errors = array( + static $errors = [ UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).', UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', @@ -257,7 +257,7 @@ public function getErrorMessage() UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.', - ); + ]; $errorCode = $this->error; $maxFilesize = UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0; diff --git a/FileBag.php b/FileBag.php index c135ad641..ca849b3d7 100644 --- a/FileBag.php +++ b/FileBag.php @@ -21,12 +21,12 @@ */ class FileBag extends ParameterBag { - private static $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type'); + private static $fileKeys = ['error', 'name', 'size', 'tmp_name', 'type']; /** * @param array $parameters An array of HTTP files */ - public function __construct(array $parameters = array()) + public function __construct(array $parameters = []) { $this->replace($parameters); } @@ -34,9 +34,9 @@ public function __construct(array $parameters = array()) /** * {@inheritdoc} */ - public function replace(array $files = array()) + public function replace(array $files = []) { - $this->parameters = array(); + $this->parameters = []; $this->add($files); } @@ -55,7 +55,7 @@ public function set($key, $value) /** * {@inheritdoc} */ - public function add(array $files = array()) + public function add(array $files = []) { foreach ($files as $key => $file) { $this->set($key, $file); @@ -87,7 +87,7 @@ protected function convertFileInformation($file) $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']); } } else { - $file = array_map(array($this, 'convertFileInformation'), $file); + $file = array_map([$this, 'convertFileInformation'], $file); if (array_keys($keys) === $keys) { $file = array_filter($file); } @@ -130,13 +130,13 @@ protected function fixPhpFilesArray($data) } foreach ($data['name'] as $key => $name) { - $files[$key] = $this->fixPhpFilesArray(array( + $files[$key] = $this->fixPhpFilesArray([ 'error' => $data['error'][$key], 'name' => $name, 'type' => $data['type'][$key], 'tmp_name' => $data['tmp_name'][$key], 'size' => $data['size'][$key], - )); + ]); } return $files; diff --git a/HeaderBag.php b/HeaderBag.php index 230253663..937afe6b7 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -18,13 +18,13 @@ */ class HeaderBag implements \IteratorAggregate, \Countable { - protected $headers = array(); - protected $cacheControl = array(); + protected $headers = []; + protected $cacheControl = []; /** * @param array $headers An array of HTTP headers */ - public function __construct(array $headers = array()) + public function __construct(array $headers = []) { foreach ($headers as $key => $values) { $this->set($key, $values); @@ -80,9 +80,9 @@ public function keys() * * @param array $headers An array of HTTP headers */ - public function replace(array $headers = array()) + public function replace(array $headers = []) { - $this->headers = array(); + $this->headers = []; $this->add($headers); } @@ -114,10 +114,10 @@ public function get($key, $default = null, $first = true) if (!array_key_exists($key, $headers)) { if (null === $default) { - return $first ? null : array(); + return $first ? null : []; } - return $first ? $default : array($default); + return $first ? $default : [$default]; } if ($first) { @@ -148,7 +148,7 @@ public function set($key, $values, $replace = true) } } else { if (true === $replace || !isset($this->headers[$key])) { - $this->headers[$key] = array($values); + $this->headers[$key] = [$values]; } else { $this->headers[$key][] = $values; } @@ -196,7 +196,7 @@ public function remove($key) unset($this->headers[$key]); if ('cache-control' === $key) { - $this->cacheControl = array(); + $this->cacheControl = []; } } @@ -294,7 +294,7 @@ public function count() protected function getCacheControlHeader() { - $parts = array(); + $parts = []; ksort($this->cacheControl); foreach ($this->cacheControl as $key => $value) { if (true === $value) { @@ -320,7 +320,7 @@ protected function getCacheControlHeader() */ protected function parseCacheControl($header) { - $cacheControl = array(); + $cacheControl = []; 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); diff --git a/IpUtils.php b/IpUtils.php index a1bfa9088..67d13e57a 100644 --- a/IpUtils.php +++ b/IpUtils.php @@ -18,7 +18,7 @@ */ class IpUtils { - private static $checkedIps = array(); + private static $checkedIps = []; /** * This class should not be instantiated. @@ -38,7 +38,7 @@ private function __construct() public static function checkIp($requestIp, $ips) { if (!\is_array($ips)) { - $ips = array($ips); + $ips = [$ips]; } $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4'; diff --git a/JsonResponse.php b/JsonResponse.php index d741ce099..6fb32ee41 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -39,7 +39,7 @@ class JsonResponse extends Response * @param array $headers An array of response headers * @param bool $json If the data is already a JSON string */ - public function __construct($data = null, $status = 200, $headers = array(), $json = false) + public function __construct($data = null, $status = 200, $headers = [], $json = false) { parent::__construct('', $status, $headers); @@ -64,7 +64,7 @@ public function __construct($data = null, $status = 200, $headers = array(), $js * * @return static */ - public static function create($data = null, $status = 200, $headers = array()) + public static function create($data = null, $status = 200, $headers = []) { return new static($data, $status, $headers); } @@ -72,7 +72,7 @@ public static function create($data = null, $status = 200, $headers = array()) /** * Make easier the creation of JsonResponse from raw json. */ - public static function fromJsonString($data = null, $status = 200, $headers = array()) + public static function fromJsonString($data = null, $status = 200, $headers = []) { return new static($data, $status, $headers, true); } @@ -94,11 +94,11 @@ public function setCallback($callback = null) // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details. // (c) William Durand $pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u'; - $reserved = array( + $reserved = [ 'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while', 'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export', 'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false', - ); + ]; $parts = explode('.', $callback); foreach ($parts as $part) { if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) { @@ -137,7 +137,7 @@ public function setJson($json) * * @throws \InvalidArgumentException */ - public function setData($data = array()) + public function setData($data = []) { if (\defined('HHVM_VERSION')) { // HHVM does not trigger any warnings and let exceptions diff --git a/ParameterBag.php b/ParameterBag.php index 19d7ee913..3c6ba46a6 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -26,7 +26,7 @@ class ParameterBag implements \IteratorAggregate, \Countable /** * @param array $parameters An array of parameters */ - public function __construct(array $parameters = array()) + public function __construct(array $parameters = []) { $this->parameters = $parameters; } @@ -56,7 +56,7 @@ public function keys() * * @param array $parameters An array of parameters */ - public function replace(array $parameters = array()) + public function replace(array $parameters = []) { $this->parameters = $parameters; } @@ -66,7 +66,7 @@ public function replace(array $parameters = array()) * * @param array $parameters An array of parameters */ - public function add(array $parameters = array()) + public function add(array $parameters = []) { $this->parameters = array_replace($this->parameters, $parameters); } @@ -154,7 +154,7 @@ public function getAlnum($key, $default = '') public function getDigits($key, $default = '') { // we need to remove - and + because they're allowed in the filter - return str_replace(array('-', '+'), '', $this->filter($key, $default, FILTER_SANITIZE_NUMBER_INT)); + return str_replace(['-', '+'], '', $this->filter($key, $default, FILTER_SANITIZE_NUMBER_INT)); } /** @@ -195,13 +195,13 @@ public function getBoolean($key, $default = false) * * @return mixed */ - public function filter($key, $default = null, $filter = FILTER_DEFAULT, $options = array()) + public function filter($key, $default = null, $filter = FILTER_DEFAULT, $options = []) { $value = $this->get($key, $default); // Always turn $options into an array - this allows filter_var option shortcuts. if (!\is_array($options) && $options) { - $options = array('flags' => $options); + $options = ['flags' => $options]; } // Add a convenience check for arrays. diff --git a/RedirectResponse.php b/RedirectResponse.php index 01681dcdf..970d82b5a 100644 --- a/RedirectResponse.php +++ b/RedirectResponse.php @@ -32,7 +32,7 @@ class RedirectResponse extends Response * * @see http://tools.ietf.org/html/rfc2616#section-10.3 */ - public function __construct($url, $status = 302, $headers = array()) + public function __construct($url, $status = 302, $headers = []) { parent::__construct('', $status, $headers); @@ -56,7 +56,7 @@ public function __construct($url, $status = 302, $headers = array()) * * @return static */ - public static function create($url = '', $status = 302, $headers = array()) + public static function create($url = '', $status = 302, $headers = []) { return new static($url, $status, $headers); } diff --git a/Request.php b/Request.php index 10687e35c..8dc01b91e 100644 --- a/Request.php +++ b/Request.php @@ -61,17 +61,17 @@ class Request /** * @var string[] */ - protected static $trustedProxies = array(); + protected static $trustedProxies = []; /** * @var string[] */ - protected static $trustedHostPatterns = array(); + protected static $trustedHostPatterns = []; /** * @var string[] */ - protected static $trustedHosts = array(); + protected static $trustedHosts = []; /** * Names for headers that can be trusted when @@ -84,13 +84,13 @@ class Request * * @deprecated since version 3.3, to be removed in 4.0 */ - protected static $trustedHeaders = array( + protected static $trustedHeaders = [ self::HEADER_FORWARDED => 'FORWARDED', self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR', self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST', self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO', self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT', - ); + ]; protected static $httpMethodParameterOverride = false; @@ -226,20 +226,20 @@ class Request private static $trustedHeaderSet = -1; /** @deprecated since version 3.3, to be removed in 4.0 */ - private static $trustedHeaderNames = array( + private static $trustedHeaderNames = [ self::HEADER_FORWARDED => 'FORWARDED', self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR', self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST', self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO', self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT', - ); + ]; - private static $forwardedParams = array( + private static $forwardedParams = [ self::HEADER_X_FORWARDED_FOR => 'for', self::HEADER_X_FORWARDED_HOST => 'host', self::HEADER_X_FORWARDED_PROTO => 'proto', self::HEADER_X_FORWARDED_PORT => 'host', - ); + ]; /** * @param array $query The GET parameters @@ -250,7 +250,7 @@ class Request * @param array $server The SERVER parameters * @param string|resource|null $content The raw body data */ - public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) + public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) { $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content); } @@ -268,7 +268,7 @@ public function __construct(array $query = array(), array $request = array(), ar * @param array $server The SERVER parameters * @param string|resource|null $content The raw body data */ - public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) + public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) { $this->request = new ParameterBag($request); $this->query = new ParameterBag($query); @@ -311,10 +311,10 @@ public static function createFromGlobals() } } - $request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server); + $request = self::createRequestFromFactory($_GET, $_POST, [], $_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')), ['PUT', 'DELETE', 'PATCH']) ) { parse_str($request->getContent(), $data); $request->request = new ParameterBag($data); @@ -339,9 +339,9 @@ public static function createFromGlobals() * * @return static */ - public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null) + public static function create($uri, $method = 'GET', $parameters = [], $cookies = [], $files = [], $server = [], $content = null) { - $server = array_replace(array( + $server = array_replace([ 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'HTTP_HOST' => 'localhost', @@ -354,7 +354,7 @@ public static function create($uri, $method = 'GET', $parameters = array(), $coo 'SCRIPT_FILENAME' => '', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'REQUEST_TIME' => time(), - ), $server); + ], $server); $server['PATH_INFO'] = ''; $server['REQUEST_METHOD'] = strtoupper($method); @@ -402,10 +402,10 @@ public static function create($uri, $method = 'GET', $parameters = array(), $coo // no break case 'PATCH': $request = $parameters; - $query = array(); + $query = []; break; default: - $request = array(); + $request = []; $query = $parameters; break; } @@ -428,7 +428,7 @@ public static function create($uri, $method = 'GET', $parameters = array(), $coo $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : ''); $server['QUERY_STRING'] = $queryString; - return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content); + return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content); } /** @@ -532,7 +532,7 @@ public function __toString() } $cookieHeader = ''; - $cookies = array(); + $cookies = []; foreach ($this->cookies as $k => $v) { $cookies[] = $k.'='.$v; @@ -566,19 +566,19 @@ public function overrideGlobals() 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, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { $_SERVER[$key] = implode(', ', $value); } else { $_SERVER['HTTP_'.$key] = implode(', ', $value); } } - $request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE); + $request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE]; $requestOrder = ini_get('request_order') ?: ini_get('variables_order'); $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp'; - $_REQUEST = array(); + $_REQUEST = []; foreach (str_split($requestOrder) as $order) { $_REQUEST = array_merge($_REQUEST, $request[$order]); } @@ -644,7 +644,7 @@ public static function setTrustedHosts(array $hostPatterns) return sprintf('{%s}i', $hostPattern); }, $hostPatterns); // we need to reset trusted hosts on trusted host patterns change - self::$trustedHosts = array(); + self::$trustedHosts = []; } /** @@ -745,8 +745,8 @@ public static function normalizeQueryString($qs) return ''; } - $parts = array(); - $order = array(); + $parts = []; + $order = []; foreach (explode('&', $qs) as $param) { if ('' === $param || '=' === $param[0]) { @@ -893,10 +893,10 @@ public function getClientIps() $ip = $this->server->get('REMOTE_ADDR'); if (!$this->isFromTrustedProxy()) { - return array($ip); + return [$ip]; } - return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: array($ip); + return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: [$ip]; } /** @@ -1242,7 +1242,7 @@ public function getQueryString() public function isSecure() { if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_CLIENT_PROTO)) { - return \in_array(strtolower($proto[0]), array('https', 'on', 'ssl', '1'), true); + return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true); } $https = $this->server->get('HTTPS'); @@ -1405,7 +1405,7 @@ public static function getMimeTypes($format) static::initializeFormats(); } - return isset(static::$formats[$format]) ? static::$formats[$format] : array(); + return isset(static::$formats[$format]) ? static::$formats[$format] : []; } /** @@ -1448,7 +1448,7 @@ public function setFormat($format, $mimeTypes) static::initializeFormats(); } - static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : array($mimeTypes); + static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : [$mimeTypes]; } /** @@ -1565,10 +1565,10 @@ public function isMethodSafe(/* $andCacheable = true */) // then setting $andCacheable to false should be deprecated in 4.1 @trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since Symfony 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.', E_USER_DEPRECATED); - return \in_array($this->getMethod(), array('GET', 'HEAD')); + return \in_array($this->getMethod(), ['GET', 'HEAD']); } - return \in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE')); + return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']); } /** @@ -1578,7 +1578,7 @@ public function isMethodSafe(/* $andCacheable = true */) */ public function isMethodIdempotent() { - return \in_array($this->getMethod(), array('HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE')); + return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']); } /** @@ -1590,7 +1590,7 @@ public function isMethodIdempotent() */ public function isMethodCacheable() { - return \in_array($this->getMethod(), array('GET', 'HEAD')); + return \in_array($this->getMethod(), ['GET', 'HEAD']); } /** @@ -1704,7 +1704,7 @@ public function getPreferredLanguage(array $locales = null) return $locales[0]; } - $extendedPreferredLanguages = array(); + $extendedPreferredLanguages = []; foreach ($preferredLanguages as $language) { $extendedPreferredLanguages[] = $language; if (false !== $position = strpos($language, '_')) { @@ -1732,7 +1732,7 @@ public function getLanguages() } $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all(); - $this->languages = array(); + $this->languages = []; foreach ($languages as $lang => $acceptHeaderItem) { if (false !== strpos($lang, '-')) { $codes = explode('-', $lang); @@ -2002,19 +2002,19 @@ protected function preparePathInfo() */ protected static function initializeFormats() { - static::$formats = array( - 'html' => array('text/html', 'application/xhtml+xml'), - 'txt' => array('text/plain'), - 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'), - 'css' => array('text/css'), - 'json' => array('application/json', 'application/x-json'), - 'jsonld' => array('application/ld+json'), - 'xml' => array('text/xml', 'application/xml', 'application/x-xml'), - 'rdf' => array('application/rdf+xml'), - 'atom' => array('application/atom+xml'), - 'rss' => array('application/rss+xml'), - 'form' => array('application/x-www-form-urlencoded'), - ); + static::$formats = [ + 'html' => ['text/html', 'application/xhtml+xml'], + 'txt' => ['text/plain'], + 'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'], + 'css' => ['text/css'], + 'json' => ['application/json', 'application/x-json'], + 'jsonld' => ['application/ld+json'], + 'xml' => ['text/xml', 'application/xml', 'application/x-xml'], + 'rdf' => ['application/rdf+xml'], + 'atom' => ['application/atom+xml'], + 'rss' => ['application/rss+xml'], + 'form' => ['application/x-www-form-urlencoded'], + ]; } /** @@ -2059,7 +2059,7 @@ private function getUrlencodedPrefix($string, $prefix) return false; } - private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) + private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) { if (self::$requestFactory) { $request = \call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content); @@ -2089,8 +2089,8 @@ public function isFromTrustedProxy() private function getTrustedValues($type, $ip = null) { - $clientValues = array(); - $forwardedValues = array(); + $clientValues = []; + $forwardedValues = []; if (self::$trustedHeaders[$type] && $this->headers->has(self::$trustedHeaders[$type])) { foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) { @@ -2100,7 +2100,7 @@ private function getTrustedValues($type, $ip = null) if (self::$trustedHeaders[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(); + $forwardedValues = preg_match_all(sprintf('{(?:%s)="?([a-zA-Z0-9\.:_\-/\[\]]*+)}', self::$forwardedParams[$type]), $forwardedValues, $matches) ? $matches[1] : []; if (self::HEADER_CLIENT_PORT === $type) { foreach ($forwardedValues as $k => $v) { if (']' === substr($v, -1) || false === $v = strrchr($v, ':')) { @@ -2125,7 +2125,7 @@ private function getTrustedValues($type, $ip = null) } if (!$this->isForwardedValid) { - return null !== $ip ? array('0.0.0.0', $ip) : array(); + return null !== $ip ? ['0.0.0.0', $ip] : []; } $this->isForwardedValid = false; @@ -2135,7 +2135,7 @@ private function getTrustedValues($type, $ip = null) private function normalizeAndFilterClientIps(array $clientIps, $ip) { if (!$clientIps) { - return array(); + return []; } $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from $firstTrustedIp = null; @@ -2171,6 +2171,6 @@ private function normalizeAndFilterClientIps(array $clientIps, $ip) } // Now the IP chain contains only untrusted proxies and the client IP - return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp); + return $clientIps ? array_reverse($clientIps) : [$firstTrustedIp]; } } diff --git a/RequestMatcher.php b/RequestMatcher.php index 6b4cef147..cadf70c5b 100644 --- a/RequestMatcher.php +++ b/RequestMatcher.php @@ -31,22 +31,22 @@ class RequestMatcher implements RequestMatcherInterface /** * @var string[] */ - private $methods = array(); + private $methods = []; /** * @var string[] */ - private $ips = array(); + private $ips = []; /** * @var array */ - private $attributes = array(); + private $attributes = []; /** * @var string[] */ - private $schemes = array(); + private $schemes = []; /** * @param string|null $path @@ -56,7 +56,7 @@ class RequestMatcher implements RequestMatcherInterface * @param array $attributes * @param string|string[]|null $schemes */ - public function __construct($path = null, $host = null, $methods = null, $ips = null, array $attributes = array(), $schemes = null) + public function __construct($path = null, $host = null, $methods = null, $ips = null, array $attributes = [], $schemes = null) { $this->matchPath($path); $this->matchHost($host); @@ -76,7 +76,7 @@ public function __construct($path = null, $host = null, $methods = null, $ips = */ public function matchScheme($scheme) { - $this->schemes = null !== $scheme ? array_map('strtolower', (array) $scheme) : array(); + $this->schemes = null !== $scheme ? array_map('strtolower', (array) $scheme) : []; } /** @@ -116,7 +116,7 @@ public function matchIp($ip) */ public function matchIps($ips) { - $this->ips = null !== $ips ? (array) $ips : array(); + $this->ips = null !== $ips ? (array) $ips : []; } /** @@ -126,7 +126,7 @@ public function matchIps($ips) */ public function matchMethod($method) { - $this->methods = null !== $method ? array_map('strtoupper', (array) $method) : array(); + $this->methods = null !== $method ? array_map('strtoupper', (array) $method) : []; } /** diff --git a/RequestStack.php b/RequestStack.php index 40123f66f..885d78a50 100644 --- a/RequestStack.php +++ b/RequestStack.php @@ -21,7 +21,7 @@ class RequestStack /** * @var Request[] */ - private $requests = array(); + private $requests = []; /** * Pushes a Request on the stack. diff --git a/Response.php b/Response.php index f267d1e0e..4d63219b2 100644 --- a/Response.php +++ b/Response.php @@ -128,7 +128,7 @@ class Response * * @var array */ - public static $statusTexts = array( + public static $statusTexts = [ 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', // RFC2518 @@ -191,7 +191,7 @@ class Response 508 => 'Loop Detected', // RFC5842 510 => 'Not Extended', // RFC2774 511 => 'Network Authentication Required', // RFC6585 - ); + ]; /** * @param mixed $content The response content, see setContent() @@ -200,7 +200,7 @@ class Response * * @throws \InvalidArgumentException When the HTTP status code is not valid */ - public function __construct($content = '', $status = 200, $headers = array()) + public function __construct($content = '', $status = 200, $headers = []) { $this->headers = new ResponseHeaderBag($headers); $this->setContent($content); @@ -222,7 +222,7 @@ public function __construct($content = '', $status = 200, $headers = array()) * * @return static */ - public static function create($content = '', $status = 200, $headers = array()) + public static function create($content = '', $status = 200, $headers = []) { return new static($content, $status, $headers); } @@ -375,7 +375,7 @@ public function send() if (\function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); - } elseif (!\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true)) { + } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { static::closeOutputBuffers(0, true); } @@ -395,7 +395,7 @@ public function send() */ public function setContent($content) { - if (null !== $content && !\is_string($content) && !is_numeric($content) && !\is_callable(array($content, '__toString'))) { + if (null !== $content && !\is_string($content) && !is_numeric($content) && !\is_callable([$content, '__toString'])) { throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', \gettype($content))); } @@ -542,7 +542,7 @@ public function getCharset() */ public function isCacheable() { - if (!\in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) { + if (!\in_array($this->statusCode, [200, 203, 300, 301, 302, 404, 410])) { return false; } @@ -974,7 +974,7 @@ public function setEtag($etag = null, $weak = false) */ public function setCache(array $options) { - if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'))) { + if ($diff = array_diff(array_keys($options), ['etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'])) { throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff))); } @@ -1035,7 +1035,7 @@ public function setNotModified() $this->setContent(null); // remove headers that MUST NOT be included with 304 Not Modified responses - foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) { + foreach (['Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified'] as $header) { $this->headers->remove($header); } @@ -1064,10 +1064,10 @@ public function hasVary() public function getVary() { if (!$vary = $this->headers->get('Vary', null, false)) { - return array(); + return []; } - $ret = array(); + $ret = []; foreach ($vary as $item) { $ret = array_merge($ret, preg_split('/[\s,]+/', $item)); } @@ -1249,7 +1249,7 @@ public function isNotFound() */ public function isRedirect($location = null) { - return \in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location')); + return \in_array($this->statusCode, [201, 301, 302, 303, 307, 308]) && (null === $location ?: $location == $this->headers->get('Location')); } /** @@ -1261,7 +1261,7 @@ public function isRedirect($location = null) */ public function isEmpty() { - return \in_array($this->statusCode, array(204, 304)); + return \in_array($this->statusCode, [204, 304]); } /** diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index 00cff7af0..dc721a9de 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -24,11 +24,11 @@ class ResponseHeaderBag extends HeaderBag const DISPOSITION_ATTACHMENT = 'attachment'; const DISPOSITION_INLINE = 'inline'; - protected $computedCacheControl = array(); - protected $cookies = array(); - protected $headerNames = array(); + protected $computedCacheControl = []; + protected $cookies = []; + protected $headerNames = []; - public function __construct(array $headers = array()) + public function __construct(array $headers = []) { parent::__construct($headers); @@ -49,7 +49,7 @@ public function __construct(array $headers = array()) */ public function allPreserveCase() { - $headers = array(); + $headers = []; foreach ($this->all() as $name => $value) { $headers[isset($this->headerNames[$name]) ? $this->headerNames[$name] : $name] = $value; } @@ -70,9 +70,9 @@ public function allPreserveCaseWithoutCookies() /** * {@inheritdoc} */ - public function replace(array $headers = array()) + public function replace(array $headers = []) { - $this->headerNames = array(); + $this->headerNames = []; parent::replace($headers); @@ -107,7 +107,7 @@ public function set($key, $values, $replace = true) if ('set-cookie' === $uniqueKey) { if ($replace) { - $this->cookies = array(); + $this->cookies = []; } foreach ((array) $values as $cookie) { $this->setCookie(Cookie::fromString($cookie)); @@ -122,9 +122,9 @@ public function set($key, $values, $replace = true) parent::set($key, $values, $replace); // ensure the cache-control header has sensible defaults - if (\in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'), true)) { + if (\in_array($uniqueKey, ['cache-control', 'etag', 'last-modified', 'expires'], true)) { $computed = $this->computeCacheControlValue(); - $this->headers['cache-control'] = array($computed); + $this->headers['cache-control'] = [$computed]; $this->headerNames['cache-control'] = 'Cache-Control'; $this->computedCacheControl = $this->parseCacheControl($computed); } @@ -139,7 +139,7 @@ public function remove($key) unset($this->headerNames[$uniqueKey]); if ('set-cookie' === $uniqueKey) { - $this->cookies = array(); + $this->cookies = []; return; } @@ -147,7 +147,7 @@ public function remove($key) parent::remove($key); if ('cache-control' === $uniqueKey) { - $this->computedCacheControl = array(); + $this->computedCacheControl = []; } if ('date' === $uniqueKey) { @@ -216,15 +216,15 @@ public function removeCookie($name, $path = '/', $domain = null) */ public function getCookies($format = self::COOKIES_FLAT) { - 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)))); + if (!\in_array($format, [self::COOKIES_FLAT, self::COOKIES_ARRAY])) { + throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', [self::COOKIES_FLAT, self::COOKIES_ARRAY]))); } if (self::COOKIES_ARRAY === $format) { return $this->cookies; } - $flattenedCookies = array(); + $flattenedCookies = []; foreach ($this->cookies as $path) { foreach ($path as $cookies) { foreach ($cookies as $cookie) { @@ -267,7 +267,7 @@ public function clearCookie($name, $path = '/', $domain = null, $secure = false, */ public function makeDisposition($disposition, $filename, $filenameFallback = '') { - if (!\in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) { + if (!\in_array($disposition, [self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE])) { throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE)); } diff --git a/ServerBag.php b/ServerBag.php index d8ab561aa..90da49fae 100644 --- a/ServerBag.php +++ b/ServerBag.php @@ -27,8 +27,8 @@ class ServerBag extends ParameterBag */ public function getHeaders() { - $headers = array(); - $contentHeaders = array('CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true); + $headers = []; + $contentHeaders = ['CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true]; foreach ($this->parameters as $key => $value) { if (0 === strpos($key, 'HTTP_')) { $headers[substr($key, 5)] = $value; diff --git a/Session/Attribute/AttributeBag.php b/Session/Attribute/AttributeBag.php index fc5fb1410..b5666f854 100644 --- a/Session/Attribute/AttributeBag.php +++ b/Session/Attribute/AttributeBag.php @@ -19,7 +19,7 @@ class AttributeBag implements AttributeBagInterface, \IteratorAggregate, \Counta private $name = 'attributes'; private $storageKey; - protected $attributes = array(); + protected $attributes = []; /** * @param string $storageKey The key used to store attributes in the session @@ -95,7 +95,7 @@ public function all() */ public function replace(array $attributes) { - $this->attributes = array(); + $this->attributes = []; foreach ($attributes as $key => $value) { $this->set($key, $value); } @@ -121,7 +121,7 @@ public function remove($name) public function clear() { $return = $this->attributes; - $this->attributes = array(); + $this->attributes = []; return $return; } diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index 2f1e01a97..95e48253b 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -115,7 +115,7 @@ protected function &resolveAttributePath($name, $writeContext = false) return $array; } - $array[$parts[0]] = array(); + $array[$parts[0]] = []; return $array; } @@ -130,7 +130,7 @@ protected function &resolveAttributePath($name, $writeContext = false) return $null; } - $array[$part] = array(); + $array[$part] = []; } $array = &$array[$part]; diff --git a/Session/Flash/AutoExpireFlashBag.php b/Session/Flash/AutoExpireFlashBag.php index 77521c247..12345c823 100644 --- a/Session/Flash/AutoExpireFlashBag.php +++ b/Session/Flash/AutoExpireFlashBag.php @@ -19,7 +19,7 @@ class AutoExpireFlashBag implements FlashBagInterface { private $name = 'flashes'; - private $flashes = array('display' => array(), 'new' => array()); + private $flashes = ['display' => [], 'new' => []]; private $storageKey; /** @@ -53,8 +53,8 @@ public function initialize(array &$flashes) // The logic: messages from the last request will be stored in new, so we move them to previous // This request we will show what is in 'display'. What is placed into 'new' this time round will // be moved to display next time round. - $this->flashes['display'] = array_key_exists('new', $this->flashes) ? $this->flashes['new'] : array(); - $this->flashes['new'] = array(); + $this->flashes['display'] = array_key_exists('new', $this->flashes) ? $this->flashes['new'] : []; + $this->flashes['new'] = []; } /** @@ -68,7 +68,7 @@ public function add($type, $message) /** * {@inheritdoc} */ - public function peek($type, array $default = array()) + public function peek($type, array $default = []) { return $this->has($type) ? $this->flashes['display'][$type] : $default; } @@ -78,13 +78,13 @@ public function peek($type, array $default = array()) */ public function peekAll() { - return array_key_exists('display', $this->flashes) ? (array) $this->flashes['display'] : array(); + return array_key_exists('display', $this->flashes) ? (array) $this->flashes['display'] : []; } /** * {@inheritdoc} */ - public function get($type, array $default = array()) + public function get($type, array $default = []) { $return = $default; @@ -106,7 +106,7 @@ public function get($type, array $default = array()) public function all() { $return = $this->flashes['display']; - $this->flashes['display'] = array(); + $this->flashes['display'] = []; return $return; } diff --git a/Session/Flash/FlashBag.php b/Session/Flash/FlashBag.php index 12fb740c5..19baabb94 100644 --- a/Session/Flash/FlashBag.php +++ b/Session/Flash/FlashBag.php @@ -19,7 +19,7 @@ class FlashBag implements FlashBagInterface { private $name = 'flashes'; - private $flashes = array(); + private $flashes = []; private $storageKey; /** @@ -62,7 +62,7 @@ public function add($type, $message) /** * {@inheritdoc} */ - public function peek($type, array $default = array()) + public function peek($type, array $default = []) { return $this->has($type) ? $this->flashes[$type] : $default; } @@ -78,7 +78,7 @@ public function peekAll() /** * {@inheritdoc} */ - public function get($type, array $default = array()) + public function get($type, array $default = []) { if (!$this->has($type)) { return $default; @@ -97,7 +97,7 @@ public function get($type, array $default = array()) public function all() { $return = $this->peekAll(); - $this->flashes = array(); + $this->flashes = []; return $return; } diff --git a/Session/Flash/FlashBagInterface.php b/Session/Flash/FlashBagInterface.php index f53c9dae6..2bd1d62bd 100644 --- a/Session/Flash/FlashBagInterface.php +++ b/Session/Flash/FlashBagInterface.php @@ -44,7 +44,7 @@ public function set($type, $message); * * @return array */ - public function peek($type, array $default = array()); + public function peek($type, array $default = []); /** * Gets all flash messages. @@ -61,7 +61,7 @@ public function peekAll(); * * @return array */ - public function get($type, array $default = array()); + public function get($type, array $default = []); /** * Gets and clears flashes from the stack. diff --git a/Session/Session.php b/Session/Session.php index 334990687..867ceba97 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -28,7 +28,7 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable private $flashName; private $attributeName; - private $data = array(); + private $data = []; private $usageIndex = 0; /** diff --git a/Session/Storage/Handler/AbstractSessionHandler.php b/Session/Storage/Handler/AbstractSessionHandler.php index 0d119498d..eb09c0b54 100644 --- a/Session/Storage/Handler/AbstractSessionHandler.php +++ b/Session/Storage/Handler/AbstractSessionHandler.php @@ -113,7 +113,7 @@ public function write($sessionId, $data) } if (null === $this->igbinaryEmptyData) { // see https://github.com/igbinary/igbinary/issues/146 - $this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize(array()) : ''; + $this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize([]) : ''; } if ('' === $data || $this->igbinaryEmptyData === $data) { return $this->destroy($sessionId); @@ -138,7 +138,7 @@ public function destroy($sessionId) $sessionCookie = sprintf(' %s=', urlencode($this->sessionName)); $sessionCookieWithId = sprintf('%s%s;', $sessionCookie, urlencode($sessionId)); $sessionCookieFound = false; - $otherCookies = array(); + $otherCookies = []; foreach (headers_list() as $h) { if (0 !== stripos($h, 'Set-Cookie:')) { continue; diff --git a/Session/Storage/Handler/MemcacheSessionHandler.php b/Session/Storage/Handler/MemcacheSessionHandler.php index 1b12c9218..3abc33caa 100644 --- a/Session/Storage/Handler/MemcacheSessionHandler.php +++ b/Session/Storage/Handler/MemcacheSessionHandler.php @@ -44,9 +44,9 @@ class MemcacheSessionHandler implements \SessionHandlerInterface * * @throws \InvalidArgumentException When unsupported options are passed */ - public function __construct(\Memcache $memcache, array $options = array()) + public function __construct(\Memcache $memcache, array $options = []) { - if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) { + if ($diff = array_diff(array_keys($options), ['prefix', 'expiretime'])) { throw new \InvalidArgumentException(sprintf('The following options are not supported "%s"', implode(', ', $diff))); } diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 61a7afd90..3c3e3b2d2 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -45,11 +45,11 @@ class MemcachedSessionHandler extends AbstractSessionHandler * * @throws \InvalidArgumentException When unsupported options are passed */ - public function __construct(\Memcached $memcached, array $options = array()) + public function __construct(\Memcached $memcached, array $options = []) { $this->memcached = $memcached; - if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) { + if ($diff = array_diff(array_keys($options), ['prefix', 'expiretime'])) { throw new \InvalidArgumentException(sprintf('The following options are not supported "%s"', implode(', ', $diff))); } diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index 7d3fa218a..3b5ccaa83 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -83,12 +83,12 @@ public function __construct($mongo, array $options) $this->mongo = $mongo; - $this->options = array_merge(array( + $this->options = array_merge([ 'id_field' => '_id', 'data_field' => 'data', 'time_field' => 'time', 'expiry_field' => 'expires_at', - ), $options); + ], $options); } /** @@ -106,9 +106,9 @@ protected function doDestroy($sessionId) { $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove'; - $this->getCollection()->$methodName(array( + $this->getCollection()->$methodName([ $this->options['id_field'] => $sessionId, - )); + ]); return true; } @@ -120,9 +120,9 @@ public function gc($maxlifetime) { $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteMany' : 'remove'; - $this->getCollection()->$methodName(array( - $this->options['expiry_field'] => array('$lt' => $this->createDateTime()), - )); + $this->getCollection()->$methodName([ + $this->options['expiry_field'] => ['$lt' => $this->createDateTime()], + ]); return true; } @@ -134,12 +134,12 @@ protected function doWrite($sessionId, $data) { $expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime')); - $fields = array( + $fields = [ $this->options['time_field'] => $this->createDateTime(), $this->options['expiry_field'] => $expiry, - ); + ]; - $options = array('upsert' => true); + $options = ['upsert' => true]; if ($this->mongo instanceof \MongoDB\Client) { $fields[$this->options['data_field']] = new \MongoDB\BSON\Binary($data, \MongoDB\BSON\Binary::TYPE_OLD_BINARY); @@ -151,8 +151,8 @@ protected function doWrite($sessionId, $data) $methodName = $this->mongo instanceof \MongoDB\Client ? 'updateOne' : 'update'; $this->getCollection()->$methodName( - array($this->options['id_field'] => $sessionId), - array('$set' => $fields), + [$this->options['id_field'] => $sessionId], + ['$set' => $fields], $options ); @@ -168,18 +168,18 @@ public function updateTimestamp($sessionId, $data) if ($this->mongo instanceof \MongoDB\Client) { $methodName = 'updateOne'; - $options = array(); + $options = []; } else { $methodName = 'update'; - $options = array('multiple' => false); + $options = ['multiple' => false]; } $this->getCollection()->$methodName( - array($this->options['id_field'] => $sessionId), - array('$set' => array( + [$this->options['id_field'] => $sessionId], + ['$set' => [ $this->options['time_field'] => $this->createDateTime(), $this->options['expiry_field'] => $expiry, - )), + ]], $options ); @@ -191,10 +191,10 @@ public function updateTimestamp($sessionId, $data) */ protected function doRead($sessionId) { - $dbData = $this->getCollection()->findOne(array( + $dbData = $this->getCollection()->findOne([ $this->options['id_field'] => $sessionId, - $this->options['expiry_field'] => array('$gte' => $this->createDateTime()), - )); + $this->options['expiry_field'] => ['$gte' => $this->createDateTime()], + ]); if (null === $dbData) { return ''; diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 8c0c42fd2..c027a9e6e 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -118,7 +118,7 @@ class PdoSessionHandler extends AbstractSessionHandler /** * @var array Connection options when lazy-connect */ - private $connectionOptions = array(); + private $connectionOptions = []; /** * @var int The strategy for locking, see constants @@ -130,7 +130,7 @@ class PdoSessionHandler extends AbstractSessionHandler * * @var \PDOStatement[] An array of statements to release advisory locks */ - private $unlockStatements = array(); + private $unlockStatements = []; /** * @var bool True when the current session exists but expired according to session.gc_maxlifetime @@ -169,7 +169,7 @@ class PdoSessionHandler extends AbstractSessionHandler * * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION */ - public function __construct($pdoOrDsn = null, array $options = array()) + public function __construct($pdoOrDsn = null, array $options = []) { if ($pdoOrDsn instanceof \PDO) { if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) { @@ -468,13 +468,13 @@ private function buildDsnFromUrl($dsnOrUrl) throw new \InvalidArgumentException('URLs without scheme are not supported to configure the PdoSessionHandler'); } - $driverAliasMap = array( + $driverAliasMap = [ 'mssql' => 'sqlsrv', 'mysql2' => 'mysql', // Amazon RDS, for some weird reason 'postgres' => 'pgsql', 'postgresql' => 'pgsql', 'sqlite3' => 'sqlite', - ); + ]; $driver = isset($driverAliasMap[$params['scheme']]) ? $driverAliasMap[$params['scheme']] : $params['scheme']; diff --git a/Session/Storage/MetadataBag.php b/Session/Storage/MetadataBag.php index 6f59af486..a62f108b3 100644 --- a/Session/Storage/MetadataBag.php +++ b/Session/Storage/MetadataBag.php @@ -39,7 +39,7 @@ class MetadataBag implements SessionBagInterface /** * @var array */ - protected $meta = array(self::CREATED => 0, self::UPDATED => 0, self::LIFETIME => 0); + protected $meta = [self::CREATED => 0, self::UPDATED => 0, self::LIFETIME => 0]; /** * Unix timestamp. diff --git a/Session/Storage/MockArraySessionStorage.php b/Session/Storage/MockArraySessionStorage.php index 027f4efff..c1e7523c5 100644 --- a/Session/Storage/MockArraySessionStorage.php +++ b/Session/Storage/MockArraySessionStorage.php @@ -50,7 +50,7 @@ class MockArraySessionStorage implements SessionStorageInterface /** * @var array */ - protected $data = array(); + protected $data = []; /** * @var MetadataBag @@ -60,7 +60,7 @@ class MockArraySessionStorage implements SessionStorageInterface /** * @var array|SessionBagInterface[] */ - protected $bags = array(); + protected $bags = []; /** * @param string $name Session name @@ -170,7 +170,7 @@ public function clear() } // clear out the session - $this->data = array(); + $this->data = []; // reconnect the bags to the session $this->loadSession(); @@ -242,11 +242,11 @@ protected function generateId() protected function loadSession() { - $bags = array_merge($this->bags, array($this->metadataBag)); + $bags = array_merge($this->bags, [$this->metadataBag]); foreach ($bags as $bag) { $key = $bag->getStorageKey(); - $this->data[$key] = isset($this->data[$key]) ? $this->data[$key] : array(); + $this->data[$key] = isset($this->data[$key]) ? $this->data[$key] : []; $bag->initialize($this->data[$key]); } diff --git a/Session/Storage/MockFileSessionStorage.php b/Session/Storage/MockFileSessionStorage.php index 14f427007..9bbd1baf2 100644 --- a/Session/Storage/MockFileSessionStorage.php +++ b/Session/Storage/MockFileSessionStorage.php @@ -98,7 +98,7 @@ public function save() unset($data[$key]); } } - if (array($key = $this->metadataBag->getStorageKey()) === array_keys($data)) { + if ([$key = $this->metadataBag->getStorageKey()] === array_keys($data)) { unset($data[$key]); } @@ -145,7 +145,7 @@ private function getFilePath() private function read() { $filePath = $this->getFilePath(); - $this->data = is_readable($filePath) && is_file($filePath) ? unserialize(file_get_contents($filePath)) : array(); + $this->data = is_readable($filePath) && is_file($filePath) ? unserialize(file_get_contents($filePath)) : []; $this->loadSession(); } diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index a18f812d5..a2f64a3af 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -26,7 +26,7 @@ class NativeSessionStorage implements SessionStorageInterface /** * @var SessionBagInterface[] */ - protected $bags = array(); + protected $bags = []; /** * @var bool @@ -98,14 +98,14 @@ class NativeSessionStorage implements SessionStorageInterface * @param \SessionHandlerInterface|null $handler * @param MetadataBag $metaBag MetadataBag */ - public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null) + public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null) { - $options += array( + $options += [ 'cache_limiter' => '', 'cache_expire' => 0, 'use_cookies' => 1, 'lazy_write' => 1, - ); + ]; session_register_shutdown(); @@ -226,7 +226,7 @@ public function save() unset($_SESSION[$key]); } } - if (array($key = $this->metadataBag->getStorageKey()) === array_keys($_SESSION)) { + if ([$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) { unset($_SESSION[$key]); } @@ -262,7 +262,7 @@ public function clear() } // clear out the session - $_SESSION = array(); + $_SESSION = []; // reconnect the bags to the session $this->loadSession(); @@ -341,7 +341,7 @@ public function setOptions(array $options) return; } - $validOptions = array_flip(array( + $validOptions = array_flip([ 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly', 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'entropy_file', 'entropy_length', 'gc_divisor', @@ -352,7 +352,7 @@ public function setOptions(array $options) 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name', 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags', 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags', - )); + ]); foreach ($options as $key => $value) { if (isset($validOptions[$key])) { @@ -422,11 +422,11 @@ protected function loadSession(array &$session = null) $session = &$_SESSION; } - $bags = array_merge($this->bags, array($this->metadataBag)); + $bags = array_merge($this->bags, [$this->metadataBag]); foreach ($bags as $bag) { $key = $bag->getStorageKey(); - $session[$key] = isset($session[$key]) ? $session[$key] : array(); + $session[$key] = isset($session[$key]) ? $session[$key] : []; $bag->initialize($session[$key]); } diff --git a/StreamedResponse.php b/StreamedResponse.php index 3a55d5d2b..8bc5fc91a 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -35,7 +35,7 @@ class StreamedResponse extends Response * @param int $status The response status code * @param array $headers An array of response headers */ - public function __construct(callable $callback = null, $status = 200, $headers = array()) + public function __construct(callable $callback = null, $status = 200, $headers = []) { parent::__construct(null, $status, $headers); @@ -55,7 +55,7 @@ public function __construct(callable $callback = null, $status = 200, $headers = * * @return static */ - public static function create($callback = null, $status = 200, $headers = array()) + public static function create($callback = null, $status = 200, $headers = []) { return new static($callback, $status, $headers); } diff --git a/Tests/AcceptHeaderItemTest.php b/Tests/AcceptHeaderItemTest.php index cb43bb351..a40a7621d 100644 --- a/Tests/AcceptHeaderItemTest.php +++ b/Tests/AcceptHeaderItemTest.php @@ -28,24 +28,24 @@ public function testFromString($string, $value, array $attributes) public function provideFromStringData() { - return array( - array( + return [ + [ 'text/html', - 'text/html', array(), - ), - array( + 'text/html', [], + ], + [ '"this;should,not=matter"', - 'this;should,not=matter', array(), - ), - array( + 'this;should,not=matter', [], + ], + [ "text/plain; charset=utf-8;param=\"this;should,not=matter\";\tfootnotes=true", - 'text/plain', array('charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'), - ), - array( + 'text/plain', ['charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'], + ], + [ '"this;should,not=matter";charset=utf-8', - 'this;should,not=matter', array('charset' => 'utf-8'), - ), - ); + 'this;should,not=matter', ['charset' => 'utf-8'], + ], + ]; } /** @@ -59,21 +59,21 @@ public function testToString($value, array $attributes, $string) public function provideToStringData() { - return array( - array( - 'text/html', array(), + return [ + [ + 'text/html', [], 'text/html', - ), - array( - 'text/plain', array('charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'), + ], + [ + 'text/plain', ['charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'], 'text/plain;charset=utf-8;param="this;should,not=matter";footnotes=true', - ), - ); + ], + ]; } public function testValue() { - $item = new AcceptHeaderItem('value', array()); + $item = new AcceptHeaderItem('value', []); $this->assertEquals('value', $item->getValue()); $item->setValue('new value'); @@ -85,7 +85,7 @@ public function testValue() public function testQuality() { - $item = new AcceptHeaderItem('value', array()); + $item = new AcceptHeaderItem('value', []); $this->assertEquals(1.0, $item->getQuality()); $item->setQuality(0.5); @@ -98,14 +98,14 @@ public function testQuality() public function testAttribute() { - $item = new AcceptHeaderItem('value', array()); - $this->assertEquals(array(), $item->getAttributes()); + $item = new AcceptHeaderItem('value', []); + $this->assertEquals([], $item->getAttributes()); $this->assertFalse($item->hasAttribute('test')); $this->assertNull($item->getAttribute('test')); $this->assertEquals('default', $item->getAttribute('test', 'default')); $item->setAttribute('test', 'value'); - $this->assertEquals(array('test' => 'value'), $item->getAttributes()); + $this->assertEquals(['test' => 'value'], $item->getAttributes()); $this->assertTrue($item->hasAttribute('test')); $this->assertEquals('value', $item->getAttribute('test')); $this->assertEquals('value', $item->getAttribute('test', 'default')); diff --git a/Tests/AcceptHeaderTest.php b/Tests/AcceptHeaderTest.php index 9929eac28..459b693d5 100644 --- a/Tests/AcceptHeaderTest.php +++ b/Tests/AcceptHeaderTest.php @@ -39,13 +39,13 @@ public function testFromString($string, array $items) public function provideFromStringData() { - return array( - array('', array()), - array('gzip', array(new AcceptHeaderItem('gzip'))), - array('gzip,deflate,sdch', array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch'))), - array("gzip, deflate\t,sdch", array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch'))), - array('"this;should,not=matter"', array(new AcceptHeaderItem('this;should,not=matter'))), - ); + return [ + ['', []], + ['gzip', [new AcceptHeaderItem('gzip')]], + ['gzip,deflate,sdch', [new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')]], + ["gzip, deflate\t,sdch", [new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')]], + ['"this;should,not=matter"', [new AcceptHeaderItem('this;should,not=matter')]], + ]; } /** @@ -59,12 +59,12 @@ public function testToString(array $items, $string) public function provideToStringData() { - return array( - array(array(), ''), - array(array(new AcceptHeaderItem('gzip')), 'gzip'), - array(array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')), 'gzip,deflate,sdch'), - array(array(new AcceptHeaderItem('this;should,not=matter')), 'this;should,not=matter'), - ); + return [ + [[], ''], + [[new AcceptHeaderItem('gzip')], 'gzip'], + [[new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')], 'gzip,deflate,sdch'], + [[new AcceptHeaderItem('this;should,not=matter')], 'this;should,not=matter'], + ]; } /** @@ -78,9 +78,9 @@ public function testFilter($string, $filter, array $values) public function provideFilterData() { - return array( - array('fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4', '/fr.*/', array('fr-FR', 'fr')), - ); + return [ + ['fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4', '/fr.*/', ['fr-FR', 'fr']], + ]; } /** @@ -94,10 +94,10 @@ public function testSorting($string, array $values) public function provideSortingData() { - return array( - 'quality has priority' => array('*;q=0.3,ISO-8859-1,utf-8;q=0.7', array('ISO-8859-1', 'utf-8', '*')), - 'order matters when q is equal' => array('*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', array('ISO-8859-1', 'utf-8', '*')), - 'order matters when q is equal2' => array('*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', array('utf-8', 'ISO-8859-1', '*')), - ); + return [ + 'quality has priority' => ['*;q=0.3,ISO-8859-1,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']], + 'order matters when q is equal' => ['*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']], + 'order matters when q is equal2' => ['*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', ['utf-8', 'ISO-8859-1', '*']], + ]; } } diff --git a/Tests/ApacheRequestTest.php b/Tests/ApacheRequestTest.php index 157ab90ec..6fa3b8891 100644 --- a/Tests/ApacheRequestTest.php +++ b/Tests/ApacheRequestTest.php @@ -31,63 +31,63 @@ public function testUriMethods($server, $expectedRequestUri, $expectedBaseUrl, $ public function provideServerVars() { - return array( - array( - array( + return [ + [ + [ 'REQUEST_URI' => '/foo/app_dev.php/bar', 'SCRIPT_NAME' => '/foo/app_dev.php', 'PATH_INFO' => '/bar', - ), + ], '/foo/app_dev.php/bar', '/foo/app_dev.php', '/bar', - ), - array( - array( + ], + [ + [ 'REQUEST_URI' => '/foo/bar', 'SCRIPT_NAME' => '/foo/app_dev.php', - ), + ], '/foo/bar', '/foo', '/bar', - ), - array( - array( + ], + [ + [ 'REQUEST_URI' => '/app_dev.php/foo/bar', 'SCRIPT_NAME' => '/app_dev.php', 'PATH_INFO' => '/foo/bar', - ), + ], '/app_dev.php/foo/bar', '/app_dev.php', '/foo/bar', - ), - array( - array( + ], + [ + [ 'REQUEST_URI' => '/foo/bar', 'SCRIPT_NAME' => '/app_dev.php', - ), + ], '/foo/bar', '', '/foo/bar', - ), - array( - array( + ], + [ + [ 'REQUEST_URI' => '/app_dev.php', 'SCRIPT_NAME' => '/app_dev.php', - ), + ], '/app_dev.php', '/app_dev.php', '/', - ), - array( - array( + ], + [ + [ 'REQUEST_URI' => '/', 'SCRIPT_NAME' => '/app_dev.php', - ), + ], '/', '', '/', - ), - ); + ], + ]; } } diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index d21791f00..c89f20d05 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -22,14 +22,14 @@ class BinaryFileResponseTest extends ResponseTestCase public function testConstruction() { $file = __DIR__.'/../README.md'; - $response = new BinaryFileResponse($file, 404, array('X-Header' => 'Foo'), true, null, true, true); + $response = new BinaryFileResponse($file, 404, ['X-Header' => 'Foo'], true, null, true, true); $this->assertEquals(404, $response->getStatusCode()); $this->assertEquals('Foo', $response->headers->get('X-Header')); $this->assertTrue($response->headers->has('ETag')); $this->assertTrue($response->headers->has('Last-Modified')); $this->assertFalse($response->headers->has('Content-Disposition')); - $response = BinaryFileResponse::create($file, 404, array(), true, ResponseHeaderBag::DISPOSITION_INLINE); + $response = BinaryFileResponse::create($file, 404, [], true, ResponseHeaderBag::DISPOSITION_INLINE); $this->assertEquals(404, $response->getStatusCode()); $this->assertFalse($response->headers->has('ETag')); $this->assertEquals('inline; filename="README.md"', $response->headers->get('Content-Disposition')); @@ -39,7 +39,7 @@ public function testConstructWithNonAsciiFilename() { touch(sys_get_temp_dir().'/fööö.html'); - $response = new BinaryFileResponse(sys_get_temp_dir().'/fööö.html', 200, array(), true, 'attachment'); + $response = new BinaryFileResponse(sys_get_temp_dir().'/fööö.html', 200, [], true, 'attachment'); @unlink(sys_get_temp_dir().'/fööö.html'); @@ -85,7 +85,7 @@ public function testSetContentDispositionGeneratesSafeFallbackFilenameForWrongly */ public function testRequests($requestRange, $offset, $length, $responseRange) { - $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'))->setAutoEtag(); + $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'])->setAutoEtag(); // do a request to get the ETag $request = Request::create('/'); @@ -117,7 +117,7 @@ public function testRequests($requestRange, $offset, $length, $responseRange) */ public function testRequestsWithoutEtag($requestRange, $offset, $length, $responseRange) { - $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream')); + $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']); // do a request to get the LastModified $request = Request::create('/'); @@ -145,19 +145,19 @@ public function testRequestsWithoutEtag($requestRange, $offset, $length, $respon public function provideRanges() { - return array( - array('bytes=1-4', 1, 4, 'bytes 1-4/35'), - array('bytes=-5', 30, 5, 'bytes 30-34/35'), - array('bytes=30-', 30, 5, 'bytes 30-34/35'), - array('bytes=30-30', 30, 1, 'bytes 30-30/35'), - array('bytes=30-34', 30, 5, 'bytes 30-34/35'), - ); + return [ + ['bytes=1-4', 1, 4, 'bytes 1-4/35'], + ['bytes=-5', 30, 5, 'bytes 30-34/35'], + ['bytes=30-', 30, 5, 'bytes 30-34/35'], + ['bytes=30-30', 30, 1, 'bytes 30-30/35'], + ['bytes=30-34', 30, 5, 'bytes 30-34/35'], + ]; } public function testRangeRequestsWithoutLastModifiedDate() { // prevent auto last modified - $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'), true, null, false, false); + $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'], true, null, false, false); // prepare a request for a range of the testing file $request = Request::create('/'); @@ -178,7 +178,7 @@ public function testRangeRequestsWithoutLastModifiedDate() */ public function testFullFileRequests($requestRange) { - $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'))->setAutoEtag(); + $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'])->setAutoEtag(); // prepare a request for a range of the testing file $request = Request::create('/'); @@ -198,14 +198,14 @@ public function testFullFileRequests($requestRange) public function provideFullFileRanges() { - return array( - array('bytes=0-'), - array('bytes=0-34'), - array('bytes=-35'), + return [ + ['bytes=0-'], + ['bytes=0-34'], + ['bytes=-35'], // Syntactical invalid range-request should also return the full resource - array('bytes=20-10'), - array('bytes=50-40'), - ); + ['bytes=20-10'], + ['bytes=50-40'], + ]; } public function testUnpreparedResponseSendsFullFile() @@ -226,7 +226,7 @@ public function testUnpreparedResponseSendsFullFile() */ public function testInvalidRequests($requestRange) { - $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'))->setAutoEtag(); + $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'])->setAutoEtag(); // prepare a request for a range of the testing file $request = Request::create('/'); @@ -242,10 +242,10 @@ public function testInvalidRequests($requestRange) public function provideInvalidRanges() { - return array( - array('bytes=-40'), - array('bytes=30-40'), - ); + return [ + ['bytes=-40'], + ['bytes=30-40'], + ]; } /** @@ -257,7 +257,7 @@ public function testXSendfile($file) $request->headers->set('X-Sendfile-Type', 'X-Sendfile'); BinaryFileResponse::trustXSendfileTypeHeader(); - $response = BinaryFileResponse::create($file, 200, array('Content-Type' => 'application/octet-stream')); + $response = BinaryFileResponse::create($file, 200, ['Content-Type' => 'application/octet-stream']); $response->prepare($request); $this->expectOutputString(''); @@ -268,10 +268,10 @@ public function testXSendfile($file) public function provideXSendfileFiles() { - return array( - array(__DIR__.'/../README.md'), - array('file://'.__DIR__.'/../README.md'), - ); + return [ + [__DIR__.'/../README.md'], + ['file://'.__DIR__.'/../README.md'], + ]; } /** @@ -286,7 +286,7 @@ public function testXAccelMapping($realpath, $mapping, $virtual) $file = new FakeFile($realpath, __DIR__.'/File/Fixtures/test'); BinaryFileResponse::trustXSendfileTypeHeader(); - $response = new BinaryFileResponse($file, 200, array('Content-Type' => 'application/octet-stream')); + $response = new BinaryFileResponse($file, 200, ['Content-Type' => 'application/octet-stream']); $reflection = new \ReflectionObject($response); $property = $reflection->getProperty('file'); $property->setAccessible(true); @@ -305,7 +305,7 @@ public function testDeleteFileAfterSend() $realPath = realpath($path); $this->assertFileExists($realPath); - $response = new BinaryFileResponse($realPath, 200, array('Content-Type' => 'application/octet-stream')); + $response = new BinaryFileResponse($realPath, 200, ['Content-Type' => 'application/octet-stream']); $response->deleteFileAfterSend(true); $response->prepare($request); @@ -317,7 +317,7 @@ public function testDeleteFileAfterSend() public function testAcceptRangeOnUnsafeMethods() { $request = Request::create('/', 'POST'); - $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream')); + $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']); $response->prepare($request); $this->assertEquals('none', $response->headers->get('Accept-Ranges')); @@ -326,7 +326,7 @@ public function testAcceptRangeOnUnsafeMethods() public function testAcceptRangeNotOverriden() { $request = Request::create('/', 'POST'); - $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream')); + $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']); $response->headers->set('Accept-Ranges', 'foo'); $response->prepare($request); @@ -335,16 +335,16 @@ public function testAcceptRangeNotOverriden() public function getSampleXAccelMappings() { - return array( - array('/var/www/var/www/files/foo.txt', '/var/www/=/files/', '/files/var/www/files/foo.txt'), - array('/home/foo/bar.txt', '/var/www/=/files/,/home/foo/=/baz/', '/baz/bar.txt'), - ); + return [ + ['/var/www/var/www/files/foo.txt', '/var/www/=/files/', '/files/var/www/files/foo.txt'], + ['/home/foo/bar.txt', '/var/www/=/files/,/home/foo/=/baz/', '/baz/bar.txt'], + ]; } public function testStream() { $request = Request::create('/'); - $response = new BinaryFileResponse(new Stream(__DIR__.'/../README.md'), 200, array('Content-Type' => 'text/plain')); + $response = new BinaryFileResponse(new Stream(__DIR__.'/../README.md'), 200, ['Content-Type' => 'text/plain']); $response->prepare($request); $this->assertNull($response->headers->get('Content-Length')); @@ -352,7 +352,7 @@ public function testStream() protected function provideResponse() { - return new BinaryFileResponse(__DIR__.'/../README.md', 200, array('Content-Type' => 'application/octet-stream')); + return new BinaryFileResponse(__DIR__.'/../README.md', 200, ['Content-Type' => 'application/octet-stream']); } public static function tearDownAfterClass() diff --git a/Tests/CookieTest.php b/Tests/CookieTest.php index 14c45c9a6..aaf2edb38 100644 --- a/Tests/CookieTest.php +++ b/Tests/CookieTest.php @@ -26,17 +26,17 @@ class CookieTest extends TestCase { public function invalidNames() { - return array( - array(''), - array(',MyName'), - array(';MyName'), - array(' MyName'), - array("\tMyName"), - array("\rMyName"), - array("\nMyName"), - array("\013MyName"), - array("\014MyName"), - ); + return [ + [''], + [',MyName'], + [';MyName'], + [' MyName'], + ["\tMyName"], + ["\rMyName"], + ["\nMyName"], + ["\013MyName"], + ["\014MyName"], + ]; } /** diff --git a/Tests/ExpressionRequestMatcherTest.php b/Tests/ExpressionRequestMatcherTest.php index 1152e46c0..2afdade67 100644 --- a/Tests/ExpressionRequestMatcherTest.php +++ b/Tests/ExpressionRequestMatcherTest.php @@ -55,15 +55,15 @@ public function testMatchesWhenParentMatchesIsFalse($expression) public function provideExpressions() { - return array( - array('request.getMethod() == method', true), - array('request.getPathInfo() == path', true), - array('request.getHost() == host', true), - array('request.getClientIp() == ip', true), - array('request.attributes.all() == attributes', true), - array('request.getMethod() == method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', true), - array('request.getMethod() != method', false), - array('request.getMethod() != method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', false), - ); + return [ + ['request.getMethod() == method', true], + ['request.getPathInfo() == path', true], + ['request.getHost() == host', true], + ['request.getClientIp() == ip', true], + ['request.attributes.all() == attributes', true], + ['request.getMethod() == method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', true], + ['request.getMethod() != method', false], + ['request.getMethod() != method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', false], + ]; } } diff --git a/Tests/File/FileTest.php b/Tests/File/FileTest.php index dbd9c44bd..fb82dae76 100644 --- a/Tests/File/FileTest.php +++ b/Tests/File/FileTest.php @@ -110,14 +110,14 @@ public function testMoveWithNewName() public function getFilenameFixtures() { - return array( - array('original.gif', 'original.gif'), - array('..\\..\\original.gif', 'original.gif'), - array('../../original.gif', 'original.gif'), - array('файлfile.gif', 'файлfile.gif'), - array('..\\..\\файлfile.gif', 'файлfile.gif'), - array('../../файлfile.gif', 'файлfile.gif'), - ); + return [ + ['original.gif', 'original.gif'], + ['..\\..\\original.gif', 'original.gif'], + ['../../original.gif', 'original.gif'], + ['файлfile.gif', 'файлfile.gif'], + ['..\\..\\файлfile.gif', 'файлfile.gif'], + ['../../файлfile.gif', 'файлfile.gif'], + ]; } /** diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 1a88d4835..9c02b478e 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -249,13 +249,13 @@ public function testIsInvalidOnUploadError($error) public function uploadedFileErrorProvider() { - return array( - array(UPLOAD_ERR_INI_SIZE), - array(UPLOAD_ERR_FORM_SIZE), - array(UPLOAD_ERR_PARTIAL), - array(UPLOAD_ERR_NO_TMP_DIR), - array(UPLOAD_ERR_EXTENSION), - ); + return [ + [UPLOAD_ERR_INI_SIZE], + [UPLOAD_ERR_FORM_SIZE], + [UPLOAD_ERR_PARTIAL], + [UPLOAD_ERR_NO_TMP_DIR], + [UPLOAD_ERR_EXTENSION], + ]; } public function testIsInvalidIfNotHttpUpload() diff --git a/Tests/FileBagTest.php b/Tests/FileBagTest.php index b1bbba0d3..0b6d66042 100644 --- a/Tests/FileBagTest.php +++ b/Tests/FileBagTest.php @@ -28,7 +28,7 @@ class FileBagTest extends TestCase */ public function testFileMustBeAnArrayOrUploadedFile() { - new FileBag(array('file' => 'foo')); + new FileBag(['file' => 'foo']); } public function testShouldConvertsUploadedFiles() @@ -36,54 +36,54 @@ public function testShouldConvertsUploadedFiles() $tmpFile = $this->createTempFile(); $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); - $bag = new FileBag(array('file' => array( + $bag = new FileBag(['file' => [ 'name' => basename($tmpFile), 'type' => 'text/plain', 'tmp_name' => $tmpFile, 'error' => 0, 'size' => 100, - ))); + ]]); $this->assertEquals($file, $bag->get('file')); } public function testShouldSetEmptyUploadedFilesToNull() { - $bag = new FileBag(array('file' => array( + $bag = new FileBag(['file' => [ 'name' => '', 'type' => '', 'tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'size' => 0, - ))); + ]]); $this->assertNull($bag->get('file')); } public function testShouldRemoveEmptyUploadedFilesForMultiUpload() { - $bag = new FileBag(array('files' => array( - 'name' => array(''), - 'type' => array(''), - 'tmp_name' => array(''), - 'error' => array(UPLOAD_ERR_NO_FILE), - 'size' => array(0), - ))); - - $this->assertSame(array(), $bag->get('files')); + $bag = new FileBag(['files' => [ + 'name' => [''], + 'type' => [''], + 'tmp_name' => [''], + 'error' => [UPLOAD_ERR_NO_FILE], + 'size' => [0], + ]]); + + $this->assertSame([], $bag->get('files')); } public function testShouldNotRemoveEmptyUploadedFilesForAssociativeArray() { - $bag = new FileBag(array('files' => array( - 'name' => array('file1' => ''), - 'type' => array('file1' => ''), - 'tmp_name' => array('file1' => ''), - 'error' => array('file1' => UPLOAD_ERR_NO_FILE), - 'size' => array('file1' => 0), - ))); - - $this->assertSame(array('file1' => null), $bag->get('files')); + $bag = new FileBag(['files' => [ + 'name' => ['file1' => ''], + 'type' => ['file1' => ''], + 'tmp_name' => ['file1' => ''], + 'error' => ['file1' => UPLOAD_ERR_NO_FILE], + 'size' => ['file1' => 0], + ]]); + + $this->assertSame(['file1' => null], $bag->get('files')); } public function testShouldConvertUploadedFilesWithPhpBug() @@ -91,25 +91,25 @@ public function testShouldConvertUploadedFilesWithPhpBug() $tmpFile = $this->createTempFile(); $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); - $bag = new FileBag(array( - 'child' => array( - 'name' => array( + $bag = new FileBag([ + 'child' => [ + 'name' => [ 'file' => basename($tmpFile), - ), - 'type' => array( + ], + 'type' => [ 'file' => 'text/plain', - ), - 'tmp_name' => array( + ], + 'tmp_name' => [ 'file' => $tmpFile, - ), - 'error' => array( + ], + 'error' => [ 'file' => 0, - ), - 'size' => array( + ], + 'size' => [ 'file' => 100, - ), - ), - )); + ], + ], + ]); $files = $bag->all(); $this->assertEquals($file, $files['child']['file']); @@ -120,25 +120,25 @@ public function testShouldConvertNestedUploadedFilesWithPhpBug() $tmpFile = $this->createTempFile(); $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); - $bag = new FileBag(array( - 'child' => array( - 'name' => array( - 'sub' => array('file' => basename($tmpFile)), - ), - 'type' => array( - 'sub' => array('file' => 'text/plain'), - ), - 'tmp_name' => array( - 'sub' => array('file' => $tmpFile), - ), - 'error' => array( - 'sub' => array('file' => 0), - ), - 'size' => array( - 'sub' => array('file' => 100), - ), - ), - )); + $bag = new FileBag([ + 'child' => [ + 'name' => [ + 'sub' => ['file' => basename($tmpFile)], + ], + 'type' => [ + 'sub' => ['file' => 'text/plain'], + ], + 'tmp_name' => [ + 'sub' => ['file' => $tmpFile], + ], + 'error' => [ + 'sub' => ['file' => 0], + ], + 'size' => [ + 'sub' => ['file' => 100], + ], + ], + ]); $files = $bag->all(); $this->assertEquals($file, $files['child']['sub']['file']); @@ -148,7 +148,7 @@ public function testShouldNotConvertNestedUploadedFiles() { $tmpFile = $this->createTempFile(); $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0); - $bag = new FileBag(array('image' => array('file' => $file))); + $bag = new FileBag(['image' => ['file' => $file]]); $files = $bag->all(); $this->assertEquals($file, $files['image']['file']); diff --git a/Tests/HeaderBagTest.php b/Tests/HeaderBagTest.php index c5a437f99..6c4915f2e 100644 --- a/Tests/HeaderBagTest.php +++ b/Tests/HeaderBagTest.php @@ -18,7 +18,7 @@ class HeaderBagTest extends TestCase { public function testConstructor() { - $bag = new HeaderBag(array('foo' => 'bar')); + $bag = new HeaderBag(['foo' => 'bar']); $this->assertTrue($bag->has('foo')); } @@ -30,20 +30,20 @@ public function testToStringNull() public function testToStringNotNull() { - $bag = new HeaderBag(array('foo' => 'bar')); + $bag = new HeaderBag(['foo' => 'bar']); $this->assertEquals("Foo: bar\r\n", $bag->__toString()); } public function testKeys() { - $bag = new HeaderBag(array('foo' => 'bar')); + $bag = new HeaderBag(['foo' => 'bar']); $keys = $bag->keys(); $this->assertEquals('foo', $keys[0]); } public function testGetDate() { - $bag = new HeaderBag(array('foo' => 'Tue, 4 Sep 2012 20:00:00 +0200')); + $bag = new HeaderBag(['foo' => 'Tue, 4 Sep 2012 20:00:00 +0200']); $headerDate = $bag->getDate('foo'); $this->assertInstanceOf('DateTime', $headerDate); } @@ -53,7 +53,7 @@ public function testGetDate() */ public function testGetDateException() { - $bag = new HeaderBag(array('foo' => 'Tue')); + $bag = new HeaderBag(['foo' => 'Tue']); $headerDate = $bag->getDate('foo'); } @@ -67,50 +67,50 @@ public function testGetCacheControlHeader() public function testAll() { - $bag = new HeaderBag(array('foo' => 'bar')); - $this->assertEquals(array('foo' => array('bar')), $bag->all(), '->all() gets all the input'); + $bag = new HeaderBag(['foo' => 'bar']); + $this->assertEquals(['foo' => ['bar']], $bag->all(), '->all() gets all the input'); - $bag = new HeaderBag(array('FOO' => 'BAR')); - $this->assertEquals(array('foo' => array('BAR')), $bag->all(), '->all() gets all the input key are lower case'); + $bag = new HeaderBag(['FOO' => 'BAR']); + $this->assertEquals(['foo' => ['BAR']], $bag->all(), '->all() gets all the input key are lower case'); } public function testReplace() { - $bag = new HeaderBag(array('foo' => 'bar')); + $bag = new HeaderBag(['foo' => 'bar']); - $bag->replace(array('NOPE' => 'BAR')); - $this->assertEquals(array('nope' => array('BAR')), $bag->all(), '->replace() replaces the input with the argument'); + $bag->replace(['NOPE' => 'BAR']); + $this->assertEquals(['nope' => ['BAR']], $bag->all(), '->replace() replaces the input with the argument'); $this->assertFalse($bag->has('foo'), '->replace() overrides previously set the input'); } public function testGet() { - $bag = new HeaderBag(array('foo' => 'bar', 'fuzz' => 'bizz')); + $bag = new HeaderBag(['foo' => 'bar', 'fuzz' => 'bizz']); $this->assertEquals('bar', $bag->get('foo'), '->get return current value'); $this->assertEquals('bar', $bag->get('FoO'), '->get key in case insensitive'); - $this->assertEquals(array('bar'), $bag->get('foo', 'nope', false), '->get return the value as array'); + $this->assertEquals(['bar'], $bag->get('foo', 'nope', false), '->get return the value as array'); // defaults $this->assertNull($bag->get('none'), '->get unknown values returns null'); $this->assertEquals('default', $bag->get('none', 'default'), '->get unknown values returns default'); - $this->assertEquals(array('default'), $bag->get('none', 'default', false), '->get unknown values returns default as array'); + $this->assertEquals(['default'], $bag->get('none', 'default', false), '->get unknown values returns default as array'); $bag->set('foo', 'bor', false); $this->assertEquals('bar', $bag->get('foo'), '->get return first value'); - $this->assertEquals(array('bar', 'bor'), $bag->get('foo', 'nope', false), '->get return all values as array'); + $this->assertEquals(['bar', 'bor'], $bag->get('foo', 'nope', false), '->get return all values as array'); } public function testSetAssociativeArray() { $bag = new HeaderBag(); - $bag->set('foo', array('bad-assoc-index' => 'value')); + $bag->set('foo', ['bad-assoc-index' => 'value']); $this->assertSame('value', $bag->get('foo')); - $this->assertEquals(array('value'), $bag->get('foo', 'nope', false), 'assoc indices of multi-valued headers are ignored'); + $this->assertEquals(['value'], $bag->get('foo', 'nope', false), 'assoc indices of multi-valued headers are ignored'); } public function testContains() { - $bag = new HeaderBag(array('foo' => 'bar', 'fuzz' => 'bizz')); + $bag = new HeaderBag(['foo' => 'bar', 'fuzz' => 'bizz']); $this->assertTrue($bag->contains('foo', 'bar'), '->contains first value'); $this->assertTrue($bag->contains('fuzz', 'bizz'), '->contains second value'); $this->assertFalse($bag->contains('nope', 'nope'), '->contains unknown value'); @@ -143,7 +143,7 @@ public function testCacheControlDirectiveAccessors() public function testCacheControlDirectiveParsing() { - $bag = new HeaderBag(array('cache-control' => 'public, max-age=10')); + $bag = new HeaderBag(['cache-control' => 'public, max-age=10']); $this->assertTrue($bag->hasCacheControlDirective('public')); $this->assertTrue($bag->getCacheControlDirective('public')); @@ -156,15 +156,15 @@ public function testCacheControlDirectiveParsing() public function testCacheControlDirectiveParsingQuotedZero() { - $bag = new HeaderBag(array('cache-control' => 'max-age="0"')); + $bag = new HeaderBag(['cache-control' => 'max-age="0"']); $this->assertTrue($bag->hasCacheControlDirective('max-age')); $this->assertEquals(0, $bag->getCacheControlDirective('max-age')); } public function testCacheControlDirectiveOverrideWithReplace() { - $bag = new HeaderBag(array('cache-control' => 'private, max-age=100')); - $bag->replace(array('cache-control' => 'public, max-age=10')); + $bag = new HeaderBag(['cache-control' => 'private, max-age=100']); + $bag->replace(['cache-control' => 'public, max-age=10']); $this->assertTrue($bag->hasCacheControlDirective('public')); $this->assertTrue($bag->getCacheControlDirective('public')); @@ -174,7 +174,7 @@ public function testCacheControlDirectiveOverrideWithReplace() public function testCacheControlClone() { - $headers = array('foo' => 'bar'); + $headers = ['foo' => 'bar']; $bag1 = new HeaderBag($headers); $bag2 = new HeaderBag($bag1->all()); @@ -183,13 +183,13 @@ public function testCacheControlClone() public function testGetIterator() { - $headers = array('foo' => 'bar', 'hello' => 'world', 'third' => 'charm'); + $headers = ['foo' => 'bar', 'hello' => 'world', 'third' => 'charm']; $headerBag = new HeaderBag($headers); $i = 0; foreach ($headerBag as $key => $val) { ++$i; - $this->assertEquals(array($headers[$key]), $val); + $this->assertEquals([$headers[$key]], $val); } $this->assertEquals(\count($headers), $i); @@ -197,7 +197,7 @@ public function testGetIterator() public function testCount() { - $headers = array('foo' => 'bar', 'HELLO' => 'WORLD'); + $headers = ['foo' => 'bar', 'HELLO' => 'WORLD']; $headerBag = new HeaderBag($headers); $this->assertCount(\count($headers), $headerBag); diff --git a/Tests/IpUtilsTest.php b/Tests/IpUtilsTest.php index 232a2040f..c7f76b5de 100644 --- a/Tests/IpUtilsTest.php +++ b/Tests/IpUtilsTest.php @@ -26,20 +26,20 @@ public function testIpv4($matches, $remoteAddr, $cidr) public function getIpv4Data() { - return array( - array(true, '192.168.1.1', '192.168.1.1'), - array(true, '192.168.1.1', '192.168.1.1/1'), - array(true, '192.168.1.1', '192.168.1.0/24'), - array(false, '192.168.1.1', '1.2.3.4/1'), - array(false, '192.168.1.1', '192.168.1.1/33'), // invalid subnet - array(true, '192.168.1.1', array('1.2.3.4/1', '192.168.1.0/24')), - array(true, '192.168.1.1', array('192.168.1.0/24', '1.2.3.4/1')), - array(false, '192.168.1.1', array('1.2.3.4/1', '4.3.2.1/1')), - array(true, '1.2.3.4', '0.0.0.0/0'), - array(true, '1.2.3.4', '192.168.1.0/0'), - array(false, '1.2.3.4', '256.256.256/0'), // invalid CIDR notation - array(false, 'an_invalid_ip', '192.168.1.0/24'), - ); + return [ + [true, '192.168.1.1', '192.168.1.1'], + [true, '192.168.1.1', '192.168.1.1/1'], + [true, '192.168.1.1', '192.168.1.0/24'], + [false, '192.168.1.1', '1.2.3.4/1'], + [false, '192.168.1.1', '192.168.1.1/33'], // invalid subnet + [true, '192.168.1.1', ['1.2.3.4/1', '192.168.1.0/24']], + [true, '192.168.1.1', ['192.168.1.0/24', '1.2.3.4/1']], + [false, '192.168.1.1', ['1.2.3.4/1', '4.3.2.1/1']], + [true, '1.2.3.4', '0.0.0.0/0'], + [true, '1.2.3.4', '192.168.1.0/0'], + [false, '1.2.3.4', '256.256.256/0'], // invalid CIDR notation + [false, 'an_invalid_ip', '192.168.1.0/24'], + ]; } /** @@ -56,20 +56,20 @@ public function testIpv6($matches, $remoteAddr, $cidr) public function getIpv6Data() { - return array( - array(true, '2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'), - array(false, '2a00:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'), - array(false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'), - array(true, '0:0:0:0:0:0:0:1', '::1'), - array(false, '0:0:603:0:396e:4789:8e99:0001', '::1'), - array(true, '0:0:603:0:396e:4789:8e99:0001', '::/0'), - array(true, '0:0:603:0:396e:4789:8e99:0001', '2a01:198:603:0::/0'), - array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '2a01:198:603:0::/65')), - array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('2a01:198:603:0::/65', '::1')), - array(false, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '1a01:198:603:0::/65')), - array(false, '}__test|O:21:"JDatabaseDriverMysqli":3:{s:2', '::1'), - array(false, '2a01:198:603:0:396e:4789:8e99:890f', 'unknown'), - ); + return [ + [true, '2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'], + [false, '2a00:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'], + [false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'], + [true, '0:0:0:0:0:0:0:1', '::1'], + [false, '0:0:603:0:396e:4789:8e99:0001', '::1'], + [true, '0:0:603:0:396e:4789:8e99:0001', '::/0'], + [true, '0:0:603:0:396e:4789:8e99:0001', '2a01:198:603:0::/0'], + [true, '2a01:198:603:0:396e:4789:8e99:890f', ['::1', '2a01:198:603:0::/65']], + [true, '2a01:198:603:0:396e:4789:8e99:890f', ['2a01:198:603:0::/65', '::1']], + [false, '2a01:198:603:0:396e:4789:8e99:890f', ['::1', '1a01:198:603:0::/65']], + [false, '}__test|O:21:"JDatabaseDriverMysqli":3:{s:2', '::1'], + [false, '2a01:198:603:0:396e:4789:8e99:890f', 'unknown'], + ]; } /** @@ -95,10 +95,10 @@ public function testInvalidIpAddressesDoNotMatch($requestIp, $proxyIp) public function invalidIpAddressData() { - return array( - 'invalid proxy wildcard' => array('192.168.20.13', '*'), - 'invalid proxy missing netmask' => array('192.168.20.13', '0.0.0.0'), - 'invalid request IP with invalid proxy wildcard' => array('0.0.0.0', '*'), - ); + return [ + 'invalid proxy wildcard' => ['192.168.20.13', '*'], + 'invalid proxy missing netmask' => ['192.168.20.13', '0.0.0.0'], + 'invalid request IP with invalid proxy wildcard' => ['0.0.0.0', '*'], + ]; } } diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index 6687fde5b..5425896df 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -33,13 +33,13 @@ public function testConstructorEmptyCreatesJsonObject() public function testConstructorWithArrayCreatesJsonArray() { - $response = new JsonResponse(array(0, 1, 2, 3)); + $response = new JsonResponse([0, 1, 2, 3]); $this->assertSame('[0,1,2,3]', $response->getContent()); } public function testConstructorWithAssocArrayCreatesJsonObject() { - $response = new JsonResponse(array('foo' => 'bar')); + $response = new JsonResponse(['foo' => 'bar']); $this->assertSame('{"foo":"bar"}', $response->getContent()); } @@ -60,7 +60,7 @@ public function testConstructorWithSimpleTypes() public function testConstructorWithCustomStatus() { - $response = new JsonResponse(array(), 202); + $response = new JsonResponse([], 202); $this->assertSame(202, $response->getStatusCode()); } @@ -72,35 +72,35 @@ public function testConstructorAddsContentTypeHeader() public function testConstructorWithCustomHeaders() { - $response = new JsonResponse(array(), 200, array('ETag' => 'foo')); + $response = new JsonResponse([], 200, ['ETag' => 'foo']); $this->assertSame('application/json', $response->headers->get('Content-Type')); $this->assertSame('foo', $response->headers->get('ETag')); } public function testConstructorWithCustomContentType() { - $headers = array('Content-Type' => 'application/vnd.acme.blog-v1+json'); + $headers = ['Content-Type' => 'application/vnd.acme.blog-v1+json']; - $response = new JsonResponse(array(), 200, $headers); + $response = new JsonResponse([], 200, $headers); $this->assertSame('application/vnd.acme.blog-v1+json', $response->headers->get('Content-Type')); } public function testSetJson() { - $response = new JsonResponse('1', 200, array(), true); + $response = new JsonResponse('1', 200, [], true); $this->assertEquals('1', $response->getContent()); - $response = new JsonResponse('[1]', 200, array(), true); + $response = new JsonResponse('[1]', 200, [], true); $this->assertEquals('[1]', $response->getContent()); - $response = new JsonResponse(null, 200, array()); + $response = new JsonResponse(null, 200, []); $response->setJson('true'); $this->assertEquals('true', $response->getContent()); } public function testCreate() { - $response = JsonResponse::create(array('foo' => 'bar'), 204); + $response = JsonResponse::create(['foo' => 'bar'], 204); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); $this->assertEquals('{"foo":"bar"}', $response->getContent()); @@ -116,14 +116,14 @@ public function testStaticCreateEmptyJsonObject() public function testStaticCreateJsonArray() { - $response = JsonResponse::create(array(0, 1, 2, 3)); + $response = JsonResponse::create([0, 1, 2, 3]); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); $this->assertSame('[0,1,2,3]', $response->getContent()); } public function testStaticCreateJsonObject() { - $response = JsonResponse::create(array('foo' => 'bar')); + $response = JsonResponse::create(['foo' => 'bar']); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); $this->assertSame('{"foo":"bar"}', $response->getContent()); } @@ -149,7 +149,7 @@ public function testStaticCreateWithSimpleTypes() public function testStaticCreateWithCustomStatus() { - $response = JsonResponse::create(array(), 202); + $response = JsonResponse::create([], 202); $this->assertSame(202, $response->getStatusCode()); } @@ -161,22 +161,22 @@ public function testStaticCreateAddsContentTypeHeader() public function testStaticCreateWithCustomHeaders() { - $response = JsonResponse::create(array(), 200, array('ETag' => 'foo')); + $response = JsonResponse::create([], 200, ['ETag' => 'foo']); $this->assertSame('application/json', $response->headers->get('Content-Type')); $this->assertSame('foo', $response->headers->get('ETag')); } public function testStaticCreateWithCustomContentType() { - $headers = array('Content-Type' => 'application/vnd.acme.blog-v1+json'); + $headers = ['Content-Type' => 'application/vnd.acme.blog-v1+json']; - $response = JsonResponse::create(array(), 200, $headers); + $response = JsonResponse::create([], 200, $headers); $this->assertSame('application/vnd.acme.blog-v1+json', $response->headers->get('Content-Type')); } public function testSetCallback() { - $response = JsonResponse::create(array('foo' => 'bar'))->setCallback('callback'); + $response = JsonResponse::create(['foo' => 'bar'])->setCallback('callback'); $this->assertEquals('/**/callback({"foo":"bar"});', $response->getContent()); $this->assertEquals('text/javascript', $response->headers->get('Content-Type')); @@ -199,7 +199,7 @@ public function testGetEncodingOptions() public function testSetEncodingOptions() { $response = new JsonResponse(); - $response->setData(array(array(1, 2, 3))); + $response->setData([[1, 2, 3]]); $this->assertEquals('[[1,2,3]]', $response->getContent()); @@ -248,7 +248,7 @@ public function testSetContentJsonSerializeError() public function testSetComplexCallback() { - $response = JsonResponse::create(array('foo' => 'bar')); + $response = JsonResponse::create(['foo' => 'bar']); $response->setCallback('ಠ_ಠ["foo"].bar[0]'); $this->assertEquals('/**/ಠ_ಠ["foo"].bar[0]({"foo":"bar"});', $response->getContent()); diff --git a/Tests/ParameterBagTest.php b/Tests/ParameterBagTest.php index dccfd4f30..d2a5c991c 100644 --- a/Tests/ParameterBagTest.php +++ b/Tests/ParameterBagTest.php @@ -23,44 +23,44 @@ public function testConstructor() public function testAll() { - $bag = new ParameterBag(array('foo' => 'bar')); - $this->assertEquals(array('foo' => 'bar'), $bag->all(), '->all() gets all the input'); + $bag = new ParameterBag(['foo' => 'bar']); + $this->assertEquals(['foo' => 'bar'], $bag->all(), '->all() gets all the input'); } public function testKeys() { - $bag = new ParameterBag(array('foo' => 'bar')); - $this->assertEquals(array('foo'), $bag->keys()); + $bag = new ParameterBag(['foo' => 'bar']); + $this->assertEquals(['foo'], $bag->keys()); } public function testAdd() { - $bag = new ParameterBag(array('foo' => 'bar')); - $bag->add(array('bar' => 'bas')); - $this->assertEquals(array('foo' => 'bar', 'bar' => 'bas'), $bag->all()); + $bag = new ParameterBag(['foo' => 'bar']); + $bag->add(['bar' => 'bas']); + $this->assertEquals(['foo' => 'bar', 'bar' => 'bas'], $bag->all()); } public function testRemove() { - $bag = new ParameterBag(array('foo' => 'bar')); - $bag->add(array('bar' => 'bas')); - $this->assertEquals(array('foo' => 'bar', 'bar' => 'bas'), $bag->all()); + $bag = new ParameterBag(['foo' => 'bar']); + $bag->add(['bar' => 'bas']); + $this->assertEquals(['foo' => 'bar', 'bar' => 'bas'], $bag->all()); $bag->remove('bar'); - $this->assertEquals(array('foo' => 'bar'), $bag->all()); + $this->assertEquals(['foo' => 'bar'], $bag->all()); } public function testReplace() { - $bag = new ParameterBag(array('foo' => 'bar')); + $bag = new ParameterBag(['foo' => 'bar']); - $bag->replace(array('FOO' => 'BAR')); - $this->assertEquals(array('FOO' => 'BAR'), $bag->all(), '->replace() replaces the input with the argument'); + $bag->replace(['FOO' => 'BAR']); + $this->assertEquals(['FOO' => 'BAR'], $bag->all(), '->replace() replaces the input with the argument'); $this->assertFalse($bag->has('foo'), '->replace() overrides previously set the input'); } public function testGet() { - $bag = new ParameterBag(array('foo' => 'bar', 'null' => null)); + $bag = new ParameterBag(['foo' => 'bar', 'null' => null]); $this->assertEquals('bar', $bag->get('foo'), '->get() gets the value of a parameter'); $this->assertEquals('default', $bag->get('unknown', 'default'), '->get() returns second argument as default if a parameter is not defined'); @@ -69,14 +69,14 @@ public function testGet() public function testGetDoesNotUseDeepByDefault() { - $bag = new ParameterBag(array('foo' => array('bar' => 'moo'))); + $bag = new ParameterBag(['foo' => ['bar' => 'moo']]); $this->assertNull($bag->get('foo[bar]')); } public function testSet() { - $bag = new ParameterBag(array()); + $bag = new ParameterBag([]); $bag->set('foo', 'bar'); $this->assertEquals('bar', $bag->get('foo'), '->set() sets the value of parameter'); @@ -87,7 +87,7 @@ public function testSet() public function testHas() { - $bag = new ParameterBag(array('foo' => 'bar')); + $bag = new ParameterBag(['foo' => 'bar']); $this->assertTrue($bag->has('foo'), '->has() returns true if a parameter is defined'); $this->assertFalse($bag->has('unknown'), '->has() return false if a parameter is not defined'); @@ -95,7 +95,7 @@ public function testHas() public function testGetAlpha() { - $bag = new ParameterBag(array('word' => 'foo_BAR_012')); + $bag = new ParameterBag(['word' => 'foo_BAR_012']); $this->assertEquals('fooBAR', $bag->getAlpha('word'), '->getAlpha() gets only alphabetic characters'); $this->assertEquals('', $bag->getAlpha('unknown'), '->getAlpha() returns empty string if a parameter is not defined'); @@ -103,7 +103,7 @@ public function testGetAlpha() public function testGetAlnum() { - $bag = new ParameterBag(array('word' => 'foo_BAR_012')); + $bag = new ParameterBag(['word' => 'foo_BAR_012']); $this->assertEquals('fooBAR012', $bag->getAlnum('word'), '->getAlnum() gets only alphanumeric characters'); $this->assertEquals('', $bag->getAlnum('unknown'), '->getAlnum() returns empty string if a parameter is not defined'); @@ -111,7 +111,7 @@ public function testGetAlnum() public function testGetDigits() { - $bag = new ParameterBag(array('word' => 'foo_BAR_012')); + $bag = new ParameterBag(['word' => 'foo_BAR_012']); $this->assertEquals('012', $bag->getDigits('word'), '->getDigits() gets only digits as string'); $this->assertEquals('', $bag->getDigits('unknown'), '->getDigits() returns empty string if a parameter is not defined'); @@ -119,7 +119,7 @@ public function testGetDigits() public function testGetInt() { - $bag = new ParameterBag(array('digits' => '0123')); + $bag = new ParameterBag(['digits' => '0123']); $this->assertEquals(123, $bag->getInt('digits'), '->getInt() gets a value of parameter as integer'); $this->assertEquals(0, $bag->getInt('unknown'), '->getInt() returns zero if a parameter is not defined'); @@ -127,14 +127,14 @@ public function testGetInt() public function testFilter() { - $bag = new ParameterBag(array( + $bag = new ParameterBag([ 'digits' => '0123ab', 'email' => 'example@example.com', 'url' => 'http://example.com/foo', 'dec' => '256', 'hex' => '0x100', - 'array' => array('bang'), - )); + 'array' => ['bang'], + ]); $this->assertEmpty($bag->filter('nokey'), '->filter() should return empty by default if no key is found'); @@ -142,27 +142,27 @@ public function testFilter() $this->assertEquals('example@example.com', $bag->filter('email', '', FILTER_VALIDATE_EMAIL), '->filter() gets a value of parameter as email'); - $this->assertEquals('http://example.com/foo', $bag->filter('url', '', FILTER_VALIDATE_URL, array('flags' => FILTER_FLAG_PATH_REQUIRED)), '->filter() gets a value of parameter as URL with a path'); + $this->assertEquals('http://example.com/foo', $bag->filter('url', '', FILTER_VALIDATE_URL, ['flags' => FILTER_FLAG_PATH_REQUIRED]), '->filter() gets a value of parameter as URL with a path'); // This test is repeated for code-coverage $this->assertEquals('http://example.com/foo', $bag->filter('url', '', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED), '->filter() gets a value of parameter as URL with a path'); - $this->assertFalse($bag->filter('dec', '', FILTER_VALIDATE_INT, array( + $this->assertFalse($bag->filter('dec', '', FILTER_VALIDATE_INT, [ 'flags' => FILTER_FLAG_ALLOW_HEX, - 'options' => array('min_range' => 1, 'max_range' => 0xff), - )), '->filter() gets a value of parameter as integer between boundaries'); + 'options' => ['min_range' => 1, 'max_range' => 0xff], + ]), '->filter() gets a value of parameter as integer between boundaries'); - $this->assertFalse($bag->filter('hex', '', FILTER_VALIDATE_INT, array( + $this->assertFalse($bag->filter('hex', '', FILTER_VALIDATE_INT, [ 'flags' => FILTER_FLAG_ALLOW_HEX, - 'options' => array('min_range' => 1, 'max_range' => 0xff), - )), '->filter() gets a value of parameter as integer between boundaries'); + 'options' => ['min_range' => 1, 'max_range' => 0xff], + ]), '->filter() gets a value of parameter as integer between boundaries'); - $this->assertEquals(array('bang'), $bag->filter('array', ''), '->filter() gets a value of parameter as an array'); + $this->assertEquals(['bang'], $bag->filter('array', ''), '->filter() gets a value of parameter as an array'); } public function testGetIterator() { - $parameters = array('foo' => 'bar', 'hello' => 'world'); + $parameters = ['foo' => 'bar', 'hello' => 'world']; $bag = new ParameterBag($parameters); $i = 0; @@ -176,7 +176,7 @@ public function testGetIterator() public function testCount() { - $parameters = array('foo' => 'bar', 'hello' => 'world'); + $parameters = ['foo' => 'bar', 'hello' => 'world']; $bag = new ParameterBag($parameters); $this->assertCount(\count($parameters), $bag); @@ -184,7 +184,7 @@ public function testCount() public function testGetBoolean() { - $parameters = array('string_true' => 'true', 'string_false' => 'false'); + $parameters = ['string_true' => 'true', 'string_false' => 'false']; $bag = new ParameterBag($parameters); $this->assertTrue($bag->getBoolean('string_true'), '->getBoolean() gets the string true as boolean true'); diff --git a/Tests/RedirectResponseTest.php b/Tests/RedirectResponseTest.php index d389e83db..64c3e73ee 100644 --- a/Tests/RedirectResponseTest.php +++ b/Tests/RedirectResponseTest.php @@ -22,7 +22,7 @@ public function testGenerateMetaRedirect() $this->assertEquals(1, preg_match( '##', - preg_replace(array('/\s+/', '/\'/'), array(' ', '"'), $response->getContent()) + preg_replace(['/\s+/', '/\'/'], [' ', '"'], $response->getContent()) )); } @@ -87,7 +87,7 @@ public function testCacheHeaders() $response = new RedirectResponse('foo.bar', 301); $this->assertFalse($response->headers->hasCacheControlDirective('no-cache')); - $response = new RedirectResponse('foo.bar', 301, array('cache-control' => 'max-age=86400')); + $response = new RedirectResponse('foo.bar', 301, ['cache-control' => 'max-age=86400']); $this->assertFalse($response->headers->hasCacheControlDirective('no-cache')); $this->assertTrue($response->headers->hasCacheControlDirective('max-age')); diff --git a/Tests/RequestMatcherTest.php b/Tests/RequestMatcherTest.php index 10d764a77..7fb6925bb 100644 --- a/Tests/RequestMatcherTest.php +++ b/Tests/RequestMatcherTest.php @@ -34,20 +34,20 @@ public function testMethod($requestMethod, $matcherMethod, $isMatch) public function getMethodData() { - return array( - array('get', 'get', true), - array('get', array('get', 'post'), true), - array('get', 'post', false), - array('get', 'GET', true), - array('get', array('GET', 'POST'), true), - array('get', 'POST', false), - ); + return [ + ['get', 'get', true], + ['get', ['get', 'post'], true], + ['get', 'post', false], + ['get', 'GET', true], + ['get', ['GET', 'POST'], true], + ['get', 'POST', false], + ]; } public function testScheme() { $httpRequest = $request = $request = Request::create(''); - $httpsRequest = $request = $request = Request::create('', 'get', array(), array(), array(), array('HTTPS' => 'on')); + $httpsRequest = $request = $request = Request::create('', 'get', [], [], [], ['HTTPS' => 'on']); $matcher = new RequestMatcher(); $matcher->matchScheme('https'); @@ -69,7 +69,7 @@ public function testScheme() public function testHost($pattern, $isMatch) { $matcher = new RequestMatcher(); - $request = Request::create('', 'get', array(), array(), array(), array('HTTP_HOST' => 'foo.example.com')); + $request = Request::create('', 'get', [], [], [], ['HTTP_HOST' => 'foo.example.com']); $matcher->matchHost($pattern); $this->assertSame($isMatch, $matcher->matches($request)); @@ -80,16 +80,16 @@ public function testHost($pattern, $isMatch) public function getHostData() { - return array( - array('.*\.example\.com', true), - array('\.example\.com$', true), - array('^.*\.example\.com$', true), - array('.*\.sensio\.com', false), - array('.*\.example\.COM', true), - array('\.example\.COM$', true), - array('^.*\.example\.COM$', true), - array('.*\.sensio\.COM', false), - ); + return [ + ['.*\.example\.com', true], + ['\.example\.com$', true], + ['^.*\.example\.com$', true], + ['.*\.sensio\.com', false], + ['.*\.example\.COM', true], + ['\.example\.COM$', true], + ['^.*\.example\.COM$', true], + ['.*\.sensio\.COM', false], + ]; } public function testPath() diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index f2c8f94f7..505f271ea 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -21,24 +21,24 @@ class RequestTest extends TestCase { protected function tearDown() { - Request::setTrustedProxies(array(), -1); - Request::setTrustedHosts(array()); + Request::setTrustedProxies([], -1); + Request::setTrustedHosts([]); } public function testInitialize() { $request = new Request(); - $request->initialize(array('foo' => 'bar')); + $request->initialize(['foo' => 'bar']); $this->assertEquals('bar', $request->query->get('foo'), '->initialize() takes an array of query parameters as its first argument'); - $request->initialize(array(), array('foo' => 'bar')); + $request->initialize([], ['foo' => 'bar']); $this->assertEquals('bar', $request->request->get('foo'), '->initialize() takes an array of request parameters as its second argument'); - $request->initialize(array(), array(), array('foo' => 'bar')); + $request->initialize([], [], ['foo' => 'bar']); $this->assertEquals('bar', $request->attributes->get('foo'), '->initialize() takes an array of attributes as its third argument'); - $request->initialize(array(), array(), array(), array(), array(), array('HTTP_FOO' => 'bar')); + $request->initialize([], [], [], [], [], ['HTTP_FOO' => 'bar']); $this->assertEquals('bar', $request->headers->get('FOO'), '->initialize() takes an array of HTTP headers as its sixth argument'); } @@ -101,7 +101,7 @@ public function testCreate() $this->assertEquals('test.com', $request->getHttpHost()); $this->assertFalse($request->isSecure()); - $request = Request::create('http://test.com/foo', 'GET', array('bar' => 'baz')); + $request = Request::create('http://test.com/foo', 'GET', ['bar' => 'baz']); $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('bar=baz', $request->getQueryString()); @@ -109,7 +109,7 @@ public function testCreate() $this->assertEquals('test.com', $request->getHttpHost()); $this->assertFalse($request->isSecure()); - $request = Request::create('http://test.com/foo?bar=foo', 'GET', array('bar' => 'baz')); + $request = Request::create('http://test.com/foo?bar=foo', 'GET', ['bar' => 'baz']); $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); $this->assertEquals('bar=baz', $request->getQueryString()); @@ -166,7 +166,7 @@ public function testCreate() $this->assertTrue($request->isSecure()); $json = '{"jsonrpc":"2.0","method":"echo","id":7,"params":["Hello World"]}'; - $request = Request::create('http://example.com/jsonrpc', 'POST', array(), array(), array(), array(), $json); + $request = Request::create('http://example.com/jsonrpc', 'POST', [], [], [], [], $json); $this->assertEquals($json, $request->getContent()); $this->assertFalse($request->isSecure()); @@ -216,16 +216,16 @@ public function testCreate() $request = Request::create('http://test.com/?foo'); $this->assertEquals('/?foo', $request->getRequestUri()); - $this->assertEquals(array('foo' => ''), $request->query->all()); + $this->assertEquals(['foo' => ''], $request->query->all()); // assume rewrite rule: (.*) --> app/app.php; app/ is a symlink to a symfony web/ directory - $request = Request::create('http://test.com/apparthotel-1234', 'GET', array(), array(), array(), - array( + $request = Request::create('http://test.com/apparthotel-1234', 'GET', [], [], [], + [ 'DOCUMENT_ROOT' => '/var/www/www.test.com', 'SCRIPT_FILENAME' => '/var/www/www.test.com/app/app.php', 'SCRIPT_NAME' => '/app/app.php', 'PHP_SELF' => '/app/app.php/apparthotel-1234', - )); + ]); $this->assertEquals('http://test.com/apparthotel-1234', $request->getUri()); $this->assertEquals('/apparthotel-1234', $request->getPathInfo()); $this->assertEquals('', $request->getQueryString()); @@ -258,7 +258,7 @@ public function testCreateWithRequestUri() $this->assertEquals(8080, $request->getPort()); $this->assertFalse($request->isSecure()); - $request = Request::create('http://test.com/foo?bar=foo', 'GET', array('bar' => 'baz')); + $request = Request::create('http://test.com/foo?bar=foo', 'GET', ['bar' => 'baz']); $request->server->set('REQUEST_URI', 'http://test.com/foo?bar=foo'); $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri()); $this->assertEquals('/foo', $request->getPathInfo()); @@ -289,13 +289,13 @@ public function testCreateWithRequestUri() public function testGetRequestUri($serverRequestUri, $expected, $message) { $request = new Request(); - $request->server->add(array( + $request->server->add([ 'REQUEST_URI' => $serverRequestUri, // For having http://test.com 'SERVER_NAME' => 'test.com', 'SERVER_PORT' => 80, - )); + ]); $this->assertSame($expected, $request->getRequestUri(), $message); $this->assertSame($expected, $request->server->get('REQUEST_URI'), 'Normalize the request URI.'); @@ -304,21 +304,21 @@ public function testGetRequestUri($serverRequestUri, $expected, $message) public function getRequestUriData() { $message = 'Do not modify the path.'; - yield array('/foo', '/foo', $message); - yield array('//bar/foo', '//bar/foo', $message); - yield array('///bar/foo', '///bar/foo', $message); + yield ['/foo', '/foo', $message]; + yield ['//bar/foo', '//bar/foo', $message]; + yield ['///bar/foo', '///bar/foo', $message]; $message = 'Handle when the scheme, host are on REQUEST_URI.'; - yield array('http://test.com/foo?bar=baz', '/foo?bar=baz', $message); + yield ['http://test.com/foo?bar=baz', '/foo?bar=baz', $message]; $message = 'Handle when the scheme, host and port are on REQUEST_URI.'; - yield array('http://test.com:80/foo', '/foo', $message); - yield array('https://test.com:8080/foo', '/foo', $message); - yield array('https://test.com:443/foo', '/foo', $message); + yield ['http://test.com:80/foo', '/foo', $message]; + yield ['https://test.com:8080/foo', '/foo', $message]; + yield ['https://test.com:443/foo', '/foo', $message]; $message = 'Fragment should not be included in the URI'; - yield array('http://test.com/foo#bar', '/foo', $message); - yield array('/foo#bar', '/foo', $message); + yield ['http://test.com/foo#bar', '/foo', $message]; + yield ['/foo#bar', '/foo', $message]; } public function testGetRequestUriWithoutRequiredHeader() @@ -335,7 +335,7 @@ public function testGetRequestUriWithoutRequiredHeader() public function testCreateCheckPrecedence() { // server is used by default - $request = Request::create('/', 'DELETE', array(), array(), array(), array( + $request = Request::create('/', 'DELETE', [], [], [], [ 'HTTP_HOST' => 'example.com', 'HTTPS' => 'on', 'SERVER_PORT' => 443, @@ -343,7 +343,7 @@ public function testCreateCheckPrecedence() 'PHP_AUTH_PW' => 'pa$$', 'QUERY_STRING' => 'foo=bar', 'CONTENT_TYPE' => 'application/json', - )); + ]); $this->assertEquals('example.com', $request->getHost()); $this->assertEquals(443, $request->getPort()); $this->assertTrue($request->isSecure()); @@ -353,11 +353,11 @@ public function testCreateCheckPrecedence() $this->assertEquals('application/json', $request->headers->get('CONTENT_TYPE')); // URI has precedence over server - $request = Request::create('http://thomas:pokemon@example.net:8080/?foo=bar', 'GET', array(), array(), array(), array( + $request = Request::create('http://thomas:pokemon@example.net:8080/?foo=bar', 'GET', [], [], [], [ 'HTTP_HOST' => 'example.com', 'HTTPS' => 'on', 'SERVER_PORT' => 443, - )); + ]); $this->assertEquals('example.net', $request->getHost()); $this->assertEquals(8080, $request->getPort()); $this->assertFalse($request->isSecure()); @@ -368,7 +368,7 @@ public function testCreateCheckPrecedence() public function testDuplicate() { - $request = new Request(array('foo' => 'bar'), array('foo' => 'bar'), array('foo' => 'bar'), array(), array(), array('HTTP_FOO' => 'bar')); + $request = new Request(['foo' => 'bar'], ['foo' => 'bar'], ['foo' => 'bar'], [], [], ['HTTP_FOO' => 'bar']); $dup = $request->duplicate(); $this->assertEquals($request->query->all(), $dup->query->all(), '->duplicate() duplicates a request an copy the current query parameters'); @@ -376,17 +376,17 @@ public function testDuplicate() $this->assertEquals($request->attributes->all(), $dup->attributes->all(), '->duplicate() duplicates a request an copy the current attributes'); $this->assertEquals($request->headers->all(), $dup->headers->all(), '->duplicate() duplicates a request an copy the current HTTP headers'); - $dup = $request->duplicate(array('foo' => 'foobar'), array('foo' => 'foobar'), array('foo' => 'foobar'), array(), array(), array('HTTP_FOO' => 'foobar')); + $dup = $request->duplicate(['foo' => 'foobar'], ['foo' => 'foobar'], ['foo' => 'foobar'], [], [], ['HTTP_FOO' => 'foobar']); - $this->assertEquals(array('foo' => 'foobar'), $dup->query->all(), '->duplicate() overrides the query parameters if provided'); - $this->assertEquals(array('foo' => 'foobar'), $dup->request->all(), '->duplicate() overrides the request parameters if provided'); - $this->assertEquals(array('foo' => 'foobar'), $dup->attributes->all(), '->duplicate() overrides the attributes if provided'); - $this->assertEquals(array('foo' => array('foobar')), $dup->headers->all(), '->duplicate() overrides the HTTP header if provided'); + $this->assertEquals(['foo' => 'foobar'], $dup->query->all(), '->duplicate() overrides the query parameters if provided'); + $this->assertEquals(['foo' => 'foobar'], $dup->request->all(), '->duplicate() overrides the request parameters if provided'); + $this->assertEquals(['foo' => 'foobar'], $dup->attributes->all(), '->duplicate() overrides the attributes if provided'); + $this->assertEquals(['foo' => ['foobar']], $dup->headers->all(), '->duplicate() overrides the HTTP header if provided'); } public function testDuplicateWithFormat() { - $request = new Request(array(), array(), array('_format' => 'json')); + $request = new Request([], [], ['_format' => 'json']); $dup = $request->duplicate(); $this->assertEquals('json', $dup->getRequestFormat()); @@ -421,7 +421,7 @@ public function testGetFormatFromMimeType($format, $mimeTypes) public function getFormatToMimeTypeMapProviderWithAdditionalNullFormat() { return array_merge( - array(array(null, array(null, 'unexistent-mime-type'))), + [[null, [null, 'unexistent-mime-type']]], $this->getFormatToMimeTypeMapProvider() ); } @@ -456,7 +456,7 @@ public function testGetMimeTypesFromInexistentFormat() { $request = new Request(); $this->assertNull($request->getMimeType('foo')); - $this->assertEquals(array(), Request::getMimeTypes('foo')); + $this->assertEquals([], Request::getMimeTypes('foo')); } public function testGetFormatWithCustomMimeType() @@ -468,21 +468,21 @@ public function testGetFormatWithCustomMimeType() public function getFormatToMimeTypeMapProvider() { - return array( - array('txt', array('text/plain')), - array('js', array('application/javascript', 'application/x-javascript', 'text/javascript')), - array('css', array('text/css')), - array('json', array('application/json', 'application/x-json')), - array('jsonld', array('application/ld+json')), - array('xml', array('text/xml', 'application/xml', 'application/x-xml')), - array('rdf', array('application/rdf+xml')), - array('atom', array('application/atom+xml')), - ); + return [ + ['txt', ['text/plain']], + ['js', ['application/javascript', 'application/x-javascript', 'text/javascript']], + ['css', ['text/css']], + ['json', ['application/json', 'application/x-json']], + ['jsonld', ['application/ld+json']], + ['xml', ['text/xml', 'application/xml', 'application/x-xml']], + ['rdf', ['application/rdf+xml']], + ['atom', ['application/atom+xml']], + ]; } public function testGetUri() { - $server = array(); + $server = []; // Standard Request on non default PORT // http://host:8080/index.php/path/info?query=string @@ -501,7 +501,7 @@ public function testGetUri() $request = new Request(); - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host:8080/index.php/path/info?query=string', $request->getUri(), '->getUri() with non default port'); @@ -510,7 +510,7 @@ public function testGetUri() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port'); @@ -519,7 +519,7 @@ public function testGetUri() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port without HOST_HEADER'); @@ -527,7 +527,7 @@ public function testGetUri() // RewriteCond %{REQUEST_FILENAME} !-f // RewriteRule ^(.*)$ index.php [QSA,L] // http://host:8080/path/info?query=string - $server = array(); + $server = []; $server['HTTP_HOST'] = 'host:8080'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '8080'; @@ -541,7 +541,7 @@ public function testGetUri() $server['PHP_SELF'] = '/index.php'; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host:8080/path/info?query=string', $request->getUri(), '->getUri() with rewrite'); // Use std port number @@ -550,7 +550,7 @@ public function testGetUri() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host/path/info?query=string', $request->getUri(), '->getUri() with rewrite and default port'); @@ -559,13 +559,13 @@ public function testGetUri() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername/path/info?query=string', $request->getUri(), '->getUri() with rewrite, default port without HOST_HEADER'); // With encoded characters - $server = array( + $server = [ 'HTTP_HOST' => 'host:8080', 'SERVER_NAME' => 'servername', 'SERVER_PORT' => '8080', @@ -575,9 +575,9 @@ public function testGetUri() 'PATH_TRANSLATED' => 'redirect:/index.php/foo bar/in+fo', 'PHP_SELF' => '/ba se/index_dev.php/path/info', 'SCRIPT_FILENAME' => '/some/where/ba se/index_dev.php', - ); + ]; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals( 'http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', @@ -587,11 +587,11 @@ public function testGetUri() // with user info $server['PHP_AUTH_USER'] = 'fabien'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri()); $server['PHP_AUTH_PW'] = 'symfony'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri()); } @@ -609,7 +609,7 @@ public function testGetUriForPath() $request = Request::create('https://test.com:90/foo?bar=baz'); $this->assertEquals('https://test.com:90/some/path', $request->getUriForPath('/some/path')); - $server = array(); + $server = []; // Standard Request on non default PORT // http://host:8080/index.php/path/info?query=string @@ -628,7 +628,7 @@ public function testGetUriForPath() $request = new Request(); - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host:8080/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with non default port'); @@ -637,7 +637,7 @@ public function testGetUriForPath() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port'); @@ -646,7 +646,7 @@ public function testGetUriForPath() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port without HOST_HEADER'); @@ -654,7 +654,7 @@ public function testGetUriForPath() // RewriteCond %{REQUEST_FILENAME} !-f // RewriteRule ^(.*)$ index.php [QSA,L] // http://host:8080/path/info?query=string - $server = array(); + $server = []; $server['HTTP_HOST'] = 'host:8080'; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '8080'; @@ -668,7 +668,7 @@ public function testGetUriForPath() $server['PHP_SELF'] = '/index.php'; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host:8080/some/path', $request->getUriForPath('/some/path'), '->getUri() with rewrite'); // Use std port number @@ -677,7 +677,7 @@ public function testGetUriForPath() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://host/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite and default port'); @@ -686,7 +686,7 @@ public function testGetUriForPath() $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '80'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite, default port without HOST_HEADER'); $this->assertEquals('servername', $request->getHttpHost()); @@ -694,11 +694,11 @@ public function testGetUriForPath() // with user info $server['PHP_AUTH_USER'] = 'fabien'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path')); $server['PHP_AUTH_PW'] = 'symfony'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path')); } @@ -712,30 +712,30 @@ public function testGetRelativeUriForPath($expected, $pathinfo, $path) public function getRelativeUriForPathData() { - return array( - array('me.png', '/foo', '/me.png'), - array('../me.png', '/foo/bar', '/me.png'), - array('me.png', '/foo/bar', '/foo/me.png'), - array('../baz/me.png', '/foo/bar/b', '/foo/baz/me.png'), - array('../../fooz/baz/me.png', '/foo/bar/b', '/fooz/baz/me.png'), - array('baz/me.png', '/foo/bar/b', 'baz/me.png'), - ); + return [ + ['me.png', '/foo', '/me.png'], + ['../me.png', '/foo/bar', '/me.png'], + ['me.png', '/foo/bar', '/foo/me.png'], + ['../baz/me.png', '/foo/bar/b', '/foo/baz/me.png'], + ['../../fooz/baz/me.png', '/foo/bar/b', '/fooz/baz/me.png'], + ['baz/me.png', '/foo/bar/b', 'baz/me.png'], + ]; } public function testGetUserInfo() { $request = new Request(); - $server = array('PHP_AUTH_USER' => 'fabien'); - $request->initialize(array(), array(), array(), array(), array(), $server); + $server = ['PHP_AUTH_USER' => 'fabien']; + $request->initialize([], [], [], [], [], $server); $this->assertEquals('fabien', $request->getUserInfo()); $server['PHP_AUTH_USER'] = '0'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('0', $request->getUserInfo()); $server['PHP_AUTH_PW'] = '0'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('0:0', $request->getUserInfo()); } @@ -743,22 +743,22 @@ public function testGetSchemeAndHttpHost() { $request = new Request(); - $server = array(); + $server = []; $server['SERVER_NAME'] = 'servername'; $server['SERVER_PORT'] = '90'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost()); $server['PHP_AUTH_USER'] = 'fabien'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost()); $server['PHP_AUTH_USER'] = '0'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost()); $server['PHP_AUTH_PW'] = '0'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost()); } @@ -775,29 +775,29 @@ public function testGetQueryString($query, $expectedQuery, $msg) public function getQueryStringNormalizationData() { - return array( - array('foo', 'foo', 'works with valueless parameters'), - array('foo=', 'foo=', 'includes a dangling equal sign'), - array('bar=&foo=bar', 'bar=&foo=bar', '->works with empty parameters'), - array('foo=bar&bar=', 'bar=&foo=bar', 'sorts keys alphabetically'), + return [ + ['foo', 'foo', 'works with valueless parameters'], + ['foo=', 'foo=', 'includes a dangling equal sign'], + ['bar=&foo=bar', 'bar=&foo=bar', '->works with empty parameters'], + ['foo=bar&bar=', 'bar=&foo=bar', 'sorts keys alphabetically'], // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded). // PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. - array('him=John%20Doe&her=Jane+Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes spaces in both encodings "%20" and "+"'), + ['him=John%20Doe&her=Jane+Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes spaces in both encodings "%20" and "+"'], - array('foo[]=1&foo[]=2', 'foo%5B%5D=1&foo%5B%5D=2', 'allows array notation'), - array('foo=1&foo=2', 'foo=1&foo=2', 'allows repeated parameters'), - array('pa%3Dram=foo%26bar%3Dbaz&test=test', 'pa%3Dram=foo%26bar%3Dbaz&test=test', 'works with encoded delimiters'), - array('0', '0', 'allows "0"'), - array('Jane Doe&John%20Doe', 'Jane%20Doe&John%20Doe', 'normalizes encoding in keys'), - array('her=Jane Doe&him=John%20Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes encoding in values'), - array('foo=bar&&&test&&', 'foo=bar&test', 'removes unneeded delimiters'), - array('formula=e=m*c^2', 'formula=e%3Dm%2Ac%5E2', 'correctly treats only the first "=" as delimiter and the next as value'), + ['foo[]=1&foo[]=2', 'foo%5B%5D=1&foo%5B%5D=2', 'allows array notation'], + ['foo=1&foo=2', 'foo=1&foo=2', 'allows repeated parameters'], + ['pa%3Dram=foo%26bar%3Dbaz&test=test', 'pa%3Dram=foo%26bar%3Dbaz&test=test', 'works with encoded delimiters'], + ['0', '0', 'allows "0"'], + ['Jane Doe&John%20Doe', 'Jane%20Doe&John%20Doe', 'normalizes encoding in keys'], + ['her=Jane Doe&him=John%20Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes encoding in values'], + ['foo=bar&&&test&&', 'foo=bar&test', 'removes unneeded delimiters'], + ['formula=e=m*c^2', 'formula=e%3Dm%2Ac%5E2', 'correctly treats only the first "=" as delimiter and the next as value'], // Ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway. // PHP also does not include them when building _GET. - array('foo=bar&=a=b&=x=y', 'foo=bar', 'removes params with empty key'), - ); + ['foo=bar&=a=b&=x=y', 'foo=bar', 'removes params with empty key'], + ]; } public function testGetQueryStringReturnsNull() @@ -814,74 +814,74 @@ public function testGetHost() { $request = new Request(); - $request->initialize(array('foo' => 'bar')); + $request->initialize(['foo' => 'bar']); $this->assertEquals('', $request->getHost(), '->getHost() return empty string if not initialized'); - $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.example.com')); + $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.example.com']); $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header'); // Host header with port number - $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.example.com:8080')); + $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.example.com:8080']); $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header with port number'); // Server values - $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.example.com')); + $request->initialize([], [], [], [], [], ['SERVER_NAME' => 'www.example.com']); $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from server name'); - $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.example.com', 'HTTP_HOST' => 'www.host.com')); + $request->initialize([], [], [], [], [], ['SERVER_NAME' => 'www.example.com', 'HTTP_HOST' => 'www.host.com']); $this->assertEquals('www.host.com', $request->getHost(), '->getHost() value from Host header has priority over SERVER_NAME '); } public function testGetPort() { - $request = Request::create('http://example.com', 'GET', array(), array(), array(), array( + $request = Request::create('http://example.com', 'GET', [], [], [], [ 'HTTP_X_FORWARDED_PROTO' => 'https', 'HTTP_X_FORWARDED_PORT' => '443', - )); + ]); $port = $request->getPort(); $this->assertEquals(80, $port, 'Without trusted proxies FORWARDED_PROTO and FORWARDED_PORT are ignored.'); - Request::setTrustedProxies(array('1.1.1.1'), Request::HEADER_X_FORWARDED_ALL); - $request = Request::create('http://example.com', 'GET', array(), array(), array(), array( + Request::setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_ALL); + $request = Request::create('http://example.com', 'GET', [], [], [], [ 'HTTP_X_FORWARDED_PROTO' => 'https', 'HTTP_X_FORWARDED_PORT' => '8443', - )); + ]); $this->assertEquals(80, $request->getPort(), 'With PROTO and PORT on untrusted connection server value takes precedence.'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $this->assertEquals(8443, $request->getPort(), 'With PROTO and PORT set PORT takes precedence.'); - $request = Request::create('http://example.com', 'GET', array(), array(), array(), array( + $request = Request::create('http://example.com', 'GET', [], [], [], [ 'HTTP_X_FORWARDED_PROTO' => 'https', - )); + ]); $this->assertEquals(80, $request->getPort(), 'With only PROTO set getPort() ignores trusted headers on untrusted connection.'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $this->assertEquals(443, $request->getPort(), 'With only PROTO set getPort() defaults to 443.'); - $request = Request::create('http://example.com', 'GET', array(), array(), array(), array( + $request = Request::create('http://example.com', 'GET', [], [], [], [ 'HTTP_X_FORWARDED_PROTO' => 'http', - )); + ]); $this->assertEquals(80, $request->getPort(), 'If X_FORWARDED_PROTO is set to HTTP getPort() ignores trusted headers on untrusted connection.'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $this->assertEquals(80, $request->getPort(), 'If X_FORWARDED_PROTO is set to HTTP getPort() returns port of the original request.'); - $request = Request::create('http://example.com', 'GET', array(), array(), array(), array( + $request = Request::create('http://example.com', 'GET', [], [], [], [ 'HTTP_X_FORWARDED_PROTO' => 'On', - )); + ]); $this->assertEquals(80, $request->getPort(), 'With only PROTO set and value is On, getPort() ignores trusted headers on untrusted connection.'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $this->assertEquals(443, $request->getPort(), 'With only PROTO set and value is On, getPort() defaults to 443.'); - $request = Request::create('http://example.com', 'GET', array(), array(), array(), array( + $request = Request::create('http://example.com', 'GET', [], [], [], [ 'HTTP_X_FORWARDED_PROTO' => '1', - )); + ]); $this->assertEquals(80, $request->getPort(), 'With only PROTO set and value is 1, getPort() ignores trusted headers on untrusted connection.'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $this->assertEquals(443, $request->getPort(), 'With only PROTO set and value is 1, getPort() defaults to 443.'); - $request = Request::create('http://example.com', 'GET', array(), array(), array(), array( + $request = Request::create('http://example.com', 'GET', [], [], [], [ 'HTTP_X_FORWARDED_PROTO' => 'something-else', - )); + ]); $port = $request->getPort(); $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.'); } @@ -892,7 +892,7 @@ public function testGetPort() public function testGetHostWithFakeHttpHostValue() { $request = new Request(); - $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.host.com?query=string')); + $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.host.com?query=string']); $request->getHost(); } @@ -952,7 +952,7 @@ public function testGetSetMethod() $request = new Request(); $request->setMethod('POST'); - $request->query->set('_method', array('delete', 'patch')); + $request->query->set('_method', ['delete', 'patch']); $this->assertSame('POST', $request->getMethod(), '->getMethod() returns the request method if invalid type is defined in query'); } @@ -989,69 +989,69 @@ public function testGetClientIpsForwarded($expected, $remoteAddr, $httpForwarded public function getClientIpsForwardedProvider() { // $expected $remoteAddr $httpForwarded $trustedProxies - return array( - array(array('127.0.0.1'), '127.0.0.1', 'for="_gazonk"', null), - array(array('127.0.0.1'), '127.0.0.1', 'for="_gazonk"', array('127.0.0.1')), - array(array('88.88.88.88'), '127.0.0.1', 'for="88.88.88.88:80"', array('127.0.0.1')), - array(array('192.0.2.60'), '::1', 'for=192.0.2.60;proto=http;by=203.0.113.43', array('::1')), - array(array('2620:0:1cfe:face:b00c::3', '192.0.2.43'), '::1', 'for=192.0.2.43, for=2620:0:1cfe:face:b00c::3', array('::1')), - array(array('2001:db8:cafe::17'), '::1', 'for="[2001:db8:cafe::17]:4711', array('::1')), - ); + return [ + [['127.0.0.1'], '127.0.0.1', 'for="_gazonk"', null], + [['127.0.0.1'], '127.0.0.1', 'for="_gazonk"', ['127.0.0.1']], + [['88.88.88.88'], '127.0.0.1', 'for="88.88.88.88:80"', ['127.0.0.1']], + [['192.0.2.60'], '::1', 'for=192.0.2.60;proto=http;by=203.0.113.43', ['::1']], + [['2620:0:1cfe:face:b00c::3', '192.0.2.43'], '::1', 'for=192.0.2.43, for=2620:0:1cfe:face:b00c::3', ['::1']], + [['2001:db8:cafe::17'], '::1', 'for="[2001:db8:cafe::17]:4711', ['::1']], + ]; } public function getClientIpsProvider() { // $expected $remoteAddr $httpForwardedFor $trustedProxies - return array( + return [ // simple IPv4 - array(array('88.88.88.88'), '88.88.88.88', null, null), + [['88.88.88.88'], '88.88.88.88', null, null], // trust the IPv4 remote addr - array(array('88.88.88.88'), '88.88.88.88', null, array('88.88.88.88')), + [['88.88.88.88'], '88.88.88.88', null, ['88.88.88.88']], // simple IPv6 - array(array('::1'), '::1', null, null), + [['::1'], '::1', null, null], // trust the IPv6 remote addr - array(array('::1'), '::1', null, array('::1')), + [['::1'], '::1', null, ['::1']], // forwarded for with remote IPv4 addr not trusted - array(array('127.0.0.1'), '127.0.0.1', '88.88.88.88', null), + [['127.0.0.1'], '127.0.0.1', '88.88.88.88', null], // 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')), + [['88.88.88.88'], '127.0.0.1', '88.88.88.88,', ['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')), + [['88.88.88.88'], '127.0.0.1', '88.88.88.88', ['127.0.0.1', '88.88.88.88']], // forwarded for with remote IPv4 range trusted - array(array('88.88.88.88'), '123.45.67.89', '88.88.88.88', array('123.45.67.0/24')), + [['88.88.88.88'], '123.45.67.89', '88.88.88.88', ['123.45.67.0/24']], // forwarded for with remote IPv6 addr not trusted - array(array('1620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', null), + [['1620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', null], // forwarded for with remote IPv6 addr trusted - array(array('2620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3')), + [['2620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', ['1620:0:1cfe:face:b00c::3']], // forwarded for with remote IPv6 range trusted - array(array('88.88.88.88'), '2a01:198:603:0:396e:4789:8e99:890f', '88.88.88.88', array('2a01:198:603:0::/65')), + [['88.88.88.88'], '2a01:198:603:0:396e:4789:8e99:890f', '88.88.88.88', ['2a01:198:603:0::/65']], // multiple forwarded for with remote IPv4 addr trusted - array(array('88.88.88.88', '87.65.43.21', '127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89')), + [['88.88.88.88', '87.65.43.21', '127.0.0.1'], '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', ['123.45.67.89']], // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted - array(array('87.65.43.21', '127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '88.88.88.88')), + [['87.65.43.21', '127.0.0.1'], '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', ['123.45.67.89', '88.88.88.88']], // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle - array(array('88.88.88.88', '127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '87.65.43.21')), + [['88.88.88.88', '127.0.0.1'], '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', ['123.45.67.89', '87.65.43.21']], // multiple forwarded for with remote IPv4 addr and all reverse proxies trusted - array(array('127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '87.65.43.21', '88.88.88.88', '127.0.0.1')), + [['127.0.0.1'], '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', ['123.45.67.89', '87.65.43.21', '88.88.88.88', '127.0.0.1']], // multiple forwarded for with remote IPv6 addr trusted - array(array('2620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3')), + [['2620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', ['1620:0:1cfe:face:b00c::3']], // multiple forwarded for with remote IPv6 addr and some reverse proxies trusted - array(array('3620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3')), + [['3620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', ['1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3']], // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle - array(array('2620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3,3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3')), + [['2620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3,3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', ['1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3']], // client IP with port - array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88:12345, 127.0.0.1', array('127.0.0.1')), + [['88.88.88.88'], '127.0.0.1', '88.88.88.88:12345, 127.0.0.1', ['127.0.0.1']], // invalid forwarded IP is ignored - array(array('88.88.88.88'), '127.0.0.1', 'unknown,88.88.88.88', array('127.0.0.1')), - array(array('88.88.88.88'), '127.0.0.1', '}__test|O:21:"JDatabaseDriverMysqli":3:{s:2,88.88.88.88', array('127.0.0.1')), - ); + [['88.88.88.88'], '127.0.0.1', 'unknown,88.88.88.88', ['127.0.0.1']], + [['88.88.88.88'], '127.0.0.1', '}__test|O:21:"JDatabaseDriverMysqli":3:{s:2,88.88.88.88', ['127.0.0.1']], + ]; } /** @@ -1062,15 +1062,15 @@ public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXFor { $request = new Request(); - $server = array( + $server = [ 'REMOTE_ADDR' => '88.88.88.88', 'HTTP_FORWARDED' => $httpForwarded, 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor, - ); + ]; - Request::setTrustedProxies(array('88.88.88.88'), Request::HEADER_X_FORWARDED_ALL | Request::HEADER_FORWARDED); + Request::setTrustedProxies(['88.88.88.88'], Request::HEADER_X_FORWARDED_ALL | Request::HEADER_FORWARDED); - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $request->getClientIps(); } @@ -1082,15 +1082,15 @@ public function testGetClientIpsOnlyXHttpForwardedForTrusted($httpForwarded, $ht { $request = new Request(); - $server = array( + $server = [ 'REMOTE_ADDR' => '88.88.88.88', 'HTTP_FORWARDED' => $httpForwarded, 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor, - ); + ]; - Request::setTrustedProxies(array('88.88.88.88'), Request::HEADER_X_FORWARDED_FOR); + Request::setTrustedProxies(['88.88.88.88'], Request::HEADER_X_FORWARDED_FOR); - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertSame(array_reverse(explode(',', $httpXForwardedFor)), $request->getClientIps()); } @@ -1098,13 +1098,13 @@ public function testGetClientIpsOnlyXHttpForwardedForTrusted($httpForwarded, $ht public function getClientIpsWithConflictingHeadersProvider() { // $httpForwarded $httpXForwardedFor - return array( - array('for=87.65.43.21', '192.0.2.60'), - array('for=87.65.43.21, for=192.0.2.60', '192.0.2.60'), - array('for=192.0.2.60', '192.0.2.60,87.65.43.21'), - array('for="::face", for=192.0.2.60', '192.0.2.60,192.0.2.43'), - array('for=87.65.43.21, for=192.0.2.60', '192.0.2.60,87.65.43.21'), - ); + return [ + ['for=87.65.43.21', '192.0.2.60'], + ['for=87.65.43.21, for=192.0.2.60', '192.0.2.60'], + ['for=192.0.2.60', '192.0.2.60,87.65.43.21'], + ['for="::face", for=192.0.2.60', '192.0.2.60,192.0.2.43'], + ['for=87.65.43.21, for=192.0.2.60', '192.0.2.60,87.65.43.21'], + ]; } /** @@ -1114,15 +1114,15 @@ public function testGetClientIpsWithAgreeingHeaders($httpForwarded, $httpXForwar { $request = new Request(); - $server = array( + $server = [ 'REMOTE_ADDR' => '88.88.88.88', 'HTTP_FORWARDED' => $httpForwarded, 'HTTP_X_FORWARDED_FOR' => $httpXForwardedFor, - ); + ]; - Request::setTrustedProxies(array('88.88.88.88'), -1); + Request::setTrustedProxies(['88.88.88.88'], -1); - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $clientIps = $request->getClientIps(); @@ -1132,14 +1132,14 @@ public function testGetClientIpsWithAgreeingHeaders($httpForwarded, $httpXForwar public function getClientIpsWithAgreeingHeadersProvider() { // $httpForwarded $httpXForwardedFor - return array( - array('for="192.0.2.60"', '192.0.2.60', array('192.0.2.60')), - array('for=192.0.2.60, for=87.65.43.21', '192.0.2.60,87.65.43.21', array('87.65.43.21', '192.0.2.60')), - array('for="[::face]", for=192.0.2.60', '::face,192.0.2.60', array('192.0.2.60', '::face')), - array('for="192.0.2.60:80"', '192.0.2.60', array('192.0.2.60')), - array('for=192.0.2.60;proto=http;by=203.0.113.43', '192.0.2.60', array('192.0.2.60')), - array('for="[2001:db8:cafe::17]:4711"', '2001:db8:cafe::17', array('2001:db8:cafe::17')), - ); + return [ + ['for="192.0.2.60"', '192.0.2.60', ['192.0.2.60']], + ['for=192.0.2.60, for=87.65.43.21', '192.0.2.60,87.65.43.21', ['87.65.43.21', '192.0.2.60']], + ['for="[::face]", for=192.0.2.60', '::face,192.0.2.60', ['192.0.2.60', '::face']], + ['for="192.0.2.60:80"', '192.0.2.60', ['192.0.2.60']], + ['for=192.0.2.60;proto=http;by=203.0.113.43', '192.0.2.60', ['192.0.2.60']], + ['for="[2001:db8:cafe::17]:4711"', '2001:db8:cafe::17', ['2001:db8:cafe::17']], + ]; } public function testGetContentWorksTwiceInDefaultMode() @@ -1160,7 +1160,7 @@ public function testGetContentReturnsResource() public function testGetContentReturnsResourceWhenContentSetInConstructor() { - $req = new Request(array(), array(), array(), array(), array(), array(), 'MyContent'); + $req = new Request([], [], [], [], [], [], 'MyContent'); $resource = $req->getContent(true); $this->assertInternalType('resource', $resource); @@ -1173,7 +1173,7 @@ public function testContentAsResource() fwrite($resource, 'My other content'); rewind($resource); - $req = new Request(array(), array(), array(), array(), array(), array(), $resource); + $req = new Request([], [], [], [], [], [], $resource); $this->assertEquals('My other content', stream_get_contents($req->getContent(true))); $this->assertEquals('My other content', $req->getContent()); } @@ -1195,10 +1195,10 @@ public function testGetContentCantBeCalledTwiceWithResources($first, $second) public function getContentCantBeCalledTwiceWithResourcesProvider() { - return array( - 'Resource then fetch' => array(true, false), - 'Resource then resource' => array(true, true), - ); + return [ + 'Resource then fetch' => [true, false], + 'Resource then resource' => [true, true], + ]; } /** @@ -1224,24 +1224,24 @@ public function testGetContentCanBeCalledTwiceWithResources($first, $second) public function getContentCanBeCalledTwiceWithResourcesProvider() { - return array( - 'Fetch then fetch' => array(false, false), - 'Fetch then resource' => array(false, true), - 'Resource then fetch' => array(true, false), - 'Resource then resource' => array(true, true), - ); + return [ + 'Fetch then fetch' => [false, false], + 'Fetch then resource' => [false, true], + 'Resource then fetch' => [true, false], + 'Resource then resource' => [true, true], + ]; } public function provideOverloadedMethods() { - return array( - array('PUT'), - array('DELETE'), - array('PATCH'), - array('put'), - array('delete'), - array('patch'), - ); + return [ + ['PUT'], + ['DELETE'], + ['PATCH'], + ['put'], + ['delete'], + ['patch'], + ]; } /** @@ -1254,14 +1254,14 @@ public function testCreateFromGlobals($method) $_GET['foo1'] = 'bar1'; $_POST['foo2'] = 'bar2'; $_COOKIE['foo3'] = 'bar3'; - $_FILES['foo4'] = array('bar4'); + $_FILES['foo4'] = ['bar4']; $_SERVER['foo5'] = 'bar5'; $request = Request::createFromGlobals(); $this->assertEquals('bar1', $request->query->get('foo1'), '::fromGlobals() uses values from $_GET'); $this->assertEquals('bar2', $request->request->get('foo2'), '::fromGlobals() uses values from $_POST'); $this->assertEquals('bar3', $request->cookies->get('foo3'), '::fromGlobals() uses values from $_COOKIE'); - $this->assertEquals(array('bar4'), $request->files->get('foo4'), '::fromGlobals() uses values from $_FILES'); + $this->assertEquals(['bar4'], $request->files->get('foo4'), '::fromGlobals() uses values from $_FILES'); $this->assertEquals('bar5', $request->server->get('foo5'), '::fromGlobals() uses values from $_SERVER'); unset($_GET['foo1'], $_POST['foo2'], $_COOKIE['foo3'], $_FILES['foo4'], $_SERVER['foo5']); @@ -1291,25 +1291,25 @@ public function testCreateFromGlobals($method) public function testOverrideGlobals() { $request = new Request(); - $request->initialize(array('foo' => 'bar')); + $request->initialize(['foo' => 'bar']); // as the Request::overrideGlobals really work, it erase $_SERVER, so we must backup it $server = $_SERVER; $request->overrideGlobals(); - $this->assertEquals(array('foo' => 'bar'), $_GET); + $this->assertEquals(['foo' => 'bar'], $_GET); - $request->initialize(array(), array('foo' => 'bar')); + $request->initialize([], ['foo' => 'bar']); $request->overrideGlobals(); - $this->assertEquals(array('foo' => 'bar'), $_POST); + $this->assertEquals(['foo' => 'bar'], $_POST); $this->assertArrayNotHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER); $request->headers->set('X_FORWARDED_PROTO', 'https'); - Request::setTrustedProxies(array('1.1.1.1'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_ALL); $this->assertFalse($request->isSecure()); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $this->assertTrue($request->isSecure()); @@ -1326,12 +1326,12 @@ public function testOverrideGlobals() $this->assertArrayHasKey('CONTENT_TYPE', $_SERVER); $this->assertArrayHasKey('CONTENT_LENGTH', $_SERVER); - $request->initialize(array('foo' => 'bar', 'baz' => 'foo')); + $request->initialize(['foo' => 'bar', 'baz' => 'foo']); $request->query->remove('baz'); $request->overrideGlobals(); - $this->assertEquals(array('foo' => 'bar'), $_GET); + $this->assertEquals(['foo' => 'bar'], $_GET); $this->assertEquals('foo=bar', $_SERVER['QUERY_STRING']); $this->assertEquals('foo=bar', $request->server->get('QUERY_STRING')); @@ -1344,23 +1344,23 @@ public function testGetScriptName() $request = new Request(); $this->assertEquals('', $request->getScriptName()); - $server = array(); + $server = []; $server['SCRIPT_NAME'] = '/index.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('/index.php', $request->getScriptName()); - $server = array(); + $server = []; $server['ORIG_SCRIPT_NAME'] = '/frontend.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('/frontend.php', $request->getScriptName()); - $server = array(); + $server = []; $server['SCRIPT_NAME'] = '/index.php'; $server['ORIG_SCRIPT_NAME'] = '/frontend.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('/index.php', $request->getScriptName()); } @@ -1370,29 +1370,29 @@ public function testGetBasePath() $request = new Request(); $this->assertEquals('', $request->getBasePath()); - $server = array(); + $server = []; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('', $request->getBasePath()); - $server = array(); + $server = []; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $server['SCRIPT_NAME'] = '/index.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('', $request->getBasePath()); - $server = array(); + $server = []; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $server['PHP_SELF'] = '/index.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('', $request->getBasePath()); - $server = array(); + $server = []; $server['SCRIPT_FILENAME'] = '/some/where/index.php'; $server['ORIG_SCRIPT_NAME'] = '/index.php'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('', $request->getBasePath()); } @@ -1402,21 +1402,21 @@ public function testGetPathInfo() $request = new Request(); $this->assertEquals('/', $request->getPathInfo()); - $server = array(); + $server = []; $server['REQUEST_URI'] = '/path/info'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('/path/info', $request->getPathInfo()); - $server = array(); + $server = []; $server['REQUEST_URI'] = '/path%20test/info'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('/path%20test/info', $request->getPathInfo()); - $server = array(); + $server = []; $server['REQUEST_URI'] = '?a=b'; - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); $this->assertEquals('/', $request->getPathInfo()); } @@ -1444,27 +1444,27 @@ public function testGetPreferredLanguage() { $request = new Request(); $this->assertNull($request->getPreferredLanguage()); - $this->assertNull($request->getPreferredLanguage(array())); - $this->assertEquals('fr', $request->getPreferredLanguage(array('fr'))); - $this->assertEquals('fr', $request->getPreferredLanguage(array('fr', 'en'))); - $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'fr'))); - $this->assertEquals('fr-ch', $request->getPreferredLanguage(array('fr-ch', 'fr-fr'))); + $this->assertNull($request->getPreferredLanguage([])); + $this->assertEquals('fr', $request->getPreferredLanguage(['fr'])); + $this->assertEquals('fr', $request->getPreferredLanguage(['fr', 'en'])); + $this->assertEquals('en', $request->getPreferredLanguage(['en', 'fr'])); + $this->assertEquals('fr-ch', $request->getPreferredLanguage(['fr-ch', 'fr-fr'])); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); - $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'en-us'))); + $this->assertEquals('en', $request->getPreferredLanguage(['en', 'en-us'])); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); - $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en'))); + $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en'])); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8'); - $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en'))); + $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en'])); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, fr-fr; q=0.6, fr; q=0.5'); - $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en'))); + $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en'])); } public function testIsXmlHttpRequest() @@ -1502,72 +1502,72 @@ public function testIntlLocale() public function testGetCharsets() { $request = new Request(); - $this->assertEquals(array(), $request->getCharsets()); + $this->assertEquals([], $request->getCharsets()); $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6'); - $this->assertEquals(array(), $request->getCharsets()); // testing caching + $this->assertEquals([], $request->getCharsets()); // testing caching $request = new Request(); $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6'); - $this->assertEquals(array('ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'), $request->getCharsets()); + $this->assertEquals(['ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'], $request->getCharsets()); $request = new Request(); $request->headers->set('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'); - $this->assertEquals(array('ISO-8859-1', 'utf-8', '*'), $request->getCharsets()); + $this->assertEquals(['ISO-8859-1', 'utf-8', '*'], $request->getCharsets()); } public function testGetEncodings() { $request = new Request(); - $this->assertEquals(array(), $request->getEncodings()); + $this->assertEquals([], $request->getEncodings()); $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch'); - $this->assertEquals(array(), $request->getEncodings()); // testing caching + $this->assertEquals([], $request->getEncodings()); // testing caching $request = new Request(); $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch'); - $this->assertEquals(array('gzip', 'deflate', 'sdch'), $request->getEncodings()); + $this->assertEquals(['gzip', 'deflate', 'sdch'], $request->getEncodings()); $request = new Request(); $request->headers->set('Accept-Encoding', 'gzip;q=0.4,deflate;q=0.9,compress;q=0.7'); - $this->assertEquals(array('deflate', 'compress', 'gzip'), $request->getEncodings()); + $this->assertEquals(['deflate', 'compress', 'gzip'], $request->getEncodings()); } public function testGetAcceptableContentTypes() { $request = new Request(); - $this->assertEquals(array(), $request->getAcceptableContentTypes()); + $this->assertEquals([], $request->getAcceptableContentTypes()); $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*'); - $this->assertEquals(array(), $request->getAcceptableContentTypes()); // testing caching + $this->assertEquals([], $request->getAcceptableContentTypes()); // testing caching $request = new Request(); $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*'); - $this->assertEquals(array('application/vnd.wap.wmlscriptc', 'text/vnd.wap.wml', 'application/vnd.wap.xhtml+xml', 'application/xhtml+xml', 'text/html', 'multipart/mixed', '*/*'), $request->getAcceptableContentTypes()); + $this->assertEquals(['application/vnd.wap.wmlscriptc', 'text/vnd.wap.wml', 'application/vnd.wap.xhtml+xml', 'application/xhtml+xml', 'text/html', 'multipart/mixed', '*/*'], $request->getAcceptableContentTypes()); } public function testGetLanguages() { $request = new Request(); - $this->assertEquals(array(), $request->getLanguages()); + $this->assertEquals([], $request->getLanguages()); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); - $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages()); - $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages()); + $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages()); + $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages()); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.6, en; q=0.8'); - $this->assertEquals(array('zh', 'en', 'en_US'), $request->getLanguages()); // Test out of order qvalues + $this->assertEquals(['zh', 'en', 'en_US'], $request->getLanguages()); // Test out of order qvalues $request = new Request(); $request->headers->set('Accept-language', 'zh, en, en-us'); - $this->assertEquals(array('zh', 'en', 'en_US'), $request->getLanguages()); // Test equal weighting without qvalues + $this->assertEquals(['zh', 'en', 'en_US'], $request->getLanguages()); // Test equal weighting without qvalues $request = new Request(); $request->headers->set('Accept-language', 'zh; q=0.6, en, en-us; q=0.6'); - $this->assertEquals(array('en', 'zh', 'en_US'), $request->getLanguages()); // Test equal weighting with qvalues + $this->assertEquals(['en', 'zh', 'en_US'], $request->getLanguages()); // Test equal weighting with qvalues $request = new Request(); $request->headers->set('Accept-language', 'zh, i-cherokee; q=0.6'); - $this->assertEquals(array('zh', 'cherokee'), $request->getLanguages()); + $this->assertEquals(['zh', 'cherokee'], $request->getLanguages()); } public function testGetRequestFormat() @@ -1587,7 +1587,7 @@ public function testGetRequestFormat() $this->assertNull($request->setRequestFormat('foo')); $this->assertEquals('foo', $request->getRequestFormat(null)); - $request = new Request(array('_format' => 'foo')); + $request = new Request(['_format' => 'foo']); $this->assertEquals('html', $request->getRequestFormat()); } @@ -1664,7 +1664,7 @@ public function testIsMethod() */ public function testGetBaseUrl($uri, $server, $expectedBaseUrl, $expectedPathInfo) { - $request = Request::create($uri, 'GET', array(), array(), array(), $server); + $request = Request::create($uri, 'GET', [], [], [], $server); $this->assertSame($expectedBaseUrl, $request->getBaseUrl(), 'baseUrl'); $this->assertSame($expectedPathInfo, $request->getPathInfo(), 'pathInfo'); @@ -1672,78 +1672,78 @@ public function testGetBaseUrl($uri, $server, $expectedBaseUrl, $expectedPathInf public function getBaseUrlData() { - return array( - array( + return [ + [ '/fruit/strawberry/1234index.php/blah', - array( + [ 'SCRIPT_FILENAME' => 'E:/Sites/cc-new/public_html/fruit/index.php', 'SCRIPT_NAME' => '/fruit/index.php', 'PHP_SELF' => '/fruit/index.php', - ), + ], '/fruit', '/strawberry/1234index.php/blah', - ), - array( + ], + [ '/fruit/strawberry/1234index.php/blah', - array( + [ 'SCRIPT_FILENAME' => 'E:/Sites/cc-new/public_html/index.php', 'SCRIPT_NAME' => '/index.php', 'PHP_SELF' => '/index.php', - ), + ], '', '/fruit/strawberry/1234index.php/blah', - ), - array( + ], + [ '/foo%20bar/', - array( + [ 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', - ), + ], '/foo%20bar', '/', - ), - array( + ], + [ '/foo%20bar/home', - array( + [ 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', - ), + ], '/foo%20bar', '/home', - ), - array( + ], + [ '/foo%20bar/app.php/home', - array( + [ 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', - ), + ], '/foo%20bar/app.php', '/home', - ), - array( + ], + [ '/foo%20bar/app.php/home%3Dbaz', - array( + [ 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php', 'SCRIPT_NAME' => '/foo bar/app.php', 'PHP_SELF' => '/foo bar/app.php', - ), + ], '/foo%20bar/app.php', '/home%3Dbaz', - ), - array( + ], + [ '/foo/bar+baz', - array( + [ 'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo/app.php', 'SCRIPT_NAME' => '/foo/app.php', 'PHP_SELF' => '/foo/app.php', - ), + ], '/foo', '/bar+baz', - ), - ); + ], + ]; } /** @@ -1761,16 +1761,16 @@ public function testUrlencodedStringPrefix($string, $prefix, $expect) public function urlencodedStringPrefixData() { - return array( - array('foo', 'foo', 'foo'), - array('fo%6f', 'foo', 'fo%6f'), - array('foo/bar', 'foo', 'foo'), - array('fo%6f/bar', 'foo', 'fo%6f'), - array('f%6f%6f/bar', 'foo', 'f%6f%6f'), - array('%66%6F%6F/bar', 'foo', '%66%6F%6F'), - array('fo+o/bar', 'fo+o', 'fo+o'), - array('fo%2Bo/bar', 'fo+o', 'fo%2Bo'), - ); + return [ + ['foo', 'foo', 'foo'], + ['fo%6f', 'foo', 'fo%6f'], + ['foo/bar', 'foo', 'foo'], + ['fo%6f/bar', 'foo', 'fo%6f'], + ['f%6f%6f/bar', 'foo', 'f%6f%6f'], + ['%66%6F%6F/bar', 'foo', '%66%6F%6F'], + ['fo+o/bar', 'fo+o', 'fo+o'], + ['fo%2Bo/bar', 'fo+o', 'fo%2Bo'], + ]; } private function disableHttpMethodParameterOverride() @@ -1785,7 +1785,7 @@ private function getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedF { $request = new Request(); - $server = array('REMOTE_ADDR' => $remoteAddr); + $server = ['REMOTE_ADDR' => $remoteAddr]; if (null !== $httpForwardedFor) { $server['HTTP_X_FORWARDED_FOR'] = $httpForwardedFor; } @@ -1794,7 +1794,7 @@ private function getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedF Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_ALL); } - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); return $request; } @@ -1803,7 +1803,7 @@ private function getRequestInstanceForClientIpsForwardedTests($remoteAddr, $http { $request = new Request(); - $server = array('REMOTE_ADDR' => $remoteAddr); + $server = ['REMOTE_ADDR' => $remoteAddr]; if (null !== $httpForwarded) { $server['HTTP_FORWARDED'] = $httpForwarded; @@ -1813,7 +1813,7 @@ private function getRequestInstanceForClientIpsForwardedTests($remoteAddr, $http Request::setTrustedProxies($trustedProxies, Request::HEADER_FORWARDED); } - $request->initialize(array(), array(), array(), array(), array(), $server); + $request->initialize([], [], [], [], [], $server); return $request; } @@ -1834,35 +1834,35 @@ public function testTrustedProxiesXForwardedFor() $this->assertFalse($request->isSecure()); // disabling proxy trusting - Request::setTrustedProxies(array(), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies([], Request::HEADER_X_FORWARDED_ALL); $this->assertEquals('3.3.3.3', $request->getClientIp()); $this->assertEquals('example.com', $request->getHost()); $this->assertEquals(80, $request->getPort()); $this->assertFalse($request->isSecure()); // request is forwarded by a non-trusted proxy - Request::setTrustedProxies(array('2.2.2.2'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['2.2.2.2'], Request::HEADER_X_FORWARDED_ALL); $this->assertEquals('3.3.3.3', $request->getClientIp()); $this->assertEquals('example.com', $request->getHost()); $this->assertEquals(80, $request->getPort()); $this->assertFalse($request->isSecure()); // trusted proxy via setTrustedProxies() - Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_X_FORWARDED_ALL); $this->assertEquals('1.1.1.1', $request->getClientIp()); $this->assertEquals('foo.example.com', $request->getHost()); $this->assertEquals(443, $request->getPort()); $this->assertTrue($request->isSecure()); // trusted proxy via setTrustedProxies() - Request::setTrustedProxies(array('3.3.3.4', '2.2.2.2'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['3.3.3.4', '2.2.2.2'], Request::HEADER_X_FORWARDED_ALL); $this->assertEquals('3.3.3.3', $request->getClientIp()); $this->assertEquals('example.com', $request->getHost()); $this->assertEquals(80, $request->getPort()); $this->assertFalse($request->isSecure()); // check various X_FORWARDED_PROTO header values - Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_X_FORWARDED_ALL); $request->headers->set('X_FORWARDED_PROTO', 'ssl'); $this->assertTrue($request->isSecure()); @@ -1887,7 +1887,7 @@ public function testLegacyTrustedProxies() $request->headers->set('X_MY_PROTO', 'http'); $request->headers->set('X_MY_PORT', 81); - Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_X_FORWARDED_ALL); // custom header names Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_MY_FOR'); @@ -1930,35 +1930,35 @@ public function testTrustedProxiesForwarded() $this->assertFalse($request->isSecure()); // disabling proxy trusting - Request::setTrustedProxies(array(), Request::HEADER_FORWARDED); + Request::setTrustedProxies([], Request::HEADER_FORWARDED); $this->assertEquals('3.3.3.3', $request->getClientIp()); $this->assertEquals('example.com', $request->getHost()); $this->assertEquals(80, $request->getPort()); $this->assertFalse($request->isSecure()); // request is forwarded by a non-trusted proxy - Request::setTrustedProxies(array('2.2.2.2'), Request::HEADER_FORWARDED); + Request::setTrustedProxies(['2.2.2.2'], Request::HEADER_FORWARDED); $this->assertEquals('3.3.3.3', $request->getClientIp()); $this->assertEquals('example.com', $request->getHost()); $this->assertEquals(80, $request->getPort()); $this->assertFalse($request->isSecure()); // trusted proxy via setTrustedProxies() - Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'), Request::HEADER_FORWARDED); + Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_FORWARDED); $this->assertEquals('1.1.1.1', $request->getClientIp()); $this->assertEquals('foo.example.com', $request->getHost()); $this->assertEquals(8080, $request->getPort()); $this->assertTrue($request->isSecure()); // trusted proxy via setTrustedProxies() - Request::setTrustedProxies(array('3.3.3.4', '2.2.2.2'), Request::HEADER_FORWARDED); + Request::setTrustedProxies(['3.3.3.4', '2.2.2.2'], Request::HEADER_FORWARDED); $this->assertEquals('3.3.3.3', $request->getClientIp()); $this->assertEquals('example.com', $request->getHost()); $this->assertEquals(80, $request->getPort()); $this->assertFalse($request->isSecure()); // check various X_FORWARDED_PROTO header values - Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'), Request::HEADER_FORWARDED); + Request::setTrustedProxies(['3.3.3.3', '2.2.2.2'], Request::HEADER_FORWARDED); $request->headers->set('FORWARDED', 'proto=ssl'); $this->assertTrue($request->isSecure()); @@ -1998,37 +1998,37 @@ public function testIISRequestUri($headers, $server, $expectedRequestUri) $this->assertEquals($expectedRequestUri, $request->getRequestUri(), '->getRequestUri() is correct'); $subRequestUri = '/bar/foo'; - $subRequest = Request::create($subRequestUri, 'get', array(), array(), array(), $request->server->all()); + $subRequest = Request::create($subRequestUri, 'get', [], [], [], $request->server->all()); $this->assertEquals($subRequestUri, $subRequest->getRequestUri(), '->getRequestUri() is correct in sub request'); } public function iisRequestUriProvider() { - return array( - array( - array(), - array( + return [ + [ + [], + [ 'IIS_WasUrlRewritten' => '1', 'UNENCODED_URL' => '/foo/bar', - ), + ], '/foo/bar', - ), - array( - array(), - array( + ], + [ + [], + [ 'ORIG_PATH_INFO' => '/foo/bar', - ), + ], '/foo/bar', - ), - array( - array(), - array( + ], + [ + [], + [ 'ORIG_PATH_INFO' => '/foo/bar', 'QUERY_STRING' => 'foo=bar', - ), + ], '/foo/bar?foo=bar', - ), - ); + ], + ]; } public function testTrustedHosts() @@ -2041,7 +2041,7 @@ public function testTrustedHosts() $this->assertEquals('evil.com', $request->getHost()); // add a trusted domain and all its subdomains - Request::setTrustedHosts(array('^([a-z]{9}\.)?trusted\.com$')); + Request::setTrustedHosts(['^([a-z]{9}\.)?trusted\.com$']); // untrusted host $request->headers->set('host', 'evil.com'); @@ -2073,7 +2073,7 @@ public function testTrustedHosts() public function testSetTrustedHostsDoesNotBreakOnSpecialCharacters() { - Request::setTrustedHosts(array('localhost(\.local){0,1}#,example.com', 'localhost')); + Request::setTrustedHosts(['localhost(\.local){0,1}#,example.com', 'localhost']); $request = Request::create('/'); $request->headers->set('host', 'localhost'); @@ -2082,7 +2082,7 @@ public function testSetTrustedHostsDoesNotBreakOnSpecialCharacters() public function testFactory() { - Request::setFactory(function (array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) { + Request::setFactory(function (array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) { return new NewRequest(); }); @@ -2131,23 +2131,23 @@ public function testHostValidity($host, $isValid, $expectedHost = null, $expecte public function getHostValidities() { - return array( - array('.a', false), - array('a..', false), - array('a.', true), - array("\xE9", false), - array('[::1]', true), - array('[::1]:80', true, '[::1]', 80), - array(str_repeat('.', 101), false), - ); + return [ + ['.a', false], + ['a..', false], + ['a.', true], + ["\xE9", false], + ['[::1]', true], + ['[::1]:80', true, '[::1]', 80], + [str_repeat('.', 101), false], + ]; } public function getLongHostNames() { - return array( - array('a'.str_repeat('.a', 40000)), - array(str_repeat(':', 101)), - ); + return [ + ['a'.str_repeat('.a', 40000)], + [str_repeat(':', 101)], + ]; } /** @@ -2162,18 +2162,18 @@ public function testMethodIdempotent($method, $idempotent) public function methodIdempotentProvider() { - return array( - array('HEAD', true), - array('GET', true), - array('POST', false), - array('PUT', true), - array('PATCH', false), - array('DELETE', true), - array('PURGE', true), - array('OPTIONS', true), - array('TRACE', true), - array('CONNECT', false), - ); + return [ + ['HEAD', true], + ['GET', true], + ['POST', false], + ['PUT', true], + ['PATCH', false], + ['DELETE', true], + ['PURGE', true], + ['OPTIONS', true], + ['TRACE', true], + ['CONNECT', false], + ]; } /** @@ -2188,18 +2188,18 @@ public function testMethodSafe($method, $safe) public function methodSafeProvider() { - return array( - array('HEAD', true), - array('GET', true), - array('POST', false), - array('PUT', false), - array('PATCH', false), - array('DELETE', false), - array('PURGE', false), - array('OPTIONS', true), - array('TRACE', true), - array('CONNECT', false), - ); + return [ + ['HEAD', true], + ['GET', true], + ['POST', false], + ['PUT', false], + ['PATCH', false], + ['DELETE', false], + ['PURGE', false], + ['OPTIONS', true], + ['TRACE', true], + ['CONNECT', false], + ]; } /** @@ -2225,18 +2225,18 @@ public function testMethodCacheable($method, $cacheable) public function methodCacheableProvider() { - return array( - array('HEAD', true), - array('GET', true), - array('POST', false), - array('PUT', false), - array('PATCH', false), - array('DELETE', false), - array('PURGE', false), - array('OPTIONS', false), - array('TRACE', false), - array('CONNECT', false), - ); + return [ + ['HEAD', true], + ['GET', true], + ['POST', false], + ['PUT', false], + ['PATCH', false], + ['DELETE', false], + ['PURGE', false], + ['OPTIONS', false], + ['TRACE', false], + ['CONNECT', false], + ]; } /** @@ -2244,7 +2244,7 @@ public function methodCacheableProvider() */ public function testGetTrustedHeaderName() { - Request::setTrustedProxies(array('8.8.8.8'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['8.8.8.8'], Request::HEADER_X_FORWARDED_ALL); $this->assertNull(Request::getTrustedHeaderName(Request::HEADER_FORWARDED)); $this->assertSame('X_FORWARDED_FOR', Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)); @@ -2252,7 +2252,7 @@ public function testGetTrustedHeaderName() $this->assertSame('X_FORWARDED_PORT', Request::getTrustedHeaderName(Request::HEADER_CLIENT_PORT)); $this->assertSame('X_FORWARDED_PROTO', Request::getTrustedHeaderName(Request::HEADER_CLIENT_PROTO)); - Request::setTrustedProxies(array('8.8.8.8'), Request::HEADER_FORWARDED); + Request::setTrustedProxies(['8.8.8.8'], Request::HEADER_FORWARDED); $this->assertSame('FORWARDED', Request::getTrustedHeaderName(Request::HEADER_FORWARDED)); $this->assertNull(Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)); @@ -2266,7 +2266,7 @@ public function testGetTrustedHeaderName() Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'D'); Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'E'); - Request::setTrustedProxies(array('8.8.8.8'), Request::HEADER_FORWARDED); + Request::setTrustedProxies(['8.8.8.8'], Request::HEADER_FORWARDED); $this->assertSame('A', Request::getTrustedHeaderName(Request::HEADER_FORWARDED)); $this->assertNull(Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)); @@ -2274,7 +2274,7 @@ public function testGetTrustedHeaderName() $this->assertNull(Request::getTrustedHeaderName(Request::HEADER_CLIENT_PORT)); $this->assertNull(Request::getTrustedHeaderName(Request::HEADER_CLIENT_PROTO)); - Request::setTrustedProxies(array('8.8.8.8'), Request::HEADER_X_FORWARDED_ALL); + Request::setTrustedProxies(['8.8.8.8'], Request::HEADER_X_FORWARDED_ALL); $this->assertNull(Request::getTrustedHeaderName(Request::HEADER_FORWARDED)); $this->assertSame('B', Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)); @@ -2282,7 +2282,7 @@ public function testGetTrustedHeaderName() $this->assertSame('D', Request::getTrustedHeaderName(Request::HEADER_CLIENT_PORT)); $this->assertSame('E', Request::getTrustedHeaderName(Request::HEADER_CLIENT_PROTO)); - Request::setTrustedProxies(array('8.8.8.8'), Request::HEADER_FORWARDED); + Request::setTrustedProxies(['8.8.8.8'], Request::HEADER_FORWARDED); $this->assertSame('A', Request::getTrustedHeaderName(Request::HEADER_FORWARDED)); @@ -2300,7 +2300,7 @@ public function testGetTrustedHeaderName() public function testProtocolVersion($serverProtocol, $trustedProxy, $via, $expected) { if ($trustedProxy) { - Request::setTrustedProxies(array('1.1.1.1'), -1); + Request::setTrustedProxies(['1.1.1.1'], -1); } $request = new Request(); @@ -2313,41 +2313,41 @@ public function testProtocolVersion($serverProtocol, $trustedProxy, $via, $expec public function protocolVersionProvider() { - return array( - 'untrusted without via' => array('HTTP/2.0', false, '', 'HTTP/2.0'), - 'untrusted with via' => array('HTTP/2.0', false, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/2.0'), - 'trusted without via' => array('HTTP/2.0', true, '', 'HTTP/2.0'), - 'trusted with via' => array('HTTP/2.0', true, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'), - 'trusted with via and protocol name' => array('HTTP/2.0', true, 'HTTP/1.0 fred, HTTP/1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'), - 'trusted with broken via' => array('HTTP/2.0', true, 'HTTP/1^0 foo', 'HTTP/2.0'), - 'trusted with partially-broken via' => array('HTTP/2.0', true, '1.0 fred, foo', 'HTTP/1.0'), - ); + return [ + 'untrusted without via' => ['HTTP/2.0', false, '', 'HTTP/2.0'], + 'untrusted with via' => ['HTTP/2.0', false, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/2.0'], + 'trusted without via' => ['HTTP/2.0', true, '', 'HTTP/2.0'], + 'trusted with via' => ['HTTP/2.0', true, '1.0 fred, 1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'], + 'trusted with via and protocol name' => ['HTTP/2.0', true, 'HTTP/1.0 fred, HTTP/1.1 nowhere.com (Apache/1.1)', 'HTTP/1.0'], + 'trusted with broken via' => ['HTTP/2.0', true, 'HTTP/1^0 foo', 'HTTP/2.0'], + 'trusted with partially-broken via' => ['HTTP/2.0', true, '1.0 fred, foo', 'HTTP/1.0'], + ]; } public function nonstandardRequestsData() { - return array( - array('', '', '/', 'http://host:8080/', ''), - array('/', '', '/', 'http://host:8080/', ''), + return [ + ['', '', '/', 'http://host:8080/', ''], + ['/', '', '/', 'http://host:8080/', ''], - array('hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'), - array('/hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'), + ['hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'], + ['/hello/app.php/x', '', '/x', 'http://host:8080/hello/app.php/x', '/hello', '/hello/app.php'], - array('', 'a=b', '/', 'http://host:8080/?a=b'), - array('?a=b', 'a=b', '/', 'http://host:8080/?a=b'), - array('/?a=b', 'a=b', '/', 'http://host:8080/?a=b'), + ['', 'a=b', '/', 'http://host:8080/?a=b'], + ['?a=b', 'a=b', '/', 'http://host:8080/?a=b'], + ['/?a=b', 'a=b', '/', 'http://host:8080/?a=b'], - array('x', 'a=b', '/x', 'http://host:8080/x?a=b'), - array('x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'), - array('/x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'), + ['x', 'a=b', '/x', 'http://host:8080/x?a=b'], + ['x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'], + ['/x?a=b', 'a=b', '/x', 'http://host:8080/x?a=b'], - array('hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'), - array('/hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'), + ['hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'], + ['/hello/x', '', '/x', 'http://host:8080/hello/x', '/hello'], - array('hello/app.php/x', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'), - array('hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'), - array('/hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'), - ); + ['hello/app.php/x', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'], + ['hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'], + ['/hello/app.php/x?a=b', 'a=b', '/x', 'http://host:8080/hello/app.php/x?a=b', '/hello', '/hello/app.php'], + ]; } /** @@ -2359,16 +2359,16 @@ public function testNonstandardRequests($requestUri, $queryString, $expectedPath $expectedBaseUrl = $expectedBasePath; } - $server = array( + $server = [ 'HTTP_HOST' => 'host:8080', 'SERVER_PORT' => '8080', 'QUERY_STRING' => $queryString, 'PHP_SELF' => '/hello/app.php', 'SCRIPT_FILENAME' => '/some/path/app.php', 'REQUEST_URI' => $requestUri, - ); + ]; - $request = new Request(array(), array(), array(), array(), array(), $server); + $request = new Request([], [], [], [], [], $server); $this->assertEquals($expectedPathInfo, $request->getPathInfo()); $this->assertEquals($expectedUri, $request->getUri()); @@ -2381,7 +2381,7 @@ public function testNonstandardRequests($requestUri, $queryString, $expectedPath public function testTrustedHost() { - Request::setTrustedProxies(array('1.1.1.1'), -1); + Request::setTrustedProxies(['1.1.1.1'], -1); $request = Request::create('/'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); @@ -2403,7 +2403,7 @@ public function testTrustedHost() public function testTrustedPort() { - Request::setTrustedProxies(array('1.1.1.1'), -1); + Request::setTrustedProxies(['1.1.1.1'], -1); $request = Request::create('/'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); @@ -2433,7 +2433,7 @@ class RequestContentProxy extends Request { public function getContent($asResource = false) { - return http_build_query(array('_method' => 'PUT', 'content' => 'mycontent'), '', '&'); + return http_build_query(['_method' => 'PUT', 'content' => 'mycontent'], '', '&'); } } diff --git a/Tests/ResponseFunctionalTest.php b/Tests/ResponseFunctionalTest.php index 22f25e978..3d3e696c7 100644 --- a/Tests/ResponseFunctionalTest.php +++ b/Tests/ResponseFunctionalTest.php @@ -22,10 +22,10 @@ class ResponseFunctionalTest extends TestCase public static function setUpBeforeClass() { - $spec = array( - 1 => array('file', '/dev/null', 'w'), - 2 => array('file', '/dev/null', 'w'), - ); + $spec = [ + 1 => ['file', '/dev/null', 'w'], + 2 => ['file', '/dev/null', 'w'], + ]; if (!self::$server = @proc_open('exec php -S localhost:8054', $spec, $pipes, __DIR__.'/Fixtures/response-functional')) { self::markTestSkipped('PHP server unable to start.'); } @@ -52,7 +52,7 @@ public function testCookie($fixture) public function provideCookie() { foreach (glob(__DIR__.'/Fixtures/response-functional/*.php') as $file) { - yield array(pathinfo($file, PATHINFO_FILENAME)); + yield [pathinfo($file, PATHINFO_FILENAME)]; } } } diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index 06e2d41d0..93aacf24d 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -22,7 +22,7 @@ class ResponseHeaderBagTest extends TestCase { public function testAllPreserveCase() { - $headers = array( + $headers = [ 'fOo' => 'BAR', 'ETag' => 'xyzzy', 'Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ==', @@ -30,7 +30,7 @@ public function testAllPreserveCase() 'WWW-Authenticate' => 'Basic realm="WallyWorld"', 'X-UA-Compatible' => 'IE=edge,chrome=1', 'X-XSS-Protection' => '1; mode=block', - ); + ]; $bag = new ResponseHeaderBag($headers); $allPreservedCase = $bag->allPreserveCase(); @@ -42,45 +42,45 @@ public function testAllPreserveCase() public function testCacheControlHeader() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); - $bag = new ResponseHeaderBag(array('Cache-Control' => 'public')); + $bag = new ResponseHeaderBag(['Cache-Control' => 'public']); $this->assertEquals('public', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('public')); - $bag = new ResponseHeaderBag(array('ETag' => 'abcde')); + $bag = new ResponseHeaderBag(['ETag' => 'abcde']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('private')); $this->assertTrue($bag->hasCacheControlDirective('must-revalidate')); $this->assertFalse($bag->hasCacheControlDirective('max-age')); - $bag = new ResponseHeaderBag(array('Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT')); + $bag = new ResponseHeaderBag(['Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array( + $bag = new ResponseHeaderBag([ 'Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT', 'Cache-Control' => 'max-age=3600', - )); + ]); $this->assertEquals('max-age=3600, private', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('Last-Modified' => 'abcde')); + $bag = new ResponseHeaderBag(['Last-Modified' => 'abcde']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('Etag' => 'abcde', 'Last-Modified' => 'abcde')); + $bag = new ResponseHeaderBag(['Etag' => 'abcde', 'Last-Modified' => 'abcde']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 'max-age=100')); + $bag = new ResponseHeaderBag(['cache-control' => 'max-age=100']); $this->assertEquals('max-age=100, private', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 's-maxage=100')); + $bag = new ResponseHeaderBag(['cache-control' => 's-maxage=100']); $this->assertEquals('s-maxage=100', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 'private, max-age=100')); + $bag = new ResponseHeaderBag(['cache-control' => 'private, max-age=100']); $this->assertEquals('max-age=100, private', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 'public, max-age=100')); + $bag = new ResponseHeaderBag(['cache-control' => 'public, max-age=100']); $this->assertEquals('max-age=100, public', $bag->get('Cache-Control')); $bag = new ResponseHeaderBag(); @@ -88,7 +88,7 @@ public function testCacheControlHeader() $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); $bag = new ResponseHeaderBag(); - $bag->set('Cache-Control', array('public', 'must-revalidate')); + $bag->set('Cache-Control', ['public', 'must-revalidate']); $this->assertCount(1, $bag->get('Cache-Control', null, false)); $this->assertEquals('must-revalidate, public', $bag->get('Cache-Control')); @@ -101,7 +101,7 @@ public function testCacheControlHeader() public function testCacheControlClone() { - $headers = array('foo' => 'bar'); + $headers = ['foo' => 'bar']; $bag1 = new ResponseHeaderBag($headers); $bag2 = new ResponseHeaderBag($bag1->allPreserveCase()); $this->assertEquals($bag1->allPreserveCase(), $bag2->allPreserveCase()); @@ -109,7 +109,7 @@ public function testCacheControlClone() public function testToStringIncludesCookieHeaders() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $bag->setCookie(new Cookie('foo', 'bar')); $this->assertSetCookieHeader('foo=bar; path=/; httponly', $bag); @@ -121,7 +121,7 @@ public function testToStringIncludesCookieHeaders() public function testClearCookieSecureNotHttpOnly() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $bag->clearCookie('foo', '/', null, true, false); @@ -130,23 +130,23 @@ public function testClearCookieSecureNotHttpOnly() public function testReplace() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); - $bag->replace(array('Cache-Control' => 'public')); + $bag->replace(['Cache-Control' => 'public']); $this->assertEquals('public', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('public')); } public function testReplaceWithRemove() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); $bag->remove('Cache-Control'); - $bag->replace(array()); + $bag->replace([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); } @@ -161,12 +161,12 @@ public function testCookiesWithSameNames() $this->assertCount(4, $bag->getCookies()); $this->assertEquals('foo=bar; path=/path/foo; domain=foo.bar; httponly', $bag->get('set-cookie')); - $this->assertEquals(array( + $this->assertEquals([ 'foo=bar; path=/path/foo; domain=foo.bar; httponly', 'foo=bar; path=/path/bar; domain=foo.bar; httponly', 'foo=bar; path=/path/bar; domain=bar.foo; httponly', 'foo=bar; path=/; httponly', - ), $bag->get('set-cookie', null, false)); + ], $bag->get('set-cookie', null, false)); $this->assertSetCookieHeader('foo=bar; path=/path/foo; domain=foo.bar; httponly', $bag); $this->assertSetCookieHeader('foo=bar; path=/path/bar; domain=foo.bar; httponly', $bag); @@ -228,16 +228,16 @@ public function testSetCookieHeader() { $bag = new ResponseHeaderBag(); $bag->set('set-cookie', 'foo=bar'); - $this->assertEquals(array(new Cookie('foo', 'bar', 0, '/', null, false, false, true)), $bag->getCookies()); + $this->assertEquals([new Cookie('foo', 'bar', 0, '/', null, false, false, true)], $bag->getCookies()); $bag->set('set-cookie', 'foo2=bar2', false); - $this->assertEquals(array( + $this->assertEquals([ new Cookie('foo', 'bar', 0, '/', null, false, false, true), new Cookie('foo2', 'bar2', 0, '/', null, false, false, true), - ), $bag->getCookies()); + ], $bag->getCookies()); $bag->remove('set-cookie'); - $this->assertEquals(array(), $bag->getCookies()); + $this->assertEquals([], $bag->getCookies()); } /** @@ -280,20 +280,20 @@ public function testToStringDoesntMessUpHeaders() (string) $headers; $allHeaders = $headers->allPreserveCase(); - $this->assertEquals(array('http://www.symfony.com'), $allHeaders['Location']); - $this->assertEquals(array('text/html'), $allHeaders['Content-type']); + $this->assertEquals(['http://www.symfony.com'], $allHeaders['Location']); + $this->assertEquals(['text/html'], $allHeaders['Content-type']); } public function provideMakeDisposition() { - return array( - array('attachment', 'foo.html', 'foo.html', 'attachment; filename="foo.html"'), - array('attachment', 'foo.html', '', 'attachment; filename="foo.html"'), - array('attachment', 'foo bar.html', '', 'attachment; filename="foo bar.html"'), - array('attachment', 'foo "bar".html', '', 'attachment; filename="foo \\"bar\\".html"'), - array('attachment', 'foo%20bar.html', 'foo bar.html', 'attachment; filename="foo bar.html"; filename*=utf-8\'\'foo%2520bar.html'), - array('attachment', 'föö.html', 'foo.html', 'attachment; filename="foo.html"; filename*=utf-8\'\'f%C3%B6%C3%B6.html'), - ); + return [ + ['attachment', 'foo.html', 'foo.html', 'attachment; filename="foo.html"'], + ['attachment', 'foo.html', '', 'attachment; filename="foo.html"'], + ['attachment', 'foo bar.html', '', 'attachment; filename="foo bar.html"'], + ['attachment', 'foo "bar".html', '', 'attachment; filename="foo \\"bar\\".html"'], + ['attachment', 'foo%20bar.html', 'foo bar.html', 'attachment; filename="foo bar.html"; filename*=utf-8\'\'foo%2520bar.html'], + ['attachment', 'föö.html', 'foo.html', 'attachment; filename="foo.html"; filename*=utf-8\'\'f%C3%B6%C3%B6.html'], + ]; } /** @@ -309,14 +309,14 @@ public function testMakeDispositionFail($disposition, $filename) public function provideMakeDispositionFail() { - return array( - array('attachment', 'foo%20bar.html'), - array('attachment', 'foo/bar.html'), - array('attachment', '/foo.html'), - array('attachment', 'foo\bar.html'), - array('attachment', '\foo.html'), - array('attachment', 'föö.html'), - ); + return [ + ['attachment', 'foo%20bar.html'], + ['attachment', 'foo/bar.html'], + ['attachment', '/foo.html'], + ['attachment', 'foo\bar.html'], + ['attachment', '\foo.html'], + ['attachment', 'föö.html'], + ]; } public function testDateHeaderAddedOnCreation() @@ -332,7 +332,7 @@ public function testDateHeaderAddedOnCreation() public function testDateHeaderCanBeSetOnCreation() { $someDate = 'Thu, 23 Mar 2017 09:15:12 GMT'; - $bag = new ResponseHeaderBag(array('Date' => $someDate)); + $bag = new ResponseHeaderBag(['Date' => $someDate]); $this->assertEquals($someDate, $bag->get('Date')); } @@ -340,7 +340,7 @@ public function testDateHeaderCanBeSetOnCreation() public function testDateHeaderWillBeRecreatedWhenRemoved() { $someDate = 'Thu, 23 Mar 2017 09:15:12 GMT'; - $bag = new ResponseHeaderBag(array('Date' => $someDate)); + $bag = new ResponseHeaderBag(['Date' => $someDate]); $bag->remove('Date'); // a (new) Date header is still present @@ -351,7 +351,7 @@ public function testDateHeaderWillBeRecreatedWhenRemoved() public function testDateHeaderWillBeRecreatedWhenHeadersAreReplaced() { $bag = new ResponseHeaderBag(); - $bag->replace(array()); + $bag->replace([]); $this->assertTrue($bag->has('Date')); } diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 43fa9b70a..f6fb1309e 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -21,7 +21,7 @@ class ResponseTest extends ResponseTestCase { public function testCreate() { - $response = Response::create('foo', 301, array('Foo' => 'bar')); + $response = Response::create('foo', 301, ['Foo' => 'bar']); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); $this->assertEquals(301, $response->getStatusCode()); @@ -253,10 +253,10 @@ public function testIsNotModifiedIfModifiedSinceAndEtagWithoutLastModified() public function testIsValidateable() { - $response = new Response('', 200, array('Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822))); + $response = new Response('', 200, ['Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)]); $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present'); - $response = new Response('', 200, array('ETag' => '"12345"')); + $response = new Response('', 200, ['ETag' => '"12345"']); $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if ETag is present'); $response = new Response(); @@ -266,7 +266,7 @@ public function testIsValidateable() public function testGetDate() { $oneHourAgo = $this->createDateTimeOneHourAgo(); - $response = new Response('', 200, array('Date' => $oneHourAgo->format(DATE_RFC2822))); + $response = new Response('', 200, ['Date' => $oneHourAgo->format(DATE_RFC2822)]); $date = $response->getDate(); $this->assertEquals($oneHourAgo->getTimestamp(), $date->getTimestamp(), '->getDate() returns the Date header if present'); @@ -274,7 +274,7 @@ public function testGetDate() $date = $response->getDate(); $this->assertEquals(time(), $date->getTimestamp(), '->getDate() returns the current Date if no Date header present'); - $response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822))); + $response = new Response('', 200, ['Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)]); $now = $this->createDateTimeNow(); $response->headers->set('Date', $now->format(DATE_RFC2822)); $date = $response->getDate(); @@ -414,21 +414,21 @@ public function testGetSetProtocolVersion() public function testGetVary() { $response = new Response(); - $this->assertEquals(array(), $response->getVary(), '->getVary() returns an empty array if no Vary header is present'); + $this->assertEquals([], $response->getVary(), '->getVary() returns an empty array if no Vary header is present'); $response = new Response(); $response->headers->set('Vary', 'Accept-Language'); - $this->assertEquals(array('Accept-Language'), $response->getVary(), '->getVary() parses a single header name value'); + $this->assertEquals(['Accept-Language'], $response->getVary(), '->getVary() parses a single header name value'); $response = new Response(); $response->headers->set('Vary', 'Accept-Language User-Agent X-Foo'); - $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by spaces'); + $this->assertEquals(['Accept-Language', 'User-Agent', 'X-Foo'], $response->getVary(), '->getVary() parses multiple header name values separated by spaces'); $response = new Response(); $response->headers->set('Vary', 'Accept-Language,User-Agent, X-Foo'); - $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by commas'); + $this->assertEquals(['Accept-Language', 'User-Agent', 'X-Foo'], $response->getVary(), '->getVary() parses multiple header name values separated by commas'); - $vary = array('Accept-Language', 'User-Agent', 'X-foo'); + $vary = ['Accept-Language', 'User-Agent', 'X-foo']; $response = new Response(); $response->headers->set('Vary', $vary); @@ -443,18 +443,18 @@ public function testSetVary() { $response = new Response(); $response->setVary('Accept-Language'); - $this->assertEquals(array('Accept-Language'), $response->getVary()); + $this->assertEquals(['Accept-Language'], $response->getVary()); $response->setVary('Accept-Language, User-Agent'); - $this->assertEquals(array('Accept-Language', 'User-Agent'), $response->getVary(), '->setVary() replace the vary header by default'); + $this->assertEquals(['Accept-Language', 'User-Agent'], $response->getVary(), '->setVary() replace the vary header by default'); $response->setVary('X-Foo', false); - $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->setVary() doesn\'t wipe out earlier Vary headers if replace is set to false'); + $this->assertEquals(['Accept-Language', 'User-Agent', 'X-Foo'], $response->getVary(), '->setVary() doesn\'t wipe out earlier Vary headers if replace is set to false'); } public function testDefaultContentType() { - $headerMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\ResponseHeaderBag')->setMethods(array('set'))->getMock(); + $headerMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\ResponseHeaderBag')->setMethods(['set'])->getMock(); $headerMock->expects($this->at(0)) ->method('set') ->with('Content-Type', 'text/html'); @@ -578,53 +578,53 @@ public function testSetCache() $response = new Response(); //array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public') try { - $response->setCache(array('wrong option' => 'value')); + $response->setCache(['wrong option' => 'value']); $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported'); } catch (\Exception $e) { $this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported'); $this->assertContains('"wrong option"', $e->getMessage()); } - $options = array('etag' => '"whatever"'); + $options = ['etag' => '"whatever"']; $response->setCache($options); $this->assertEquals($response->getEtag(), '"whatever"'); $now = $this->createDateTimeNow(); - $options = array('last_modified' => $now); + $options = ['last_modified' => $now]; $response->setCache($options); $this->assertEquals($response->getLastModified()->getTimestamp(), $now->getTimestamp()); - $options = array('max_age' => 100); + $options = ['max_age' => 100]; $response->setCache($options); $this->assertEquals($response->getMaxAge(), 100); - $options = array('s_maxage' => 200); + $options = ['s_maxage' => 200]; $response->setCache($options); $this->assertEquals($response->getMaxAge(), 200); $this->assertTrue($response->headers->hasCacheControlDirective('public')); $this->assertFalse($response->headers->hasCacheControlDirective('private')); - $response->setCache(array('public' => true)); + $response->setCache(['public' => true]); $this->assertTrue($response->headers->hasCacheControlDirective('public')); $this->assertFalse($response->headers->hasCacheControlDirective('private')); - $response->setCache(array('public' => false)); + $response->setCache(['public' => false]); $this->assertFalse($response->headers->hasCacheControlDirective('public')); $this->assertTrue($response->headers->hasCacheControlDirective('private')); - $response->setCache(array('private' => true)); + $response->setCache(['private' => true]); $this->assertFalse($response->headers->hasCacheControlDirective('public')); $this->assertTrue($response->headers->hasCacheControlDirective('private')); - $response->setCache(array('private' => false)); + $response->setCache(['private' => false]); $this->assertTrue($response->headers->hasCacheControlDirective('public')); $this->assertFalse($response->headers->hasCacheControlDirective('private')); - $response->setCache(array('immutable' => true)); + $response->setCache(['immutable' => true]); $this->assertTrue($response->headers->hasCacheControlDirective('immutable')); - $response->setCache(array('immutable' => false)); + $response->setCache(['immutable' => false]); $this->assertFalse($response->headers->hasCacheControlDirective('immutable')); } @@ -725,14 +725,14 @@ public function testSetStatusCode($code, $text, $expectedText) public function getStatusCodeFixtures() { - return array( - array('200', null, 'OK'), - array('200', false, ''), - array('200', 'foo', 'foo'), - array('199', null, 'unknown status'), - array('199', false, ''), - array('199', 'foo', 'foo'), - ); + return [ + ['200', null, 'OK'], + ['200', false, ''], + ['200', 'foo', 'foo'], + ['199', null, 'unknown status'], + ['199', false, ''], + ['199', 'foo', 'foo'], + ]; } public function testIsInformational() @@ -746,7 +746,7 @@ public function testIsInformational() public function testIsRedirectRedirection() { - foreach (array(301, 302, 303, 307) as $code) { + foreach ([301, 302, 303, 307] as $code) { $response = new Response('', $code); $this->assertTrue($response->isRedirection()); $this->assertTrue($response->isRedirect()); @@ -764,7 +764,7 @@ public function testIsRedirectRedirection() $this->assertFalse($response->isRedirection()); $this->assertFalse($response->isRedirect()); - $response = new Response('', 301, array('Location' => '/good-uri')); + $response = new Response('', 301, ['Location' => '/good-uri']); $this->assertFalse($response->isRedirect('/bad-uri')); $this->assertTrue($response->isRedirect('/good-uri')); } @@ -780,7 +780,7 @@ public function testIsNotFound() public function testIsEmpty() { - foreach (array(204, 304) as $code) { + foreach ([204, 304] as $code) { $response = new Response('', $code); $this->assertTrue($response->isEmpty()); } @@ -829,7 +829,7 @@ public function testHasVary() public function testSetEtag() { - $response = new Response('', 200, array('ETag' => '"12345"')); + $response = new Response('', 200, ['ETag' => '"12345"']); $response->setEtag(); $this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null'); @@ -859,7 +859,7 @@ public function testSettersAreChainable() { $response = new Response(); - $setters = array( + $setters = [ 'setProtocolVersion' => '1.0', 'setCharset' => 'UTF-8', 'setPublic' => null, @@ -870,7 +870,7 @@ public function testSettersAreChainable() 'setSharedMaxAge' => 1, 'setTtl' => 1, 'setClientTtl' => 1, - ); + ]; foreach ($setters as $setter => $arg) { $this->assertEquals($response, $response->{$setter}($arg)); @@ -889,20 +889,20 @@ public function testNoDeprecationsAreTriggered() public function validContentProvider() { - return array( - 'obj' => array(new StringableObject()), - 'string' => array('Foo'), - 'int' => array(2), - ); + return [ + 'obj' => [new StringableObject()], + 'string' => ['Foo'], + 'int' => [2], + ]; } public function invalidContentProvider() { - return array( - 'obj' => array(new \stdClass()), - 'array' => array(array()), - 'bool' => array(true, '1'), - ); + return [ + 'obj' => [new \stdClass()], + 'array' => [[]], + 'bool' => [true, '1'], + ]; } protected function createDateTimeOneHourAgo() @@ -942,19 +942,19 @@ public function ianaCodesReasonPhrasesProvider() $ianaHttpStatusCodes = new \DOMDocument(); - libxml_set_streams_context(stream_context_create(array( - 'http' => array( + libxml_set_streams_context(stream_context_create([ + 'http' => [ 'method' => 'GET', 'timeout' => 30, - ), - ))); + ], + ])); $ianaHttpStatusCodes->load('https://www.iana.org/assignments/http-status-codes/http-status-codes.xml'); if (!$ianaHttpStatusCodes->relaxNGValidate(__DIR__.'/schema/http-status-codes.rng')) { self::fail('Invalid IANA\'s HTTP status code list.'); } - $ianaCodesReasonPhrases = array(); + $ianaCodesReasonPhrases = []; $xpath = new \DOMXPath($ianaHttpStatusCodes); $xpath->registerNamespace('ns', 'http://www.iana.org/assignments'); @@ -964,16 +964,16 @@ public function ianaCodesReasonPhrasesProvider() $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, ['Unassigned', '(Unused)'], true)) { continue; } if (preg_match('/^([0-9]+)\s*\-\s*([0-9]+)$/', $value, $matches)) { for ($value = $matches[1]; $value <= $matches[2]; ++$value) { - $ianaCodesReasonPhrases[] = array($value, $description); + $ianaCodesReasonPhrases[] = [$value, $description]; } } else { - $ianaCodesReasonPhrases[] = array($value, $description); + $ianaCodesReasonPhrases[] = [$value, $description]; } } diff --git a/Tests/ServerBagTest.php b/Tests/ServerBagTest.php index f8becec5a..0663b118e 100644 --- a/Tests/ServerBagTest.php +++ b/Tests/ServerBagTest.php @@ -23,7 +23,7 @@ class ServerBagTest extends TestCase { public function testShouldExtractHeadersFromServerArray() { - $server = array( + $server = [ 'SOME_SERVER_VARIABLE' => 'value', 'SOME_SERVER_VARIABLE2' => 'value', 'ROOT' => 'value', @@ -32,45 +32,45 @@ public function testShouldExtractHeadersFromServerArray() 'HTTP_ETAG' => 'asdf', 'PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'bar', - ); + ]; $bag = new ServerBag($server); - $this->assertEquals(array( + $this->assertEquals([ 'CONTENT_TYPE' => 'text/html', 'CONTENT_LENGTH' => '0', 'ETAG' => 'asdf', 'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'), 'PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'bar', - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testHttpPasswordIsOptional() { - $bag = new ServerBag(array('PHP_AUTH_USER' => 'foo')); + $bag = new ServerBag(['PHP_AUTH_USER' => 'foo']); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => 'Basic '.base64_encode('foo:'), 'PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => '', - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testHttpBasicAuthWithPhpCgi() { - $bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'))); + $bag = new ServerBag(['HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:bar')]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'), 'PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'bar', - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testHttpBasicAuthWithPhpCgiBogus() { - $bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic_'.base64_encode('foo:bar'))); + $bag = new ServerBag(['HTTP_AUTHORIZATION' => 'Basic_'.base64_encode('foo:bar')]); // Username and passwords should not be set as the header is bogus $headers = $bag->getHeaders(); @@ -80,41 +80,41 @@ public function testHttpBasicAuthWithPhpCgiBogus() public function testHttpBasicAuthWithPhpCgiRedirect() { - $bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => 'Basic '.base64_encode('username:pass:word'))); + $bag = new ServerBag(['REDIRECT_HTTP_AUTHORIZATION' => 'Basic '.base64_encode('username:pass:word')]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => 'Basic '.base64_encode('username:pass:word'), 'PHP_AUTH_USER' => 'username', 'PHP_AUTH_PW' => 'pass:word', - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testHttpBasicAuthWithPhpCgiEmptyPassword() { - $bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:'))); + $bag = new ServerBag(['HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:')]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => 'Basic '.base64_encode('foo:'), 'PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => '', - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testHttpDigestAuthWithPhpCgi() { $digest = 'Digest username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"'; - $bag = new ServerBag(array('HTTP_AUTHORIZATION' => $digest)); + $bag = new ServerBag(['HTTP_AUTHORIZATION' => $digest]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => $digest, 'PHP_AUTH_DIGEST' => $digest, - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testHttpDigestAuthWithPhpCgiBogus() { $digest = 'Digest_username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"'; - $bag = new ServerBag(array('HTTP_AUTHORIZATION' => $digest)); + $bag = new ServerBag(['HTTP_AUTHORIZATION' => $digest]); // Username and passwords should not be set as the header is bogus $headers = $bag->getHeaders(); @@ -125,32 +125,32 @@ public function testHttpDigestAuthWithPhpCgiBogus() public function testHttpDigestAuthWithPhpCgiRedirect() { $digest = 'Digest username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"'; - $bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => $digest)); + $bag = new ServerBag(['REDIRECT_HTTP_AUTHORIZATION' => $digest]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => $digest, 'PHP_AUTH_DIGEST' => $digest, - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testOAuthBearerAuth() { $headerContent = 'Bearer L-yLEOr9zhmUYRkzN1jwwxwQ-PBNiKDc8dgfB4hTfvo'; - $bag = new ServerBag(array('HTTP_AUTHORIZATION' => $headerContent)); + $bag = new ServerBag(['HTTP_AUTHORIZATION' => $headerContent]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => $headerContent, - ), $bag->getHeaders()); + ], $bag->getHeaders()); } public function testOAuthBearerAuthWithRedirect() { $headerContent = 'Bearer L-yLEOr9zhmUYRkzN1jwwxwQ-PBNiKDc8dgfB4hTfvo'; - $bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => $headerContent)); + $bag = new ServerBag(['REDIRECT_HTTP_AUTHORIZATION' => $headerContent]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => $headerContent, - ), $bag->getHeaders()); + ], $bag->getHeaders()); } /** @@ -159,12 +159,12 @@ public function testOAuthBearerAuthWithRedirect() public function testItDoesNotOverwriteTheAuthorizationHeaderIfItIsAlreadySet() { $headerContent = 'Bearer L-yLEOr9zhmUYRkzN1jwwxwQ-PBNiKDc8dgfB4hTfvo'; - $bag = new ServerBag(array('PHP_AUTH_USER' => 'foo', 'HTTP_AUTHORIZATION' => $headerContent)); + $bag = new ServerBag(['PHP_AUTH_USER' => 'foo', 'HTTP_AUTHORIZATION' => $headerContent]); - $this->assertEquals(array( + $this->assertEquals([ 'AUTHORIZATION' => $headerContent, 'PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => '', - ), $bag->getHeaders()); + ], $bag->getHeaders()); } } diff --git a/Tests/Session/Attribute/AttributeBagTest.php b/Tests/Session/Attribute/AttributeBagTest.php index 43644e23e..3f2f7b3c8 100644 --- a/Tests/Session/Attribute/AttributeBagTest.php +++ b/Tests/Session/Attribute/AttributeBagTest.php @@ -21,7 +21,7 @@ */ class AttributeBagTest extends TestCase { - private $array = array(); + private $array = []; /** * @var AttributeBag @@ -30,21 +30,21 @@ class AttributeBagTest extends TestCase protected function setUp() { - $this->array = array( + $this->array = [ 'hello' => 'world', 'always' => 'be happy', 'user.login' => 'drak', - 'csrf.token' => array( + 'csrf.token' => [ 'a' => '1234', 'b' => '4321', - ), - 'category' => array( - 'fishing' => array( + ], + 'category' => [ + 'fishing' => [ 'first' => 'cod', 'second' => 'sole', - ), - ), - ); + ], + ], + ]; $this->bag = new AttributeBag('_sf2'); $this->bag->initialize($this->array); } @@ -52,7 +52,7 @@ protected function setUp() protected function tearDown() { $this->bag = null; - $this->array = array(); + $this->array = []; } public function testInitialize() @@ -60,7 +60,7 @@ public function testInitialize() $bag = new AttributeBag(); $bag->initialize($this->array); $this->assertEquals($this->array, $bag->all()); - $array = array('should' => 'change'); + $array = ['should' => 'change']; $bag->initialize($array); $this->assertEquals($array, $bag->all()); } @@ -122,7 +122,7 @@ public function testAll() public function testReplace() { - $array = array(); + $array = []; $array['name'] = 'jack'; $array['foo.bar'] = 'beep'; $this->bag->replace($array); @@ -150,22 +150,22 @@ public function testRemove() public function testClear() { $this->bag->clear(); - $this->assertEquals(array(), $this->bag->all()); + $this->assertEquals([], $this->bag->all()); } public function attributesProvider() { - return array( - array('hello', 'world', true), - array('always', 'be happy', true), - array('user.login', 'drak', true), - array('csrf.token', array('a' => '1234', 'b' => '4321'), true), - array('category', array('fishing' => array('first' => 'cod', 'second' => 'sole')), true), - array('user2.login', null, false), - array('never', null, false), - array('bye', null, false), - array('bye/for/now', null, false), - ); + return [ + ['hello', 'world', true], + ['always', 'be happy', true], + ['user.login', 'drak', true], + ['csrf.token', ['a' => '1234', 'b' => '4321'], true], + ['category', ['fishing' => ['first' => 'cod', 'second' => 'sole']], true], + ['user2.login', null, false], + ['never', null, false], + ['bye', null, false], + ['bye/for/now', null, false], + ]; } public function testGetIterator() diff --git a/Tests/Session/Attribute/NamespacedAttributeBagTest.php b/Tests/Session/Attribute/NamespacedAttributeBagTest.php index ec4cd5ad1..6b4bb17d6 100644 --- a/Tests/Session/Attribute/NamespacedAttributeBagTest.php +++ b/Tests/Session/Attribute/NamespacedAttributeBagTest.php @@ -21,7 +21,7 @@ */ class NamespacedAttributeBagTest extends TestCase { - private $array = array(); + private $array = []; /** * @var NamespacedAttributeBag @@ -30,21 +30,21 @@ class NamespacedAttributeBagTest extends TestCase protected function setUp() { - $this->array = array( + $this->array = [ 'hello' => 'world', 'always' => 'be happy', 'user.login' => 'drak', - 'csrf.token' => array( + 'csrf.token' => [ 'a' => '1234', 'b' => '4321', - ), - 'category' => array( - 'fishing' => array( + ], + 'category' => [ + 'fishing' => [ 'first' => 'cod', 'second' => 'sole', - ), - ), - ); + ], + ], + ]; $this->bag = new NamespacedAttributeBag('_sf2', '/'); $this->bag->initialize($this->array); } @@ -52,7 +52,7 @@ protected function setUp() protected function tearDown() { $this->bag = null; - $this->array = array(); + $this->array = []; } public function testInitialize() @@ -60,7 +60,7 @@ public function testInitialize() $bag = new NamespacedAttributeBag(); $bag->initialize($this->array); $this->assertEquals($this->array, $this->bag->all()); - $array = array('should' => 'not stick'); + $array = ['should' => 'not stick']; $bag->initialize($array); // should have remained the same @@ -139,7 +139,7 @@ public function testAll() public function testReplace() { - $array = array(); + $array = []; $array['name'] = 'jack'; $array['foo.bar'] = 'beep'; $this->bag->replace($array); @@ -177,28 +177,28 @@ public function testRemoveNonexistingNamespacedAttribute() public function testClear() { $this->bag->clear(); - $this->assertEquals(array(), $this->bag->all()); + $this->assertEquals([], $this->bag->all()); } public function attributesProvider() { - return array( - array('hello', 'world', true), - array('always', 'be happy', true), - array('user.login', 'drak', true), - array('csrf.token', array('a' => '1234', 'b' => '4321'), true), - array('csrf.token/a', '1234', true), - array('csrf.token/b', '4321', true), - array('category', array('fishing' => array('first' => 'cod', 'second' => 'sole')), true), - array('category/fishing', array('first' => 'cod', 'second' => 'sole'), true), - array('category/fishing/missing/first', null, false), - array('category/fishing/first', 'cod', true), - array('category/fishing/second', 'sole', true), - array('category/fishing/missing/second', null, false), - array('user2.login', null, false), - array('never', null, false), - array('bye', null, false), - array('bye/for/now', null, false), - ); + return [ + ['hello', 'world', true], + ['always', 'be happy', true], + ['user.login', 'drak', true], + ['csrf.token', ['a' => '1234', 'b' => '4321'], true], + ['csrf.token/a', '1234', true], + ['csrf.token/b', '4321', true], + ['category', ['fishing' => ['first' => 'cod', 'second' => 'sole']], true], + ['category/fishing', ['first' => 'cod', 'second' => 'sole'], true], + ['category/fishing/missing/first', null, false], + ['category/fishing/first', 'cod', true], + ['category/fishing/second', 'sole', true], + ['category/fishing/missing/second', null, false], + ['user2.login', null, false], + ['never', null, false], + ['bye', null, false], + ['bye/for/now', null, false], + ]; } } diff --git a/Tests/Session/Flash/AutoExpireFlashBagTest.php b/Tests/Session/Flash/AutoExpireFlashBagTest.php index fa8626ab9..b4e2c3a5a 100644 --- a/Tests/Session/Flash/AutoExpireFlashBagTest.php +++ b/Tests/Session/Flash/AutoExpireFlashBagTest.php @@ -26,13 +26,13 @@ class AutoExpireFlashBagTest extends TestCase */ private $bag; - protected $array = array(); + protected $array = []; protected function setUp() { parent::setUp(); $this->bag = new FlashBag(); - $this->array = array('new' => array('notice' => array('A previous flash message'))); + $this->array = ['new' => ['notice' => ['A previous flash message']]]; $this->bag->initialize($this->array); } @@ -45,16 +45,16 @@ protected function tearDown() public function testInitialize() { $bag = new FlashBag(); - $array = array('new' => array('notice' => array('A previous flash message'))); + $array = ['new' => ['notice' => ['A previous flash message']]]; $bag->initialize($array); - $this->assertEquals(array('A previous flash message'), $bag->peek('notice')); - $array = array('new' => array( - 'notice' => array('Something else'), - 'error' => array('a'), - )); + $this->assertEquals(['A previous flash message'], $bag->peek('notice')); + $array = ['new' => [ + 'notice' => ['Something else'], + 'error' => ['a'], + ]]; $bag->initialize($array); - $this->assertEquals(array('Something else'), $bag->peek('notice')); - $this->assertEquals(array('a'), $bag->peek('error')); + $this->assertEquals(['Something else'], $bag->peek('notice')); + $this->assertEquals(['a'], $bag->peek('error')); } public function testGetStorageKey() @@ -73,16 +73,16 @@ public function testGetSetName() public function testPeek() { - $this->assertEquals(array(), $this->bag->peek('non_existing')); - $this->assertEquals(array('default'), $this->bag->peek('non_existing', array('default'))); - $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice')); - $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice')); + $this->assertEquals([], $this->bag->peek('non_existing')); + $this->assertEquals(['default'], $this->bag->peek('non_existing', ['default'])); + $this->assertEquals(['A previous flash message'], $this->bag->peek('notice')); + $this->assertEquals(['A previous flash message'], $this->bag->peek('notice')); } public function testSet() { $this->bag->set('notice', 'Foo'); - $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice')); + $this->assertEquals(['A previous flash message'], $this->bag->peek('notice')); } public function testHas() @@ -93,43 +93,43 @@ public function testHas() public function testKeys() { - $this->assertEquals(array('notice'), $this->bag->keys()); + $this->assertEquals(['notice'], $this->bag->keys()); } public function testPeekAll() { - $array = array( - 'new' => array( + $array = [ + 'new' => [ 'notice' => 'Foo', 'error' => 'Bar', - ), - ); + ], + ]; $this->bag->initialize($array); - $this->assertEquals(array( + $this->assertEquals([ 'notice' => 'Foo', 'error' => 'Bar', - ), $this->bag->peekAll() + ], $this->bag->peekAll() ); - $this->assertEquals(array( + $this->assertEquals([ 'notice' => 'Foo', 'error' => 'Bar', - ), $this->bag->peekAll() + ], $this->bag->peekAll() ); } public function testGet() { - $this->assertEquals(array(), $this->bag->get('non_existing')); - $this->assertEquals(array('default'), $this->bag->get('non_existing', array('default'))); - $this->assertEquals(array('A previous flash message'), $this->bag->get('notice')); - $this->assertEquals(array(), $this->bag->get('notice')); + $this->assertEquals([], $this->bag->get('non_existing')); + $this->assertEquals(['default'], $this->bag->get('non_existing', ['default'])); + $this->assertEquals(['A previous flash message'], $this->bag->get('notice')); + $this->assertEquals([], $this->bag->get('notice')); } public function testSetAll() { - $this->bag->setAll(array('a' => 'first', 'b' => 'second')); + $this->bag->setAll(['a' => 'first', 'b' => 'second']); $this->assertFalse($this->bag->has('a')); $this->assertFalse($this->bag->has('b')); } @@ -138,17 +138,17 @@ public function testAll() { $this->bag->set('notice', 'Foo'); $this->bag->set('error', 'Bar'); - $this->assertEquals(array( - 'notice' => array('A previous flash message'), - ), $this->bag->all() + $this->assertEquals([ + 'notice' => ['A previous flash message'], + ], $this->bag->all() ); - $this->assertEquals(array(), $this->bag->all()); + $this->assertEquals([], $this->bag->all()); } public function testClear() { - $this->assertEquals(array('notice' => array('A previous flash message')), $this->bag->clear()); + $this->assertEquals(['notice' => ['A previous flash message']], $this->bag->clear()); } public function testDoNotRemoveTheNewFlashesWhenDisplayingTheExistingOnes() @@ -156,6 +156,6 @@ public function testDoNotRemoveTheNewFlashesWhenDisplayingTheExistingOnes() $this->bag->add('success', 'Something'); $this->bag->all(); - $this->assertEquals(array('new' => array('success' => array('Something')), 'display' => array()), $this->array); + $this->assertEquals(['new' => ['success' => ['Something']], 'display' => []], $this->array); } } diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index 905a1f751..6d8619e07 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -26,13 +26,13 @@ class FlashBagTest extends TestCase */ private $bag; - protected $array = array(); + protected $array = []; protected function setUp() { parent::setUp(); $this->bag = new FlashBag(); - $this->array = array('notice' => array('A previous flash message')); + $this->array = ['notice' => ['A previous flash message']]; $this->bag->initialize($this->array); } @@ -47,7 +47,7 @@ public function testInitialize() $bag = new FlashBag(); $bag->initialize($this->array); $this->assertEquals($this->array, $bag->peekAll()); - $array = array('should' => array('change')); + $array = ['should' => ['change']]; $bag->initialize($array); $this->assertEquals($array, $bag->peekAll()); } @@ -68,49 +68,49 @@ public function testGetSetName() public function testPeek() { - $this->assertEquals(array(), $this->bag->peek('non_existing')); - $this->assertEquals(array('default'), $this->bag->peek('not_existing', array('default'))); - $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice')); - $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice')); + $this->assertEquals([], $this->bag->peek('non_existing')); + $this->assertEquals(['default'], $this->bag->peek('not_existing', ['default'])); + $this->assertEquals(['A previous flash message'], $this->bag->peek('notice')); + $this->assertEquals(['A previous flash message'], $this->bag->peek('notice')); } public function testAdd() { - $tab = array('bar' => 'baz'); + $tab = ['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')); + $this->assertEquals(['lorem'], $this->bag->get('string_message')); + $this->assertEquals([new \stdClass()], $this->bag->get('object_message')); + $this->assertEquals([$tab], $this->bag->get('array_message')); } public function testGet() { - $this->assertEquals(array(), $this->bag->get('non_existing')); - $this->assertEquals(array('default'), $this->bag->get('not_existing', array('default'))); - $this->assertEquals(array('A previous flash message'), $this->bag->get('notice')); - $this->assertEquals(array(), $this->bag->get('notice')); + $this->assertEquals([], $this->bag->get('non_existing')); + $this->assertEquals(['default'], $this->bag->get('not_existing', ['default'])); + $this->assertEquals(['A previous flash message'], $this->bag->get('notice')); + $this->assertEquals([], $this->bag->get('notice')); } public function testAll() { $this->bag->set('notice', 'Foo'); $this->bag->set('error', 'Bar'); - $this->assertEquals(array( - 'notice' => array('Foo'), - 'error' => array('Bar'), ), $this->bag->all() + $this->assertEquals([ + 'notice' => ['Foo'], + 'error' => ['Bar'], ], $this->bag->all() ); - $this->assertEquals(array(), $this->bag->all()); + $this->assertEquals([], $this->bag->all()); } public function testSet() { $this->bag->set('notice', 'Foo'); $this->bag->set('notice', 'Bar'); - $this->assertEquals(array('Bar'), $this->bag->peek('notice')); + $this->assertEquals(['Bar'], $this->bag->peek('notice')); } public function testHas() @@ -121,7 +121,7 @@ public function testHas() public function testKeys() { - $this->assertEquals(array('notice'), $this->bag->keys()); + $this->assertEquals(['notice'], $this->bag->keys()); } public function testSetAll() @@ -130,28 +130,28 @@ public function testSetAll() $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->bag->setAll(['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()); + $this->assertSame(['unique_flash' => 'FooBar'], $this->bag->all()); + $this->assertSame([], $this->bag->all()); } public function testPeekAll() { $this->bag->set('notice', 'Foo'); $this->bag->set('error', 'Bar'); - $this->assertEquals(array( - 'notice' => array('Foo'), - 'error' => array('Bar'), - ), $this->bag->peekAll() + $this->assertEquals([ + 'notice' => ['Foo'], + 'error' => ['Bar'], + ], $this->bag->peekAll() ); $this->assertTrue($this->bag->has('notice')); $this->assertTrue($this->bag->has('error')); - $this->assertEquals(array( - 'notice' => array('Foo'), - 'error' => array('Bar'), - ), $this->bag->peekAll() + $this->assertEquals([ + 'notice' => ['Foo'], + 'error' => ['Bar'], + ], $this->bag->peekAll() ); } } diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index 63351e575..afa00fc7c 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -127,10 +127,10 @@ public function testHas($key, $value) public function testReplace() { - $this->session->replace(array('happiness' => 'be good', 'symfony' => 'awesome')); - $this->assertEquals(array('happiness' => 'be good', 'symfony' => 'awesome'), $this->session->all()); - $this->session->replace(array()); - $this->assertEquals(array(), $this->session->all()); + $this->session->replace(['happiness' => 'be good', 'symfony' => 'awesome']); + $this->assertEquals(['happiness' => 'be good', 'symfony' => 'awesome'], $this->session->all()); + $this->session->replace([]); + $this->assertEquals([], $this->session->all()); } /** @@ -150,16 +150,16 @@ public function testClear($key, $value) $this->session->set('hi', 'fabien'); $this->session->set($key, $value); $this->session->clear(); - $this->assertEquals(array(), $this->session->all()); + $this->assertEquals([], $this->session->all()); } public function setProvider() { - return array( - array('foo', 'bar', array('foo' => 'bar')), - array('foo.bar', 'too much beer', array('foo.bar' => 'too much beer')), - array('great', 'symfony is great', array('great' => 'symfony is great')), - ); + return [ + ['foo', 'bar', ['foo' => 'bar']], + ['foo.bar', 'too much beer', ['foo.bar' => 'too much beer']], + ['great', 'symfony is great', ['great' => 'symfony is great']], + ]; } /** @@ -170,14 +170,14 @@ public function testRemove($key, $value) $this->session->set('hi.world', 'have a nice day'); $this->session->set($key, $value); $this->session->remove($key); - $this->assertEquals(array('hi.world' => 'have a nice day'), $this->session->all()); + $this->assertEquals(['hi.world' => 'have a nice day'], $this->session->all()); } public function testInvalidate() { $this->session->set('invalidate', 123); $this->session->invalidate(); - $this->assertEquals(array(), $this->session->all()); + $this->assertEquals([], $this->session->all()); } public function testMigrate() @@ -216,7 +216,7 @@ public function testGetFlashBag() public function testGetIterator() { - $attributes = array('hello' => 'world', 'symfony' => 'rocks'); + $attributes = ['hello' => 'world', 'symfony' => 'rocks']; foreach ($attributes as $key => $val) { $this->session->set($key, $val); } diff --git a/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php index 3ac081e38..98bc67bca 100644 --- a/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php @@ -22,10 +22,10 @@ class AbstractSessionHandlerTest extends TestCase public static function setUpBeforeClass() { - $spec = array( - 1 => array('file', '/dev/null', 'w'), - 2 => array('file', '/dev/null', 'w'), - ); + $spec = [ + 1 => ['file', '/dev/null', 'w'], + 2 => ['file', '/dev/null', 'w'], + ]; if (!self::$server = @proc_open('exec php -S localhost:8053', $spec, $pipes, __DIR__.'/Fixtures')) { self::markTestSkipped('PHP server unable to start.'); } @@ -45,7 +45,7 @@ public static function tearDownAfterClass() */ public function testSession($fixture) { - $context = array('http' => array('header' => "Cookie: sid=123abc\r\n")); + $context = ['http' => ['header' => "Cookie: sid=123abc\r\n"]]; $context = stream_context_create($context); $result = file_get_contents(sprintf('http://localhost:8053/%s.php', $fixture), false, $context); @@ -55,7 +55,7 @@ public function testSession($fixture) public function provideSession() { foreach (glob(__DIR__.'/Fixtures/*.php') as $file) { - yield array(pathinfo($file, PATHINFO_FILENAME)); + yield [pathinfo($file, PATHINFO_FILENAME)]; } } } diff --git a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php index d3d31762a..68daa4e5c 100644 --- a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php @@ -41,7 +41,7 @@ protected function setUp() $this->memcache = $this->getMockBuilder('Memcache')->getMock(); $this->storage = new MemcacheSessionHandler( $this->memcache, - array('prefix' => self::PREFIX, 'expiretime' => self::TTL) + ['prefix' => self::PREFIX, 'expiretime' => self::TTL] ); } @@ -117,12 +117,12 @@ public function testSupportedOptions($options, $supported) public function getOptionFixtures() { - return array( - array(array('prefix' => 'session'), true), - array(array('expiretime' => 100), true), - array(array('prefix' => 'session', 'expiretime' => 200), true), - array(array('expiretime' => 100, 'foo' => 'bar'), false), - ); + return [ + [['prefix' => 'session'], true], + [['expiretime' => 100], true], + [['prefix' => 'session', 'expiretime' => 200], true], + [['expiretime' => 100, 'foo' => 'bar'], false], + ]; } public function testGetConnection() diff --git a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php index 2a1148010..70bc3d146 100644 --- a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php @@ -45,7 +45,7 @@ protected function setUp() $this->memcached = $this->getMockBuilder('Memcached')->getMock(); $this->storage = new MemcachedSessionHandler( $this->memcached, - array('prefix' => self::PREFIX, 'expiretime' => self::TTL) + ['prefix' => self::PREFIX, 'expiretime' => self::TTL] ); } @@ -121,12 +121,12 @@ public function testSupportedOptions($options, $supported) public function getOptionFixtures() { - return array( - array(array('prefix' => 'session'), true), - array(array('expiretime' => 100), true), - array(array('prefix' => 'session', 'expiretime' => 200), true), - array(array('expiretime' => 100, 'foo' => 'bar'), false), - ); + return [ + [['prefix' => 'session'], true], + [['expiretime' => 100], true], + [['prefix' => 'session', 'expiretime' => 200], true], + [['expiretime' => 100, 'foo' => 'bar'], false], + ]; } public function testGetConnection() diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 186fc0a2d..6f2742ca7 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -50,14 +50,14 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->options = array( + $this->options = [ 'id_field' => '_id', 'data_field' => 'data', 'time_field' => 'time', 'expiry_field' => 'expires_at', 'database' => 'sf2-test', 'collection' => 'session-test', - ); + ]; $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); } @@ -75,7 +75,7 @@ public function testConstructorShouldThrowExceptionForInvalidMongo() */ public function testConstructorShouldThrowExceptionForMissingOptions() { - new MongoDbSessionHandler($this->mongo, array()); + new MongoDbSessionHandler($this->mongo, []); } public function testOpenMethodAlwaysReturnTrue() @@ -118,9 +118,9 @@ public function testRead() $this->assertGreaterThanOrEqual($criteria[$this->options['expiry_field']]['$gte']->sec, $testTimeout); } - $fields = array( + $fields = [ $this->options['id_field'] => 'foo', - ); + ]; if (phpversion('mongodb')) { $fields[$this->options['data_field']] = new \MongoDB\BSON\Binary('bar', \MongoDB\BSON\Binary::TYPE_OLD_BINARY); @@ -145,19 +145,19 @@ public function testWrite() ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); - $data = array(); + $data = []; $methodName = phpversion('mongodb') ? 'updateOne' : 'update'; $collection->expects($this->once()) ->method($methodName) ->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) { - $this->assertEquals(array($this->options['id_field'] => 'foo'), $criteria); + $this->assertEquals([$this->options['id_field'] => 'foo'], $criteria); if (phpversion('mongodb')) { - $this->assertEquals(array('upsert' => true), $options); + $this->assertEquals(['upsert' => true], $options); } else { - $this->assertEquals(array('upsert' => true, 'multiple' => false), $options); + $this->assertEquals(['upsert' => true, 'multiple' => false], $options); } $data = $updateData['$set']; @@ -181,14 +181,14 @@ public function testWrite() public function testWriteWhenUsingExpiresField() { - $this->options = array( + $this->options = [ 'id_field' => '_id', 'data_field' => 'data', 'time_field' => 'time', 'database' => 'sf2-test', 'collection' => 'session-test', 'expiry_field' => 'expiresAt', - ); + ]; $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); @@ -199,19 +199,19 @@ public function testWriteWhenUsingExpiresField() ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); - $data = array(); + $data = []; $methodName = phpversion('mongodb') ? 'updateOne' : 'update'; $collection->expects($this->once()) ->method($methodName) ->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) { - $this->assertEquals(array($this->options['id_field'] => 'foo'), $criteria); + $this->assertEquals([$this->options['id_field'] => 'foo'], $criteria); if (phpversion('mongodb')) { - $this->assertEquals(array('upsert' => true), $options); + $this->assertEquals(['upsert' => true], $options); } else { - $this->assertEquals(array('upsert' => true, 'multiple' => false), $options); + $this->assertEquals(['upsert' => true, 'multiple' => false], $options); } $data = $updateData['$set']; @@ -239,7 +239,7 @@ public function testReplaceSessionData() ->with($this->options['database'], $this->options['collection']) ->will($this->returnValue($collection)); - $data = array(); + $data = []; $methodName = phpversion('mongodb') ? 'updateOne' : 'update'; @@ -272,7 +272,7 @@ public function testDestroy() $collection->expects($this->once()) ->method($methodName) - ->with(array($this->options['id_field'] => 'foo')); + ->with([$this->options['id_field'] => 'foo']); $this->assertTrue($this->storage->destroy('foo')); } diff --git a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php index a6264e51d..dc827d8ab 100644 --- a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php @@ -27,7 +27,7 @@ class NativeFileSessionHandlerTest extends TestCase { public function testConstruct() { - $storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler(sys_get_temp_dir())); + $storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler(sys_get_temp_dir())); $this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName()); $this->assertEquals('user', ini_get('session.save_handler')); @@ -52,11 +52,11 @@ public function savePathDataProvider() { $base = sys_get_temp_dir(); - return array( - array("$base/foo", "$base/foo", "$base/foo"), - array("5;$base/foo", "5;$base/foo", "$base/foo"), - array("5;0600;$base/foo", "5;0600;$base/foo", "$base/foo"), - ); + return [ + ["$base/foo", "$base/foo", "$base/foo"], + ["5;$base/foo", "5;$base/foo", "$base/foo"], + ["5;0600;$base/foo", "5;0600;$base/foo", "$base/foo"], + ]; } /** @@ -70,7 +70,7 @@ public function testConstructException() public function testConstructDefault() { $path = ini_get('session.save_path'); - $storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler()); + $storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler()); $this->assertEquals($path, ini_get('session.save_path')); } diff --git a/Tests/Session/Storage/Handler/NullSessionHandlerTest.php b/Tests/Session/Storage/Handler/NullSessionHandlerTest.php index 9a2212b8b..0d246e1aa 100644 --- a/Tests/Session/Storage/Handler/NullSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NullSessionHandlerTest.php @@ -54,6 +54,6 @@ public function testNothingIsPersisted() public function getStorage() { - return new NativeSessionStorage(array(), new NullSessionHandler()); + return new NativeSessionStorage([], new NullSessionHandler()); } } diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 853e96d28..901078478 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -64,7 +64,7 @@ public function testWrongPdoErrMode() */ public function testInexistentTable() { - $storage = new PdoSessionHandler($this->getMemorySqlitePdo(), array('db_table' => 'inexistent_table')); + $storage = new PdoSessionHandler($this->getMemorySqlitePdo(), ['db_table' => 'inexistent_table']); $storage->open('', 'sid'); $storage->read('id'); $storage->write('id', 'data'); @@ -147,7 +147,7 @@ public function testReadConvertsStreamToString() $stream = $this->createStream($content); $pdo->prepareResult->expects($this->once())->method('fetchAll') - ->will($this->returnValue(array(array($stream, 42, time())))); + ->will($this->returnValue([[$stream, 42, time()]])); $storage = new PdoSessionHandler($pdo); $result = $storage->read('foo'); @@ -178,7 +178,7 @@ public function testReadLockedConvertsStreamToString() $selectStmt->expects($this->atLeast(2))->method('fetchAll') ->will($this->returnCallback(function () use (&$exception, $stream) { - return $exception ? array(array($stream, 42, time())) : array(); + return $exception ? [[$stream, 42, time()]] : []; })); $insertStmt->expects($this->once())->method('execute') @@ -344,19 +344,19 @@ public function testUrlDsn($url, $expectedDsn, $expectedUser = null, $expectedPa public function provideUrlDsnPairs() { - yield array('mysql://localhost/test', 'mysql:host=localhost;dbname=test;'); - yield array('mysql://localhost:56/test', 'mysql:host=localhost;port=56;dbname=test;'); - yield array('mysql2://root:pwd@localhost/test', 'mysql:host=localhost;dbname=test;', 'root', 'pwd'); - yield array('postgres://localhost/test', 'pgsql:host=localhost;dbname=test;'); - yield array('postgresql://localhost:5634/test', 'pgsql:host=localhost;port=5634;dbname=test;'); - yield array('postgres://root:pwd@localhost/test', 'pgsql:host=localhost;dbname=test;', 'root', 'pwd'); - yield 'sqlite relative path' => array('sqlite://localhost/tmp/test', 'sqlite:tmp/test'); - yield 'sqlite absolute path' => array('sqlite://localhost//tmp/test', 'sqlite:/tmp/test'); - yield 'sqlite relative path without host' => array('sqlite:///tmp/test', 'sqlite:tmp/test'); - yield 'sqlite absolute path without host' => array('sqlite3:////tmp/test', 'sqlite:/tmp/test'); - yield array('sqlite://localhost/:memory:', 'sqlite::memory:'); - yield array('mssql://localhost/test', 'sqlsrv:server=localhost;Database=test'); - yield array('mssql://localhost:56/test', 'sqlsrv:server=localhost,56;Database=test'); + yield ['mysql://localhost/test', 'mysql:host=localhost;dbname=test;']; + yield ['mysql://localhost:56/test', 'mysql:host=localhost;port=56;dbname=test;']; + yield ['mysql2://root:pwd@localhost/test', 'mysql:host=localhost;dbname=test;', 'root', 'pwd']; + yield ['postgres://localhost/test', 'pgsql:host=localhost;dbname=test;']; + yield ['postgresql://localhost:5634/test', 'pgsql:host=localhost;port=5634;dbname=test;']; + yield ['postgres://root:pwd@localhost/test', 'pgsql:host=localhost;dbname=test;', 'root', 'pwd']; + yield 'sqlite relative path' => ['sqlite://localhost/tmp/test', 'sqlite:tmp/test']; + yield 'sqlite absolute path' => ['sqlite://localhost//tmp/test', 'sqlite:/tmp/test']; + yield 'sqlite relative path without host' => ['sqlite:///tmp/test', 'sqlite:tmp/test']; + yield 'sqlite absolute path without host' => ['sqlite3:////tmp/test', 'sqlite:/tmp/test']; + yield ['sqlite://localhost/:memory:', 'sqlite::memory:']; + yield ['mssql://localhost/test', 'sqlsrv:server=localhost;Database=test']; + yield ['mssql://localhost:56/test', 'sqlsrv:server=localhost,56;Database=test']; } private function createStream($content) @@ -394,7 +394,7 @@ public function getAttribute($attribute) return parent::getAttribute($attribute); } - public function prepare($statement, $driverOptions = array()) + public function prepare($statement, $driverOptions = []) { return \is_callable($this->prepareResult) ? \call_user_func($this->prepareResult, $statement, $driverOptions) diff --git a/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php b/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php index b02c41ae8..6a0d16876 100644 --- a/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/StrictSessionHandlerTest.php @@ -84,7 +84,7 @@ public function testReadWithValidateIdMismatch() { $handler = $this->getMockBuilder('SessionHandlerInterface')->getMock(); $handler->expects($this->exactly(2))->method('read') - ->withConsecutive(array('id1'), array('id2')) + ->withConsecutive(['id1'], ['id2']) ->will($this->onConsecutiveCalls('data1', 'data2')); $proxy = new StrictSessionHandler($handler); diff --git a/Tests/Session/Storage/MetadataBagTest.php b/Tests/Session/Storage/MetadataBagTest.php index 69cf6163c..2c4758b91 100644 --- a/Tests/Session/Storage/MetadataBagTest.php +++ b/Tests/Session/Storage/MetadataBagTest.php @@ -26,26 +26,26 @@ class MetadataBagTest extends TestCase */ protected $bag; - protected $array = array(); + protected $array = []; protected function setUp() { parent::setUp(); $this->bag = new MetadataBag(); - $this->array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 0); + $this->array = [MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 0]; $this->bag->initialize($this->array); } protected function tearDown() { - $this->array = array(); + $this->array = []; $this->bag = null; parent::tearDown(); } public function testInitialize() { - $sessionMetadata = array(); + $sessionMetadata = []; $bag1 = new MetadataBag(); $bag1->initialize($sessionMetadata); @@ -82,7 +82,7 @@ public function testGetStorageKey() public function testGetLifetime() { $bag = new MetadataBag(); - $array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 1000); + $array = [MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 1000]; $bag->initialize($array); $this->assertEquals(1000, $bag->getLifetime()); } @@ -111,11 +111,11 @@ public function testSkipLastUsedUpdate() $timeStamp = time(); $created = $timeStamp - 15; - $sessionMetadata = array( + $sessionMetadata = [ MetadataBag::CREATED => $created, MetadataBag::UPDATED => $created, MetadataBag::LIFETIME => 1000, - ); + ]; $bag->initialize($sessionMetadata); $this->assertEquals($created, $sessionMetadata[MetadataBag::UPDATED]); @@ -127,11 +127,11 @@ public function testDoesNotSkipLastUsedUpdate() $timeStamp = time(); $created = $timeStamp - 45; - $sessionMetadata = array( + $sessionMetadata = [ MetadataBag::CREATED => $created, MetadataBag::UPDATED => $created, MetadataBag::LIFETIME => 1000, - ); + ]; $bag->initialize($sessionMetadata); $this->assertEquals($timeStamp, $sessionMetadata[MetadataBag::UPDATED]); diff --git a/Tests/Session/Storage/MockArraySessionStorageTest.php b/Tests/Session/Storage/MockArraySessionStorageTest.php index 893e120ce..2e3024ef1 100644 --- a/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -45,10 +45,10 @@ protected function setUp() $this->attributes = new AttributeBag(); $this->flashes = new FlashBag(); - $this->data = array( - $this->attributes->getStorageKey() => array('foo' => 'bar'), - $this->flashes->getStorageKey() => array('notice' => 'hello'), - ); + $this->data = [ + $this->attributes->getStorageKey() => ['foo' => 'bar'], + $this->flashes->getStorageKey() => ['notice' => 'hello'], + ]; $this->storage = new MockArraySessionStorage(); $this->storage->registerBag($this->flashes); @@ -80,14 +80,14 @@ public function testRegenerate() $id = $this->storage->getId(); $this->storage->regenerate(); $this->assertNotEquals($id, $this->storage->getId()); - $this->assertEquals(array('foo' => 'bar'), $this->storage->getBag('attributes')->all()); - $this->assertEquals(array('notice' => 'hello'), $this->storage->getBag('flashes')->peekAll()); + $this->assertEquals(['foo' => 'bar'], $this->storage->getBag('attributes')->all()); + $this->assertEquals(['notice' => 'hello'], $this->storage->getBag('flashes')->peekAll()); $id = $this->storage->getId(); $this->storage->regenerate(true); $this->assertNotEquals($id, $this->storage->getId()); - $this->assertEquals(array('foo' => 'bar'), $this->storage->getBag('attributes')->all()); - $this->assertEquals(array('notice' => 'hello'), $this->storage->getBag('flashes')->peekAll()); + $this->assertEquals(['foo' => 'bar'], $this->storage->getBag('attributes')->all()); + $this->assertEquals(['notice' => 'hello'], $this->storage->getBag('flashes')->peekAll()); } public function testGetId() @@ -101,8 +101,8 @@ public function testClearClearsBags() { $this->storage->clear(); - $this->assertSame(array(), $this->storage->getBag('attributes')->all()); - $this->assertSame(array(), $this->storage->getBag('flashes')->peekAll()); + $this->assertSame([], $this->storage->getBag('attributes')->all()); + $this->assertSame([], $this->storage->getBag('flashes')->peekAll()); } public function testClearStartsSession() diff --git a/Tests/Session/Storage/MockFileSessionStorageTest.php b/Tests/Session/Storage/MockFileSessionStorageTest.php index 169579817..9e2692dc0 100644 --- a/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -91,7 +91,7 @@ public function testSave() $storage->start(); $this->assertEquals('108', $storage->getBag('attributes')->get('new')); $this->assertTrue($storage->getBag('flashes')->has('newkey')); - $this->assertEquals(array('test'), $storage->getBag('flashes')->peek('newkey')); + $this->assertEquals(['test'], $storage->getBag('flashes')->peek('newkey')); } public function testMultipleInstances() diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 52da2947c..d4aa476a4 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -56,7 +56,7 @@ protected function tearDown() /** * @return NativeSessionStorage */ - protected function getStorage(array $options = array()) + protected function getStorage(array $options = []) { $storage = new NativeSessionStorage($options); $storage->registerBag(new AttributeBag()); @@ -157,23 +157,23 @@ public function testExplicitSessionCacheLimiter() { $this->iniSet('session.cache_limiter', 'nocache'); - $storage = new NativeSessionStorage(array('cache_limiter' => 'public')); + $storage = new NativeSessionStorage(['cache_limiter' => 'public']); $this->assertEquals('public', ini_get('session.cache_limiter')); } public function testCookieOptions() { - $options = array( + $options = [ 'cookie_lifetime' => 123456, 'cookie_path' => '/my/cookie/path', 'cookie_domain' => 'symfony.example.com', 'cookie_secure' => true, 'cookie_httponly' => false, - ); + ]; $this->getStorage($options); $temp = session_get_cookie_params(); - $gco = array(); + $gco = []; foreach ($temp as $key => $value) { $gco['cookie_'.$key] = $value; @@ -188,10 +188,10 @@ public function testSessionOptions() $this->markTestSkipped('HHVM is not handled in this test case.'); } - $options = array( + $options = [ 'url_rewriter.tags' => 'a=href', 'cache_expire' => '200', - ); + ]; $this->getStorage($options); @@ -272,9 +272,9 @@ public function testCanCreateNativeSessionStorageWhenSessionAlreadyStarted() public function testSetSessionOptionsOnceSessionStartedIsIgnored() { session_start(); - $this->getStorage(array( + $this->getStorage([ 'name' => 'something-else', - )); + ]); // Assert no exception has been thrown by `getStorage()` $this->addToAssertionCount(1); diff --git a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php index 7cb63c5aa..752be618b 100644 --- a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php +++ b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php @@ -87,10 +87,10 @@ public function testClear() $_SESSION['drak'] = 'loves symfony'; $storage->getBag('attributes')->set('symfony', 'greatness'); $key = $storage->getBag('attributes')->getStorageKey(); - $this->assertEquals($_SESSION[$key], array('symfony' => 'greatness')); + $this->assertEquals($_SESSION[$key], ['symfony' => 'greatness']); $this->assertEquals($_SESSION['drak'], 'loves symfony'); $storage->clear(); - $this->assertEquals($_SESSION[$key], array()); + $this->assertEquals($_SESSION[$key], []); $this->assertEquals($_SESSION['drak'], 'loves symfony'); } } diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index 0b48250e0..0459a8ce9 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -127,7 +127,7 @@ public function testGc() */ public function testValidateId() { - $mock = $this->getMockBuilder(array('SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'))->getMock(); + $mock = $this->getMockBuilder(['SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'])->getMock(); $mock->expects($this->once()) ->method('validateId'); @@ -142,7 +142,7 @@ public function testValidateId() */ public function testUpdateTimestamp() { - $mock = $this->getMockBuilder(array('SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'))->getMock(); + $mock = $this->getMockBuilder(['SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'])->getMock(); $mock->expects($this->once()) ->method('updateTimestamp'); diff --git a/Tests/StreamedResponseTest.php b/Tests/StreamedResponseTest.php index 699222e37..62dfc9bc9 100644 --- a/Tests/StreamedResponseTest.php +++ b/Tests/StreamedResponseTest.php @@ -19,7 +19,7 @@ class StreamedResponseTest extends TestCase { public function testConstructor() { - $response = new StreamedResponse(function () { echo 'foo'; }, 404, array('Content-Type' => 'text/plain')); + $response = new StreamedResponse(function () { echo 'foo'; }, 404, ['Content-Type' => 'text/plain']); $this->assertEquals(404, $response->getStatusCode()); $this->assertEquals('text/plain', $response->headers->get('Content-Type')); @@ -51,7 +51,7 @@ public function testPrepareWith10Protocol() public function testPrepareWithHeadRequest() { - $response = new StreamedResponse(function () { echo 'foo'; }, 200, array('Content-Length' => '123')); + $response = new StreamedResponse(function () { echo 'foo'; }, 200, ['Content-Length' => '123']); $request = Request::create('/', 'HEAD'); $response->prepare($request); @@ -61,7 +61,7 @@ public function testPrepareWithHeadRequest() public function testPrepareWithCacheHeaders() { - $response = new StreamedResponse(function () { echo 'foo'; }, 200, array('Cache-Control' => 'max-age=600, public')); + $response = new StreamedResponse(function () { echo 'foo'; }, 200, ['Cache-Control' => 'max-age=600, public']); $request = Request::create('/', 'GET'); $response->prepare($request); From 74402adbf42e3734fcb5b63f4ab7081ceebf8d59 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 16 Jan 2019 13:47:19 +0100 Subject: [PATCH 158/225] fixed CS in generated files --- Tests/AcceptHeaderTest.php | 6 +++--- Tests/RequestTest.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/AcceptHeaderTest.php b/Tests/AcceptHeaderTest.php index 459b693d5..d5518cc3c 100644 --- a/Tests/AcceptHeaderTest.php +++ b/Tests/AcceptHeaderTest.php @@ -95,9 +95,9 @@ public function testSorting($string, array $values) public function provideSortingData() { return [ - 'quality has priority' => ['*;q=0.3,ISO-8859-1,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']], - 'order matters when q is equal' => ['*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']], - 'order matters when q is equal2' => ['*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', ['utf-8', 'ISO-8859-1', '*']], + 'quality has priority' => ['*;q=0.3,ISO-8859-1,utf-8;q=0.7', array ('ISO-8859-1', 'utf-8', '*')], + 'order matters when q is equal' => ['*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', array ('ISO-8859-1', 'utf-8', '*')], + 'order matters when q is equal2' => ['*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', array ('utf-8', 'ISO-8859-1', '*')], ]; } } diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 505f271ea..9e60e4705 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1025,7 +1025,7 @@ public function getClientIpsProvider() // forwarded for with remote IPv6 addr not trusted [['1620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', null], // forwarded for with remote IPv6 addr trusted - [['2620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', ['1620:0:1cfe:face:b00c::3']], + [['2620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', array ('1620:0:1cfe:face:b00c::3')], // forwarded for with remote IPv6 range trusted [['88.88.88.88'], '2a01:198:603:0:396e:4789:8e99:890f', '88.88.88.88', ['2a01:198:603:0::/65']], From def24ee06e8a2663f5f29aeae217617060755fa5 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 16 Jan 2019 14:03:22 +0100 Subject: [PATCH 159/225] fixed short array CS in comments --- Session/Storage/Handler/PdoSessionHandler.php | 2 +- Session/Storage/NativeSessionStorage.php | 2 +- Tests/ResponseTest.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index c027a9e6e..bc088e774 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -161,7 +161,7 @@ class PdoSessionHandler extends AbstractSessionHandler * * db_time_col: The column where to store the timestamp [default: sess_time] * * db_username: The username when lazy-connect [default: ''] * * db_password: The password when lazy-connect [default: ''] - * * db_connection_options: An array of driver-specific connection options [default: array()] + * * db_connection_options: An array of driver-specific connection options [default: []] * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL] * * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index a2f64a3af..c4dbe7586 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -331,7 +331,7 @@ public function isStarted() * For convenience we omit 'session.' from the beginning of the keys. * Explicitly ignores other ini keys. * - * @param array $options Session ini directives array(key => value) + * @param array $options Session ini directives [key => value] * * @see http://php.net/session.configuration */ diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index f6fb1309e..68634f6d4 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -576,7 +576,7 @@ public function testPrepareSetsPragmaOnHttp10Only() public function testSetCache() { $response = new Response(); - //array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public') + // ['etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public'] try { $response->setCache(['wrong option' => 'value']); $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported'); From ea1b4d99e1d434e3726d23faf1ba7cfaa186f8b8 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 16 Jan 2019 14:43:35 +0100 Subject: [PATCH 160/225] fixed CS --- Tests/AcceptHeaderTest.php | 6 +++--- Tests/RequestTest.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/AcceptHeaderTest.php b/Tests/AcceptHeaderTest.php index d5518cc3c..31998696d 100644 --- a/Tests/AcceptHeaderTest.php +++ b/Tests/AcceptHeaderTest.php @@ -95,9 +95,9 @@ public function testSorting($string, array $values) public function provideSortingData() { return [ - 'quality has priority' => ['*;q=0.3,ISO-8859-1,utf-8;q=0.7', array ('ISO-8859-1', 'utf-8', '*')], - 'order matters when q is equal' => ['*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', array ('ISO-8859-1', 'utf-8', '*')], - 'order matters when q is equal2' => ['*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', array ('utf-8', 'ISO-8859-1', '*')], + 'quality has priority' => ['*;q=0.3,ISO-8859-1,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']], + 'order matters when q is equal' => ['*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']], + 'order matters when q is equal2' => ['*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', ['utf-8', 'ISO-8859-1', '*']], ]; } } diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 9e60e4705..6a8a73db8 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1025,7 +1025,7 @@ public function getClientIpsProvider() // forwarded for with remote IPv6 addr not trusted [['1620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', null], // forwarded for with remote IPv6 addr trusted - [['2620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', array ('1620:0:1cfe:face:b00c::3')], + [['2620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', ['1620:0:1cfe:face:b00c::3']], // forwarded for with remote IPv6 range trusted [['88.88.88.88'], '2a01:198:603:0:396e:4789:8e99:890f', '88.88.88.88', ['2a01:198:603:0::/65']], From 307ad775e4f84d041459ff5ef95e5d8aa2c13f9d Mon Sep 17 00:00:00 2001 From: Tom Van Looy Date: Thu, 20 Dec 2018 22:16:23 +0100 Subject: [PATCH 161/225] Enable PHP 7.3 on Travis --- Tests/Session/Storage/NativeSessionStorageTest.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index d4aa476a4..7cc2eb79c 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -179,6 +179,8 @@ public function testCookieOptions() $gco['cookie_'.$key] = $value; } + unset($gco['cookie_samesite']); + $this->assertEquals($options, $gco); } From 6952b50fb591060575a5a27c4365321ee23aff97 Mon Sep 17 00:00:00 2001 From: adam-mospan Date: Thu, 3 Jan 2019 17:40:56 +0200 Subject: [PATCH 162/225] [HttpFoundation] Check file exists before unlink --- BinaryFileResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 557577a1e..cf648dfe9 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -305,7 +305,7 @@ public function sendContent() fclose($out); fclose($file); - if ($this->deleteFileAfterSend) { + if ($this->deleteFileAfterSend && file_exists($this->file->getPathname())) { unlink($this->file->getPathname()); } From 9a81d2330ea255ded06a69b4f7fb7804836e7a05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABll=20Roussel?= Date: Sat, 26 Jan 2019 23:05:56 +0100 Subject: [PATCH 163/225] Remove gendered pronouns --- Tests/RequestTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 6a8a73db8..d266e1f68 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -783,14 +783,14 @@ public function getQueryStringNormalizationData() // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded). // PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. - ['him=John%20Doe&her=Jane+Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes spaces in both encodings "%20" and "+"'], + ['baz=Foo%20Baz&bar=Foo+Bar', 'bar=Foo%20Bar&baz=Foo%20Baz', 'normalizes spaces in both encodings "%20" and "+"'], ['foo[]=1&foo[]=2', 'foo%5B%5D=1&foo%5B%5D=2', 'allows array notation'], ['foo=1&foo=2', 'foo=1&foo=2', 'allows repeated parameters'], ['pa%3Dram=foo%26bar%3Dbaz&test=test', 'pa%3Dram=foo%26bar%3Dbaz&test=test', 'works with encoded delimiters'], ['0', '0', 'allows "0"'], - ['Jane Doe&John%20Doe', 'Jane%20Doe&John%20Doe', 'normalizes encoding in keys'], - ['her=Jane Doe&him=John%20Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes encoding in values'], + ['Foo Bar&Foo%20Baz', 'Foo%20Bar&Foo%20Baz', 'normalizes encoding in keys'], + ['bar=Foo Bar&baz=Foo%20Baz', 'bar=Foo%20Bar&baz=Foo%20Baz', 'normalizes encoding in values'], ['foo=bar&&&test&&', 'foo=bar&test', 'removes unneeded delimiters'], ['formula=e=m*c^2', 'formula=e%3Dm%2Ac%5E2', 'correctly treats only the first "=" as delimiter and the next as value'], From 9a96d77ceb1fd913c9d4a89e8a7e1be87604be8a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 23 Feb 2019 16:06:07 +0100 Subject: [PATCH 164/225] Apply php-cs-fixer rule for array_key_exists() --- HeaderBag.php | 8 ++++---- ParameterBag.php | 4 ++-- RedirectResponse.php | 2 +- Request.php | 8 ++++---- ResponseHeaderBag.php | 4 ++-- Session/Attribute/AttributeBag.php | 6 +++--- Session/Attribute/NamespacedAttributeBag.php | 8 ++++---- Session/Flash/AutoExpireFlashBag.php | 6 +++--- Session/Flash/FlashBag.php | 2 +- 9 files changed, 24 insertions(+), 24 deletions(-) diff --git a/HeaderBag.php b/HeaderBag.php index 937afe6b7..9798173e6 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -112,7 +112,7 @@ public function get($key, $default = null, $first = true) $key = str_replace('_', '-', strtolower($key)); $headers = $this->all(); - if (!array_key_exists($key, $headers)) { + if (!\array_key_exists($key, $headers)) { if (null === $default) { return $first ? null : []; } @@ -168,7 +168,7 @@ public function set($key, $values, $replace = true) */ public function has($key) { - return array_key_exists(str_replace('_', '-', strtolower($key)), $this->all()); + return \array_key_exists(str_replace('_', '-', strtolower($key)), $this->all()); } /** @@ -245,7 +245,7 @@ public function addCacheControlDirective($key, $value = true) */ public function hasCacheControlDirective($key) { - return array_key_exists($key, $this->cacheControl); + return \array_key_exists($key, $this->cacheControl); } /** @@ -257,7 +257,7 @@ public function hasCacheControlDirective($key) */ public function getCacheControlDirective($key) { - return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null; + return \array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null; } /** diff --git a/ParameterBag.php b/ParameterBag.php index 3c6ba46a6..f05e4a215 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -81,7 +81,7 @@ public function add(array $parameters = []) */ public function get($key, $default = null) { - return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default; + return \array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default; } /** @@ -104,7 +104,7 @@ public function set($key, $value) */ public function has($key) { - return array_key_exists($key, $this->parameters); + return \array_key_exists($key, $this->parameters); } /** diff --git a/RedirectResponse.php b/RedirectResponse.php index 970d82b5a..5e1dfe585 100644 --- a/RedirectResponse.php +++ b/RedirectResponse.php @@ -42,7 +42,7 @@ public function __construct($url, $status = 302, $headers = []) throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status)); } - if (301 == $status && !array_key_exists('cache-control', $headers)) { + if (301 == $status && !\array_key_exists('cache-control', $headers)) { $this->headers->remove('cache-control'); } } diff --git a/Request.php b/Request.php index 8dc01b91e..f6ff0f509 100644 --- a/Request.php +++ b/Request.php @@ -303,10 +303,10 @@ public static function createFromGlobals() // HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields. $server = $_SERVER; if ('cli-server' === \PHP_SAPI) { - if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) { + if (\array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) { $server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH']; } - if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) { + if (\array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) { $server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE']; } } @@ -691,7 +691,7 @@ public static function setTrustedHeaderName($key, $value) $key = self::HEADER_CLIENT_PROTO; } elseif ('client_port' === $key) { $key = self::HEADER_CLIENT_PORT; - } elseif (!array_key_exists($key, self::$trustedHeaders)) { + } elseif (!\array_key_exists($key, self::$trustedHeaders)) { throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key)); } @@ -722,7 +722,7 @@ public static function getTrustedHeaderName($key) @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.', __METHOD__), E_USER_DEPRECATED); } - if (!array_key_exists($key, self::$trustedHeaders)) { + if (!\array_key_exists($key, self::$trustedHeaders)) { throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key)); } diff --git a/ResponseHeaderBag.php b/ResponseHeaderBag.php index dc721a9de..1dc8dc2c5 100644 --- a/ResponseHeaderBag.php +++ b/ResponseHeaderBag.php @@ -160,7 +160,7 @@ public function remove($key) */ public function hasCacheControlDirective($key) { - return array_key_exists($key, $this->computedCacheControl); + return \array_key_exists($key, $this->computedCacheControl); } /** @@ -168,7 +168,7 @@ public function hasCacheControlDirective($key) */ public function getCacheControlDirective($key) { - return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null; + return \array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null; } public function setCookie(Cookie $cookie) diff --git a/Session/Attribute/AttributeBag.php b/Session/Attribute/AttributeBag.php index b5666f854..07118e891 100644 --- a/Session/Attribute/AttributeBag.php +++ b/Session/Attribute/AttributeBag.php @@ -63,7 +63,7 @@ public function getStorageKey() */ public function has($name) { - return array_key_exists($name, $this->attributes); + return \array_key_exists($name, $this->attributes); } /** @@ -71,7 +71,7 @@ public function has($name) */ public function get($name, $default = null) { - return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; + return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } /** @@ -107,7 +107,7 @@ public function replace(array $attributes) public function remove($name) { $retval = null; - if (array_key_exists($name, $this->attributes)) { + if (\array_key_exists($name, $this->attributes)) { $retval = $this->attributes[$name]; unset($this->attributes[$name]); } diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index 95e48253b..bbf2e39c8 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -44,7 +44,7 @@ public function has($name) return false; } - return array_key_exists($name, $attributes); + return \array_key_exists($name, $attributes); } /** @@ -60,7 +60,7 @@ public function get($name, $default = null) return $default; } - return array_key_exists($name, $attributes) ? $attributes[$name] : $default; + return \array_key_exists($name, $attributes) ? $attributes[$name] : $default; } /** @@ -81,7 +81,7 @@ public function remove($name) $retval = null; $attributes = &$this->resolveAttributePath($name); $name = $this->resolveKey($name); - if (null !== $attributes && array_key_exists($name, $attributes)) { + if (null !== $attributes && \array_key_exists($name, $attributes)) { $retval = $attributes[$name]; unset($attributes[$name]); } @@ -123,7 +123,7 @@ protected function &resolveAttributePath($name, $writeContext = false) unset($parts[\count($parts) - 1]); foreach ($parts as $part) { - if (null !== $array && !array_key_exists($part, $array)) { + if (null !== $array && !\array_key_exists($part, $array)) { if (!$writeContext) { $null = null; diff --git a/Session/Flash/AutoExpireFlashBag.php b/Session/Flash/AutoExpireFlashBag.php index 12345c823..451c4a5a1 100644 --- a/Session/Flash/AutoExpireFlashBag.php +++ b/Session/Flash/AutoExpireFlashBag.php @@ -53,7 +53,7 @@ public function initialize(array &$flashes) // The logic: messages from the last request will be stored in new, so we move them to previous // This request we will show what is in 'display'. What is placed into 'new' this time round will // be moved to display next time round. - $this->flashes['display'] = array_key_exists('new', $this->flashes) ? $this->flashes['new'] : []; + $this->flashes['display'] = \array_key_exists('new', $this->flashes) ? $this->flashes['new'] : []; $this->flashes['new'] = []; } @@ -78,7 +78,7 @@ public function peek($type, array $default = []) */ public function peekAll() { - return array_key_exists('display', $this->flashes) ? (array) $this->flashes['display'] : []; + return \array_key_exists('display', $this->flashes) ? (array) $this->flashes['display'] : []; } /** @@ -132,7 +132,7 @@ public function set($type, $messages) */ public function has($type) { - return array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type]; + return \array_key_exists($type, $this->flashes['display']) && $this->flashes['display'][$type]; } /** diff --git a/Session/Flash/FlashBag.php b/Session/Flash/FlashBag.php index 19baabb94..f5d984af0 100644 --- a/Session/Flash/FlashBag.php +++ b/Session/Flash/FlashBag.php @@ -123,7 +123,7 @@ public function setAll(array $messages) */ public function has($type) { - return array_key_exists($type, $this->flashes) && $this->flashes[$type]; + return \array_key_exists($type, $this->flashes) && $this->flashes[$type]; } /** From 2d5d1f07e02269f6f5cd5a7e6b8f3a2f38552ef6 Mon Sep 17 00:00:00 2001 From: Teoh Han Hui Date: Tue, 12 Mar 2019 15:29:13 +0100 Subject: [PATCH 165/225] Fix return type of Request::getRequestFormat --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index f6ff0f509..fe1a33a59 100644 --- a/Request.php +++ b/Request.php @@ -1462,7 +1462,7 @@ public function setFormat($format, $mimeTypes) * * @param string|null $default The default format * - * @return string The request format + * @return string|null The request format */ public function getRequestFormat($default = 'html') { From 78cfeccc99a060c7c220e61668e760d4317df0f9 Mon Sep 17 00:00:00 2001 From: ScoobyDam Date: Thu, 21 Mar 2019 19:51:37 +0100 Subject: [PATCH 166/225] Response prepare method update Response prepare updated for more coherence. --- Response.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Response.php b/Response.php index 4d63219b2..b7d116259 100644 --- a/Response.php +++ b/Response.php @@ -310,9 +310,9 @@ public function prepare(Request $request) } // Check if we need to send extra expire info headers - if ('1.0' == $this->getProtocolVersion() && false !== strpos($this->headers->get('Cache-Control'), 'no-cache')) { - $this->headers->set('pragma', 'no-cache'); - $this->headers->set('expires', -1); + if ('1.0' == $this->getProtocolVersion() && false !== strpos($headers->get('Cache-Control'), 'no-cache')) { + $headers->set('pragma', 'no-cache'); + $headers->set('expires', -1); } $this->ensureIEOverSSLCompatibility($request); From 9e598a10c16df72659cc711c10f2dcd6e455b474 Mon Sep 17 00:00:00 2001 From: David Maicher Date: Thu, 21 Mar 2019 09:24:23 +0100 Subject: [PATCH 167/225] [FrameworkBundle][HttpFoundation] make session service resettable --- Session/Session.php | 4 +++- Tests/Session/SessionTest.php | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Session/Session.php b/Session/Session.php index 867ceba97..62ce948b6 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -193,7 +193,9 @@ public function migrate($destroy = false, $lifetime = null) */ public function save() { - $this->storage->save(); + if ($this->isStarted()) { + $this->storage->save(); + } } /** diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index afa00fc7c..e75b3321b 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -260,4 +260,14 @@ public function testIsEmpty() $flash->get('hello'); $this->assertTrue($this->session->isEmpty()); } + + public function testSaveIfNotStarted() + { + $storage = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface')->getMock(); + $session = new Session($storage); + + $storage->expects($this->once())->method('isStarted')->willReturn(false); + $storage->expects($this->never())->method('save'); + $session->save(); + } } From 61094ca72e8934c6502af5259ef6296eb09aa424 Mon Sep 17 00:00:00 2001 From: Oskar Stark Date: Mon, 25 Mar 2019 08:48:46 +0100 Subject: [PATCH 168/225] use behavior instead of behaviour --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97b279df1..7bfde80ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -144,10 +144,10 @@ CHANGELOG * Added `FlashBag`. Flashes expire when retrieved by `get()` or `all()`. This implementation is ESI compatible. * Added `AutoExpireFlashBag` (default) to replicate Symfony 2.0.x auto expire - behaviour of messages auto expiring after one page page load. Messages must + behavior of messages auto expiring after one page page load. Messages must be retrieved by `get()` or `all()`. * Added `Symfony\Component\HttpFoundation\Attribute\AttributeBag` to replicate - attributes storage behaviour from 2.0.x (default). + attributes storage behavior from 2.0.x (default). * Added `Symfony\Component\HttpFoundation\Attribute\NamespacedAttributeBag` for namespace session attributes. * Flash API can stores messages in an array so there may be multiple messages From 9fa232656ea594524146a8d596dd072beb5492f0 Mon Sep 17 00:00:00 2001 From: Tony Vermeiren Date: Tue, 16 Apr 2019 08:01:19 +0200 Subject: [PATCH 169/225] Make MimeTypeExtensionGuesser case insensitive --- File/MimeType/MimeTypeExtensionGuesser.php | 8 +++++++- .../File/Fixtures/case-sensitive-mime-type.xlsm | Bin 0 -> 4791 bytes Tests/File/UploadedFileTest.php | 13 +++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 Tests/File/Fixtures/case-sensitive-mime-type.xlsm diff --git a/File/MimeType/MimeTypeExtensionGuesser.php b/File/MimeType/MimeTypeExtensionGuesser.php index d5acb3409..c0f9140c8 100644 --- a/File/MimeType/MimeTypeExtensionGuesser.php +++ b/File/MimeType/MimeTypeExtensionGuesser.php @@ -808,6 +808,12 @@ class MimeTypeExtensionGuesser implements ExtensionGuesserInterface */ public function guess($mimeType) { - return isset($this->defaultExtensions[$mimeType]) ? $this->defaultExtensions[$mimeType] : null; + if (isset($this->defaultExtensions[$mimeType])) { + return $this->defaultExtensions[$mimeType]; + } + + $lcMimeType = strtolower($mimeType); + + return isset($this->defaultExtensions[$lcMimeType]) ? $this->defaultExtensions[$lcMimeType] : null; } } diff --git a/Tests/File/Fixtures/case-sensitive-mime-type.xlsm b/Tests/File/Fixtures/case-sensitive-mime-type.xlsm new file mode 100644 index 0000000000000000000000000000000000000000..94d85e6132c553225a1628f056151bee22f5b352 GIT binary patch literal 4791 zcmaJ_by$;q7bYA%x^yBTjifNTk=Ou7hct}dMu}1)H4rK35NQxZL_|6iLAsH0l%O;y zAfX`N_Qof#*ZX=ue{9#To%1};ea^YhIX@Vb@EkoJ2?+__b=!Ddyfe6f{eIhB*xC#3 z?k#)^<>h9FLb(auMz{;%etDYEOV%breeK{RS|lKAJR(Z`=4F*yeMPpyQQ{h{u6B*n z*{FQR29E{Tx?QOQv8jFV-bQGgOaY+KlYru-m{AD`ztgML^bI(^ig14+X1YeKyEMF4N~R&w0F@TI(O9KU^{Q%+*e{J|iPM;uBli)XwJwO0^Qg zpu{Bc1O#}^*jG%)$HRmDCkf1dl7M@CZ)Z5%$6NT14^bQsu}1Ip--}QOZJXTQo1M(V z^t9Wi4a!IoX2AS-vfD4dFW)8S5>`7kyDrYUkKt^sNq-Zm@Qb`r0E0;A&D^i#W<*PG1%abL(59t#%7#hGF!MY7$c5 zyJlS;sC)~4;!m<<{IbhE1V{WW5fXKs{D(7yvvfoCi$_GhN$1&B+@^(=-*jCt=?plX+`^<*m; zt6gl=fy3Sl4*Sn8Blp*3C2wfmGa5pQNxQwnOp9;W=%GM9?b^5a+aQOd-9G-09_|HS z>7kkVUQsu<+Q1=UWHY{#a{HThOl)!%)INJ++0qiJ!a2SXESu^Qu))yA!RiZFxkhmC zEf23bf563DU4L<*Tgxos?Rg=sMo`C#WdXrQWUJqJxMTErX0XDpt{=5?v=???!HrOwGfj~uTb1MB*4QnA^KhQQ2nf)zr`cgpc{!Tn&tz6 zbF&CRt2O3SLXDaPycz0}?uRRhHML zc}9J0wy)%1^+Ms(9UJQgGU=j&943G?bLBoEo2kv6nGc2i3Zwqp!$EL+V|K9jT&*8K zqE>b0ZoX!zPX7b#7rO}iyG%6%ugt&cQEQ)Ml6T02*B`M`Sf+ABz8s*E;N4K7(2Q%J zHO_zTUe6m5zFff`FWJvyMYkE=`|zmOWZF6=?Mq;=vwlyUS$7e@wR)sva7wc4fy@Ve zv1jun3pyfO20!i&X=WIrA3j|)d)56TuC`dUX+k}4f~+3%NgaCrs(7TE1V=Q-sfojT z%C&n=HMbsFhx708IacTQX6<&fSgVCF2ztn5#s?SzHZ|2&8NmtDI zVy>CA=XtCxkr+OE`I!AwM+50}GGTzsy_Lvh+na1b1z_+MQ;xnE!H~h(<|xE#b1AwD zf1h^@p}WXLg5IGEg0-``^PT5aTnlA04)=|1-TLJEOqqix?hPAB8za-e;p_bGRwS^yj@bbl_9?u=Vrvb9AcZBbK6vidaWwG4hW31$&2!EG2z&{hm z+sDrx?v2yh&2(i{mI!_4_ILW!ZGnVh7g>Cx_xD`VO3e*iMykUIiOMg4rgTByRu5uG zLk!=gZd4jVglkUaPG{$+ZioV(88c{HH+12?79K{&dYNB8LsU=g(DqSa(<@C7hge%t zE)DYWTaz!5uq^cG_eA}$yKFw;Q2Vv(k4i=pjn#6xGRbZyLXBt$RgG>p7$-YS>z36? zemTi7q2czp7!6M`R4*_TiogdohgU4n zQ(VaXo~G~0ocl(6wHe`l!n_=G!aYgqX-a4Rn3j|RHjyJK(R2>KvCVe6PEn01TKx5r zyGR~_ZCj;`!gs-gSc()LL$6Q$1EwLxV_|@S=6rl%df&6l1&LQ~sy98}HT{Cx-T{#P z^A(^NDV-$G-6X%#Kxac$Xm>ee zwPU_e2S#7RJ4x=h;DZeTQdvG!q^I7t{-vDvSjVtFRwS5YFN^RLCbwNwh zZ!tY(9BvQ~aNEPJC}qVHYk60&O24m?U`jp*!hhr_N_-|;eCMWUe)g&SW?UKl>}{%s ziy;HEM2I+wCJWT=+`~gjT&g#a*k@E?HIkP0cd1T}P4z!#tUu?f#MioSL@3bP0nz*i z5;IC9dBu&|nvLw@mtJuqK`-wWw1@5NtI^R?#8$nD^Sl%M!>(vn8+m0`gd1vg&&cc^ zK{K~~P)U354^KZ~aDV=tw=_~3`Y2U?ulVbby}kwIp27g11PIy6t`2k!6s88W$8!@z=PR99@!RMO7br5b6NG;Zj{t8z=m~bSq`*uOJ3j#}|nrMM= zG@0KlJgB~RZabOsJcWp+4ow>Sr>!o=(b_onljPpj^mMw0`cGaSc6&tqO|;=6PCfxT zmxDC5w{jR*u3AIxn?E}4{X~bODI!xma|=tt0G6u%9>nOd|8PLr!@N))-oo}by?sy! zoG!c^)j@@dFcW|Nt^inNxdAhzu%Q>1-KcC&3owZm536x`0y5j5F+r~kJB+>`O*;jq@oXJeix@R zFGEx$>P3{t&Gq#8rAau_ge=e1eFMgl%S)#2%-!|87^B3RC(5aTP}}T*UR>F6&W->h7uv5GgdZ2>RJ`d}14&iQ zY!F5+PR|Cie{5M#ij~VS<5H~FyC-=mmtBRXN%vYM)2RzpzQRuRe|y4|CYFgetNY)R4rZlnfP#Hx-{MmK%(LP-goS+{JR0xk=l;Ms@gU3sUQa8#G+1R+KLeNrAG{! zl$%6L5-p9^{aTEGg;>^@6A|+WJ+ZhXwma8Xa}KiS*(+}D!=Pvock?n4P2uV!_S~=?z3Th0q2~Ibf;wJ2`MrdcgB$`AO%_Z7(}N z>J^^hN`@JPqw?HXQ8xK#U?4$f*tN7tWZvhaXaXIncj`2g6 zOA02NL$f9(gsOfEi2}gj`YKreVT3&Fg*A1K%x7MM6$0)vDX^Vg? zpuLj?O+!+s=2sj(7BJkiTFfM7m$U;Od&#wY7->8wl)`s)vic6EX=lH;fBEFF&@7o?t$(*L^oJIhY~TL8b3^# zB;Z^+u}_>SaXE1<;^GyqP32%flc;spqbx2FZXz*!y!tk8*b8#gn zl}1+W^nIew@otnu_MaBer;Ele9e#WG^%%RI{f%P6Vv6?g^t~^ctX`}OK40_Pb#q)f z_ogiK3JM9nzLPKWJ7rC8A;6Jed~8E4hb10-4kzmP1oU`64;jvG-nc`Cf8xK79Den4 zb_c=j=|2I$-WluXU$^#Oy__9Lar??osA8Y}FE4*@FTWa}ZSlC7^(O+cixJlN=LGw! z>Dji2n*n~piS!>6!LNpA)f$(*KM_avuRZct2WJ%oC+a^zO>x%2UlRYT`PsU{$;?kQ qV=4H5kN!(^eziWE82^0wPn7>!i7+StOC=s2DfUvpYM%Wc_xvA{ir)|b literal 0 HcmV?d00001 diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 9c02b478e..5a37cda35 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -90,6 +90,19 @@ public function testGuessClientExtensionWithIncorrectMimeType() $this->assertEquals('jpeg', $file->guessClientExtension()); } + public function testCaseSensitiveMimeType() + { + $file = new UploadedFile( + __DIR__.'/Fixtures/case-sensitive-mime-type.xlsm', + 'test.xlsm', + 'application/vnd.ms-excel.sheet.macroEnabled.12', + filesize(__DIR__.'/Fixtures/case-sensitive-mime-type.xlsm'), + null + ); + + $this->assertEquals('xlsm', $file->guessClientExtension()); + } + public function testErrorIsOkByDefault() { $file = new UploadedFile( From d325ae5958004d8332dda16b629c7d9fc449ad23 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 2 Apr 2019 18:28:16 +0200 Subject: [PATCH 170/225] [HttpFoundation] reject invalid method override --- Request.php | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/Request.php b/Request.php index fe1a33a59..ae3f51b17 100644 --- a/Request.php +++ b/Request.php @@ -1346,22 +1346,37 @@ public function setMethod($method) */ public function getMethod() { - if (null === $this->method) { - $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET')); - - if ('POST' === $this->method) { - if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) { - $this->method = strtoupper($method); - } elseif (self::$httpMethodParameterOverride) { - $method = $this->request->get('_method', $this->query->get('_method', 'POST')); - if (\is_string($method)) { - $this->method = strtoupper($method); - } - } - } + if (null !== $this->method) { + return $this->method; + } + + $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET')); + + if ('POST' !== $this->method) { + return $this->method; + } + + $method = $this->headers->get('X-HTTP-METHOD-OVERRIDE'); + + if (!$method && self::$httpMethodParameterOverride) { + $method = $this->request->get('_method', $this->query->get('_method', 'POST')); + } + + if (!\is_string($method)) { + return $this->method; + } + + $method = strtoupper($method); + + if (\in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH', 'PURGE', 'TRACE'], true)) { + return $this->method = $method; + } + + if (!preg_match('/^[A-Z]++$/D', $method)) { + throw new SuspiciousOperationException(sprintf('Invalid method override "%s".', $method)); } - return $this->method; + return $this->method = $method; } /** From 6e55efd7d63be870606c2d908dca90285da9f577 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 19 Apr 2019 15:15:45 +0200 Subject: [PATCH 171/225] [HttpFoundation] fix tests --- Tests/ResponseTest.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 68634f6d4..fe6bc027a 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -942,14 +942,15 @@ public function ianaCodesReasonPhrasesProvider() $ianaHttpStatusCodes = new \DOMDocument(); - libxml_set_streams_context(stream_context_create([ + $context = stream_context_create([ 'http' => [ 'method' => 'GET', 'timeout' => 30, + 'user_agent' => __METHOD__, ], - ])); + ]); - $ianaHttpStatusCodes->load('https://www.iana.org/assignments/http-status-codes/http-status-codes.xml'); + $ianaHttpStatusCodes->loadXML(file_get_contents('https://www.iana.org/assignments/http-status-codes/http-status-codes.xml', false, $context)); if (!$ianaHttpStatusCodes->relaxNGValidate(__DIR__.'/schema/http-status-codes.rng')) { self::fail('Invalid IANA\'s HTTP status code list.'); } From fa02215233be8de1c2b44617088192f9e8db3512 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 1 May 2019 10:04:33 +0200 Subject: [PATCH 172/225] Revert "bug #30620 [FrameworkBundle][HttpFoundation] make session service resettable (dmaicher)" This reverts commit 029fb2e7e36b7cdf29e27d4bfa54dd11adc5d457, reversing changes made to 9dad29d61c5605b589493efe34012fdb1218b92b. --- Session/Session.php | 4 +--- Tests/Session/SessionTest.php | 10 ---------- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/Session/Session.php b/Session/Session.php index 62ce948b6..867ceba97 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -193,9 +193,7 @@ public function migrate($destroy = false, $lifetime = null) */ public function save() { - if ($this->isStarted()) { - $this->storage->save(); - } + $this->storage->save(); } /** diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index e75b3321b..afa00fc7c 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -260,14 +260,4 @@ public function testIsEmpty() $flash->get('hello'); $this->assertTrue($this->session->isEmpty()); } - - public function testSaveIfNotStarted() - { - $storage = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface')->getMock(); - $session = new Session($storage); - - $storage->expects($this->once())->method('isStarted')->willReturn(false); - $storage->expects($this->never())->method('save'); - $session->save(); - } } From f9bb07318c806a7dbe246f196b8af941585ad8e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcos=20G=C3=B3mez=20Vilches?= Date: Fri, 10 May 2019 21:58:31 +0200 Subject: [PATCH 173/225] Allow set 'None' on samesite cookie flag Allow set samesite cookie flag to 'None' value --- Cookie.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cookie.php b/Cookie.php index e61619aa6..83a97087f 100644 --- a/Cookie.php +++ b/Cookie.php @@ -28,6 +28,7 @@ class Cookie private $raw; private $sameSite; + const SAMESITE_NONE = 'none'; const SAMESITE_LAX = 'lax'; const SAMESITE_STRICT = 'strict'; @@ -128,7 +129,7 @@ public function __construct($name, $value = null, $expire = 0, $path = '/', $dom $sameSite = strtolower($sameSite); } - if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, null], true)) { + if (!\in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE, null], true)) { throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.'); } From cb67f0c746ba61916cf4dc1b1a200b284a332cb9 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sat, 18 May 2019 18:33:51 +0200 Subject: [PATCH 174/225] fixed a phpdoc --- Session/Flash/FlashBagInterface.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Session/Flash/FlashBagInterface.php b/Session/Flash/FlashBagInterface.php index 2bd1d62bd..99e807421 100644 --- a/Session/Flash/FlashBagInterface.php +++ b/Session/Flash/FlashBagInterface.php @@ -21,7 +21,7 @@ interface FlashBagInterface extends SessionBagInterface { /** - * Adds a flash message for type. + * Adds a flash message for the given type. * * @param string $type * @param mixed $message @@ -29,12 +29,12 @@ interface FlashBagInterface extends SessionBagInterface public function add($type, $message); /** - * Registers a message for a given type. + * Registers one or more messages for a given type. * * @param string $type - * @param string|array $message + * @param string|array $messages */ - public function set($type, $message); + public function set($type, $messages); /** * Gets flash messages for a given type. From 677ae5e892b081e71a665bfa7dd90fe61800c00e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4fer?= Date: Sun, 26 May 2019 22:50:43 +0200 Subject: [PATCH 175/225] Fixes a small doc blocks syntax error --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index ae3f51b17..ea3f460c4 100644 --- a/Request.php +++ b/Request.php @@ -2050,7 +2050,7 @@ private function setPhpDefaultLocale($locale) } } - /* + /** * Returns the prefix as encoded in the string when the string starts with * the given prefix, false otherwise. * From 1083dce548200fcdbf9324ec57c849a82b4f51ea Mon Sep 17 00:00:00 2001 From: mmokhi Date: Fri, 24 May 2019 19:14:44 +0200 Subject: [PATCH 176/225] Use AsserEquals for floating-point values Use AssertEquals for these two specific case will do a better job, since it'll convert both '0.1' and result of `getContent()` into PHP's internal representation of floating-point and compares them and it should be fine. Using `AssertSame` for this tests brings floating-point serialization into consideration which of course will be php.ini specific. In order not missing the type assertion point that `AssertSame` does, we also perform `assertInternalType('string'...` Sponsored-by: Platform.sh --- Tests/JsonResponseTest.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index 5425896df..ef0346cbe 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -52,7 +52,8 @@ public function testConstructorWithSimpleTypes() $this->assertSame('0', $response->getContent()); $response = new JsonResponse(0.1); - $this->assertSame('0.1', $response->getContent()); + $this->assertEquals('0.1', $response->getContent()); + $this->assertInternalType('string', $response->getContent()); $response = new JsonResponse(true); $this->assertSame('true', $response->getContent()); @@ -140,7 +141,8 @@ public function testStaticCreateWithSimpleTypes() $response = JsonResponse::create(0.1); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); - $this->assertSame('0.1', $response->getContent()); + $this->assertEquals('0.1', $response->getContent()); + $this->assertInternalType('string', $response->getContent()); $response = JsonResponse::create(true); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); From 820936976d91674a52b3589d2cc75a0e93cd1af9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vilius=20Grigali=C5=ABnas?= Date: Fri, 24 May 2019 11:41:23 +0300 Subject: [PATCH 177/225] [HttpFoundation] Do not set X-Accel-Redirect for paths outside of X-Accel-Mapping Currently BinaryFileResponse, when configured with X-Accel-Redirect sendfile type, will only substitute file paths specified in X-Accel-Mapping. But if the provided file path does not have a defined prefix, then the resulting header will include the absolute path. Nginx expects a valid URI, therefore this will result in an issue that is very hard to detect and debug as it will not show up in error logs and instead the request would just hang for some time and then be re-served without query parameters(?). --- BinaryFileResponse.php | 9 +++++++-- Tests/BinaryFileResponseTest.php | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index cf648dfe9..6c9a995e9 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -227,13 +227,18 @@ public function prepare(Request $request) if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) { $path = $location.substr($path, \strlen($pathPrefix)); + // Only set X-Accel-Redirect header if a valid URI can be produced + // as nginx does not serve arbitrary file paths. + $this->headers->set($type, $path); + $this->maxlen = 0; break; } } } + } else { + $this->headers->set($type, $path); + $this->maxlen = 0; } - $this->headers->set($type, $path); - $this->maxlen = 0; } elseif ($request->headers->has('Range')) { // Process the range headers. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) { diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index c89f20d05..853b4bb3d 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -338,6 +338,7 @@ public function getSampleXAccelMappings() return [ ['/var/www/var/www/files/foo.txt', '/var/www/=/files/', '/files/var/www/files/foo.txt'], ['/home/foo/bar.txt', '/var/www/=/files/,/home/foo/=/baz/', '/baz/bar.txt'], + ['/tmp/bar.txt', '"/var/www/"="/files/", "/home/Foo/"="/baz/"', null], ]; } From 1c057de3bb3a397e18a5a9a020f8cb764acb99bf Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Thu, 30 May 2019 16:56:20 +0200 Subject: [PATCH 178/225] Use willReturn() instead of will(returnValue()). --- Tests/File/FileTest.php | 2 +- .../Handler/MemcacheSessionHandlerTest.php | 4 +-- .../Handler/MemcachedSessionHandlerTest.php | 6 ++-- .../Handler/MongoDbSessionHandlerTest.php | 32 +++++++++---------- .../Storage/Handler/PdoSessionHandlerTest.php | 10 +++--- .../Handler/WriteCheckSessionHandlerTest.php | 10 +++--- .../Storage/Proxy/SessionHandlerProxyTest.php | 8 ++--- 7 files changed, 36 insertions(+), 36 deletions(-) diff --git a/Tests/File/FileTest.php b/Tests/File/FileTest.php index fb82dae76..caf202992 100644 --- a/Tests/File/FileTest.php +++ b/Tests/File/FileTest.php @@ -172,7 +172,7 @@ protected function createMockGuesser($path, $mimeType) ->expects($this->once()) ->method('guess') ->with($this->equalTo($path)) - ->will($this->returnValue($mimeType)) + ->willReturn($mimeType) ; return $guesser; diff --git a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php index 68daa4e5c..d7a324fc2 100644 --- a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php @@ -79,7 +79,7 @@ public function testWriteSession() ->expects($this->once()) ->method('set') ->with(self::PREFIX.'id', 'data', 0, $this->equalTo(time() + self::TTL, 2)) - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertTrue($this->storage->write('id', 'data')); @@ -91,7 +91,7 @@ public function testDestroySession() ->expects($this->once()) ->method('delete') ->with(self::PREFIX.'id') - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertTrue($this->storage->destroy('id')); diff --git a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php index 813337349..c3deb7aed 100644 --- a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php @@ -66,7 +66,7 @@ public function testCloseSession() $this->memcached ->expects($this->once()) ->method('quit') - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertTrue($this->storage->close()); @@ -89,7 +89,7 @@ public function testWriteSession() ->expects($this->once()) ->method('set') ->with(self::PREFIX.'id', 'data', $this->equalTo(time() + self::TTL, 2)) - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertTrue($this->storage->write('id', 'data')); @@ -101,7 +101,7 @@ public function testDestroySession() ->expects($this->once()) ->method('delete') ->with(self::PREFIX.'id') - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertTrue($this->storage->destroy('id')); diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 6f2742ca7..5ce6a9e5a 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -95,7 +95,7 @@ public function testRead() $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) - ->will($this->returnValue($collection)); + ->willReturn($collection); // defining the timeout before the actual method call // allows to test for "greater than" values in the $criteria @@ -103,7 +103,7 @@ public function testRead() $collection->expects($this->once()) ->method('findOne') - ->will($this->returnCallback(function ($criteria) use ($testTimeout) { + ->willReturnCallback(function ($criteria) use ($testTimeout) { $this->assertArrayHasKey($this->options['id_field'], $criteria); $this->assertEquals($criteria[$this->options['id_field']], 'foo'); @@ -131,7 +131,7 @@ public function testRead() } return $fields; - })); + }); $this->assertEquals('bar', $this->storage->read('foo')); } @@ -143,7 +143,7 @@ public function testWrite() $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) - ->will($this->returnValue($collection)); + ->willReturn($collection); $data = []; @@ -151,7 +151,7 @@ public function testWrite() $collection->expects($this->once()) ->method($methodName) - ->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) { + ->willReturnCallback(function ($criteria, $updateData, $options) use (&$data) { $this->assertEquals([$this->options['id_field'] => 'foo'], $criteria); if (phpversion('mongodb')) { @@ -161,7 +161,7 @@ public function testWrite() } $data = $updateData['$set']; - })); + }); $expectedExpiry = time() + (int) ini_get('session.gc_maxlifetime'); $this->assertTrue($this->storage->write('foo', 'bar')); @@ -197,7 +197,7 @@ public function testWriteWhenUsingExpiresField() $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) - ->will($this->returnValue($collection)); + ->willReturn($collection); $data = []; @@ -205,7 +205,7 @@ public function testWriteWhenUsingExpiresField() $collection->expects($this->once()) ->method($methodName) - ->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) { + ->willReturnCallback(function ($criteria, $updateData, $options) use (&$data) { $this->assertEquals([$this->options['id_field'] => 'foo'], $criteria); if (phpversion('mongodb')) { @@ -215,7 +215,7 @@ public function testWriteWhenUsingExpiresField() } $data = $updateData['$set']; - })); + }); $this->assertTrue($this->storage->write('foo', 'bar')); @@ -237,7 +237,7 @@ public function testReplaceSessionData() $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) - ->will($this->returnValue($collection)); + ->willReturn($collection); $data = []; @@ -245,9 +245,9 @@ public function testReplaceSessionData() $collection->expects($this->exactly(2)) ->method($methodName) - ->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) { + ->willReturnCallback(function ($criteria, $updateData, $options) use (&$data) { $data = $updateData; - })); + }); $this->storage->write('foo', 'bar'); $this->storage->write('foo', 'foobar'); @@ -266,7 +266,7 @@ public function testDestroy() $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) - ->will($this->returnValue($collection)); + ->willReturn($collection); $methodName = phpversion('mongodb') ? 'deleteOne' : 'remove'; @@ -284,13 +284,13 @@ public function testGc() $this->mongo->expects($this->once()) ->method('selectCollection') ->with($this->options['database'], $this->options['collection']) - ->will($this->returnValue($collection)); + ->willReturn($collection); $methodName = phpversion('mongodb') ? 'deleteMany' : 'remove'; $collection->expects($this->once()) ->method($methodName) - ->will($this->returnCallback(function ($criteria) { + ->willReturnCallback(function ($criteria) { if (phpversion('mongodb')) { $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $criteria[$this->options['expiry_field']]['$lt']); $this->assertGreaterThanOrEqual(time() - 1, round((string) $criteria[$this->options['expiry_field']]['$lt'] / 1000)); @@ -298,7 +298,7 @@ public function testGc() $this->assertInstanceOf('MongoDate', $criteria[$this->options['expiry_field']]['$lt']); $this->assertGreaterThanOrEqual(time() - 1, $criteria[$this->options['expiry_field']]['$lt']->sec); } - })); + }); $this->assertTrue($this->storage->gc(1)); } diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 901078478..f0914eb43 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -147,7 +147,7 @@ public function testReadConvertsStreamToString() $stream = $this->createStream($content); $pdo->prepareResult->expects($this->once())->method('fetchAll') - ->will($this->returnValue([[$stream, 42, time()]])); + ->willReturn([[$stream, 42, time()]]); $storage = new PdoSessionHandler($pdo); $result = $storage->read('foo'); @@ -177,14 +177,14 @@ public function testReadLockedConvertsStreamToString() $exception = null; $selectStmt->expects($this->atLeast(2))->method('fetchAll') - ->will($this->returnCallback(function () use (&$exception, $stream) { + ->willReturnCallback(function () use (&$exception, $stream) { return $exception ? [[$stream, 42, time()]] : []; - })); + }); $insertStmt->expects($this->once())->method('execute') - ->will($this->returnCallback(function () use (&$exception) { + ->willReturnCallback(function () use (&$exception) { throw $exception = new \PDOException('', '23'); - })); + }); $storage = new PdoSessionHandler($pdo); $result = $storage->read('foo'); diff --git a/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php b/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php index 898a7d11a..b89454f87 100644 --- a/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.php @@ -30,7 +30,7 @@ public function test() ->expects($this->once()) ->method('close') ->with() - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertTrue($writeCheckSessionHandler->close()); @@ -45,7 +45,7 @@ public function testWrite() ->expects($this->once()) ->method('write') ->with('foo', 'bar') - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertTrue($writeCheckSessionHandler->write('foo', 'bar')); @@ -60,7 +60,7 @@ public function testSkippedWrite() ->expects($this->once()) ->method('read') ->with('foo') - ->will($this->returnValue('bar')) + ->willReturn('bar') ; $wrappedSessionHandlerMock @@ -81,14 +81,14 @@ public function testNonSkippedWrite() ->expects($this->once()) ->method('read') ->with('foo') - ->will($this->returnValue('bar')) + ->willReturn('bar') ; $wrappedSessionHandlerMock ->expects($this->once()) ->method('write') ->with('foo', 'baZZZ') - ->will($this->returnValue(true)) + ->willReturn(true) ; $this->assertEquals('bar', $writeCheckSessionHandler->read('foo')); diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index 0459a8ce9..b6e0da99d 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -50,7 +50,7 @@ public function testOpenTrue() { $this->mock->expects($this->once()) ->method('open') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertFalse($this->proxy->isActive()); $this->proxy->open('name', 'id'); @@ -61,7 +61,7 @@ public function testOpenFalse() { $this->mock->expects($this->once()) ->method('open') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->proxy->isActive()); $this->proxy->open('name', 'id'); @@ -72,7 +72,7 @@ public function testClose() { $this->mock->expects($this->once()) ->method('close') - ->will($this->returnValue(true)); + ->willReturn(true); $this->assertFalse($this->proxy->isActive()); $this->proxy->close(); @@ -83,7 +83,7 @@ public function testCloseFalse() { $this->mock->expects($this->once()) ->method('close') - ->will($this->returnValue(false)); + ->willReturn(false); $this->assertFalse($this->proxy->isActive()); $this->proxy->close(); From ac4ad2bc93ca529b17a0305913e311d99c75f695 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 4 Jun 2019 20:42:06 +0200 Subject: [PATCH 179/225] [HttpFoundation] work around PHP 7.3 bug related to json_encode() --- JsonResponse.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/JsonResponse.php b/JsonResponse.php index 6fb32ee41..52f55f748 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -153,6 +153,11 @@ public function setData($data = []) restore_error_handler(); } } else { + if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $this->encodingOptions)) { + // Work around https://bugs.php.net/77997 + json_encode(null); + } + try { $data = json_encode($data, $this->encodingOptions); } catch (\Exception $e) { From 66e146ea791cd8689c1f7a55e2f6d4ea1f00b6f2 Mon Sep 17 00:00:00 2001 From: Ivo Date: Wed, 5 Jun 2019 10:24:41 +0200 Subject: [PATCH 180/225] [HttpFoundation] Fixed case-sensitive handling of cache-control header in RedirectResponse constructor. --- RedirectResponse.php | 2 +- Tests/RedirectResponseTest.php | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/RedirectResponse.php b/RedirectResponse.php index 5e1dfe585..51fd869ab 100644 --- a/RedirectResponse.php +++ b/RedirectResponse.php @@ -42,7 +42,7 @@ public function __construct($url, $status = 302, $headers = []) throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status)); } - if (301 == $status && !\array_key_exists('cache-control', $headers)) { + if (301 == $status && !\array_key_exists('cache-control', array_change_key_case($headers, \CASE_LOWER))) { $this->headers->remove('cache-control'); } } diff --git a/Tests/RedirectResponseTest.php b/Tests/RedirectResponseTest.php index 64c3e73ee..5f6a8ac08 100644 --- a/Tests/RedirectResponseTest.php +++ b/Tests/RedirectResponseTest.php @@ -91,6 +91,10 @@ public function testCacheHeaders() $this->assertFalse($response->headers->hasCacheControlDirective('no-cache')); $this->assertTrue($response->headers->hasCacheControlDirective('max-age')); + $response = new RedirectResponse('foo.bar', 301, ['Cache-Control' => 'max-age=86400']); + $this->assertFalse($response->headers->hasCacheControlDirective('no-cache')); + $this->assertTrue($response->headers->hasCacheControlDirective('max-age')); + $response = new RedirectResponse('foo.bar', 302); $this->assertTrue($response->headers->hasCacheControlDirective('no-cache')); } From 7c77e0198afaf32de3d1ca69daeef578548472ab Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 5 Jun 2019 13:22:47 +0200 Subject: [PATCH 181/225] Fix json-encoding when JSON_THROW_ON_ERROR is used --- JsonResponse.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/JsonResponse.php b/JsonResponse.php index 52f55f748..24798eea4 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -153,11 +153,6 @@ public function setData($data = []) restore_error_handler(); } } else { - if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $this->encodingOptions)) { - // Work around https://bugs.php.net/77997 - json_encode(null); - } - try { $data = json_encode($data, $this->encodingOptions); } catch (\Exception $e) { @@ -166,6 +161,10 @@ public function setData($data = []) } throw $e; } + + if (\PHP_VERSION_ID >= 70300 && (JSON_THROW_ON_ERROR & $this->encodingOptions)) { + return $this->setJson($data); + } } } From 77d3e3ae307656f08a8679f7ce39b4ecbffbd201 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 13 Jun 2019 12:34:15 +0200 Subject: [PATCH 182/225] fixed CS --- Session/Storage/Handler/PdoSessionHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index bc088e774..9369740eb 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -683,7 +683,7 @@ private function doAdvisoryLock($sessionId) switch ($this->driver) { case 'mysql': // MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced. - $lockId = \substr($sessionId, 0, 64); + $lockId = substr($sessionId, 0, 64); // should we handle the return value? 0 on timeout, null on error // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)'); From 7f495924198496c3c7383e387a48597bd580f434 Mon Sep 17 00:00:00 2001 From: Stefano Degenkamp Date: Wed, 12 Jun 2019 11:28:52 +0200 Subject: [PATCH 183/225] Fix binary operation `+`, `-` or `*` on string By type casting to integer. --- Response.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Response.php b/Response.php index b7d116259..4ab05066f 100644 --- a/Response.php +++ b/Response.php @@ -707,7 +707,7 @@ public function getAge() return (int) $age; } - return max(time() - $this->getDate()->format('U'), 0); + return max(time() - (int) $this->getDate()->format('U'), 0); } /** @@ -788,7 +788,7 @@ public function getMaxAge() } if (null !== $this->getExpires()) { - return $this->getExpires()->format('U') - $this->getDate()->format('U'); + return (int) $this->getExpires()->format('U') - (int) $this->getDate()->format('U'); } } From db1d8bed54c05ecffb364b55189679e8fbf701a2 Mon Sep 17 00:00:00 2001 From: Roland Franssen Date: Sat, 15 Jun 2019 08:54:32 +0200 Subject: [PATCH 184/225] [HttpFoundation] Fix SA/phpdoc JsonResponse --- JsonResponse.php | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/JsonResponse.php b/JsonResponse.php index 24798eea4..9c7c8e4c9 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -55,10 +55,10 @@ public function __construct($data = null, $status = 200, $headers = [], $json = * * Example: * - * return JsonResponse::create($data, 200) + * return JsonResponse::create(['key' => 'value']) * ->setSharedMaxAge(300); * - * @param mixed $data The json response data + * @param mixed $data The JSON response data * @param int $status The response status code * @param array $headers An array of response headers * @@ -70,7 +70,18 @@ public static function create($data = null, $status = 200, $headers = []) } /** - * Make easier the creation of JsonResponse from raw json. + * Factory method for chainability. + * + * Example: + * + * return JsonResponse::fromJsonString('{"key": "value"}') + * ->setSharedMaxAge(300); + * + * @param string|null $data The JSON response string + * @param int $status The response status code + * @param array $headers An array of response headers + * + * @return static */ public static function fromJsonString($data = null, $status = 200, $headers = []) { From 25720602691b20baac68bad101b2361194fe1ab3 Mon Sep 17 00:00:00 2001 From: Alex Bowers Date: Wed, 19 Jun 2019 12:46:55 +0100 Subject: [PATCH 185/225] Don't assume port 0 for X-Forwarded-Port --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index ea3f460c4..fc26304ad 100644 --- a/Request.php +++ b/Request.php @@ -1037,7 +1037,7 @@ public function getPort() $pos = strrpos($host, ':'); } - if (false !== $pos) { + if (false !== $pos && !empty(substr($host, $pos + 1))) { return (int) substr($host, $pos + 1); } From b1203f9576afbb2052108eebab375203125f2f92 Mon Sep 17 00:00:00 2001 From: Stefano Degenkamp Date: Wed, 19 Jun 2019 16:56:52 +0200 Subject: [PATCH 186/225] Update ajax security cheat sheet link As the cheat sheet series project has been moved to github. --- JsonResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JsonResponse.php b/JsonResponse.php index 24798eea4..bb1fe1d0a 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -18,7 +18,7 @@ * object. It is however recommended that you do return an object as it * protects yourself against XSSI and JSON-JavaScript Hijacking. * - * @see https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside + * @see https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/AJAX_Security_Cheat_Sheet.md#always-return-json-with-an-object-on-the-outside * * @author Igor Wiedler */ From 75c9946dee51091ce3fa561f5c76da3aef16bb11 Mon Sep 17 00:00:00 2001 From: Alex Bowers Date: Wed, 19 Jun 2019 17:03:11 +0100 Subject: [PATCH 187/225] Update Request.php --- Request.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Request.php b/Request.php index fc26304ad..38b7fc216 100644 --- a/Request.php +++ b/Request.php @@ -1037,8 +1037,8 @@ public function getPort() $pos = strrpos($host, ':'); } - if (false !== $pos && !empty(substr($host, $pos + 1))) { - return (int) substr($host, $pos + 1); + if (false !== $pos && '' !== $port = substr($host, $pos + 1)) { + return (int) $port; } return 'https' === $this->getScheme() ? 443 : 80; From 8cfbf75bb3a72963b12c513a73e9247891df24f8 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sat, 22 Jun 2019 22:10:25 +0200 Subject: [PATCH 188/225] fix accessing session bags --- Session/Session.php | 4 +++- Tests/Session/SessionTest.php | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Session/Session.php b/Session/Session.php index 867ceba97..db0b9aeb0 100644 --- a/Session/Session.php +++ b/Session/Session.php @@ -253,7 +253,9 @@ public function registerBag(SessionBagInterface $bag) */ public function getBag($name) { - return $this->storage->getBag($name)->getBag(); + $bag = $this->storage->getBag($name); + + return method_exists($bag, 'getBag') ? $bag->getBag() : $bag; } /** diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index afa00fc7c..acb129984 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -15,6 +15,7 @@ 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\SessionBagProxy; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; /** @@ -260,4 +261,28 @@ public function testIsEmpty() $flash->get('hello'); $this->assertTrue($this->session->isEmpty()); } + + public function testGetBagWithBagImplementingGetBag() + { + $bag = new AttributeBag(); + $bag->setName('foo'); + + $storage = new MockArraySessionStorage(); + $storage->registerBag($bag); + + $this->assertSame($bag, (new Session($storage))->getBag('foo')); + } + + public function testGetBagWithBagNotImplementingGetBag() + { + $data = []; + + $bag = new AttributeBag(); + $bag->setName('foo'); + + $storage = new MockArraySessionStorage(); + $storage->registerBag(new SessionBagProxy($bag, $data, $usageIndex)); + + $this->assertSame($bag, (new Session($storage))->getBag('foo')); + } } From 6005107cf296be17c4d342fb4dffcfcd410399b4 Mon Sep 17 00:00:00 2001 From: Valentin Udaltsov Date: Thu, 27 Jun 2019 13:35:22 +0300 Subject: [PATCH 189/225] [HttpFoundation] Throw exception when the \"session\" extension is not loaded --- Session/Storage/NativeSessionStorage.php | 4 ++++ Session/Storage/PhpBridgeSessionStorage.php | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index c4dbe7586..809d7002c 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -100,6 +100,10 @@ class NativeSessionStorage implements SessionStorageInterface */ public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null) { + if (!\extension_loaded('session')) { + throw new \LogicException('PHP extension "session" is required.'); + } + $options += [ 'cache_limiter' => '', 'cache_expire' => 0, diff --git a/Session/Storage/PhpBridgeSessionStorage.php b/Session/Storage/PhpBridgeSessionStorage.php index 662ed5015..8969e609a 100644 --- a/Session/Storage/PhpBridgeSessionStorage.php +++ b/Session/Storage/PhpBridgeSessionStorage.php @@ -24,6 +24,10 @@ class PhpBridgeSessionStorage extends NativeSessionStorage */ public function __construct($handler = null, MetadataBag $metaBag = null) { + if (!\extension_loaded('session')) { + throw new \LogicException('PHP extension "session" is required.'); + } + $this->setMetadataBag($metaBag); $this->setSaveHandler($handler); } From 91b374c7e43da52615e8e59232c55c13352fb141 Mon Sep 17 00:00:00 2001 From: Alex Bowers Date: Sun, 30 Jun 2019 23:48:04 +0100 Subject: [PATCH 190/225] Add test case --- Tests/RequestTest.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index d266e1f68..650d8fca7 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -2427,6 +2427,18 @@ public function testTrustedPort() $this->assertSame(443, $request->getPort()); } + + public function testTrustedPortDoesNotDefaultToZero() + { + Request::setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_ALL); + + $request = Request::create('/'); + $request->server->set('REMOTE_ADDR', '1.1.1.1'); + $request->headers->set('X-Forwarded-Host', 'test.example.com'); + $request->headers->set('X-Forwarded-Port', null); + + $this->assertSame(80, $request->getPort()); + } } class RequestContentProxy extends Request From e135ecf5443500a310d29ef3df722096d39f53de Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Thu, 4 Jul 2019 22:58:06 +0200 Subject: [PATCH 191/225] PHP 5 compat --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 38b7fc216..7185d75e9 100644 --- a/Request.php +++ b/Request.php @@ -1037,7 +1037,7 @@ public function getPort() $pos = strrpos($host, ':'); } - if (false !== $pos && '' !== $port = substr($host, $pos + 1)) { + if (false !== $pos && $port = substr($host, $pos + 1)) { return (int) $port; } From 8d530ef09f8303aba64a8400f41fff6ecf8dc924 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Mon, 8 Jul 2019 13:57:06 +0200 Subject: [PATCH 192/225] fixed CS --- Tests/RequestTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 650d8fca7..73d12cb3f 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -2435,7 +2435,7 @@ public function testTrustedPortDoesNotDefaultToZero() $request = Request::create('/'); $request->server->set('REMOTE_ADDR', '1.1.1.1'); $request->headers->set('X-Forwarded-Host', 'test.example.com'); - $request->headers->set('X-Forwarded-Port', null); + $request->headers->set('X-Forwarded-Port', ''); $this->assertSame(80, $request->getPort()); } From 61217e46f7fbc5cfbb22e15e50744c151e2675ad Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Fri, 19 Jul 2019 13:42:31 +0200 Subject: [PATCH 193/225] Remove dead tests fixtures --- Tests/ResponseTest.php | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index fe6bc027a..40200ee31 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -1001,14 +1001,3 @@ public function __toString() class DefaultResponse extends Response { } - -class ExtendedResponse extends Response -{ - public function setLastModified(\DateTime $date = null) - { - } - - public function getDate() - { - } -} From c450706851050ade2e1f30d012d50bb9173f7f3d Mon Sep 17 00:00:00 2001 From: Arman Hosseini <44655055+Arman-Hosseini@users.noreply.github.com> Date: Fri, 19 Jul 2019 23:09:57 +0430 Subject: [PATCH 194/225] [HttpFoundation] Fix URLs --- Session/Storage/Handler/MongoDbSessionHandler.php | 2 +- Session/Storage/Handler/NativeFileSessionHandler.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index 3b5ccaa83..ddedacffb 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -17,7 +17,7 @@ * @author Markus Bachmann * * @see https://packagist.org/packages/mongodb/mongodb - * @see http://php.net/manual/en/set.mongodb.php + * @see https://php.net/mongodb */ class MongoDbSessionHandler extends AbstractSessionHandler { diff --git a/Session/Storage/Handler/NativeFileSessionHandler.php b/Session/Storage/Handler/NativeFileSessionHandler.php index 4e9704bd5..04bcbbfe3 100644 --- a/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/Session/Storage/Handler/NativeFileSessionHandler.php @@ -23,7 +23,7 @@ class NativeFileSessionHandler extends NativeSessionHandler * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path * - * @see http://php.net/session.configuration.php#ini.session.save-path for further details. + * @see https://php.net/manual/session.configuration.php#ini.session.save-path for further details. * * @throws \InvalidArgumentException On invalid $savePath * @throws \RuntimeException When failing to create the save directory From a72c8a528271cb2dd5e210e8cdaa0df55fdbd0da Mon Sep 17 00:00:00 2001 From: Gocha Ossinkine Date: Tue, 23 Jul 2019 19:02:38 +0500 Subject: [PATCH 195/225] [HttpFoundation] Revert getClientIp @return docblock --- Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Request.php b/Request.php index 7185d75e9..0f7f46fff 100644 --- a/Request.php +++ b/Request.php @@ -912,7 +912,7 @@ public function getClientIps() * ("Client-Ip" for instance), configure it via the $trustedHeaderSet * argument of the Request::setTrustedProxies() method instead. * - * @return string|null The client IP address + * @return string The client IP address * * @see getClientIps() * @see http://en.wikipedia.org/wiki/X-Forwarded-For From a9a0140d87d8e3c5f3a19ee4f8f150350ebfa268 Mon Sep 17 00:00:00 2001 From: Benny Born Date: Sun, 28 Jul 2019 12:33:26 +0200 Subject: [PATCH 196/225] [HttpFoundation] Fix `getMaxFilesize` --- File/UploadedFile.php | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/File/UploadedFile.php b/File/UploadedFile.php index a44c664b4..093aaf832 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -214,13 +214,26 @@ public function move($directory, $name = null) */ public static function getMaxFilesize() { - $iniMax = strtolower(ini_get('upload_max_filesize')); + $sizePostMax = self::parseFilesize(ini_get('post_max_size')); + $sizeUploadMax = self::parseFilesize(ini_get('upload_max_filesize')); - if ('' === $iniMax) { - return PHP_INT_MAX; + return min([$sizePostMax, $sizeUploadMax]); + } + + /** + * Returns the given size from an ini value in bytes. + * + * @return int The given size in bytes + */ + private static function parseFilesize($size) + { + if ('' === $size) { + return 0; } - $max = ltrim($iniMax, '+'); + $size = strtolower($size); + + $max = ltrim($size, '+'); if (0 === strpos($max, '0x')) { $max = \intval($max, 16); } elseif (0 === strpos($max, '0')) { @@ -229,7 +242,7 @@ public static function getMaxFilesize() $max = (int) $max; } - switch (substr($iniMax, -1)) { + switch (substr($size, -1)) { case 't': $max *= 1024; // no break case 'g': $max *= 1024; From c7bad486caf88e15b55b244cdaebf8bf03d07f8f Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 31 Jul 2019 21:19:25 +0200 Subject: [PATCH 197/225] Make tests support phpunit 8 --- Tests/BinaryFileResponseTest.php | 5 ++++- Tests/File/MimeType/MimeTypeTest.php | 5 ++++- Tests/File/UploadedFileTest.php | 5 ++++- Tests/FileBagTest.php | 7 +++++-- Tests/JsonResponseTest.php | 5 ++++- Tests/RequestTest.php | 5 ++++- Tests/ResponseFunctionalTest.php | 7 +++++-- Tests/Session/Attribute/AttributeBagTest.php | 7 +++++-- Tests/Session/Attribute/NamespacedAttributeBagTest.php | 7 +++++-- Tests/Session/Flash/AutoExpireFlashBagTest.php | 7 +++++-- Tests/Session/Flash/FlashBagTest.php | 7 +++++-- Tests/Session/SessionTest.php | 7 +++++-- .../Session/Storage/Handler/AbstractSessionHandlerTest.php | 7 +++++-- .../Session/Storage/Handler/MemcacheSessionHandlerTest.php | 7 +++++-- .../Storage/Handler/MemcachedSessionHandlerTest.php | 7 +++++-- .../Session/Storage/Handler/MongoDbSessionHandlerTest.php | 5 ++++- Tests/Session/Storage/Handler/PdoSessionHandlerTest.php | 5 ++++- Tests/Session/Storage/MetadataBagTest.php | 7 +++++-- Tests/Session/Storage/MockArraySessionStorageTest.php | 7 +++++-- Tests/Session/Storage/MockFileSessionStorageTest.php | 7 +++++-- Tests/Session/Storage/NativeSessionStorageTest.php | 7 +++++-- Tests/Session/Storage/PhpBridgeSessionStorageTest.php | 7 +++++-- Tests/Session/Storage/Proxy/AbstractProxyTest.php | 7 +++++-- Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php | 7 +++++-- 24 files changed, 113 insertions(+), 41 deletions(-) diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index 853b4bb3d..74d3e8162 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\HttpFoundation\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\File\Stream; use Symfony\Component\HttpFoundation\Request; @@ -19,6 +20,8 @@ class BinaryFileResponseTest extends ResponseTestCase { + use ForwardCompatTestTrait; + public function testConstruction() { $file = __DIR__.'/../README.md'; @@ -356,7 +359,7 @@ protected function provideResponse() return new BinaryFileResponse(__DIR__.'/../README.md', 200, ['Content-Type' => 'application/octet-stream']); } - public static function tearDownAfterClass() + private static function doTearDownAfterClass() { $path = __DIR__.'/../Fixtures/to_delete'; if (file_exists($path)) { diff --git a/Tests/File/MimeType/MimeTypeTest.php b/Tests/File/MimeType/MimeTypeTest.php index bb88807ab..9f3c87c98 100644 --- a/Tests/File/MimeType/MimeTypeTest.php +++ b/Tests/File/MimeType/MimeTypeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\File\MimeType; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\MimeType\FileBinaryMimeTypeGuesser; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser; @@ -20,6 +21,8 @@ */ class MimeTypeTest extends TestCase { + use ForwardCompatTestTrait; + protected $path; public function testGuessImageWithoutExtension() @@ -79,7 +82,7 @@ public function testGuessWithNonReadablePath() } } - public static function tearDownAfterClass() + private static function doTearDownAfterClass() { $path = __DIR__.'/../Fixtures/to_delete'; if (file_exists($path)) { diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 5a37cda35..f886ebcd1 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\HttpFoundation\Tests\File; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\UploadedFile; class UploadedFileTest extends TestCase { - protected function setUp() + use ForwardCompatTestTrait; + + private function doSetUp() { if (!ini_get('file_uploads')) { $this->markTestSkipped('file_uploads is disabled in php.ini'); diff --git a/Tests/FileBagTest.php b/Tests/FileBagTest.php index 0b6d66042..3ef868eaf 100644 --- a/Tests/FileBagTest.php +++ b/Tests/FileBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\FileBag; @@ -23,6 +24,8 @@ */ class FileBagTest extends TestCase { + use ForwardCompatTestTrait; + /** * @expectedException \InvalidArgumentException */ @@ -159,12 +162,12 @@ protected function createTempFile() return tempnam(sys_get_temp_dir().'/form_test', 'FormTest'); } - protected function setUp() + private function doSetUp() { mkdir(sys_get_temp_dir().'/form_test', 0777, true); } - protected function tearDown() + private function doTearDown() { foreach (glob(sys_get_temp_dir().'/form_test/*') as $file) { unlink($file); diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index ef0346cbe..56a40420a 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\JsonResponse; class JsonResponseTest extends TestCase { - protected function setUp() + use ForwardCompatTestTrait; + + private function doSetUp() { parent::setUp(); diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 73d12cb3f..219a16256 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\Session; @@ -19,7 +20,9 @@ class RequestTest extends TestCase { - protected function tearDown() + use ForwardCompatTestTrait; + + private function doTearDown() { Request::setTrustedProxies([], -1); Request::setTrustedHosts([]); diff --git a/Tests/ResponseFunctionalTest.php b/Tests/ResponseFunctionalTest.php index 3d3e696c7..e264710d1 100644 --- a/Tests/ResponseFunctionalTest.php +++ b/Tests/ResponseFunctionalTest.php @@ -12,15 +12,18 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; /** * @requires PHP 7.0 */ class ResponseFunctionalTest extends TestCase { + use ForwardCompatTestTrait; + private static $server; - public static function setUpBeforeClass() + private static function doSetUpBeforeClass() { $spec = [ 1 => ['file', '/dev/null', 'w'], @@ -32,7 +35,7 @@ public static function setUpBeforeClass() sleep(1); } - public static function tearDownAfterClass() + private static function doTearDownAfterClass() { if (self::$server) { proc_terminate(self::$server); diff --git a/Tests/Session/Attribute/AttributeBagTest.php b/Tests/Session/Attribute/AttributeBagTest.php index 3f2f7b3c8..aef66da1d 100644 --- a/Tests/Session/Attribute/AttributeBagTest.php +++ b/Tests/Session/Attribute/AttributeBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Attribute; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; /** @@ -21,6 +22,8 @@ */ class AttributeBagTest extends TestCase { + use ForwardCompatTestTrait; + private $array = []; /** @@ -28,7 +31,7 @@ class AttributeBagTest extends TestCase */ private $bag; - protected function setUp() + private function doSetUp() { $this->array = [ 'hello' => 'world', @@ -49,7 +52,7 @@ protected function setUp() $this->bag->initialize($this->array); } - protected function tearDown() + private function doTearDown() { $this->bag = null; $this->array = []; diff --git a/Tests/Session/Attribute/NamespacedAttributeBagTest.php b/Tests/Session/Attribute/NamespacedAttributeBagTest.php index 6b4bb17d6..a1f6bf5eb 100644 --- a/Tests/Session/Attribute/NamespacedAttributeBagTest.php +++ b/Tests/Session/Attribute/NamespacedAttributeBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Attribute; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag; /** @@ -21,6 +22,8 @@ */ class NamespacedAttributeBagTest extends TestCase { + use ForwardCompatTestTrait; + private $array = []; /** @@ -28,7 +31,7 @@ class NamespacedAttributeBagTest extends TestCase */ private $bag; - protected function setUp() + private function doSetUp() { $this->array = [ 'hello' => 'world', @@ -49,7 +52,7 @@ protected function setUp() $this->bag->initialize($this->array); } - protected function tearDown() + private function doTearDown() { $this->bag = null; $this->array = []; diff --git a/Tests/Session/Flash/AutoExpireFlashBagTest.php b/Tests/Session/Flash/AutoExpireFlashBagTest.php index b4e2c3a5a..65b205814 100644 --- a/Tests/Session/Flash/AutoExpireFlashBagTest.php +++ b/Tests/Session/Flash/AutoExpireFlashBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Flash; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag as FlashBag; /** @@ -21,6 +22,8 @@ */ class AutoExpireFlashBagTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var \Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag */ @@ -28,7 +31,7 @@ class AutoExpireFlashBagTest extends TestCase protected $array = []; - protected function setUp() + private function doSetUp() { parent::setUp(); $this->bag = new FlashBag(); @@ -36,7 +39,7 @@ protected function setUp() $this->bag->initialize($this->array); } - protected function tearDown() + private function doTearDown() { $this->bag = null; parent::tearDown(); diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index 6d8619e07..427af6d67 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Flash; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; /** @@ -21,6 +22,8 @@ */ class FlashBagTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var \Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface */ @@ -28,7 +31,7 @@ class FlashBagTest extends TestCase protected $array = []; - protected function setUp() + private function doSetUp() { parent::setUp(); $this->bag = new FlashBag(); @@ -36,7 +39,7 @@ protected function setUp() $this->bag->initialize($this->array); } - protected function tearDown() + private function doTearDown() { $this->bag = null; parent::tearDown(); diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index acb129984..51516e2f2 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Session; @@ -27,6 +28,8 @@ */ class SessionTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var \Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface */ @@ -37,13 +40,13 @@ class SessionTest extends TestCase */ protected $session; - protected function setUp() + private function doSetUp() { $this->storage = new MockArraySessionStorage(); $this->session = new Session($this->storage, new AttributeBag(), new FlashBag()); } - protected function tearDown() + private function doTearDown() { $this->storage = null; $this->session = null; diff --git a/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php index 98bc67bca..d83182be7 100644 --- a/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php @@ -12,15 +12,18 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; /** * @requires PHP 7.0 */ class AbstractSessionHandlerTest extends TestCase { + use ForwardCompatTestTrait; + private static $server; - public static function setUpBeforeClass() + private static function doSetUpBeforeClass() { $spec = [ 1 => ['file', '/dev/null', 'w'], @@ -32,7 +35,7 @@ public static function setUpBeforeClass() sleep(1); } - public static function tearDownAfterClass() + private static function doTearDownAfterClass() { if (self::$server) { proc_terminate(self::$server); diff --git a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php index d7a324fc2..d2526868d 100644 --- a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler; /** @@ -21,6 +22,8 @@ */ class MemcacheSessionHandlerTest extends TestCase { + use ForwardCompatTestTrait; + const PREFIX = 'prefix_'; const TTL = 1000; @@ -31,7 +34,7 @@ class MemcacheSessionHandlerTest extends TestCase protected $memcache; - protected function setUp() + private function doSetUp() { if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcache class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); @@ -45,7 +48,7 @@ protected function setUp() ); } - protected function tearDown() + private function doTearDown() { $this->memcache = null; $this->storage = null; diff --git a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php index c3deb7aed..86ac574d2 100644 --- a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler; /** @@ -20,6 +21,8 @@ */ class MemcachedSessionHandlerTest extends TestCase { + use ForwardCompatTestTrait; + const PREFIX = 'prefix_'; const TTL = 1000; @@ -30,7 +33,7 @@ class MemcachedSessionHandlerTest extends TestCase protected $memcached; - protected function setUp() + private function doSetUp() { if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcached class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); @@ -49,7 +52,7 @@ protected function setUp() ); } - protected function tearDown() + private function doTearDown() { $this->memcached = null; $this->storage = null; diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 5ce6a9e5a..a762de01c 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; /** @@ -21,6 +22,8 @@ */ class MongoDbSessionHandlerTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var \PHPUnit_Framework_MockObject_MockObject */ @@ -28,7 +31,7 @@ class MongoDbSessionHandlerTest extends TestCase private $storage; public $options; - protected function setUp() + private function doSetUp() { parent::setUp(); diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index f0914eb43..e9439c3da 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; /** @@ -20,9 +21,11 @@ */ class PdoSessionHandlerTest extends TestCase { + use ForwardCompatTestTrait; + private $dbFile; - protected function tearDown() + private function doTearDown() { // make sure the temporary database file is deleted when it has been created (even when a test fails) if ($this->dbFile) { diff --git a/Tests/Session/Storage/MetadataBagTest.php b/Tests/Session/Storage/MetadataBagTest.php index 2c4758b91..02cea3292 100644 --- a/Tests/Session/Storage/MetadataBagTest.php +++ b/Tests/Session/Storage/MetadataBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag; /** @@ -21,6 +22,8 @@ */ class MetadataBagTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var MetadataBag */ @@ -28,7 +31,7 @@ class MetadataBagTest extends TestCase protected $array = []; - protected function setUp() + private function doSetUp() { parent::setUp(); $this->bag = new MetadataBag(); @@ -36,7 +39,7 @@ protected function setUp() $this->bag->initialize($this->array); } - protected function tearDown() + private function doTearDown() { $this->array = []; $this->bag = null; diff --git a/Tests/Session/Storage/MockArraySessionStorageTest.php b/Tests/Session/Storage/MockArraySessionStorageTest.php index 2e3024ef1..c60a78910 100644 --- a/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; @@ -23,6 +24,8 @@ */ class MockArraySessionStorageTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var MockArraySessionStorage */ @@ -40,7 +43,7 @@ class MockArraySessionStorageTest extends TestCase private $data; - protected function setUp() + private function doSetUp() { $this->attributes = new AttributeBag(); $this->flashes = new FlashBag(); @@ -56,7 +59,7 @@ protected function setUp() $this->storage->setSessionData($this->data); } - protected function tearDown() + private function doTearDown() { $this->data = null; $this->flashes = null; diff --git a/Tests/Session/Storage/MockFileSessionStorageTest.php b/Tests/Session/Storage/MockFileSessionStorageTest.php index 9e2692dc0..36b4e605b 100644 --- a/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage; @@ -23,6 +24,8 @@ */ class MockFileSessionStorageTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var string */ @@ -33,13 +36,13 @@ class MockFileSessionStorageTest extends TestCase */ protected $storage; - protected function setUp() + private function doSetUp() { $this->sessionDir = sys_get_temp_dir().'/sf2test'; $this->storage = $this->getStorage(); } - protected function tearDown() + private function doTearDown() { $this->sessionDir = null; $this->storage = null; diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 7cc2eb79c..035b674c1 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; @@ -31,9 +32,11 @@ */ class NativeSessionStorageTest extends TestCase { + use ForwardCompatTestTrait; + private $savePath; - protected function setUp() + private function doSetUp() { $this->iniSet('session.save_handler', 'files'); $this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test'); @@ -42,7 +45,7 @@ protected function setUp() } } - protected function tearDown() + private function doTearDown() { session_write_close(); array_map('unlink', glob($this->savePath.'/*')); diff --git a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php index 752be618b..c8a53f169 100644 --- a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php +++ b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage; @@ -27,9 +28,11 @@ */ class PhpBridgeSessionStorageTest extends TestCase { + use ForwardCompatTestTrait; + private $savePath; - protected function setUp() + private function doSetUp() { $this->iniSet('session.save_handler', 'files'); $this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test'); @@ -38,7 +41,7 @@ protected function setUp() } } - protected function tearDown() + private function doTearDown() { session_write_close(); array_map('unlink', glob($this->savePath.'/*')); diff --git a/Tests/Session/Storage/Proxy/AbstractProxyTest.php b/Tests/Session/Storage/Proxy/AbstractProxyTest.php index cbb291f19..499a54a8e 100644 --- a/Tests/Session/Storage/Proxy/AbstractProxyTest.php +++ b/Tests/Session/Storage/Proxy/AbstractProxyTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; @@ -22,17 +23,19 @@ */ class AbstractProxyTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var AbstractProxy */ protected $proxy; - protected function setUp() + private function doSetUp() { $this->proxy = $this->getMockForAbstractClass(AbstractProxy::class); } - protected function tearDown() + private function doTearDown() { $this->proxy = null; } diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index b6e0da99d..63b3c8afb 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; /** @@ -24,6 +25,8 @@ */ class SessionHandlerProxyTest extends TestCase { + use ForwardCompatTestTrait; + /** * @var \PHPUnit_Framework_MockObject_Matcher */ @@ -34,13 +37,13 @@ class SessionHandlerProxyTest extends TestCase */ private $proxy; - protected function setUp() + private function doSetUp() { $this->mock = $this->getMockBuilder('SessionHandlerInterface')->getMock(); $this->proxy = new SessionHandlerProxy($this->mock); } - protected function tearDown() + private function doTearDown() { $this->mock = null; $this->proxy = null; From c51914dec54b1f7b27f24cda5eb73399d908395b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Thu, 1 Aug 2019 09:31:22 +0200 Subject: [PATCH 198/225] Fix assertInternalType deprecation in phpunit 9 --- Tests/JsonResponseTest.php | 4 ++-- Tests/RequestTest.php | 4 ++-- Tests/Session/Storage/NativeSessionStorageTest.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index 56a40420a..d19620530 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -56,7 +56,7 @@ public function testConstructorWithSimpleTypes() $response = new JsonResponse(0.1); $this->assertEquals('0.1', $response->getContent()); - $this->assertInternalType('string', $response->getContent()); + $this->assertIsString($response->getContent()); $response = new JsonResponse(true); $this->assertSame('true', $response->getContent()); @@ -145,7 +145,7 @@ public function testStaticCreateWithSimpleTypes() $response = JsonResponse::create(0.1); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); $this->assertEquals('0.1', $response->getContent()); - $this->assertInternalType('string', $response->getContent()); + $this->assertIsString($response->getContent()); $response = JsonResponse::create(true); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 219a16256..3f7ba6017 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1156,7 +1156,7 @@ public function testGetContentReturnsResource() { $req = new Request(); $retval = $req->getContent(true); - $this->assertInternalType('resource', $retval); + $this->assertIsResource($retval); $this->assertEquals('', fread($retval, 1)); $this->assertTrue(feof($retval)); } @@ -1166,7 +1166,7 @@ public function testGetContentReturnsResourceWhenContentSetInConstructor() $req = new Request([], [], [], [], [], [], 'MyContent'); $resource = $req->getContent(true); - $this->assertInternalType('resource', $resource); + $this->assertIsResource($resource); $this->assertEquals('MyContent', stream_get_contents($resource)); } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 035b674c1..18540264d 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -101,7 +101,7 @@ public function testGetId() $storage->start(); $id = $storage->getId(); - $this->assertInternalType('string', $id); + $this->assertIsString($id); $this->assertNotSame('', $id); $storage->save(); From f5527fa8c3a5c76f327f9171d9e7c60194b64da1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Thu, 1 Aug 2019 16:27:42 +0200 Subject: [PATCH 199/225] Replace calls to setExpectedException by Pollyfill --- Tests/File/FileTest.php | 5 ++++- Tests/File/MimeType/MimeTypeTest.php | 6 +++--- Tests/File/UploadedFileTest.php | 2 +- Tests/RequestTest.php | 8 ++------ 4 files changed, 10 insertions(+), 11 deletions(-) diff --git a/Tests/File/FileTest.php b/Tests/File/FileTest.php index caf202992..1f2582145 100644 --- a/Tests/File/FileTest.php +++ b/Tests/File/FileTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\HttpFoundation\Tests\File; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser; class FileTest extends TestCase { + use ForwardCompatTestTrait; + protected $file; public function testGetMimeTypeUsesMimeTypeGuessers() @@ -64,7 +67,7 @@ public function testGuessExtensionWithReset() public function testConstructWhenFileNotExists() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); new File(__DIR__.'/Fixtures/not_here'); } diff --git a/Tests/File/MimeType/MimeTypeTest.php b/Tests/File/MimeType/MimeTypeTest.php index 9f3c87c98..299fc7a24 100644 --- a/Tests/File/MimeType/MimeTypeTest.php +++ b/Tests/File/MimeType/MimeTypeTest.php @@ -32,7 +32,7 @@ public function testGuessImageWithoutExtension() public function testGuessImageWithDirectory() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/directory'); } @@ -56,7 +56,7 @@ public function testGuessFileWithUnknownExtension() public function testGuessWithIncorrectPath() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/not_here'); } @@ -75,7 +75,7 @@ public function testGuessWithNonReadablePath() @chmod($path, 0333); if ('0333' == substr(sprintf('%o', fileperms($path)), -4)) { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException'); MimeTypeGuesser::getInstance()->guess($path); } else { $this->markTestSkipped('Can not verify chmod operations, change of file permissions failed'); diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index f886ebcd1..3a203b4da 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -28,7 +28,7 @@ private function doSetUp() public function testConstructWhenFileNotExists() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); new UploadedFile( __DIR__.'/Fixtures/not_here', diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 3f7ba6017..e0e719d38 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -2121,12 +2121,8 @@ public function testHostValidity($host, $isValid, $expectedHost = null, $expecte $this->assertSame($expectedPort, $request->getPort()); } } else { - if (method_exists($this, 'expectException')) { - $this->expectException(SuspiciousOperationException::class); - $this->expectExceptionMessage('Invalid Host'); - } else { - $this->setExpectedException(SuspiciousOperationException::class, 'Invalid Host'); - } + $this->expectException(SuspiciousOperationException::class); + $this->expectExceptionMessage('Invalid Host'); $request->getHost(); } From c8b6934f07abf8642a9110a53d551a1e78ff7778 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Fri, 2 Aug 2019 00:48:42 +0200 Subject: [PATCH 200/225] Fix deprecated phpunit annotation --- Tests/BinaryFileResponseTest.php | 4 +--- Tests/CookieTest.php | 9 +++++---- Tests/ExpressionRequestMatcherTest.php | 7 ++++--- Tests/File/UploadedFileTest.php | 4 +--- Tests/FileBagTest.php | 4 +--- Tests/HeaderBagTest.php | 7 ++++--- Tests/IpUtilsTest.php | 5 ++++- Tests/JsonResponseTest.php | 14 ++++---------- Tests/RedirectResponseTest.php | 15 ++++++--------- Tests/RequestTest.php | 12 +++++------- Tests/ResponseHeaderBagTest.php | 13 ++++++------- Tests/ResponseTest.php | 11 +++++++---- .../Handler/MongoDbSessionHandlerTest.php | 8 ++------ .../Handler/NativeFileSessionHandlerTest.php | 7 ++++--- .../Storage/Handler/PdoSessionHandlerTest.php | 12 +++--------- .../Storage/MockArraySessionStorageTest.php | 4 +--- .../Storage/MockFileSessionStorageTest.php | 4 +--- .../Session/Storage/NativeSessionStorageTest.php | 16 ++++------------ .../Session/Storage/Proxy/AbstractProxyTest.php | 4 ++-- .../Storage/Proxy/SessionHandlerProxyTest.php | 2 +- Tests/StreamedResponseTest.php | 11 +++++------ 21 files changed, 71 insertions(+), 102 deletions(-) diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index 74d3e8162..9e27c7313 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -49,11 +49,9 @@ public function testConstructWithNonAsciiFilename() $this->assertSame('fööö.html', $response->getFile()->getFilename()); } - /** - * @expectedException \LogicException - */ public function testSetContent() { + $this->expectException('LogicException'); $response = new BinaryFileResponse(__FILE__); $response->setContent('foo'); } diff --git a/Tests/CookieTest.php b/Tests/CookieTest.php index aaf2edb38..2d69d9ace 100644 --- a/Tests/CookieTest.php +++ b/Tests/CookieTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Cookie; /** @@ -24,6 +25,8 @@ */ class CookieTest extends TestCase { + use ForwardCompatTestTrait; + public function invalidNames() { return [ @@ -41,18 +44,16 @@ public function invalidNames() /** * @dataProvider invalidNames - * @expectedException \InvalidArgumentException */ public function testInstantiationThrowsExceptionIfCookieNameContainsInvalidCharacters($name) { + $this->expectException('InvalidArgumentException'); new Cookie($name); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidExpiration() { + $this->expectException('InvalidArgumentException'); new Cookie('MyCookie', 'foo', 'bar'); } diff --git a/Tests/ExpressionRequestMatcherTest.php b/Tests/ExpressionRequestMatcherTest.php index 2afdade67..e750f39e6 100644 --- a/Tests/ExpressionRequestMatcherTest.php +++ b/Tests/ExpressionRequestMatcherTest.php @@ -12,17 +12,18 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\HttpFoundation\ExpressionRequestMatcher; use Symfony\Component\HttpFoundation\Request; class ExpressionRequestMatcherTest extends TestCase { - /** - * @expectedException \LogicException - */ + use ForwardCompatTestTrait; + public function testWhenNoExpressionIsSet() { + $this->expectException('LogicException'); $expressionRequestMatcher = new ExpressionRequestMatcher(); $expressionRequestMatcher->matches(new Request()); } diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 3a203b4da..9b48da7a2 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -145,11 +145,9 @@ public function testGetClientOriginalExtension() $this->assertEquals('gif', $file->getClientOriginalExtension()); } - /** - * @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileException - */ public function testMoveLocalFileIsNotAllowed() { + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileException'); $file = new UploadedFile( __DIR__.'/Fixtures/test.gif', 'original.gif', diff --git a/Tests/FileBagTest.php b/Tests/FileBagTest.php index 3ef868eaf..289c12bd3 100644 --- a/Tests/FileBagTest.php +++ b/Tests/FileBagTest.php @@ -26,11 +26,9 @@ class FileBagTest extends TestCase { use ForwardCompatTestTrait; - /** - * @expectedException \InvalidArgumentException - */ public function testFileMustBeAnArrayOrUploadedFile() { + $this->expectException('InvalidArgumentException'); new FileBag(['file' => 'foo']); } diff --git a/Tests/HeaderBagTest.php b/Tests/HeaderBagTest.php index 6c4915f2e..3eff56840 100644 --- a/Tests/HeaderBagTest.php +++ b/Tests/HeaderBagTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\HeaderBag; class HeaderBagTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $bag = new HeaderBag(['foo' => 'bar']); @@ -48,11 +51,9 @@ public function testGetDate() $this->assertInstanceOf('DateTime', $headerDate); } - /** - * @expectedException \RuntimeException - */ public function testGetDateException() { + $this->expectException('RuntimeException'); $bag = new HeaderBag(['foo' => 'Tue']); $headerDate = $bag->getDate('foo'); } diff --git a/Tests/IpUtilsTest.php b/Tests/IpUtilsTest.php index c7f76b5de..338da1d25 100644 --- a/Tests/IpUtilsTest.php +++ b/Tests/IpUtilsTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\IpUtils; class IpUtilsTest extends TestCase { + use ForwardCompatTestTrait; + /** * @dataProvider getIpv4Data */ @@ -73,11 +76,11 @@ public function getIpv6Data() } /** - * @expectedException \RuntimeException * @requires extension sockets */ public function testAnIpv6WithOptionDisabledIpv6() { + $this->expectException('RuntimeException'); if (\defined('AF_INET6')) { $this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".'); } diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index d19620530..2e2645dab 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -219,29 +219,23 @@ public function testItAcceptsJsonAsString() $this->assertSame('{"foo":"bar"}', $response->getContent()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetCallbackInvalidIdentifier() { + $this->expectException('InvalidArgumentException'); $response = new JsonResponse('foo'); $response->setCallback('+invalid'); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetContent() { + $this->expectException('InvalidArgumentException'); JsonResponse::create("\xB1\x31"); } - /** - * @expectedException \Exception - * @expectedExceptionMessage This error is expected - */ public function testSetContentJsonSerializeError() { + $this->expectException('Exception'); + $this->expectExceptionMessage('This error is expected'); if (!interface_exists('JsonSerializable', false)) { $this->markTestSkipped('JsonSerializable is required.'); } diff --git a/Tests/RedirectResponseTest.php b/Tests/RedirectResponseTest.php index 5f6a8ac08..1e4b7a6ca 100644 --- a/Tests/RedirectResponseTest.php +++ b/Tests/RedirectResponseTest.php @@ -12,10 +12,13 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\RedirectResponse; class RedirectResponseTest extends TestCase { + use ForwardCompatTestTrait; + public function testGenerateMetaRedirect() { $response = new RedirectResponse('foo.bar'); @@ -26,19 +29,15 @@ public function testGenerateMetaRedirect() )); } - /** - * @expectedException \InvalidArgumentException - */ public function testRedirectResponseConstructorNullUrl() { + $this->expectException('InvalidArgumentException'); $response = new RedirectResponse(null); } - /** - * @expectedException \InvalidArgumentException - */ public function testRedirectResponseConstructorWrongStatusCode() { + $this->expectException('InvalidArgumentException'); $response = new RedirectResponse('foo.bar', 404); } @@ -65,11 +64,9 @@ public function testSetTargetUrl() $this->assertEquals('baz.beep', $response->getTargetUrl()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetTargetUrlNull() { + $this->expectException('InvalidArgumentException'); $response = new RedirectResponse('foo.bar'); $response->setTargetUrl(null); } diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index e0e719d38..dad3f0bf2 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -889,11 +889,9 @@ public function testGetPort() $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.'); } - /** - * @expectedException \RuntimeException - */ public function testGetHostWithFakeHttpHostValue() { + $this->expectException('RuntimeException'); $request = new Request(); $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.host.com?query=string']); $request->getHost(); @@ -1058,11 +1056,11 @@ public function getClientIpsProvider() } /** - * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException * @dataProvider getClientIpsWithConflictingHeadersProvider */ public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXForwardedFor) { + $this->expectException('Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException'); $request = new Request(); $server = [ @@ -1182,11 +1180,11 @@ public function testContentAsResource() } /** - * @expectedException \LogicException * @dataProvider getContentCantBeCalledTwiceWithResourcesProvider */ public function testGetContentCantBeCalledTwiceWithResources($first, $second) { + $this->expectException('LogicException'); if (\PHP_VERSION_ID >= 50600) { $this->markTestSkipped('PHP >= 5.6 allows to open php://input several times.'); } @@ -1971,20 +1969,20 @@ public function testTrustedProxiesForwarded() /** * @group legacy - * @expectedException \InvalidArgumentException */ public function testSetTrustedProxiesInvalidHeaderName() { + $this->expectException('InvalidArgumentException'); Request::create('http://example.com/'); Request::setTrustedHeaderName('bogus name', 'X_MY_FOR'); } /** * @group legacy - * @expectedException \InvalidArgumentException */ public function testGetTrustedProxiesInvalidHeaderName() { + $this->expectException('InvalidArgumentException'); Request::create('http://example.com/'); Request::getTrustedHeaderName('bogus name'); } diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index 93aacf24d..17be3cb60 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\ResponseHeaderBag; @@ -20,6 +21,8 @@ */ class ResponseHeaderBagTest extends TestCase { + use ForwardCompatTestTrait; + public function testAllPreserveCase() { $headers = [ @@ -240,21 +243,17 @@ public function testSetCookieHeader() $this->assertEquals([], $bag->getCookies()); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetCookiesWithInvalidArgument() { + $this->expectException('InvalidArgumentException'); $bag = new ResponseHeaderBag(); $bag->getCookies('invalid_argument'); } - /** - * @expectedException \InvalidArgumentException - */ public function testMakeDispositionInvalidDisposition() { + $this->expectException('InvalidArgumentException'); $headers = new ResponseHeaderBag(); $headers->makeDisposition('invalid', 'foo.html'); @@ -298,10 +297,10 @@ public function provideMakeDisposition() /** * @dataProvider provideMakeDispositionFail - * @expectedException \InvalidArgumentException */ public function testMakeDispositionFail($disposition, $filename) { + $this->expectException('InvalidArgumentException'); $headers = new ResponseHeaderBag(); $headers->makeDisposition($disposition, $filename); diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 40200ee31..7515a7a9e 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\HttpFoundation\Tests; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -19,6 +20,8 @@ */ class ResponseTest extends ResponseTestCase { + use ForwardCompatTestTrait; + public function testCreate() { $response = Response::create('foo', 301, ['Foo' => 'bar']); @@ -846,11 +849,11 @@ public function testSetContent($content) } /** - * @expectedException \UnexpectedValueException * @dataProvider invalidContentProvider */ public function testSetContentInvalid($content) { + $this->expectException('UnexpectedValueException'); $response = new Response(); $response->setContent($content); } @@ -928,11 +931,11 @@ protected function provideResponse() } /** - * @see http://github.com/zendframework/zend-diactoros for the canonical source repository + * @see http://github.com/zendframework/zend-diactoros for the canonical source repository * - * @author Fábio Pacheco + * @author Fábio Pacheco * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com) - * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License + * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License */ public function ianaCodesReasonPhrasesProvider() { diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index a762de01c..8fd72a91f 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -65,19 +65,15 @@ private function doSetUp() $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorShouldThrowExceptionForInvalidMongo() { + $this->expectException('InvalidArgumentException'); new MongoDbSessionHandler(new \stdClass(), $this->options); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorShouldThrowExceptionForMissingOptions() { + $this->expectException('InvalidArgumentException'); new MongoDbSessionHandler($this->mongo, []); } diff --git a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php index dc827d8ab..303ad3026 100644 --- a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; @@ -25,6 +26,8 @@ */ class NativeFileSessionHandlerTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstruct() { $storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler(sys_get_temp_dir())); @@ -59,11 +62,9 @@ public function savePathDataProvider() ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructException() { + $this->expectException('InvalidArgumentException'); $handler = new NativeFileSessionHandler('something;invalid;with;too-many-args'); } diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index e9439c3da..0571306ab 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -51,22 +51,18 @@ protected function getMemorySqlitePdo() return $pdo; } - /** - * @expectedException \InvalidArgumentException - */ public function testWrongPdoErrMode() { + $this->expectException('InvalidArgumentException'); $pdo = $this->getMemorySqlitePdo(); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); $storage = new PdoSessionHandler($pdo); } - /** - * @expectedException \RuntimeException - */ public function testInexistentTable() { + $this->expectException('RuntimeException'); $storage = new PdoSessionHandler($this->getMemorySqlitePdo(), ['db_table' => 'inexistent_table']); $storage->open('', 'sid'); $storage->read('id'); @@ -74,11 +70,9 @@ public function testInexistentTable() $storage->close(); } - /** - * @expectedException \RuntimeException - */ public function testCreateTableTwice() { + $this->expectException('RuntimeException'); $storage = new PdoSessionHandler($this->getMemorySqlitePdo()); $storage->createTable(); } diff --git a/Tests/Session/Storage/MockArraySessionStorageTest.php b/Tests/Session/Storage/MockArraySessionStorageTest.php index c60a78910..1285dbf1a 100644 --- a/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -124,11 +124,9 @@ public function testClearWithNoBagsStartsSession() $this->assertTrue($storage->isStarted()); } - /** - * @expectedException \RuntimeException - */ public function testUnstartedSave() { + $this->expectException('RuntimeException'); $this->storage->save(); } } diff --git a/Tests/Session/Storage/MockFileSessionStorageTest.php b/Tests/Session/Storage/MockFileSessionStorageTest.php index 36b4e605b..9a5ef1ca8 100644 --- a/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -110,11 +110,9 @@ public function testMultipleInstances() $this->assertEquals('bar', $storage2->getBag('attributes')->get('foo'), 'values persist between instances'); } - /** - * @expectedException \RuntimeException - */ public function testSaveWithoutStart() { + $this->expectException('RuntimeException'); $storage1 = $this->getStorage(); $storage1->save(); } diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 18540264d..886a5f9c9 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -75,20 +75,16 @@ public function testBag() $this->assertSame($bag, $storage->getBag($bag->getName())); } - /** - * @expectedException \InvalidArgumentException - */ public function testRegisterBagException() { + $this->expectException('InvalidArgumentException'); $storage = $this->getStorage(); $storage->getBag('non_existing'); } - /** - * @expectedException \LogicException - */ public function testRegisterBagForAStartedSessionThrowsException() { + $this->expectException('LogicException'); $storage = $this->getStorage(); $storage->start(); $storage->registerBag(new AttributeBag()); @@ -204,11 +200,9 @@ public function testSessionOptions() $this->assertSame('200', ini_get('session.cache_expire')); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetSaveHandlerException() { + $this->expectException('InvalidArgumentException'); $storage = $this->getStorage(); $storage->setSaveHandler(new \stdClass()); } @@ -231,11 +225,9 @@ public function testSetSaveHandler() $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); } - /** - * @expectedException \RuntimeException - */ public function testStarted() { + $this->expectException('RuntimeException'); $storage = $this->getStorage(); $this->assertFalse($storage->getSaveHandler()->isActive()); diff --git a/Tests/Session/Storage/Proxy/AbstractProxyTest.php b/Tests/Session/Storage/Proxy/AbstractProxyTest.php index 499a54a8e..dcd300364 100644 --- a/Tests/Session/Storage/Proxy/AbstractProxyTest.php +++ b/Tests/Session/Storage/Proxy/AbstractProxyTest.php @@ -83,10 +83,10 @@ public function testName() /** * @runInSeparateProcess * @preserveGlobalState disabled - * @expectedException \LogicException */ public function testNameException() { + $this->expectException('LogicException'); session_start(); $this->proxy->setName('foo'); } @@ -106,10 +106,10 @@ public function testId() /** * @runInSeparateProcess * @preserveGlobalState disabled - * @expectedException \LogicException */ public function testIdException() { + $this->expectException('LogicException'); session_start(); $this->proxy->setId('foo'); } diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index 63b3c8afb..d6459e10d 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -28,7 +28,7 @@ class SessionHandlerProxyTest extends TestCase use ForwardCompatTestTrait; /** - * @var \PHPUnit_Framework_MockObject_Matcher + * @var \PHPUnit\Framework\MockObject\Matcher */ private $mock; diff --git a/Tests/StreamedResponseTest.php b/Tests/StreamedResponseTest.php index 62dfc9bc9..96ab63d49 100644 --- a/Tests/StreamedResponseTest.php +++ b/Tests/StreamedResponseTest.php @@ -12,11 +12,14 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\StreamedResponse; class StreamedResponseTest extends TestCase { + use ForwardCompatTestTrait; + public function testConstructor() { $response = new StreamedResponse(function () { echo 'foo'; }, 404, ['Content-Type' => 'text/plain']); @@ -81,20 +84,16 @@ public function testSendContent() $this->assertEquals(1, $called); } - /** - * @expectedException \LogicException - */ public function testSendContentWithNonCallable() { + $this->expectException('LogicException'); $response = new StreamedResponse(null); $response->sendContent(); } - /** - * @expectedException \LogicException - */ public function testSetContent() { + $this->expectException('LogicException'); $response = new StreamedResponse(function () { echo 'foo'; }); $response->setContent('foo'); } From f256acff193d533bc37faf0f5bdccd74e7fc1e2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Fri, 2 Aug 2019 19:02:27 +0200 Subject: [PATCH 201/225] Remove use of ForwardCompatTrait --- Tests/BinaryFileResponseTest.php | 5 +---- Tests/CookieTest.php | 3 --- Tests/ExpressionRequestMatcherTest.php | 3 --- Tests/File/FileTest.php | 3 --- Tests/File/MimeType/MimeTypeTest.php | 5 +---- Tests/File/UploadedFileTest.php | 5 +---- Tests/FileBagTest.php | 7 ++----- Tests/HeaderBagTest.php | 3 --- Tests/IpUtilsTest.php | 3 --- Tests/JsonResponseTest.php | 5 +---- Tests/RedirectResponseTest.php | 3 --- Tests/RequestTest.php | 5 +---- Tests/ResponseFunctionalTest.php | 7 ++----- Tests/ResponseHeaderBagTest.php | 3 --- Tests/ResponseTest.php | 3 --- Tests/Session/Attribute/AttributeBagTest.php | 7 ++----- Tests/Session/Attribute/NamespacedAttributeBagTest.php | 7 ++----- Tests/Session/Flash/AutoExpireFlashBagTest.php | 7 ++----- Tests/Session/Flash/FlashBagTest.php | 7 ++----- Tests/Session/SessionTest.php | 7 ++----- .../Session/Storage/Handler/AbstractSessionHandlerTest.php | 7 ++----- .../Session/Storage/Handler/MemcacheSessionHandlerTest.php | 7 ++----- .../Storage/Handler/MemcachedSessionHandlerTest.php | 7 ++----- .../Session/Storage/Handler/MongoDbSessionHandlerTest.php | 5 +---- .../Storage/Handler/NativeFileSessionHandlerTest.php | 3 --- Tests/Session/Storage/Handler/PdoSessionHandlerTest.php | 5 +---- Tests/Session/Storage/MetadataBagTest.php | 7 ++----- Tests/Session/Storage/MockArraySessionStorageTest.php | 7 ++----- Tests/Session/Storage/MockFileSessionStorageTest.php | 7 ++----- Tests/Session/Storage/NativeSessionStorageTest.php | 7 ++----- Tests/Session/Storage/PhpBridgeSessionStorageTest.php | 7 ++----- Tests/Session/Storage/Proxy/AbstractProxyTest.php | 7 ++----- Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php | 7 ++----- Tests/StreamedResponseTest.php | 3 --- 34 files changed, 41 insertions(+), 143 deletions(-) diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index 9e27c7313..0bc150e8d 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -11,7 +11,6 @@ namespace Symfony\Component\HttpFoundation\Tests; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\File\Stream; use Symfony\Component\HttpFoundation\Request; @@ -20,8 +19,6 @@ class BinaryFileResponseTest extends ResponseTestCase { - use ForwardCompatTestTrait; - public function testConstruction() { $file = __DIR__.'/../README.md'; @@ -357,7 +354,7 @@ protected function provideResponse() return new BinaryFileResponse(__DIR__.'/../README.md', 200, ['Content-Type' => 'application/octet-stream']); } - private static function doTearDownAfterClass() + public static function tearDownAfterClass() { $path = __DIR__.'/../Fixtures/to_delete'; if (file_exists($path)) { diff --git a/Tests/CookieTest.php b/Tests/CookieTest.php index 2d69d9ace..e382182b4 100644 --- a/Tests/CookieTest.php +++ b/Tests/CookieTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Cookie; /** @@ -25,8 +24,6 @@ */ class CookieTest extends TestCase { - use ForwardCompatTestTrait; - public function invalidNames() { return [ diff --git a/Tests/ExpressionRequestMatcherTest.php b/Tests/ExpressionRequestMatcherTest.php index e750f39e6..8a389329e 100644 --- a/Tests/ExpressionRequestMatcherTest.php +++ b/Tests/ExpressionRequestMatcherTest.php @@ -12,15 +12,12 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\HttpFoundation\ExpressionRequestMatcher; use Symfony\Component\HttpFoundation\Request; class ExpressionRequestMatcherTest extends TestCase { - use ForwardCompatTestTrait; - public function testWhenNoExpressionIsSet() { $this->expectException('LogicException'); diff --git a/Tests/File/FileTest.php b/Tests/File/FileTest.php index 1f2582145..b463aadf8 100644 --- a/Tests/File/FileTest.php +++ b/Tests/File/FileTest.php @@ -12,14 +12,11 @@ namespace Symfony\Component\HttpFoundation\Tests\File; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser; class FileTest extends TestCase { - use ForwardCompatTestTrait; - protected $file; public function testGetMimeTypeUsesMimeTypeGuessers() diff --git a/Tests/File/MimeType/MimeTypeTest.php b/Tests/File/MimeType/MimeTypeTest.php index 299fc7a24..3960988a6 100644 --- a/Tests/File/MimeType/MimeTypeTest.php +++ b/Tests/File/MimeType/MimeTypeTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\File\MimeType; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\MimeType\FileBinaryMimeTypeGuesser; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser; @@ -21,8 +20,6 @@ */ class MimeTypeTest extends TestCase { - use ForwardCompatTestTrait; - protected $path; public function testGuessImageWithoutExtension() @@ -82,7 +79,7 @@ public function testGuessWithNonReadablePath() } } - private static function doTearDownAfterClass() + public static function tearDownAfterClass() { $path = __DIR__.'/../Fixtures/to_delete'; if (file_exists($path)) { diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 9b48da7a2..629211052 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -12,14 +12,11 @@ namespace Symfony\Component\HttpFoundation\Tests\File; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\UploadedFile; class UploadedFileTest extends TestCase { - use ForwardCompatTestTrait; - - private function doSetUp() + protected function setUp() { if (!ini_get('file_uploads')) { $this->markTestSkipped('file_uploads is disabled in php.ini'); diff --git a/Tests/FileBagTest.php b/Tests/FileBagTest.php index 289c12bd3..a3882bc86 100644 --- a/Tests/FileBagTest.php +++ b/Tests/FileBagTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\FileBag; @@ -24,8 +23,6 @@ */ class FileBagTest extends TestCase { - use ForwardCompatTestTrait; - public function testFileMustBeAnArrayOrUploadedFile() { $this->expectException('InvalidArgumentException'); @@ -160,12 +157,12 @@ protected function createTempFile() return tempnam(sys_get_temp_dir().'/form_test', 'FormTest'); } - private function doSetUp() + protected function setUp() { mkdir(sys_get_temp_dir().'/form_test', 0777, true); } - private function doTearDown() + protected function tearDown() { foreach (glob(sys_get_temp_dir().'/form_test/*') as $file) { unlink($file); diff --git a/Tests/HeaderBagTest.php b/Tests/HeaderBagTest.php index 3eff56840..a5876f9e3 100644 --- a/Tests/HeaderBagTest.php +++ b/Tests/HeaderBagTest.php @@ -12,13 +12,10 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\HeaderBag; class HeaderBagTest extends TestCase { - use ForwardCompatTestTrait; - public function testConstructor() { $bag = new HeaderBag(['foo' => 'bar']); diff --git a/Tests/IpUtilsTest.php b/Tests/IpUtilsTest.php index 338da1d25..d3b262e04 100644 --- a/Tests/IpUtilsTest.php +++ b/Tests/IpUtilsTest.php @@ -12,13 +12,10 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\IpUtils; class IpUtilsTest extends TestCase { - use ForwardCompatTestTrait; - /** * @dataProvider getIpv4Data */ diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index 2e2645dab..fd045fb9c 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -12,14 +12,11 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\JsonResponse; class JsonResponseTest extends TestCase { - use ForwardCompatTestTrait; - - private function doSetUp() + protected function setUp() { parent::setUp(); diff --git a/Tests/RedirectResponseTest.php b/Tests/RedirectResponseTest.php index 1e4b7a6ca..92f4876da 100644 --- a/Tests/RedirectResponseTest.php +++ b/Tests/RedirectResponseTest.php @@ -12,13 +12,10 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\RedirectResponse; class RedirectResponseTest extends TestCase { - use ForwardCompatTestTrait; - public function testGenerateMetaRedirect() { $response = new RedirectResponse('foo.bar'); diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index dad3f0bf2..aaefc0359 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\Session; @@ -20,9 +19,7 @@ class RequestTest extends TestCase { - use ForwardCompatTestTrait; - - private function doTearDown() + protected function tearDown() { Request::setTrustedProxies([], -1); Request::setTrustedHosts([]); diff --git a/Tests/ResponseFunctionalTest.php b/Tests/ResponseFunctionalTest.php index e264710d1..3d3e696c7 100644 --- a/Tests/ResponseFunctionalTest.php +++ b/Tests/ResponseFunctionalTest.php @@ -12,18 +12,15 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; /** * @requires PHP 7.0 */ class ResponseFunctionalTest extends TestCase { - use ForwardCompatTestTrait; - private static $server; - private static function doSetUpBeforeClass() + public static function setUpBeforeClass() { $spec = [ 1 => ['file', '/dev/null', 'w'], @@ -35,7 +32,7 @@ private static function doSetUpBeforeClass() sleep(1); } - private static function doTearDownAfterClass() + public static function tearDownAfterClass() { if (self::$server) { proc_terminate(self::$server); diff --git a/Tests/ResponseHeaderBagTest.php b/Tests/ResponseHeaderBagTest.php index 17be3cb60..d85f6e112 100644 --- a/Tests/ResponseHeaderBagTest.php +++ b/Tests/ResponseHeaderBagTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\ResponseHeaderBag; @@ -21,8 +20,6 @@ */ class ResponseHeaderBagTest extends TestCase { - use ForwardCompatTestTrait; - public function testAllPreserveCase() { $headers = [ diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 7515a7a9e..776f85cd0 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -11,7 +11,6 @@ namespace Symfony\Component\HttpFoundation\Tests; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -20,8 +19,6 @@ */ class ResponseTest extends ResponseTestCase { - use ForwardCompatTestTrait; - public function testCreate() { $response = Response::create('foo', 301, ['Foo' => 'bar']); diff --git a/Tests/Session/Attribute/AttributeBagTest.php b/Tests/Session/Attribute/AttributeBagTest.php index aef66da1d..3f2f7b3c8 100644 --- a/Tests/Session/Attribute/AttributeBagTest.php +++ b/Tests/Session/Attribute/AttributeBagTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Attribute; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; /** @@ -22,8 +21,6 @@ */ class AttributeBagTest extends TestCase { - use ForwardCompatTestTrait; - private $array = []; /** @@ -31,7 +28,7 @@ class AttributeBagTest extends TestCase */ private $bag; - private function doSetUp() + protected function setUp() { $this->array = [ 'hello' => 'world', @@ -52,7 +49,7 @@ private function doSetUp() $this->bag->initialize($this->array); } - private function doTearDown() + protected function tearDown() { $this->bag = null; $this->array = []; diff --git a/Tests/Session/Attribute/NamespacedAttributeBagTest.php b/Tests/Session/Attribute/NamespacedAttributeBagTest.php index a1f6bf5eb..6b4bb17d6 100644 --- a/Tests/Session/Attribute/NamespacedAttributeBagTest.php +++ b/Tests/Session/Attribute/NamespacedAttributeBagTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Attribute; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag; /** @@ -22,8 +21,6 @@ */ class NamespacedAttributeBagTest extends TestCase { - use ForwardCompatTestTrait; - private $array = []; /** @@ -31,7 +28,7 @@ class NamespacedAttributeBagTest extends TestCase */ private $bag; - private function doSetUp() + protected function setUp() { $this->array = [ 'hello' => 'world', @@ -52,7 +49,7 @@ private function doSetUp() $this->bag->initialize($this->array); } - private function doTearDown() + protected function tearDown() { $this->bag = null; $this->array = []; diff --git a/Tests/Session/Flash/AutoExpireFlashBagTest.php b/Tests/Session/Flash/AutoExpireFlashBagTest.php index 65b205814..b4e2c3a5a 100644 --- a/Tests/Session/Flash/AutoExpireFlashBagTest.php +++ b/Tests/Session/Flash/AutoExpireFlashBagTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Flash; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag as FlashBag; /** @@ -22,8 +21,6 @@ */ class AutoExpireFlashBagTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var \Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag */ @@ -31,7 +28,7 @@ class AutoExpireFlashBagTest extends TestCase protected $array = []; - private function doSetUp() + protected function setUp() { parent::setUp(); $this->bag = new FlashBag(); @@ -39,7 +36,7 @@ private function doSetUp() $this->bag->initialize($this->array); } - private function doTearDown() + protected function tearDown() { $this->bag = null; parent::tearDown(); diff --git a/Tests/Session/Flash/FlashBagTest.php b/Tests/Session/Flash/FlashBagTest.php index 427af6d67..6d8619e07 100644 --- a/Tests/Session/Flash/FlashBagTest.php +++ b/Tests/Session/Flash/FlashBagTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Flash; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; /** @@ -22,8 +21,6 @@ */ class FlashBagTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var \Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface */ @@ -31,7 +28,7 @@ class FlashBagTest extends TestCase protected $array = []; - private function doSetUp() + protected function setUp() { parent::setUp(); $this->bag = new FlashBag(); @@ -39,7 +36,7 @@ private function doSetUp() $this->bag->initialize($this->array); } - private function doTearDown() + protected function tearDown() { $this->bag = null; parent::tearDown(); diff --git a/Tests/Session/SessionTest.php b/Tests/Session/SessionTest.php index 51516e2f2..acb129984 100644 --- a/Tests/Session/SessionTest.php +++ b/Tests/Session/SessionTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Session; @@ -28,8 +27,6 @@ */ class SessionTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var \Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface */ @@ -40,13 +37,13 @@ class SessionTest extends TestCase */ protected $session; - private function doSetUp() + protected function setUp() { $this->storage = new MockArraySessionStorage(); $this->session = new Session($this->storage, new AttributeBag(), new FlashBag()); } - private function doTearDown() + protected function tearDown() { $this->storage = null; $this->session = null; diff --git a/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php index d83182be7..98bc67bca 100644 --- a/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/AbstractSessionHandlerTest.php @@ -12,18 +12,15 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; /** * @requires PHP 7.0 */ class AbstractSessionHandlerTest extends TestCase { - use ForwardCompatTestTrait; - private static $server; - private static function doSetUpBeforeClass() + public static function setUpBeforeClass() { $spec = [ 1 => ['file', '/dev/null', 'w'], @@ -35,7 +32,7 @@ private static function doSetUpBeforeClass() sleep(1); } - private static function doTearDownAfterClass() + public static function tearDownAfterClass() { if (self::$server) { proc_terminate(self::$server); diff --git a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php index d2526868d..d7a324fc2 100644 --- a/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler; /** @@ -22,8 +21,6 @@ */ class MemcacheSessionHandlerTest extends TestCase { - use ForwardCompatTestTrait; - const PREFIX = 'prefix_'; const TTL = 1000; @@ -34,7 +31,7 @@ class MemcacheSessionHandlerTest extends TestCase protected $memcache; - private function doSetUp() + protected function setUp() { if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcache class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); @@ -48,7 +45,7 @@ private function doSetUp() ); } - private function doTearDown() + protected function tearDown() { $this->memcache = null; $this->storage = null; diff --git a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php index 86ac574d2..c3deb7aed 100644 --- a/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler; /** @@ -21,8 +20,6 @@ */ class MemcachedSessionHandlerTest extends TestCase { - use ForwardCompatTestTrait; - const PREFIX = 'prefix_'; const TTL = 1000; @@ -33,7 +30,7 @@ class MemcachedSessionHandlerTest extends TestCase protected $memcached; - private function doSetUp() + protected function setUp() { if (\defined('HHVM_VERSION')) { $this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcached class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289'); @@ -52,7 +49,7 @@ private function doSetUp() ); } - private function doTearDown() + protected function tearDown() { $this->memcached = null; $this->storage = null; diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 8fd72a91f..7bc84f876 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; /** @@ -22,8 +21,6 @@ */ class MongoDbSessionHandlerTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var \PHPUnit_Framework_MockObject_MockObject */ @@ -31,7 +28,7 @@ class MongoDbSessionHandlerTest extends TestCase private $storage; public $options; - private function doSetUp() + protected function setUp() { parent::setUp(); diff --git a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php index 303ad3026..348714a26 100644 --- a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; @@ -26,8 +25,6 @@ */ class NativeFileSessionHandlerTest extends TestCase { - use ForwardCompatTestTrait; - public function testConstruct() { $storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler(sys_get_temp_dir())); diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 0571306ab..ff513b7ef 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; /** @@ -21,11 +20,9 @@ */ class PdoSessionHandlerTest extends TestCase { - use ForwardCompatTestTrait; - private $dbFile; - private function doTearDown() + protected function tearDown() { // make sure the temporary database file is deleted when it has been created (even when a test fails) if ($this->dbFile) { diff --git a/Tests/Session/Storage/MetadataBagTest.php b/Tests/Session/Storage/MetadataBagTest.php index 02cea3292..2c4758b91 100644 --- a/Tests/Session/Storage/MetadataBagTest.php +++ b/Tests/Session/Storage/MetadataBagTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag; /** @@ -22,8 +21,6 @@ */ class MetadataBagTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var MetadataBag */ @@ -31,7 +28,7 @@ class MetadataBagTest extends TestCase protected $array = []; - private function doSetUp() + protected function setUp() { parent::setUp(); $this->bag = new MetadataBag(); @@ -39,7 +36,7 @@ private function doSetUp() $this->bag->initialize($this->array); } - private function doTearDown() + protected function tearDown() { $this->array = []; $this->bag = null; diff --git a/Tests/Session/Storage/MockArraySessionStorageTest.php b/Tests/Session/Storage/MockArraySessionStorageTest.php index 1285dbf1a..7e0d303b9 100644 --- a/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; @@ -24,8 +23,6 @@ */ class MockArraySessionStorageTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var MockArraySessionStorage */ @@ -43,7 +40,7 @@ class MockArraySessionStorageTest extends TestCase private $data; - private function doSetUp() + protected function setUp() { $this->attributes = new AttributeBag(); $this->flashes = new FlashBag(); @@ -59,7 +56,7 @@ private function doSetUp() $this->storage->setSessionData($this->data); } - private function doTearDown() + protected function tearDown() { $this->data = null; $this->flashes = null; diff --git a/Tests/Session/Storage/MockFileSessionStorageTest.php b/Tests/Session/Storage/MockFileSessionStorageTest.php index 9a5ef1ca8..b316c83e6 100644 --- a/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage; @@ -24,8 +23,6 @@ */ class MockFileSessionStorageTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var string */ @@ -36,13 +33,13 @@ class MockFileSessionStorageTest extends TestCase */ protected $storage; - private function doSetUp() + protected function setUp() { $this->sessionDir = sys_get_temp_dir().'/sf2test'; $this->storage = $this->getStorage(); } - private function doTearDown() + protected function tearDown() { $this->sessionDir = null; $this->storage = null; diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index 886a5f9c9..fa170d17d 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; @@ -32,11 +31,9 @@ */ class NativeSessionStorageTest extends TestCase { - use ForwardCompatTestTrait; - private $savePath; - private function doSetUp() + protected function setUp() { $this->iniSet('session.save_handler', 'files'); $this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test'); @@ -45,7 +42,7 @@ private function doSetUp() } } - private function doTearDown() + protected function tearDown() { session_write_close(); array_map('unlink', glob($this->savePath.'/*')); diff --git a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php index c8a53f169..752be618b 100644 --- a/Tests/Session/Storage/PhpBridgeSessionStorageTest.php +++ b/Tests/Session/Storage/PhpBridgeSessionStorageTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage; @@ -28,11 +27,9 @@ */ class PhpBridgeSessionStorageTest extends TestCase { - use ForwardCompatTestTrait; - private $savePath; - private function doSetUp() + protected function setUp() { $this->iniSet('session.save_handler', 'files'); $this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test'); @@ -41,7 +38,7 @@ private function doSetUp() } } - private function doTearDown() + protected function tearDown() { session_write_close(); array_map('unlink', glob($this->savePath.'/*')); diff --git a/Tests/Session/Storage/Proxy/AbstractProxyTest.php b/Tests/Session/Storage/Proxy/AbstractProxyTest.php index dcd300364..ae40f2c29 100644 --- a/Tests/Session/Storage/Proxy/AbstractProxyTest.php +++ b/Tests/Session/Storage/Proxy/AbstractProxyTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; @@ -23,19 +22,17 @@ */ class AbstractProxyTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var AbstractProxy */ protected $proxy; - private function doSetUp() + protected function setUp() { $this->proxy = $this->getMockForAbstractClass(AbstractProxy::class); } - private function doTearDown() + protected function tearDown() { $this->proxy = null; } diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index d6459e10d..ec9029c7d 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; /** @@ -25,8 +24,6 @@ */ class SessionHandlerProxyTest extends TestCase { - use ForwardCompatTestTrait; - /** * @var \PHPUnit\Framework\MockObject\Matcher */ @@ -37,13 +34,13 @@ class SessionHandlerProxyTest extends TestCase */ private $proxy; - private function doSetUp() + protected function setUp() { $this->mock = $this->getMockBuilder('SessionHandlerInterface')->getMock(); $this->proxy = new SessionHandlerProxy($this->mock); } - private function doTearDown() + protected function tearDown() { $this->mock = null; $this->proxy = null; diff --git a/Tests/StreamedResponseTest.php b/Tests/StreamedResponseTest.php index 96ab63d49..a084e917d 100644 --- a/Tests/StreamedResponseTest.php +++ b/Tests/StreamedResponseTest.php @@ -12,14 +12,11 @@ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\StreamedResponse; class StreamedResponseTest extends TestCase { - use ForwardCompatTestTrait; - public function testConstructor() { $response = new StreamedResponse(function () { echo 'foo'; }, 404, ['Content-Type' => 'text/plain']); From 9f3c40c251aa69af0b0e4a6020f7d51e6831e898 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Sun, 4 Aug 2019 11:16:42 +0200 Subject: [PATCH 202/225] Remove calls to deprecated function assertAttributeX --- .../Storage/Handler/PdoSessionHandlerTest.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index ff513b7ef..123b605d2 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -324,15 +324,15 @@ public function testGetConnectionConnectsIfNeeded() public function testUrlDsn($url, $expectedDsn, $expectedUser = null, $expectedPassword = null) { $storage = new PdoSessionHandler($url); - - $this->assertAttributeEquals($expectedDsn, 'dsn', $storage); - - if (null !== $expectedUser) { - $this->assertAttributeEquals($expectedUser, 'username', $storage); - } - - if (null !== $expectedPassword) { - $this->assertAttributeEquals($expectedPassword, 'password', $storage); + $reflection = new \ReflectionClass(PdoSessionHandler::class); + + foreach (['dsn' => $expectedDsn, 'username' => $expectedUser, 'password' => $expectedPassword] as $property => $expectedValue) { + if (!isset($expectedValue)) { + continue; + } + $property = $reflection->getProperty($property); + $property->setAccessible(true); + $this->assertSame($expectedValue, $property->getValue($storage)); } } From e42bf5ec53666cf911bcb8119ba5df50f2e4fe61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Sun, 4 Aug 2019 18:55:16 +0200 Subject: [PATCH 203/225] Use PHPunit assertion --- Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php index 348714a26..9daf1a0ee 100644 --- a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php @@ -43,7 +43,7 @@ public function testConstructSavePath($savePath, $expectedSavePath, $path) { $handler = new NativeFileSessionHandler($savePath); $this->assertEquals($expectedSavePath, ini_get('session.save_path')); - $this->assertTrue(is_dir(realpath($path))); + $this->assertDirectoryExists(realpath($path)); rmdir($path); } From eca03df7b4d0cff7c35995e657bb211ec5f718e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Mon, 5 Aug 2019 16:11:35 +0200 Subject: [PATCH 204/225] Use Phpunit FQDN in tests comments --- Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 7bc84f876..f0f43d05b 100644 --- a/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; @@ -22,7 +23,7 @@ class MongoDbSessionHandlerTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $mongo; private $storage; From 1bfc779233541e9d5e5245a4258213bdeb59b839 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Mon, 5 Aug 2019 23:18:16 +0200 Subject: [PATCH 205/225] Use assertEqualsWithDelta when required --- Tests/CookieTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/CookieTest.php b/Tests/CookieTest.php index e382182b4..38c195df3 100644 --- a/Tests/CookieTest.php +++ b/Tests/CookieTest.php @@ -119,7 +119,7 @@ public function testGetExpiresTimeWithStringValue() $cookie = new Cookie('foo', 'bar', $value); $expire = strtotime($value); - $this->assertEquals($expire, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date', 1); + $this->assertEqualsWithDelta($expire, $cookie->getExpiresTime(), 1, '->getExpiresTime() returns the expire date'); } public function testGetDomain() From dadec920986892cb7dd445a46159dca44735de23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Tue, 6 Aug 2019 00:37:40 +0200 Subject: [PATCH 206/225] Use assertStringContainsString when needed --- Tests/BinaryFileResponseTest.php | 2 +- Tests/RequestTest.php | 6 +++--- Tests/ResponseTest.php | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index 0bc150e8d..3df96f393 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -261,7 +261,7 @@ public function testXSendfile($file) $this->expectOutputString(''); $response->sendContent(); - $this->assertContains('README.md', $response->headers->get('X-Sendfile')); + $this->assertStringContainsString('README.md', $response->headers->get('X-Sendfile')); } public function provideXSendfileFiles() diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index aaefc0359..396644632 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1631,14 +1631,14 @@ public function testToString() $asString = (string) $request; - $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $asString); - $this->assertContains('Cookie: Foo=Bar', $asString); + $this->assertStringContainsString('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $asString); + $this->assertStringContainsString('Cookie: Foo=Bar', $asString); $request->cookies->set('Another', 'Cookie'); $asString = (string) $request; - $this->assertContains('Cookie: Foo=Bar; Another=Cookie', $asString); + $this->assertStringContainsString('Cookie: Foo=Bar; Another=Cookie', $asString); } public function testIsMethod() diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 776f85cd0..2858b0a40 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -582,7 +582,7 @@ public function testSetCache() $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported'); } catch (\Exception $e) { $this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported'); - $this->assertContains('"wrong option"', $e->getMessage()); + $this->assertStringContainsString('"wrong option"', $e->getMessage()); } $options = ['etag' => '"whatever"']; @@ -635,7 +635,7 @@ public function testSendContent() ob_start(); $response->sendContent(); $string = ob_get_clean(); - $this->assertContains('test response rendering', $string); + $this->assertStringContainsString('test response rendering', $string); } public function testSetPublic() From ae752d690759f8873349915ccf806ffe23c56d3f Mon Sep 17 00:00:00 2001 From: Arman Hosseini <44655055+Arman-Hosseini@users.noreply.github.com> Date: Mon, 29 Jul 2019 21:55:29 +0430 Subject: [PATCH 207/225] Improve some URLs --- CHANGELOG.md | 2 +- File/MimeType/FileinfoMimeTypeGuesser.php | 2 +- JsonResponse.php | 2 +- ParameterBag.php | 2 +- RedirectResponse.php | 2 +- Request.php | 10 +++++----- Response.php | 6 +++--- ServerBag.php | 2 +- .../Storage/Handler/MemcachedSessionHandler.php | 2 +- Session/Storage/Handler/MongoDbSessionHandler.php | 2 +- .../Storage/Handler/NativeFileSessionHandler.php | 2 +- Session/Storage/Handler/NativeSessionHandler.php | 2 +- Session/Storage/Handler/PdoSessionHandler.php | 8 ++++---- Session/Storage/NativeSessionStorage.php | 14 +++++++------- Session/Storage/SessionStorageInterface.php | 2 +- 15 files changed, 30 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bfde80ff..c0d890167 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ CHANGELOG ----- * the `Request::setTrustedProxies()` method takes a new `$trustedHeaderSet` argument, - see http://symfony.com/doc/current/components/http_foundation/trusting_proxies.html for more info, + see https://symfony.com/doc/current/deployment/proxies.html for more info, * deprecated the `Request::setTrustedHeaderName()` and `Request::getTrustedHeaderName()` methods, * added `File\Stream`, to be passed to `BinaryFileResponse` when the size of the served file is unknown, disabling `Range` and `Content-Length` handling, switching to chunked encoding instead diff --git a/File/MimeType/FileinfoMimeTypeGuesser.php b/File/MimeType/FileinfoMimeTypeGuesser.php index bf1ee9f5d..62feda2ee 100644 --- a/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/File/MimeType/FileinfoMimeTypeGuesser.php @@ -26,7 +26,7 @@ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface /** * @param string $magicFile A magic file to use with the finfo instance * - * @see http://www.php.net/manual/en/function.finfo-open.php + * @see https://php.net/finfo-open */ public function __construct($magicFile = null) { diff --git a/JsonResponse.php b/JsonResponse.php index a9bdac30f..b0e765167 100644 --- a/JsonResponse.php +++ b/JsonResponse.php @@ -100,7 +100,7 @@ public static function fromJsonString($data = null, $status = 200, $headers = [] public function setCallback($callback = null) { if (null !== $callback) { - // partially taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/ + // partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/ // partially taken from https://github.com/willdurand/JsonpCallbackValidator // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details. // (c) William Durand diff --git a/ParameterBag.php b/ParameterBag.php index f05e4a215..194ba2c6c 100644 --- a/ParameterBag.php +++ b/ParameterBag.php @@ -191,7 +191,7 @@ public function getBoolean($key, $default = false) * @param int $filter FILTER_* constant * @param mixed $options Filter options * - * @see http://php.net/manual/en/function.filter-var.php + * @see https://php.net/filter-var * * @return mixed */ diff --git a/RedirectResponse.php b/RedirectResponse.php index 51fd869ab..4e3cb4f77 100644 --- a/RedirectResponse.php +++ b/RedirectResponse.php @@ -30,7 +30,7 @@ class RedirectResponse extends Response * * @throws \InvalidArgumentException * - * @see http://tools.ietf.org/html/rfc2616#section-10.3 + * @see https://tools.ietf.org/html/rfc2616#section-10.3 */ public function __construct($url, $status = 302, $headers = []) { diff --git a/Request.php b/Request.php index 7185d75e9..2dd250b80 100644 --- a/Request.php +++ b/Request.php @@ -915,7 +915,7 @@ public function getClientIps() * @return string|null The client IP address * * @see getClientIps() - * @see http://en.wikipedia.org/wiki/X-Forwarded-For + * @see https://wikipedia.org/wiki/X-Forwarded-For */ public function getClientIp() { @@ -1204,7 +1204,7 @@ public function getRelativeUriForPath($path) // 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 // as the first segment of a relative-path reference, as it would be mistaken for a scheme name - // (see http://tools.ietf.org/html/rfc3986#section-4.2). + // (see https://tools.ietf.org/html/rfc3986#section-4.2). return !isset($path[0]) || '/' === $path[0] || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) ? "./$path" : $path; @@ -1823,7 +1823,7 @@ public function getAcceptableContentTypes() * It works if your JavaScript library sets an X-Requested-With HTTP header. * It is known to work with common JavaScript frameworks: * - * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript + * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript * * @return bool true if the request is an XMLHttpRequest, false otherwise */ @@ -1835,9 +1835,9 @@ public function isXmlHttpRequest() /* * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24) * - * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd). + * Code subject to the new BSD license (https://framework.zend.com/license). * - * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * Copyright (c) 2005-2010 Zend Technologies USA Inc. (https://www.zend.com/) */ protected function prepareRequestUri() diff --git a/Response.php b/Response.php index 4ab05066f..47dae9534 100644 --- a/Response.php +++ b/Response.php @@ -121,7 +121,7 @@ class Response * Status codes translation table. * * The list of codes is complete according to the - * {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol (HTTP) Status Code Registry} + * {@link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Hypertext Transfer Protocol (HTTP) Status Code Registry} * (last updated 2016-03-01). * * Unless otherwise noted, the status code is defined in RFC2616. @@ -1025,7 +1025,7 @@ public function setCache(array $options) * * @return $this * - * @see http://tools.ietf.org/html/rfc2616#section-10.3.5 + * @see https://tools.ietf.org/html/rfc2616#section-10.3.5 * * @final since version 3.3 */ @@ -1133,7 +1133,7 @@ public function isNotModified(Request $request) * * @return bool * - * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html * * @final since version 3.2 */ diff --git a/ServerBag.php b/ServerBag.php index 90da49fae..4c82b1774 100644 --- a/ServerBag.php +++ b/ServerBag.php @@ -79,7 +79,7 @@ public function getHeaders() /* * XXX: Since there is no PHP_AUTH_BEARER in PHP predefined variables, * I'll just set $headers['AUTHORIZATION'] here. - * http://php.net/manual/en/reserved.variables.server.php + * https://php.net/reserved.variables.server */ $headers['AUTHORIZATION'] = $authorizationHeader; } diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 1db590b36..8965c089c 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -15,7 +15,7 @@ * Memcached based session storage handler based on the Memcached class * provided by the PHP memcached extension. * - * @see http://php.net/memcached + * @see https://php.net/memcached * * @author Drak */ diff --git a/Session/Storage/Handler/MongoDbSessionHandler.php b/Session/Storage/Handler/MongoDbSessionHandler.php index ddedacffb..1dd724066 100644 --- a/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/Session/Storage/Handler/MongoDbSessionHandler.php @@ -56,7 +56,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler * { "expireAfterSeconds": 0 } * ) * - * More details on: http://docs.mongodb.org/manual/tutorial/expire-data/ + * More details on: https://docs.mongodb.org/manual/tutorial/expire-data/ * * If you use such an index, you can drop `gc_probability` to 0 since * no garbage-collection is required. diff --git a/Session/Storage/Handler/NativeFileSessionHandler.php b/Session/Storage/Handler/NativeFileSessionHandler.php index 04bcbbfe3..8b7615ec1 100644 --- a/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/Session/Storage/Handler/NativeFileSessionHandler.php @@ -23,7 +23,7 @@ class NativeFileSessionHandler extends NativeSessionHandler * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path * - * @see https://php.net/manual/session.configuration.php#ini.session.save-path for further details. + * @see https://php.net/session.configuration#ini.session.save-path for further details. * * @throws \InvalidArgumentException On invalid $savePath * @throws \RuntimeException When failing to create the save directory diff --git a/Session/Storage/Handler/NativeSessionHandler.php b/Session/Storage/Handler/NativeSessionHandler.php index 9be4528ae..5159b1e35 100644 --- a/Session/Storage/Handler/NativeSessionHandler.php +++ b/Session/Storage/Handler/NativeSessionHandler.php @@ -13,7 +13,7 @@ /** * @deprecated since version 3.4, to be removed in 4.0. Use \SessionHandler instead. - * @see http://php.net/sessionhandler + * @see https://php.net/sessionhandler */ class NativeSessionHandler extends \SessionHandler { diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 9369740eb..9a50377bc 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -32,7 +32,7 @@ * Saving it in a character column could corrupt the data. You can use createTable() * to initialize a correctly defined table. * - * @see http://php.net/sessionhandlerinterface + * @see https://php.net/sessionhandlerinterface * * @author Fabien Potencier * @author Michael Williams @@ -538,7 +538,7 @@ private function buildDsnFromUrl($dsnOrUrl) * PDO::rollback or PDO::inTransaction for SQLite. * * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions - * due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ . + * due to https://percona.com/blog/2013/12/12/one-more-innodb-gap-lock-to-avoid/ . * So we change it to READ COMMITTED. */ private function beginTransaction() @@ -864,7 +864,7 @@ private function getMergeStatement($sessionId, $data, $maxlifetime) break; case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='): // MERGE is only available since SQL Server 2008 and must be terminated by semicolon - // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx + // It also requires HOLDLOCK according to https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/ $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ". "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;"; @@ -877,7 +877,7 @@ private function getMergeStatement($sessionId, $data, $maxlifetime) "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)"; break; default: - // MERGE is not supported with LOBs: http://www.oracle.com/technetwork/articles/fuecks-lobs-095315.html + // MERGE is not supported with LOBs: https://oracle.com/technetwork/articles/fuecks-lobs-095315.html return null; } diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 809d7002c..4f1c30ef5 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -54,7 +54,7 @@ class NativeSessionStorage implements SessionStorageInterface * * List of options for $options array with their defaults. * - * @see http://php.net/session.configuration for options + * @see https://php.net/session.configuration for options * but we omit 'session.' from the beginning of the keys for convenience. * * ("auto_start", is not supported as it tells PHP to start a session before @@ -212,7 +212,7 @@ public function regenerate($destroy = false, $lifetime = null) $isRegenerated = session_regenerate_id($destroy); // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it. - // @see https://bugs.php.net/bug.php?id=70013 + // @see https://bugs.php.net/70013 $this->loadSession(); return $isRegenerated; @@ -337,7 +337,7 @@ public function isStarted() * * @param array $options Session ini directives [key => value] * - * @see http://php.net/session.configuration + * @see https://php.net/session.configuration */ public function setOptions(array $options) { @@ -378,10 +378,10 @@ public function setOptions(array $options) * constructor, for a template see NativeFileSessionHandler or use handlers in * composer package drak/native-session * - * @see http://php.net/session-set-save-handler - * @see http://php.net/sessionhandlerinterface - * @see http://php.net/sessionhandler - * @see http://github.com/drak/NativeSession + * @see https://php.net/session-set-save-handler + * @see https://php.net/sessionhandlerinterface + * @see https://php.net/sessionhandler + * @see https://github.com/zikula/NativeSession * * @param \SessionHandlerInterface|null $saveHandler * diff --git a/Session/Storage/SessionStorageInterface.php b/Session/Storage/SessionStorageInterface.php index 66e8b33dd..eeb396a2f 100644 --- a/Session/Storage/SessionStorageInterface.php +++ b/Session/Storage/SessionStorageInterface.php @@ -77,7 +77,7 @@ public function setName($name); * only delete the session data from persistent storage. * * Care: When regenerating the session ID no locking is involved in PHP's - * session design. See https://bugs.php.net/bug.php?id=61470 for a discussion. + * session design. See https://bugs.php.net/61470 for a discussion. * So you must make sure the regenerated session is saved BEFORE sending the * headers with the new ID. Symfony's HttpKernel offers a listener for this. * See Symfony\Component\HttpKernel\EventListener\SaveSessionListener. From 1000881e7ac0eaac01ea74b881d869618fec7499 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Sat, 10 Aug 2019 22:41:30 +0200 Subject: [PATCH 208/225] cleanups --- Tests/RequestTest.php | 1 - Tests/ResponseTest.php | 1 - 2 files changed, 2 deletions(-) diff --git a/Tests/RequestTest.php b/Tests/RequestTest.php index 396644632..bf70a5f83 100644 --- a/Tests/RequestTest.php +++ b/Tests/RequestTest.php @@ -1549,7 +1549,6 @@ public function testGetLanguages() $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages()); - $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages()); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.6, en; q=0.8'); diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index 2858b0a40..c61dbacdd 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -532,7 +532,6 @@ public function testPrepareRemovesContentForInformationalResponse() $response->prepare($request); $this->assertEquals('', $response->getContent()); $this->assertFalse($response->headers->has('Content-Type')); - $this->assertFalse($response->headers->has('Content-Type')); $response->setContent('content'); $response->setStatusCode(304); From 27f2b785f3feaad6b924ea29d0757a6fbb91b912 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 12 Aug 2019 22:21:04 +0200 Subject: [PATCH 209/225] Fix return statements --- File/MimeType/FileBinaryMimeTypeGuesser.php | 6 +++--- File/MimeType/FileinfoMimeTypeGuesser.php | 4 ++-- File/MimeType/MimeTypeGuesserInterface.php | 2 +- RequestStack.php | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index 34e015ee5..b75242afd 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -74,7 +74,7 @@ public function guess($path) } if (!self::isSupported()) { - return; + return null; } ob_start(); @@ -84,14 +84,14 @@ public function guess($path) if ($return > 0) { ob_end_clean(); - return; + return null; } $type = trim(ob_get_clean()); if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) { // it's not a type, but an error message - return; + return null; } return $match[1]; diff --git a/File/MimeType/FileinfoMimeTypeGuesser.php b/File/MimeType/FileinfoMimeTypeGuesser.php index 62feda2ee..fc4bc4502 100644 --- a/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/File/MimeType/FileinfoMimeTypeGuesser.php @@ -57,11 +57,11 @@ public function guess($path) } if (!self::isSupported()) { - return; + return null; } if (!$finfo = new \finfo(FILEINFO_MIME_TYPE, $this->magicFile)) { - return; + return null; } return $finfo->file($path); diff --git a/File/MimeType/MimeTypeGuesserInterface.php b/File/MimeType/MimeTypeGuesserInterface.php index 5ac1acb82..e46e78eef 100644 --- a/File/MimeType/MimeTypeGuesserInterface.php +++ b/File/MimeType/MimeTypeGuesserInterface.php @@ -26,7 +26,7 @@ interface MimeTypeGuesserInterface * * @param string $path The path to the file * - * @return string The mime type or NULL, if none could be guessed + * @return string|null The mime type or NULL, if none could be guessed * * @throws FileNotFoundException If the file does not exist * @throws AccessDeniedException If the file could not be read diff --git a/RequestStack.php b/RequestStack.php index 885d78a50..244a77d63 100644 --- a/RequestStack.php +++ b/RequestStack.php @@ -47,7 +47,7 @@ public function push(Request $request) public function pop() { if (!$this->requests) { - return; + return null; } return array_pop($this->requests); @@ -73,7 +73,7 @@ public function getCurrentRequest() public function getMasterRequest() { if (!$this->requests) { - return; + return null; } return $this->requests[0]; @@ -95,7 +95,7 @@ public function getParentRequest() $pos = \count($this->requests) - 2; if (!isset($this->requests[$pos])) { - return; + return null; } return $this->requests[$pos]; From adc268778aab47e1465fd7ebf90ecfdd9ca6080c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Auswo=CC=88ger?= Date: Tue, 13 Aug 2019 19:24:27 +0200 Subject: [PATCH 210/225] Fix getMaxFilesize() returning zero --- File/UploadedFile.php | 2 +- Tests/File/UploadedFileTest.php | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/File/UploadedFile.php b/File/UploadedFile.php index 093aaf832..86153ed49 100644 --- a/File/UploadedFile.php +++ b/File/UploadedFile.php @@ -217,7 +217,7 @@ public static function getMaxFilesize() $sizePostMax = self::parseFilesize(ini_get('post_max_size')); $sizeUploadMax = self::parseFilesize(ini_get('upload_max_filesize')); - return min([$sizePostMax, $sizeUploadMax]); + return min($sizePostMax ?: PHP_INT_MAX, $sizeUploadMax ?: PHP_INT_MAX); } /** diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 629211052..4186c72a6 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -281,4 +281,18 @@ public function testIsInvalidIfNotHttpUpload() $this->assertFalse($file->isValid()); } + + public function testGetMaxFilesize() + { + $size = UploadedFile::getMaxFilesize(); + + $this->assertIsInt($size); + $this->assertGreaterThan(0, $size); + + if (0 === (int) ini_get('post_max_size') && 0 === (int) ini_get('upload_max_filesize')) { + $this->assertSame(PHP_INT_MAX, $size); + } else { + $this->assertLessThan(PHP_INT_MAX, $size); + } + } } From dacdad8436eab21a518d041dd954813b634ae932 Mon Sep 17 00:00:00 2001 From: Philippe Segatori Date: Tue, 13 Aug 2019 22:27:05 +0200 Subject: [PATCH 211/225] Remove superfluous phpdoc tags --- AcceptHeaderItem.php | 1 - RequestMatcher.php | 1 - 2 files changed, 2 deletions(-) diff --git a/AcceptHeaderItem.php b/AcceptHeaderItem.php index f6e896874..96bb0c443 100644 --- a/AcceptHeaderItem.php +++ b/AcceptHeaderItem.php @@ -25,7 +25,6 @@ class AcceptHeaderItem /** * @param string $value - * @param array $attributes */ public function __construct($value, array $attributes = []) { diff --git a/RequestMatcher.php b/RequestMatcher.php index cadf70c5b..3f5149579 100644 --- a/RequestMatcher.php +++ b/RequestMatcher.php @@ -53,7 +53,6 @@ class RequestMatcher implements RequestMatcherInterface * @param string|null $host * @param string|string[]|null $methods * @param string|string[]|null $ips - * @param array $attributes * @param string|string[]|null $schemes */ public function __construct($path = null, $host = null, $methods = null, $ips = null, array $attributes = [], $schemes = null) From 9781d8d29ee7279f53720f7c0281e6fb442e96e4 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Mon, 19 Aug 2019 23:30:37 +0200 Subject: [PATCH 212/225] Fix inconsistent return points. --- File/MimeType/ExtensionGuesser.php | 2 ++ File/MimeType/MimeTypeGuesser.php | 2 ++ Request.php | 18 ++++++++++-------- Response.php | 6 +++++- 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/File/MimeType/ExtensionGuesser.php b/File/MimeType/ExtensionGuesser.php index 80f4d47f7..f9393df90 100644 --- a/File/MimeType/ExtensionGuesser.php +++ b/File/MimeType/ExtensionGuesser.php @@ -90,5 +90,7 @@ public function guess($mimeType) return $extension; } } + + return null; } } diff --git a/File/MimeType/MimeTypeGuesser.php b/File/MimeType/MimeTypeGuesser.php index 95d1ee267..e05269fc8 100644 --- a/File/MimeType/MimeTypeGuesser.php +++ b/File/MimeType/MimeTypeGuesser.php @@ -129,5 +129,7 @@ public function guess($path) if (2 === \count($this->guessers) && !FileBinaryMimeTypeGuesser::isSupported() && !FileinfoMimeTypeGuesser::isSupported()) { throw new \LogicException('Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)'); } + + return null; } } diff --git a/Request.php b/Request.php index 9557dac30..3b9bf2f49 100644 --- a/Request.php +++ b/Request.php @@ -97,49 +97,49 @@ class Request /** * Custom parameters. * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $attributes; /** * Request body parameters ($_POST). * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $request; /** * Query string parameters ($_GET). * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $query; /** * Server and execution environment parameters ($_SERVER). * - * @var \Symfony\Component\HttpFoundation\ServerBag + * @var ServerBag */ public $server; /** * Uploaded files ($_FILES). * - * @var \Symfony\Component\HttpFoundation\FileBag + * @var FileBag */ public $files; /** * Cookies ($_COOKIE). * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $cookies; /** * Headers (taken from the $_SERVER). * - * @var \Symfony\Component\HttpFoundation\HeaderBag + * @var HeaderBag */ public $headers; @@ -199,7 +199,7 @@ class Request protected $format; /** - * @var \Symfony\Component\HttpFoundation\Session\SessionInterface + * @var SessionInterface */ protected $session; @@ -1449,6 +1449,8 @@ public function getFormat($mimeType) return $format; } } + + return null; } /** diff --git a/Response.php b/Response.php index 47dae9534..eae9b7841 100644 --- a/Response.php +++ b/Response.php @@ -88,7 +88,7 @@ class Response const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585 /** - * @var \Symfony\Component\HttpFoundation\ResponseHeaderBag + * @var ResponseHeaderBag */ public $headers; @@ -790,6 +790,8 @@ public function getMaxAge() if (null !== $this->getExpires()) { return (int) $this->getExpires()->format('U') - (int) $this->getDate()->format('U'); } + + return null; } /** @@ -846,6 +848,8 @@ public function getTtl() if (null !== $maxAge = $this->getMaxAge()) { return $maxAge - $this->getAge(); } + + return null; } /** From b3d57a1c325f39f703b249bed7998ce8c64236b4 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 21 Aug 2019 18:20:57 +0200 Subject: [PATCH 213/225] [HttpFoundation] fix return type declarations --- BinaryFileResponse.php | 4 ++-- FileBag.php | 8 +++----- HeaderBag.php | 2 +- Request.php | 6 +++++- Response.php | 2 +- Session/Attribute/NamespacedAttributeBag.php | 2 +- Session/Storage/Handler/MemcachedSessionHandler.php | 9 +++------ Session/Storage/Handler/NullSessionHandler.php | 2 +- Session/Storage/Handler/PdoSessionHandler.php | 2 +- Session/Storage/Handler/StrictSessionHandler.php | 2 +- Session/Storage/Proxy/AbstractProxy.php | 2 +- Session/Storage/Proxy/SessionHandlerProxy.php | 2 +- StreamedResponse.php | 2 -- Tests/BinaryFileResponseTest.php | 2 +- Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php | 3 ++- 15 files changed, 24 insertions(+), 26 deletions(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index 6c9a995e9..f43114111 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -327,12 +327,12 @@ public function setContent($content) if (null !== $content) { throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.'); } + + return $this; } /** * {@inheritdoc} - * - * @return false */ public function getContent() { diff --git a/FileBag.php b/FileBag.php index ca849b3d7..024fadf20 100644 --- a/FileBag.php +++ b/FileBag.php @@ -75,8 +75,8 @@ protected function convertFileInformation($file) return $file; } - $file = $this->fixPhpFilesArray($file); if (\is_array($file)) { + $file = $this->fixPhpFilesArray($file); $keys = array_keys($file); sort($keys); @@ -109,14 +109,12 @@ protected function convertFileInformation($file) * It's safe to pass an already converted array, in which case this method * just returns the original array unmodified. * + * @param array $data + * * @return array */ protected function fixPhpFilesArray($data) { - if (!\is_array($data)) { - return $data; - } - $keys = array_keys($data); sort($keys); diff --git a/HeaderBag.php b/HeaderBag.php index 9798173e6..08299977c 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -121,7 +121,7 @@ public function get($key, $default = null, $first = true) } if ($first) { - return \count($headers[$key]) ? $headers[$key][0] : $default; + return \count($headers[$key]) ? (string) $headers[$key][0] : $default; } return $headers[$key]; diff --git a/Request.php b/Request.php index 3b9bf2f49..3fc7b71e6 100644 --- a/Request.php +++ b/Request.php @@ -528,6 +528,10 @@ public function __toString() try { $content = $this->getContent(); } catch (\LogicException $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + return trigger_error($e, E_USER_ERROR); } @@ -912,7 +916,7 @@ public function getClientIps() * ("Client-Ip" for instance), configure it via the $trustedHeaderSet * argument of the Request::setTrustedProxies() method instead. * - * @return string The client IP address + * @return string|null The client IP address * * @see getClientIps() * @see https://wikipedia.org/wiki/X-Forwarded-For diff --git a/Response.php b/Response.php index eae9b7841..8a17acdd5 100644 --- a/Response.php +++ b/Response.php @@ -407,7 +407,7 @@ public function setContent($content) /** * Gets the current response content. * - * @return string Content + * @return string|false */ public function getContent() { diff --git a/Session/Attribute/NamespacedAttributeBag.php b/Session/Attribute/NamespacedAttributeBag.php index bbf2e39c8..07885e7fb 100644 --- a/Session/Attribute/NamespacedAttributeBag.php +++ b/Session/Attribute/NamespacedAttributeBag.php @@ -97,7 +97,7 @@ public function remove($name) * @param string $name Key name * @param bool $writeContext Write context, default false * - * @return array + * @return array|null */ protected function &resolveAttributePath($name, $writeContext = false) { diff --git a/Session/Storage/Handler/MemcachedSessionHandler.php b/Session/Storage/Handler/MemcachedSessionHandler.php index 8965c089c..a399be5fd 100644 --- a/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/Session/Storage/Handler/MemcachedSessionHandler.php @@ -40,9 +40,6 @@ class MemcachedSessionHandler extends AbstractSessionHandler * * prefix: The prefix to use for the memcached keys in order to avoid collision * * expiretime: The time to live in seconds. * - * @param \Memcached $memcached A \Memcached instance - * @param array $options An associative array of Memcached options - * * @throws \InvalidArgumentException When unsupported options are passed */ public function __construct(\Memcached $memcached, array $options = []) @@ -58,7 +55,7 @@ public function __construct(\Memcached $memcached, array $options = []) } /** - * {@inheritdoc} + * @return bool */ public function close() { @@ -74,7 +71,7 @@ protected function doRead($sessionId) } /** - * {@inheritdoc} + * @return bool */ public function updateTimestamp($sessionId, $data) { @@ -102,7 +99,7 @@ protected function doDestroy($sessionId) } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/Session/Storage/Handler/NullSessionHandler.php b/Session/Storage/Handler/NullSessionHandler.php index 8d193155b..3ba9378ca 100644 --- a/Session/Storage/Handler/NullSessionHandler.php +++ b/Session/Storage/Handler/NullSessionHandler.php @@ -67,7 +67,7 @@ protected function doDestroy($sessionId) } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index 9a50377bc..f9e5d1e8f 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -286,7 +286,7 @@ public function read($sessionId) } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/Session/Storage/Handler/StrictSessionHandler.php b/Session/Storage/Handler/StrictSessionHandler.php index 83a1f2c06..fab8e9a16 100644 --- a/Session/Storage/Handler/StrictSessionHandler.php +++ b/Session/Storage/Handler/StrictSessionHandler.php @@ -94,7 +94,7 @@ public function close() } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/Session/Storage/Proxy/AbstractProxy.php b/Session/Storage/Proxy/AbstractProxy.php index 09c92483c..0303729e7 100644 --- a/Session/Storage/Proxy/AbstractProxy.php +++ b/Session/Storage/Proxy/AbstractProxy.php @@ -31,7 +31,7 @@ abstract class AbstractProxy /** * Gets the session.save_handler name. * - * @return string + * @return string|null */ public function getSaveHandlerName() { diff --git a/Session/Storage/Proxy/SessionHandlerProxy.php b/Session/Storage/Proxy/SessionHandlerProxy.php index b11cc397a..e40712d93 100644 --- a/Session/Storage/Proxy/SessionHandlerProxy.php +++ b/Session/Storage/Proxy/SessionHandlerProxy.php @@ -76,7 +76,7 @@ public function destroy($sessionId) } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/StreamedResponse.php b/StreamedResponse.php index 8bc5fc91a..b9148ea87 100644 --- a/StreamedResponse.php +++ b/StreamedResponse.php @@ -136,8 +136,6 @@ public function setContent($content) /** * {@inheritdoc} - * - * @return false */ public function getContent() { diff --git a/Tests/BinaryFileResponseTest.php b/Tests/BinaryFileResponseTest.php index 3df96f393..fcad11def 100644 --- a/Tests/BinaryFileResponseTest.php +++ b/Tests/BinaryFileResponseTest.php @@ -107,7 +107,7 @@ public function testRequests($requestRange, $offset, $length, $responseRange) $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals($responseRange, $response->headers->get('Content-Range')); - $this->assertSame($length, $response->headers->get('Content-Length')); + $this->assertSame((string) $length, $response->headers->get('Content-Length')); } /** diff --git a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index ec9029c7d..1457ebd70 100644 --- a/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -144,7 +144,8 @@ public function testUpdateTimestamp() { $mock = $this->getMockBuilder(['SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'])->getMock(); $mock->expects($this->once()) - ->method('updateTimestamp'); + ->method('updateTimestamp') + ->willReturn(false); $proxy = new SessionHandlerProxy($mock); $proxy->updateTimestamp('id', 'data'); From 089da40dfa1e5f0a89f29619a1337a64d88e08f9 Mon Sep 17 00:00:00 2001 From: Daniel Rotter Date: Tue, 27 Aug 2019 10:31:03 +0200 Subject: [PATCH 214/225] Return null as Expire header if it was set to null --- HeaderBag.php | 10 +++++++++- Tests/HeaderBagTest.php | 10 ++++++++++ Tests/ResponseTest.php | 6 ++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/HeaderBag.php b/HeaderBag.php index 08299977c..35bd6ad8f 100644 --- a/HeaderBag.php +++ b/HeaderBag.php @@ -121,7 +121,15 @@ public function get($key, $default = null, $first = true) } if ($first) { - return \count($headers[$key]) ? (string) $headers[$key][0] : $default; + if (!$headers[$key]) { + return $default; + } + + if (null === $headers[$key][0]) { + return null; + } + + return (string) $headers[$key][0]; } return $headers[$key]; diff --git a/Tests/HeaderBagTest.php b/Tests/HeaderBagTest.php index a5876f9e3..dcc266f69 100644 --- a/Tests/HeaderBagTest.php +++ b/Tests/HeaderBagTest.php @@ -48,6 +48,13 @@ public function testGetDate() $this->assertInstanceOf('DateTime', $headerDate); } + public function testGetDateNull() + { + $bag = new HeaderBag(['foo' => null]); + $headerDate = $bag->getDate('foo'); + $this->assertNull($headerDate); + } + public function testGetDateException() { $this->expectException('RuntimeException'); @@ -96,6 +103,9 @@ public function testGet() $bag->set('foo', 'bor', false); $this->assertEquals('bar', $bag->get('foo'), '->get return first value'); $this->assertEquals(['bar', 'bor'], $bag->get('foo', 'nope', false), '->get return all values as array'); + + $bag->set('baz', null); + $this->assertNull($bag->get('baz', 'nope'), '->get return null although different default value is given'); } public function testSetAssociativeArray() diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index c61dbacdd..b846cdad3 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -369,6 +369,12 @@ public function testExpire() $this->assertNull($response->headers->get('Expires'), '->expire() removes the Expires header when the response is fresh'); } + public function testNullExpireHeader() + { + $response = new Response(null, 200, ['Expires' => null]); + $this->assertNull($response->getExpires()); + } + public function testGetTtl() { $response = new Response(); From ec2a74a7c858640acaebd11a9ebc2a8f6662f7aa Mon Sep 17 00:00:00 2001 From: mmokhi Date: Wed, 11 Sep 2019 11:18:08 +0200 Subject: [PATCH 215/225] Call AssertEquals with proper parameters Since `$response->getContent()` returns string and our first parameter is already string as well, in some cases (with different precisions) it may "compare strings" as "strings" and this is not what the test wants. By changing the first parameter to actual number we force `AssertEquals` to compare them numerically rather than literally by string content. --- Tests/JsonResponseTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/JsonResponseTest.php b/Tests/JsonResponseTest.php index fd045fb9c..9642dc28d 100644 --- a/Tests/JsonResponseTest.php +++ b/Tests/JsonResponseTest.php @@ -52,7 +52,7 @@ public function testConstructorWithSimpleTypes() $this->assertSame('0', $response->getContent()); $response = new JsonResponse(0.1); - $this->assertEquals('0.1', $response->getContent()); + $this->assertEquals(0.1, $response->getContent()); $this->assertIsString($response->getContent()); $response = new JsonResponse(true); @@ -141,7 +141,7 @@ public function testStaticCreateWithSimpleTypes() $response = JsonResponse::create(0.1); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); - $this->assertEquals('0.1', $response->getContent()); + $this->assertEquals(0.1, $response->getContent()); $this->assertIsString($response->getContent()); $response = JsonResponse::create(true); From 35ffbbfa73e46e28a9433692cd6c404de70e6c4c Mon Sep 17 00:00:00 2001 From: marie <15118505+marie@users.noreply.github.com> Date: Fri, 20 Sep 2019 15:03:12 +0500 Subject: [PATCH 216/225] [HttpFoundation] allow additinal characters in not raw cookies --- Cookie.php | 21 +++++++++++++---- Response.php | 2 +- Tests/CookieTest.php | 23 +++++++++++++++---- .../cookie_urlencode.expected | 3 ++- .../response-functional/cookie_urlencode.php | 9 +++++--- .../invalid_cookie_name.php | 2 +- 6 files changed, 44 insertions(+), 16 deletions(-) diff --git a/Cookie.php b/Cookie.php index 83a97087f..98a5ef00a 100644 --- a/Cookie.php +++ b/Cookie.php @@ -18,6 +18,10 @@ */ class Cookie { + const SAMESITE_NONE = 'none'; + const SAMESITE_LAX = 'lax'; + const SAMESITE_STRICT = 'strict'; + protected $name; protected $value; protected $domain; @@ -25,12 +29,13 @@ class Cookie protected $path; protected $secure; protected $httpOnly; + private $raw; private $sameSite; - const SAMESITE_NONE = 'none'; - const SAMESITE_LAX = 'lax'; - const SAMESITE_STRICT = 'strict'; + private static $reservedCharsList = "=,; \t\r\n\v\f"; + private static $reservedCharsFrom = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"]; + private static $reservedCharsTo = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C']; /** * Creates cookie from raw header string. @@ -97,7 +102,7 @@ public static function fromString($cookie, $decode = false) public function __construct($name, $value = null, $expire = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true, $raw = false, $sameSite = null) { // from PHP source code - if (preg_match("/[=,; \t\r\n\013\014]/", $name)) { + if ($raw && false !== strpbrk($name, self::$reservedCharsList)) { throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name)); } @@ -143,7 +148,13 @@ public function __construct($name, $value = null, $expire = 0, $path = '/', $dom */ public function __toString() { - $str = ($this->isRaw() ? $this->getName() : urlencode($this->getName())).'='; + if ($this->isRaw()) { + $str = $this->getName(); + } else { + $str = str_replace(self::$reservedCharsFrom, self::$reservedCharsTo, $this->getName()); + } + + $str .= '='; if ('' === (string) $this->getValue()) { $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0'; diff --git a/Response.php b/Response.php index 8a17acdd5..26e3a3378 100644 --- a/Response.php +++ b/Response.php @@ -342,7 +342,7 @@ public function sendHeaders() // cookies foreach ($this->headers->getCookies() as $cookie) { - header('Set-Cookie: '.$cookie->getName().strstr($cookie, '='), false, $this->statusCode); + header('Set-Cookie: '.$cookie, false, $this->statusCode); } // status diff --git a/Tests/CookieTest.php b/Tests/CookieTest.php index 38c195df3..169f91787 100644 --- a/Tests/CookieTest.php +++ b/Tests/CookieTest.php @@ -24,10 +24,9 @@ */ class CookieTest extends TestCase { - public function invalidNames() + public function namesWithSpecialCharacters() { return [ - [''], [',MyName'], [';MyName'], [' MyName'], @@ -40,12 +39,26 @@ public function invalidNames() } /** - * @dataProvider invalidNames + * @dataProvider namesWithSpecialCharacters */ - public function testInstantiationThrowsExceptionIfCookieNameContainsInvalidCharacters($name) + public function testInstantiationThrowsExceptionIfRawCookieNameContainsSpecialCharacters($name) { $this->expectException('InvalidArgumentException'); - new Cookie($name); + new Cookie($name, null, 0, null, null, null, false, true); + } + + /** + * @dataProvider namesWithSpecialCharacters + */ + public function testInstantiationSucceedNonRawCookieNameContainsSpecialCharacters($name) + { + $this->assertInstanceOf(Cookie::class, new Cookie($name)); + } + + public function testInstantiationThrowsExceptionIfCookieNameIsEmpty() + { + $this->expectException('InvalidArgumentException'); + new Cookie(''); } public function testInvalidExpiration() diff --git a/Tests/Fixtures/response-functional/cookie_urlencode.expected b/Tests/Fixtures/response-functional/cookie_urlencode.expected index 14e44a398..17a9efc66 100644 --- a/Tests/Fixtures/response-functional/cookie_urlencode.expected +++ b/Tests/Fixtures/response-functional/cookie_urlencode.expected @@ -4,7 +4,8 @@ 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; path=/ + [3] => Set-Cookie: %3D%2C%3B%20%09%0D%0A%0B%0C=%3D%2C%3B%20%09%0D%0A%0B%0C; path=/ [4] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/ + [5] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/ ) shutdown diff --git a/Tests/Fixtures/response-functional/cookie_urlencode.php b/Tests/Fixtures/response-functional/cookie_urlencode.php index 05b9af30d..9ffb0dfec 100644 --- a/Tests/Fixtures/response-functional/cookie_urlencode.php +++ b/Tests/Fixtures/response-functional/cookie_urlencode.php @@ -4,9 +4,12 @@ $r = require __DIR__.'/common.inc'; -$str = '?*():@&+$/%#[]'; +$str1 = "=,; \t\r\n\v\f"; +$r->headers->setCookie(new Cookie($str1, $str1, 0, '', null, false, false, false, null)); -$r->headers->setCookie(new Cookie($str, $str, 0, '', null, false, false)); +$str2 = '?*():@&+$/%#[]'; + +$r->headers->setCookie(new Cookie($str2, $str2, 0, '', null, false, false, false, null)); $r->sendHeaders(); -setcookie($str, $str, 0, '/'); +setcookie($str2, $str2, 0, '/'); diff --git a/Tests/Fixtures/response-functional/invalid_cookie_name.php b/Tests/Fixtures/response-functional/invalid_cookie_name.php index 3fe157184..3acf86039 100644 --- a/Tests/Fixtures/response-functional/invalid_cookie_name.php +++ b/Tests/Fixtures/response-functional/invalid_cookie_name.php @@ -5,7 +5,7 @@ $r = require __DIR__.'/common.inc'; try { - $r->headers->setCookie(new Cookie('Hello + world', 'hodor')); + $r->headers->setCookie(new Cookie('Hello + world', 'hodor', 0, null, null, null, false, true)); } catch (\InvalidArgumentException $e) { echo $e->getMessage(); } From 233f40cbebd595ffd91ddf291355f8a930a13777 Mon Sep 17 00:00:00 2001 From: bogdan Date: Wed, 2 Oct 2019 18:28:34 +0300 Subject: [PATCH 217/225] [HttpFoundation] Check if data passed to SessionBagProxy::initialize is an array --- Session/Storage/NativeSessionStorage.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/NativeSessionStorage.php b/Session/Storage/NativeSessionStorage.php index 4f1c30ef5..4c5873728 100644 --- a/Session/Storage/NativeSessionStorage.php +++ b/Session/Storage/NativeSessionStorage.php @@ -430,7 +430,7 @@ protected function loadSession(array &$session = null) foreach ($bags as $bag) { $key = $bag->getStorageKey(); - $session[$key] = isset($session[$key]) ? $session[$key] : []; + $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : []; $bag->initialize($session[$key]); } From 4db558c7c6777aac02293efbfe7c7c5d4c1385c3 Mon Sep 17 00:00:00 2001 From: Ilia Lazarev Date: Sat, 12 Oct 2019 10:36:35 +0300 Subject: [PATCH 218/225] Add plus character `+` to legal mime subtype For example, the following mime type (used for epub) is not recognized given the current regexp: `application/epub+zip` --- File/MimeType/FileBinaryMimeTypeGuesser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index b75242afd..cfa76843c 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -89,7 +89,7 @@ public function guess($path) $type = trim(ob_get_clean()); - if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) { + if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\+\.]+)#i', $type, $match)) { // it's not a type, but an error message return null; } From 7b4626ab40d8562707e6d1c9a6fab977a86c2037 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Thu, 24 Oct 2019 14:44:17 +0200 Subject: [PATCH 219/225] Remove unused local variables in tests --- Tests/File/UploadedFileTest.php | 2 +- Tests/HeaderBagTest.php | 2 +- Tests/RedirectResponseTest.php | 4 ++-- .../Storage/Handler/NativeFileSessionHandlerTest.php | 6 +++--- Tests/Session/Storage/Handler/NullSessionHandlerTest.php | 2 +- Tests/Session/Storage/Handler/PdoSessionHandlerTest.php | 2 +- Tests/Session/Storage/NativeSessionStorageTest.php | 4 ++-- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Tests/File/UploadedFileTest.php b/Tests/File/UploadedFileTest.php index 4186c72a6..2ea924bac 100644 --- a/Tests/File/UploadedFileTest.php +++ b/Tests/File/UploadedFileTest.php @@ -153,7 +153,7 @@ public function testMoveLocalFileIsNotAllowed() UPLOAD_ERR_OK ); - $movedFile = $file->move(__DIR__.'/Fixtures/directory'); + $file->move(__DIR__.'/Fixtures/directory'); } public function testMoveLocalFileIsAllowedInTestMode() diff --git a/Tests/HeaderBagTest.php b/Tests/HeaderBagTest.php index dcc266f69..cabe038bd 100644 --- a/Tests/HeaderBagTest.php +++ b/Tests/HeaderBagTest.php @@ -59,7 +59,7 @@ public function testGetDateException() { $this->expectException('RuntimeException'); $bag = new HeaderBag(['foo' => 'Tue']); - $headerDate = $bag->getDate('foo'); + $bag->getDate('foo'); } public function testGetCacheControlHeader() diff --git a/Tests/RedirectResponseTest.php b/Tests/RedirectResponseTest.php index 92f4876da..e1ff3bf2b 100644 --- a/Tests/RedirectResponseTest.php +++ b/Tests/RedirectResponseTest.php @@ -29,13 +29,13 @@ public function testGenerateMetaRedirect() public function testRedirectResponseConstructorNullUrl() { $this->expectException('InvalidArgumentException'); - $response = new RedirectResponse(null); + new RedirectResponse(null); } public function testRedirectResponseConstructorWrongStatusCode() { $this->expectException('InvalidArgumentException'); - $response = new RedirectResponse('foo.bar', 404); + new RedirectResponse('foo.bar', 404); } public function testGenerateLocationHeader() diff --git a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php index 9daf1a0ee..7de55798a 100644 --- a/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php @@ -41,7 +41,7 @@ public function testConstruct() */ public function testConstructSavePath($savePath, $expectedSavePath, $path) { - $handler = new NativeFileSessionHandler($savePath); + new NativeFileSessionHandler($savePath); $this->assertEquals($expectedSavePath, ini_get('session.save_path')); $this->assertDirectoryExists(realpath($path)); @@ -62,13 +62,13 @@ public function savePathDataProvider() public function testConstructException() { $this->expectException('InvalidArgumentException'); - $handler = new NativeFileSessionHandler('something;invalid;with;too-many-args'); + new NativeFileSessionHandler('something;invalid;with;too-many-args'); } public function testConstructDefault() { $path = ini_get('session.save_path'); - $storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler()); + new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler()); $this->assertEquals($path, ini_get('session.save_path')); } diff --git a/Tests/Session/Storage/Handler/NullSessionHandlerTest.php b/Tests/Session/Storage/Handler/NullSessionHandlerTest.php index 0d246e1aa..f793db144 100644 --- a/Tests/Session/Storage/Handler/NullSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/NullSessionHandlerTest.php @@ -28,7 +28,7 @@ class NullSessionHandlerTest extends TestCase { public function testSaveHandlers() { - $storage = $this->getStorage(); + $this->getStorage(); $this->assertEquals('user', ini_get('session.save_handler')); } diff --git a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index 123b605d2..e710dca92 100644 --- a/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -54,7 +54,7 @@ public function testWrongPdoErrMode() $pdo = $this->getMemorySqlitePdo(); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); - $storage = new PdoSessionHandler($pdo); + new PdoSessionHandler($pdo); } public function testInexistentTable() diff --git a/Tests/Session/Storage/NativeSessionStorageTest.php b/Tests/Session/Storage/NativeSessionStorageTest.php index fa170d17d..9ce8108da 100644 --- a/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/Tests/Session/Storage/NativeSessionStorageTest.php @@ -145,7 +145,7 @@ public function testDefaultSessionCacheLimiter() { $this->iniSet('session.cache_limiter', 'nocache'); - $storage = new NativeSessionStorage(); + new NativeSessionStorage(); $this->assertEquals('', ini_get('session.cache_limiter')); } @@ -153,7 +153,7 @@ public function testExplicitSessionCacheLimiter() { $this->iniSet('session.cache_limiter', 'nocache'); - $storage = new NativeSessionStorage(['cache_limiter' => 'public']); + new NativeSessionStorage(['cache_limiter' => 'public']); $this->assertEquals('public', ini_get('session.cache_limiter')); } From a5d46a33e8649ba802cebe520d188b04385572a2 Mon Sep 17 00:00:00 2001 From: HypeMC Date: Sun, 3 Nov 2019 03:12:45 +0100 Subject: [PATCH 220/225] Fix MockFileSessionStorageTest::sessionDir being used after it's unset --- Tests/Session/Storage/MockFileSessionStorageTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/Session/Storage/MockFileSessionStorageTest.php b/Tests/Session/Storage/MockFileSessionStorageTest.php index b316c83e6..d6bd1823f 100644 --- a/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -41,12 +41,12 @@ protected function setUp() protected function tearDown() { - $this->sessionDir = null; - $this->storage = null; - array_map('unlink', glob($this->sessionDir.'/*.session')); + array_map('unlink', glob($this->sessionDir.'/*')); if (is_dir($this->sessionDir)) { rmdir($this->sessionDir); } + $this->sessionDir = null; + $this->storage = null; } public function testStart() From 9e4b3ac8fa3348b4811674d23de32d201de225ce Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 19 Apr 2019 14:48:43 +0200 Subject: [PATCH 221/225] [HttpFoundation] fix guessing mime-types of files with leading dash --- File/MimeType/FileBinaryMimeTypeGuesser.php | 4 ++-- Tests/File/Fixtures/-test | Bin 0 -> 35 bytes Tests/File/MimeType/MimeTypeTest.php | 11 ++++++++++- 3 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 Tests/File/Fixtures/-test diff --git a/File/MimeType/FileBinaryMimeTypeGuesser.php b/File/MimeType/FileBinaryMimeTypeGuesser.php index cfa76843c..7045e94df 100644 --- a/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -31,7 +31,7 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface * * @param string $cmd The command to run to get the mime type of a file */ - public function __construct($cmd = 'file -b --mime %s 2>/dev/null') + public function __construct($cmd = 'file -b --mime -- %s 2>/dev/null') { $this->cmd = $cmd; } @@ -80,7 +80,7 @@ public function guess($path) ob_start(); // need to use --mime instead of -i. see #6641 - passthru(sprintf($this->cmd, escapeshellarg($path)), $return); + passthru(sprintf($this->cmd, escapeshellarg((0 === strpos($path, '-') ? './' : '').$path)), $return); if ($return > 0) { ob_end_clean(); diff --git a/Tests/File/Fixtures/-test b/Tests/File/Fixtures/-test new file mode 100644 index 0000000000000000000000000000000000000000..b636f4b8df536b0a85e7cea1a6cf3f0bd3179b96 GIT binary patch literal 35 jcmZ?wbh9u|WMp7uXkcLY4+c66KmZb9U}AD%WUvMRyAlZ1 literal 0 HcmV?d00001 diff --git a/Tests/File/MimeType/MimeTypeTest.php b/Tests/File/MimeType/MimeTypeTest.php index 3960988a6..0418726b5 100644 --- a/Tests/File/MimeType/MimeTypeTest.php +++ b/Tests/File/MimeType/MimeTypeTest.php @@ -20,7 +20,16 @@ */ class MimeTypeTest extends TestCase { - protected $path; + public function testGuessWithLeadingDash() + { + $cwd = getcwd(); + chdir(__DIR__.'/../Fixtures'); + try { + $this->assertEquals('image/gif', MimeTypeGuesser::getInstance()->guess('-test')); + } finally { + chdir($cwd); + } + } public function testGuessImageWithoutExtension() { From c9425bae96ae95449d59f8286529cf144bb228ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Broutier?= Date: Sat, 16 Nov 2019 12:20:14 +0100 Subject: [PATCH 222/225] Fix MySQL column type definition. Fix wrong MySQL column type definition causing Numeric value out of range exception. Ref #34409 --- Session/Storage/Handler/PdoSessionHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Session/Storage/Handler/PdoSessionHandler.php b/Session/Storage/Handler/PdoSessionHandler.php index f9e5d1e8f..c9d47b6ed 100644 --- a/Session/Storage/Handler/PdoSessionHandler.php +++ b/Session/Storage/Handler/PdoSessionHandler.php @@ -218,7 +218,7 @@ public function createTable() // - trailing space removal // - case-insensitivity // - language processing like é == e - $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol MEDIUMINT NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB"; + $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB"; break; case 'sqlite': $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; From ef5fed4469fb079c0b188ab0401cd1b28752865b Mon Sep 17 00:00:00 2001 From: Mark Beech Date: Wed, 13 Nov 2019 20:07:22 +0000 Subject: [PATCH 223/225] [HttpFoundation] Allow redirecting to URLs that contain a semicolon --- RedirectResponse.php | 2 +- Tests/RedirectResponseTest.php | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/RedirectResponse.php b/RedirectResponse.php index 4e3cb4f77..a19efba3e 100644 --- a/RedirectResponse.php +++ b/RedirectResponse.php @@ -93,7 +93,7 @@ public function setTargetUrl($url) - + Redirecting to %1$s diff --git a/Tests/RedirectResponseTest.php b/Tests/RedirectResponseTest.php index e1ff3bf2b..2bbf5aa1a 100644 --- a/Tests/RedirectResponseTest.php +++ b/Tests/RedirectResponseTest.php @@ -20,10 +20,7 @@ public function testGenerateMetaRedirect() { $response = new RedirectResponse('foo.bar'); - $this->assertEquals(1, preg_match( - '##', - preg_replace(['/\s+/', '/\'/'], [' ', '"'], $response->getContent()) - )); + $this->assertRegExp('##', preg_replace('/\s+/', ' ', $response->getContent())); } public function testRedirectResponseConstructorNullUrl() From f7efd0b387b7bdbfe0fd1e38fe6b7d4a812b4e39 Mon Sep 17 00:00:00 2001 From: Roy-Orbison Date: Wed, 20 Nov 2019 15:04:29 +1030 Subject: [PATCH 224/225] Simpler example for Apache basic auth workaround Uses a simpler regex and existing back-reference instead of reading header twice. --- ServerBag.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ServerBag.php b/ServerBag.php index 4c82b1774..f3b640234 100644 --- a/ServerBag.php +++ b/ServerBag.php @@ -46,13 +46,13 @@ public function getHeaders() /* * php-cgi under Apache does not pass HTTP Basic user/pass to PHP by default * For this workaround to work, add these lines to your .htaccess file: - * RewriteCond %{HTTP:Authorization} ^(.+)$ - * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] + * RewriteCond %{HTTP:Authorization} .+ + * RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0] * * A sample .htaccess file: * RewriteEngine On - * RewriteCond %{HTTP:Authorization} ^(.+)$ - * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] + * RewriteCond %{HTTP:Authorization} .+ + * RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0] * RewriteCond %{REQUEST_FILENAME} !-f * RewriteRule ^(.*)$ app.php [QSA,L] */ From d2d0cfe8e319d9df44c4cca570710fcf221d4593 Mon Sep 17 00:00:00 2001 From: Thomas Bisignani Date: Thu, 28 Nov 2019 13:52:59 +0100 Subject: [PATCH 225/225] [HttpFoundation] Fixed typo --- BinaryFileResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BinaryFileResponse.php b/BinaryFileResponse.php index f43114111..ea7ac8469 100644 --- a/BinaryFileResponse.php +++ b/BinaryFileResponse.php @@ -348,7 +348,7 @@ public static function trustXSendfileTypeHeader() } /** - * If this is set to true, the file will be unlinked after the request is send + * If this is set to true, the file will be unlinked after the request is sent * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used. * * @param bool $shouldDelete