From 4cbe56ef079c3bc90eaacc2cffefa46596a09d88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20L=C3=BCck?= Date: Sat, 25 May 2024 16:37:32 +0200 Subject: [PATCH] Update PHP language syntax and remove legacy workarounds --- README.md | 131 ++-- examples/03-client-request-any.php | 4 +- examples/04-client-post-json.php | 12 +- examples/05-client-put-xml.php | 4 +- examples/11-client-http-proxy.php | 4 +- examples/12-client-socks-proxy.php | 4 +- examples/13-client-ssh-proxy.php | 4 +- .../21-client-request-streaming-to-stdout.php | 2 +- .../22-client-stream-upload-from-stdin.php | 4 +- examples/51-server-hello-world.php | 2 +- examples/52-server-count-visitors.php | 2 +- examples/53-server-whatsmyip.php | 2 +- examples/54-server-query-parameter.php | 2 +- examples/55-server-cookie-handling.php | 2 +- examples/56-server-sleep.php | 2 +- examples/57-server-error-handling.php | 2 +- examples/58-server-stream-response.php | 6 +- examples/59-server-json-api.php | 26 +- examples/61-server-hello-world-https.php | 12 +- examples/62-server-form-upload.php | 2 +- examples/63-server-streaming-request.php | 2 +- examples/71-server-http-proxy.php | 2 +- examples/72-server-http-connect-proxy.php | 12 +- examples/81-server-upgrade-echo.php | 10 +- examples/82-server-upgrade-chat.php | 10 +- examples/91-client-benchmark-download.php | 2 +- examples/92-client-benchmark-upload.php | 10 +- examples/99-server-benchmark-download.php | 12 +- src/Browser.php | 74 +- src/HttpServer.php | 21 +- src/Io/AbstractMessage.php | 18 +- src/Io/AbstractRequest.php | 4 +- src/Io/BufferedBody.php | 2 +- src/Io/ChunkedDecoder.php | 14 +- src/Io/ChunkedEncoder.php | 18 +- src/Io/ClientConnectionManager.php | 27 +- src/Io/ClientRequestStream.php | 59 +- src/Io/Clock.php | 7 +- src/Io/CloseProtectionStream.php | 22 +- src/Io/EmptyBodyStream.php | 4 +- src/Io/HttpBodyStream.php | 14 +- src/Io/LengthLimitedStream.php | 16 +- src/Io/MiddlewareRunner.php | 8 +- src/Io/MultipartParser.php | 8 +- src/Io/PauseBufferStream.php | 18 +- src/Io/ReadableBodyStream.php | 30 +- src/Io/RequestHeaderParser.php | 35 +- src/Io/Sender.php | 8 +- src/Io/StreamingServer.php | 66 +- src/Io/Transaction.php | 50 +- src/Io/UploadedFile.php | 4 +- src/Message/Request.php | 2 +- src/Message/Response.php | 41 +- src/Message/ServerRequest.php | 20 +- src/Message/Uri.php | 8 +- .../LimitConcurrentRequestsMiddleware.php | 57 +- .../RequestBodyBufferMiddleware.php | 5 +- .../RequestBodyParserMiddleware.php | 4 +- tests/BrowserTest.php | 223 +++--- tests/Client/FunctionalIntegrationTest.php | 41 +- tests/FunctionalBrowserTest.php | 182 ++--- tests/FunctionalHttpServerTest.php | 205 +++--- tests/HttpServerTest.php | 78 +-- tests/Io/AbstractMessageTest.php | 100 +-- tests/Io/AbstractRequestTest.php | 96 +-- tests/Io/BufferedBodyTest.php | 2 +- tests/Io/ChunkedDecoderTest.php | 176 ++--- tests/Io/ChunkedEncoderTest.php | 8 +- tests/Io/ClientConnectionManagerTest.php | 43 +- tests/Io/ClientRequestStreamTest.php | 338 +++++---- tests/Io/CloseProtectionStreamTest.php | 8 +- tests/Io/EmptyBodyStreamTest.php | 4 +- tests/Io/HttpBodyStreamTest.php | 14 +- tests/Io/IniUtilTest.php | 52 +- tests/Io/LengthLimitedStreamTest.php | 14 +- tests/Io/MiddlewareRunnerTest.php | 170 ++--- tests/Io/MultipartParserTest.php | 232 +++--- tests/Io/PauseBufferStreamTest.php | 8 +- tests/Io/ReadableBodyStreamTest.php | 2 +- tests/Io/RequestHeaderParserTest.php | 141 ++-- tests/Io/SenderTest.php | 44 +- tests/Io/StreamingServerTest.php | 659 +++++++++--------- tests/Io/TransactionTest.php | 326 +++++---- tests/Io/UploadedFileTest.php | 12 +- tests/Message/RequestTest.php | 8 +- tests/Message/ResponseTest.php | 26 +- tests/Message/ServerRequestTest.php | 132 ++-- tests/Message/UriTest.php | 240 +++---- .../LimitConcurrentRequestsMiddlewareTest.php | 38 +- tests/Middleware/ProcessStack.php | 4 +- .../RequestBodyBufferMiddlewareTest.php | 41 +- .../RequestBodyParserMiddlewareTest.php | 94 +-- tests/TestCase.php | 10 +- tests/benchmark-middleware-runner.php | 2 +- 94 files changed, 2329 insertions(+), 2397 deletions(-) diff --git a/README.md b/README.md index 9cdf7c09..7761a245 100644 --- a/README.md +++ b/README.md @@ -144,12 +144,12 @@ Most importantly, this project provides a [`Browser`](#browser) object that offers several methods that resemble the HTTP protocol methods: ```php -$browser->get($url, array $headers = array()); -$browser->head($url, array $headers = array()); -$browser->post($url, array $headers = array(), string|ReadableStreamInterface $body = ''); -$browser->delete($url, array $headers = array(), string|ReadableStreamInterface $body = ''); -$browser->put($url, array $headers = array(), string|ReadableStreamInterface $body = ''); -$browser->patch($url, array $headers = array(), string|ReadableStreamInterface $body = ''); +$browser->get($url, array $headers = []); +$browser->head($url, array $headers = []); +$browser->post($url, array $headers = [], string|ReadableStreamInterface $body = ''); +$browser->delete($url, array $headers = [], string|ReadableStreamInterface $body = ''); +$browser->put($url, array $headers = [], string|ReadableStreamInterface $body = ''); +$browser->patch($url, array $headers = [], string|ReadableStreamInterface $body = ''); ``` Each of these methods requires a `$url` and some optional parameters to send an @@ -285,9 +285,9 @@ like this: ```php $browser = new React\Http\Browser( new React\Socket\Connector( - array( + [ 'timeout' => 5 - ) + ] ) ); ``` @@ -323,9 +323,9 @@ $token = 'abc123'; $promise = $browser->get( 'https://example.com/api', - array( + [ 'Authorization' => 'Bearer ' . $token - ) + ] ); ``` @@ -411,10 +411,10 @@ Similarly, you can also process multiple requests concurrently and await an arra use function React\Async\await; use function React\Promise\all; -$promises = array( +$promises = [ $browser->get('http://example.com/'), $browser->get('http://www.example.org/'), -); +]; $responses = await(all($promises)); ``` @@ -540,7 +540,7 @@ You can invoke the following methods on the message body: $body->on($event, $callback); $body->eof(); $body->isReadable(); -$body->pipe(React\Stream\WritableStreamInterface $dest, array $options = array()); +$body->pipe(React\Stream\WritableStreamInterface $dest, array $options = []); $body->close(); $body->pause(); $body->resume(); @@ -575,10 +575,10 @@ Consider looking into also using [react/promise-stream](https://github.com/react The resulting streaming code could look something like this: ```php -use React\Promise\Stream; +use function React\Promise\Stream\unwrapReadable; function download(Browser $browser, string $url): React\Stream\ReadableStreamInterface { - return Stream\unwrapReadable( + return unwrapReadable( $browser->requestStreaming('GET', $url)->then(function (Psr\Http\Message\ResponseInterface $response) { return $response->getBody(); }) @@ -606,7 +606,7 @@ implementing [ReactPHP's `ReadableStreamInterface`](https://github.com/reactphp/ to the [request methods](#request-methods) like this: ```php -$browser->post($url, array(), $stream)->then(function (Psr\Http\Message\ResponseInterface $response) { +$browser->post($url, [], $stream)->then(function (Psr\Http\Message\ResponseInterface $response) { echo 'Successfully sent.'; }, function (Exception $e) { echo 'Error: ' . $e->getMessage() . PHP_EOL; @@ -623,7 +623,7 @@ Loop::addTimer(1.0, function () use ($body) { $body->end("hello world"); }); -$browser->post($url, array('Content-Length' => '11'), $body); +$browser->post($url, ['Content-Length' => '11'], $body); ``` If the streaming request body emits an `error` event or is explicitly closed @@ -645,10 +645,10 @@ protocol, such as plain HTTP and TLS-encrypted HTTPS. ```php $proxy = new Clue\React\HttpProxy\ProxyConnector('127.0.0.1:8080'); -$connector = new React\Socket\Connector(array( +$connector = new React\Socket\Connector([ 'tcp' => $proxy, 'dns' => false -)); +]); $browser = new React\Http\Browser($connector); ``` @@ -669,10 +669,10 @@ only, this can technically be used to tunnel any TCP/IP-based protocol. ```php $proxy = new Clue\React\Socks\Client('127.0.0.1:1080'); -$connector = new React\Socket\Connector(array( +$connector = new React\Socket\Connector([ 'tcp' => $proxy, 'dns' => false -)); +]); $browser = new React\Http\Browser($connector); ``` @@ -698,10 +698,10 @@ plain HTTP and TLS-encrypted HTTPS. ```php $proxy = new Clue\React\SshProxy\SshSocksConnector('alice@example.com'); -$connector = new React\Socket\Connector(array( +$connector = new React\Socket\Connector([ 'tcp' => $proxy, 'dns' => false -)); +]); $browser = new React\Http\Browser($connector); ``` @@ -931,11 +931,11 @@ using a secure TLS listen address, a certificate file and optional ```php $http = new React\Http\HttpServer($handler); -$socket = new React\Socket\SocketServer('tls://0.0.0.0:8443', array( - 'tls' => array( +$socket = new React\Socket\SocketServer('tls://0.0.0.0:8443', [ + 'tls' => [ 'local_cert' => __DIR__ . '/localhost.pem' - ) -)); + ] +]); $http->listen($socket); ``` @@ -1456,9 +1456,9 @@ $http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterf return new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Content-Type' => 'text/plain' - ), + ], $stream ); }); @@ -1558,10 +1558,10 @@ $http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterf return new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Content-Length' => '13', 'Content-Type' => 'text/plain', - ), + ], $stream ); }); @@ -1628,9 +1628,9 @@ a custom `Server` response header like this: $http = new React\Http\HttpServer(function (ServerRequestInterface $request) { return new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Server' => 'PHP/3' - ) + ] ); }); ``` @@ -1643,9 +1643,9 @@ string value like this: $http = new React\Http\HttpServer(function (ServerRequestInterface $request) { return new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Server' => '' - ) + ] ); }); ``` @@ -1658,9 +1658,9 @@ like this: $http = new React\Http\HttpServer(function (ServerRequestInterface $request) { return new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Date' => gmdate('D, d M Y H:i:s \G\M\T') - ) + ] ); }); ``` @@ -1673,9 +1673,9 @@ like this: $http = new React\Http\HttpServer(function (ServerRequestInterface $request) { return new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Date' => '' - ) + ] ); }); ``` @@ -1871,16 +1871,16 @@ proxy servers etc.), you can explicitly pass a custom instance of the [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface): ```php -$connector = new React\Socket\Connector(array( +$connector = new React\Socket\Connector([ 'dns' => '127.0.0.1', - 'tcp' => array( + 'tcp' => [ 'bindto' => '192.168.10.1:0' - ), - 'tls' => array( + ], + 'tls' => [ 'verify_peer' => false, 'verify_peer_name' => false - ) -)); + ] +]); $browser = new React\Http\Browser($connector); ``` @@ -1895,7 +1895,7 @@ given event loop instance. #### get() -The `get(string $url, array $headers = array()): PromiseInterface` method can be used to +The `get(string $url, array $headers = []): PromiseInterface` method can be used to send an HTTP GET request. ```php @@ -1910,7 +1910,7 @@ See also [GET request client example](examples/01-client-get-request.php). #### post() -The `post(string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +The `post(string $url, array $headers = [], string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to send an HTTP POST request. ```php @@ -1958,12 +1958,12 @@ Loop::addTimer(1.0, function () use ($body) { $body->end("hello world"); }); -$browser->post($url, array('Content-Length' => '11'), $body); +$browser->post($url, ['Content-Length' => '11'), $body); ``` #### head() -The `head(string $url, array $headers = array()): PromiseInterface` method can be used to +The `head(string $url, array $headers = []): PromiseInterface` method can be used to send an HTTP HEAD request. ```php @@ -1976,7 +1976,7 @@ $browser->head($url)->then(function (Psr\Http\Message\ResponseInterface $respons #### patch() -The `patch(string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +The `patch(string $url, array $headers = [], string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to send an HTTP PATCH request. ```php @@ -2005,12 +2005,12 @@ Loop::addTimer(1.0, function () use ($body) { $body->end("hello world"); }); -$browser->patch($url, array('Content-Length' => '11'), $body); +$browser->patch($url, ['Content-Length' => '11'], $body); ``` #### put() -The `put(string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +The `put(string $url, array $headers = [], string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to send an HTTP PUT request. ```php @@ -2041,12 +2041,12 @@ Loop::addTimer(1.0, function () use ($body) { $body->end("hello world"); }); -$browser->put($url, array('Content-Length' => '11'), $body); +$browser->put($url, ['Content-Length' => '11'], $body); ``` #### delete() -The `delete(string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +The `delete(string $url, array $headers = [], string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to send an HTTP DELETE request. ```php @@ -2059,7 +2059,7 @@ $browser->delete($url)->then(function (Psr\Http\Message\ResponseInterface $respo #### request() -The `request(string $method, string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +The `request(string $method, string $url, array $headers = [], string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to send an arbitrary HTTP request. The preferred way to send an HTTP request is by using the above @@ -2093,12 +2093,12 @@ Loop::addTimer(1.0, function () use ($body) { $body->end("hello world"); }); -$browser->request('POST', $url, array('Content-Length' => '11'), $body); +$browser->request('POST', $url, ['Content-Length' => '11'], $body); ``` #### requestStreaming() -The `requestStreaming(string $method, string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +The `requestStreaming(string $method, string $url, array $headers = [], string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to send an arbitrary HTTP request and receive a streaming response without buffering the response body. The preferred way to send an HTTP request is by using the above @@ -2157,7 +2157,7 @@ Loop::addTimer(1.0, function () use ($body) { $body->end("hello world"); }); -$browser->requestStreaming('POST', $url, array('Content-Length' => '11'), $body); +$browser->requestStreaming('POST', $url, ['Content-Length' => '11'], $body); ``` #### withTimeout() @@ -2428,9 +2428,9 @@ represent an outgoing server response message. ```php $response = new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Content-Type' => 'text/html' - ), + ], "Hello world!\n" ); ``` @@ -2528,10 +2528,9 @@ values in the data must be encoded in UTF-8 (Unicode). If the encoding fails, this method will throw an `InvalidArgumentException`. By default, the given structured data will be encoded with the flags as -shown above. This includes pretty printing (PHP 5.4+) and preserving -zero fractions for `float` values (PHP 5.6.6+) to ease debugging. It is -assumed any additional data overhead is usually compensated by using HTTP -response compression. +shown above. This includes pretty printing and preserving zero fractions +for `float` values to ease debugging. It is assumed any additional data +overhead is usually compensated by using HTTP response compression. If you want to use a different status code or custom HTTP response headers, you can manipulate the returned response object using the @@ -2900,9 +2899,9 @@ $handler = function (Psr\Http\Message\ServerRequestInterface $request) { return new React\Http\Message\Response( React\Http\Message\Response::STATUS_OK, - array( + [ 'Content-Type' => 'text/plain' - ), + ], $name . ' uploaded ' . $uploaded ); }; diff --git a/examples/03-client-request-any.php b/examples/03-client-request-any.php index d7558bd6..9ee80131 100644 --- a/examples/03-client-request-any.php +++ b/examples/03-client-request-any.php @@ -10,13 +10,13 @@ $client = new Browser(); -$promises = array( +$promises = [ $client->head('http://www.github.com/clue/http-react'), $client->get('https://httpbingo.org/'), $client->get('https://google.com'), $client->get('http://www.lueck.tv/psocksd'), $client->get('http://httpbingo.org/absolute-redirect/5') -); +]; React\Promise\any($promises)->then(function (ResponseInterface $response) use ($promises) { // first response arrived => cancel all other pending requests diff --git a/examples/04-client-post-json.php b/examples/04-client-post-json.php index 18fa596d..2ecc0636 100644 --- a/examples/04-client-post-json.php +++ b/examples/04-client-post-json.php @@ -7,19 +7,19 @@ $client = new Browser(); -$data = array( - 'name' => array( +$data = [ + 'name' => [ 'first' => 'Alice', 'name' => 'Smith' - ), + ], 'email' => 'alice@example.com' -); +]; $client->post( 'https://httpbingo.org/post', - array( + [ 'Content-Type' => 'application/json' - ), + ], json_encode($data) )->then(function (ResponseInterface $response) { echo (string) $response->getBody(); diff --git a/examples/05-client-put-xml.php b/examples/05-client-put-xml.php index 10ee46fc..af01c47a 100644 --- a/examples/05-client-put-xml.php +++ b/examples/05-client-put-xml.php @@ -14,9 +14,9 @@ $client->put( 'https://httpbingo.org/put', - array( + [ 'Content-Type' => 'text/xml' - ), + ], $xml->asXML() )->then(function (ResponseInterface $response) { echo (string) $response->getBody(); diff --git a/examples/11-client-http-proxy.php b/examples/11-client-http-proxy.php index ec7fc2b6..f15cf2a0 100644 --- a/examples/11-client-http-proxy.php +++ b/examples/11-client-http-proxy.php @@ -16,10 +16,10 @@ $proxy = new Clue\React\HttpProxy\ProxyConnector(getenv('http_proxy') ?: '127.0.0.1:8080'); // create a Browser object that uses the HTTP CONNECT proxy client for connections -$connector = new Connector(array( +$connector = new Connector([ 'tcp' => $proxy, 'dns' => false -)); +]); $browser = new Browser($connector); diff --git a/examples/12-client-socks-proxy.php b/examples/12-client-socks-proxy.php index 8c525509..0e0039ca 100644 --- a/examples/12-client-socks-proxy.php +++ b/examples/12-client-socks-proxy.php @@ -16,10 +16,10 @@ $proxy = new Clue\React\Socks\Client(getenv('socks_proxy') ?: '127.0.0.1:1080'); // create a Browser object that uses the SOCKS proxy client for connections -$connector = new Connector(array( +$connector = new Connector([ 'tcp' => $proxy, 'dns' => false -)); +]); $browser = new Browser($connector); diff --git a/examples/13-client-ssh-proxy.php b/examples/13-client-ssh-proxy.php index 93e6e256..e387d4fc 100644 --- a/examples/13-client-ssh-proxy.php +++ b/examples/13-client-ssh-proxy.php @@ -12,10 +12,10 @@ $proxy = new Clue\React\SshProxy\SshSocksConnector(getenv('ssh_proxy') ?: 'alice@localhost'); // create a Browser object that uses the SSH proxy client for connections -$connector = new Connector(array( +$connector = new Connector([ 'tcp' => $proxy, 'dns' => false -)); +]); $browser = new Browser($connector); diff --git a/examples/21-client-request-streaming-to-stdout.php b/examples/21-client-request-streaming-to-stdout.php index b3cbbe39..47c2371f 100644 --- a/examples/21-client-request-streaming-to-stdout.php +++ b/examples/21-client-request-streaming-to-stdout.php @@ -17,7 +17,7 @@ $out = new WritableResourceStream(STDOUT); $info = new WritableResourceStream(STDERR); -$url = isset($argv[1]) ? $argv[1] : 'http://google.com/'; +$url = $argv[1] ?? 'http://google.com/'; $info->write('Requesting ' . $url . '…' . PHP_EOL); $client->requestStreaming('GET', $url)->then(function (ResponseInterface $response) use ($info, $out) { diff --git a/examples/22-client-stream-upload-from-stdin.php b/examples/22-client-stream-upload-from-stdin.php index f0a68c5f..438b6280 100644 --- a/examples/22-client-stream-upload-from-stdin.php +++ b/examples/22-client-stream-upload-from-stdin.php @@ -15,10 +15,10 @@ $in = new ReadableResourceStream(STDIN); -$url = isset($argv[1]) ? $argv[1] : 'https://httpbingo.org/post'; +$url = $argv[1] ?? 'https://httpbingo.org/post'; echo 'Sending STDIN as POST to ' . $url . '…' . PHP_EOL; -$client->post($url, array('Content-Type' => 'text/plain'), $in)->then(function (ResponseInterface $response) { +$client->post($url, ['Content-Type' => 'text/plain'], $in)->then(function (ResponseInterface $response) { echo (string) $response->getBody(); }, function (Exception $e) { echo 'Error: ' . $e->getMessage() . PHP_EOL; diff --git a/examples/51-server-hello-world.php b/examples/51-server-hello-world.php index 9ff84eee..e25efc65 100644 --- a/examples/51-server-hello-world.php +++ b/examples/51-server-hello-world.php @@ -8,7 +8,7 @@ ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/52-server-count-visitors.php b/examples/52-server-count-visitors.php index 341f9498..333a8011 100644 --- a/examples/52-server-count-visitors.php +++ b/examples/52-server-count-visitors.php @@ -9,7 +9,7 @@ ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/53-server-whatsmyip.php b/examples/53-server-whatsmyip.php index 1e394b9e..d9018a64 100644 --- a/examples/53-server-whatsmyip.php +++ b/examples/53-server-whatsmyip.php @@ -10,7 +10,7 @@ ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/54-server-query-parameter.php b/examples/54-server-query-parameter.php index 9b2d5749..507e8862 100644 --- a/examples/54-server-query-parameter.php +++ b/examples/54-server-query-parameter.php @@ -17,7 +17,7 @@ ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/55-server-cookie-handling.php b/examples/55-server-cookie-handling.php index b5e68862..b2b62100 100644 --- a/examples/55-server-cookie-handling.php +++ b/examples/55-server-cookie-handling.php @@ -18,7 +18,7 @@ )->withHeader('Set-Cookie', $key . '=' . urlencode('Hello world!')); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/56-server-sleep.php b/examples/56-server-sleep.php index 2a3c9027..45f64149 100644 --- a/examples/56-server-sleep.php +++ b/examples/56-server-sleep.php @@ -18,7 +18,7 @@ }); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/57-server-error-handling.php b/examples/57-server-error-handling.php index a9fb6bad..c5141161 100644 --- a/examples/57-server-error-handling.php +++ b/examples/57-server-error-handling.php @@ -15,7 +15,7 @@ ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/58-server-stream-response.php b/examples/58-server-stream-response.php index 9d12461a..d99b1548 100644 --- a/examples/58-server-stream-response.php +++ b/examples/58-server-stream-response.php @@ -32,14 +32,14 @@ return new Response( Response::STATUS_OK, - array( + [ 'Content-Type' => 'text/plain' - ), + ], $stream ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/59-server-json-api.php b/examples/59-server-json-api.php index f48be7e3..7e7477c0 100644 --- a/examples/59-server-json-api.php +++ b/examples/59-server-json-api.php @@ -12,30 +12,30 @@ $http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { if ($request->getHeaderLine('Content-Type') !== 'application/json') { - return Response::json( - array('error' => 'Only supports application/json') - )->withStatus(Response::STATUS_UNSUPPORTED_MEDIA_TYPE); + return Response::json([ + 'error' => 'Only supports application/json' + ])->withStatus(Response::STATUS_UNSUPPORTED_MEDIA_TYPE); } $input = json_decode($request->getBody()->getContents()); if (json_last_error() !== JSON_ERROR_NONE) { - return Response::json( - array('error' => 'Invalid JSON data given') - )->withStatus(Response::STATUS_BAD_REQUEST); + return Response::json([ + 'error' => 'Invalid JSON data given' + ])->withStatus(Response::STATUS_BAD_REQUEST); } if (!isset($input->name) || !is_string($input->name)) { - return Response::json( - array('error' => 'JSON data does not contain a string "name" property') - )->withStatus(Response::STATUS_UNPROCESSABLE_ENTITY); + return Response::json([ + 'error' => 'JSON data does not contain a string "name" property' + ])->withStatus(Response::STATUS_UNPROCESSABLE_ENTITY); } - return Response::json( - array('message' => 'Hello ' . $input->name) - ); + return Response::json([ + 'message' => 'Hello ' . $input->name + ]); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/61-server-hello-world-https.php b/examples/61-server-hello-world-https.php index 23906430..8ce487c7 100644 --- a/examples/61-server-hello-world-https.php +++ b/examples/61-server-hello-world-https.php @@ -8,12 +8,12 @@ ); }); -$uri = 'tls://' . (isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); -$socket = new React\Socket\SocketServer($uri, array( - 'tls' => array( - 'local_cert' => isset($argv[2]) ? $argv[2] : __DIR__ . '/localhost.pem' - ) -)); +$uri = 'tls://' . ($argv[1] ?? '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($uri, [ + 'tls' => [ + 'local_cert' => $argv[2] ?? __DIR__ . '/localhost.pem' + ] +]); $http->listen($socket); $socket->on('error', function (Exception $e) { diff --git a/examples/62-server-form-upload.php b/examples/62-server-form-upload.php index 52864c82..9c5c8aa3 100644 --- a/examples/62-server-form-upload.php +++ b/examples/62-server-form-upload.php @@ -124,7 +124,7 @@ $handler ); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/63-server-streaming-request.php b/examples/63-server-streaming-request.php index fef6f008..8ed3a4e1 100644 --- a/examples/63-server-streaming-request.php +++ b/examples/63-server-streaming-request.php @@ -38,7 +38,7 @@ function (Psr\Http\Message\ServerRequestInterface $request) { echo 'Error: ' . $e->getMessage() . PHP_EOL; }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/71-server-http-proxy.php b/examples/71-server-http-proxy.php index de9fa10b..d513ede2 100644 --- a/examples/71-server-http-proxy.php +++ b/examples/71-server-http-proxy.php @@ -32,7 +32,7 @@ ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/72-server-http-connect-proxy.php b/examples/72-server-http-connect-proxy.php index 0500822a..98a21f34 100644 --- a/examples/72-server-http-connect-proxy.php +++ b/examples/72-server-http-connect-proxy.php @@ -20,10 +20,10 @@ if ($request->getMethod() !== 'CONNECT') { return new Response( Response::STATUS_METHOD_NOT_ALLOWED, - array( + [ 'Content-Type' => 'text/plain', 'Allow' => 'CONNECT' - ), + ], 'This is an HTTP CONNECT (secure HTTPS) proxy' ); } @@ -34,23 +34,23 @@ function (ConnectionInterface $remote) { // connection established => forward data return new Response( Response::STATUS_OK, - array(), + [], $remote ); }, function (Exception $e) { return new Response( Response::STATUS_BAD_GATEWAY, - array( + [ 'Content-Type' => 'text/plain' - ), + ], 'Unable to connect: ' . $e->getMessage() ); } ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/81-server-upgrade-echo.php b/examples/81-server-upgrade-echo.php index cd3dc156..fbc4d75a 100644 --- a/examples/81-server-upgrade-echo.php +++ b/examples/81-server-upgrade-echo.php @@ -31,9 +31,9 @@ if ($request->getHeaderLine('Upgrade') !== 'echo' || $request->getProtocolVersion() === '1.0') { return new Response( Response::STATUS_UPGRADE_REQUIRED, - array( + [ 'Upgrade' => 'echo' - ), + ], '"Upgrade: echo" required' ); } @@ -49,14 +49,14 @@ return new Response( Response::STATUS_SWITCHING_PROTOCOLS, - array( + [ 'Upgrade' => 'echo' - ), + ], $stream ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/82-server-upgrade-chat.php b/examples/82-server-upgrade-chat.php index bd791fb0..00788922 100644 --- a/examples/82-server-upgrade-chat.php +++ b/examples/82-server-upgrade-chat.php @@ -39,9 +39,9 @@ if ($request->getHeaderLine('Upgrade') !== 'chat' || $request->getProtocolVersion() === '1.0') { return new Response( Response::STATUS_UPGRADE_REQUIRED, - array( + [ 'Upgrade' => 'chat' - ), + ], '"Upgrade: chat" required' ); } @@ -77,14 +77,14 @@ return new Response( Response::STATUS_SWITCHING_PROTOCOLS, - array( + [ 'Upgrade' => 'chat' - ), + ], $stream ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/examples/91-client-benchmark-download.php b/examples/91-client-benchmark-download.php index 712d9f10..f74b8925 100644 --- a/examples/91-client-benchmark-download.php +++ b/examples/91-client-benchmark-download.php @@ -16,7 +16,7 @@ use React\Http\Browser; use React\Stream\ReadableStreamInterface; -$url = isset($argv[1]) ? $argv[1] : 'http://google.com/'; +$url = $argv[1] ?? 'http://google.com/'; require __DIR__ . '/../vendor/autoload.php'; diff --git a/examples/92-client-benchmark-upload.php b/examples/92-client-benchmark-upload.php index 9fa1848a..10434bfd 100644 --- a/examples/92-client-benchmark-upload.php +++ b/examples/92-client-benchmark-upload.php @@ -55,7 +55,7 @@ public function resume() $this->paused = false; while ($this->position < $this->count && !$this->paused) { ++$this->position; - $this->emit('data', array($this->chunk)); + $this->emit('data', [$this->chunk]); } // end once the last chunk has been written @@ -65,7 +65,7 @@ public function resume() } } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { return Util::pipe($this, $dest, $options); } @@ -95,8 +95,8 @@ public function getPosition() $client = new Browser(); -$url = isset($argv[1]) ? $argv[1] : 'http://httpbin.org/post'; -$n = isset($argv[2]) ? $argv[2] : 10; +$url = $argv[1] ?? 'http://httpbin.org/post'; +$n = $argv[2] ?? 10; $source = new ChunkRepeater(str_repeat('x', 1000000), $n); Loop::futureTick(function () use ($source) { $source->resume(); @@ -109,7 +109,7 @@ public function getPosition() printf("\r%d bytes in %0.3fs...", $source->getPosition(), microtime(true) - $start); }); -$client->post($url, array('Content-Length' => $n * 1000000), $source)->then(function (ResponseInterface $response) use ($source, $report, $start) { +$client->post($url, ['Content-Length' => $n * 1000000], $source)->then(function (ResponseInterface $response) use ($source, $report, $start) { $now = microtime(true); Loop::cancelTimer($report); diff --git a/examples/99-server-benchmark-download.php b/examples/99-server-benchmark-download.php index ddd4760a..ee1cfc8f 100644 --- a/examples/99-server-benchmark-download.php +++ b/examples/99-server-benchmark-download.php @@ -52,7 +52,7 @@ public function resume() $this->paused = false; while ($this->position < $this->count && !$this->paused) { ++$this->position; - $this->emit('data', array($this->chunk)); + $this->emit('data', [$this->chunk]); } // end once the last chunk has been written @@ -62,7 +62,7 @@ public function resume() } } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { return; } @@ -106,19 +106,19 @@ public function getSize() return new Response(Response::STATUS_NOT_FOUND); } - React\EventLoop\Loop::addTimer(0, array($stream, 'resume')); + React\EventLoop\Loop::addTimer(0, [$stream, 'resume']); return new Response( Response::STATUS_OK, - array( + [ 'Content-Type' => 'application/octet-data', 'Content-Length' => $stream->getSize() - ), + ], $stream ); }); -$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0'); +$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0'); $http->listen($socket); echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL; diff --git a/src/Browser.php b/src/Browser.php index a24d24e7..06e194d9 100644 --- a/src/Browser.php +++ b/src/Browser.php @@ -22,9 +22,9 @@ class Browser private $transaction; private $baseUrl; private $protocolVersion = '1.1'; - private $defaultHeaders = array( + private $defaultHeaders = [ 'User-Agent' => 'ReactPHP/1' - ); + ]; /** * The `Browser` is responsible for sending HTTP requests to your HTTP server @@ -45,16 +45,16 @@ class Browser * [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface): * * ```php - * $connector = new React\Socket\Connector(array( + * $connector = new React\Socket\Connector([ * 'dns' => '127.0.0.1', - * 'tcp' => array( + * 'tcp' => [ * 'bindto' => '192.168.10.1:0' - * ), - * 'tls' => array( + * ], + * 'tls' => [ * 'verify_peer' => false, * 'verify_peer_name' => false - * ) - * )); + * ] + * ]); * * $browser = new React\Http\Browser($connector); * ``` @@ -70,7 +70,7 @@ class Browser */ public function __construct(ConnectorInterface $connector = null, LoopInterface $loop = null) { - $loop = $loop ?: Loop::get(); + $loop = $loop ?? Loop::get(); $this->transaction = new Transaction( Sender::createFromLoop($loop, $connector), $loop @@ -94,7 +94,7 @@ public function __construct(ConnectorInterface $connector = null, LoopInterface * @param array $headers * @return PromiseInterface */ - public function get($url, array $headers = array()) + public function get($url, array $headers = []) { return $this->requestMayBeStreaming('GET', $url, $headers); } @@ -147,7 +147,7 @@ public function get($url, array $headers = array()) * $body->end("hello world"); * }); * - * $browser->post($url, array('Content-Length' => '11'), $body); + * $browser->post($url, ['Content-Length' => '11'], $body); * ``` * * @param string $url URL for the request. @@ -155,7 +155,7 @@ public function get($url, array $headers = array()) * @param string|ReadableStreamInterface $body * @return PromiseInterface */ - public function post($url, array $headers = array(), $body = '') + public function post($url, array $headers = [], $body = '') { return $this->requestMayBeStreaming('POST', $url, $headers, $body); } @@ -175,7 +175,7 @@ public function post($url, array $headers = array(), $body = '') * @param array $headers * @return PromiseInterface */ - public function head($url, array $headers = array()) + public function head($url, array $headers = []) { return $this->requestMayBeStreaming('HEAD', $url, $headers); } @@ -209,7 +209,7 @@ public function head($url, array $headers = array()) * $body->end("hello world"); * }); * - * $browser->patch($url, array('Content-Length' => '11'), $body); + * $browser->patch($url, ['Content-Length' => '11'], $body); * ``` * * @param string $url URL for the request. @@ -217,7 +217,7 @@ public function head($url, array $headers = array()) * @param string|ReadableStreamInterface $body * @return PromiseInterface */ - public function patch($url, array $headers = array(), $body = '') + public function patch($url, array $headers = [], $body = '') { return $this->requestMayBeStreaming('PATCH', $url , $headers, $body); } @@ -253,7 +253,7 @@ public function patch($url, array $headers = array(), $body = '') * $body->end("hello world"); * }); * - * $browser->put($url, array('Content-Length' => '11'), $body); + * $browser->put($url, ['Content-Length' => '11'], $body); * ``` * * @param string $url URL for the request. @@ -261,7 +261,7 @@ public function patch($url, array $headers = array(), $body = '') * @param string|ReadableStreamInterface $body * @return PromiseInterface */ - public function put($url, array $headers = array(), $body = '') + public function put($url, array $headers = [], $body = '') { return $this->requestMayBeStreaming('PUT', $url, $headers, $body); } @@ -282,7 +282,7 @@ public function put($url, array $headers = array(), $body = '') * @param string|ReadableStreamInterface $body * @return PromiseInterface */ - public function delete($url, array $headers = array(), $body = '') + public function delete($url, array $headers = [], $body = '') { return $this->requestMayBeStreaming('DELETE', $url, $headers, $body); } @@ -321,7 +321,7 @@ public function delete($url, array $headers = array(), $body = '') * $body->end("hello world"); * }); * - * $browser->request('POST', $url, array('Content-Length' => '11'), $body); + * $browser->request('POST', $url, ['Content-Length' => '11'], $body); * ``` * * @param string $method HTTP request method, e.g. GET/HEAD/POST etc. @@ -330,9 +330,9 @@ public function delete($url, array $headers = array(), $body = '') * @param string|ReadableStreamInterface $body HTTP request body contents * @return PromiseInterface */ - public function request($method, $url, array $headers = array(), $body = '') + public function request($method, $url, array $headers = [], $body = '') { - return $this->withOptions(array('streaming' => false))->requestMayBeStreaming($method, $url, $headers, $body); + return $this->withOptions(['streaming' => false])->requestMayBeStreaming($method, $url, $headers, $body); } /** @@ -394,7 +394,7 @@ public function request($method, $url, array $headers = array(), $body = '') * $body->end("hello world"); * }); * - * $browser->requestStreaming('POST', $url, array('Content-Length' => '11'), $body); + * $browser->requestStreaming('POST', $url, ['Content-Length' => '11'], $body); * ``` * * @param string $method HTTP request method, e.g. GET/HEAD/POST etc. @@ -403,9 +403,9 @@ public function request($method, $url, array $headers = array(), $body = '') * @param string|ReadableStreamInterface $body HTTP request body contents * @return PromiseInterface */ - public function requestStreaming($method, $url, $headers = array(), $body = '') + public function requestStreaming($method, $url, $headers = [], $body = '') { - return $this->withOptions(array('streaming' => true))->requestMayBeStreaming($method, $url, $headers, $body); + return $this->withOptions(['streaming' => true])->requestMayBeStreaming($method, $url, $headers, $body); } /** @@ -450,9 +450,9 @@ public function withTimeout($timeout) $timeout = 0; } - return $this->withOptions(array( + return $this->withOptions([ 'timeout' => $timeout, - )); + ]); } /** @@ -512,10 +512,10 @@ public function withTimeout($timeout) */ public function withFollowRedirects($followRedirects) { - return $this->withOptions(array( + return $this->withOptions([ 'followRedirects' => $followRedirects !== false, 'maxRedirects' => \is_bool($followRedirects) ? null : $followRedirects - )); + ]); } /** @@ -566,9 +566,9 @@ public function withFollowRedirects($followRedirects) */ public function withRejectErrorResponse($obeySuccessCode) { - return $this->withOptions(array( + return $this->withOptions([ 'obeySuccessCode' => $obeySuccessCode, - )); + ]); } /** @@ -618,7 +618,7 @@ public function withBase($baseUrl) } $browser->baseUrl = new Uri($baseUrl); - if (!\in_array($browser->baseUrl->getScheme(), array('http', 'https')) || $browser->baseUrl->getHost() === '') { + if (!\in_array($browser->baseUrl->getScheme(), ['http', 'https']) || $browser->baseUrl->getHost() === '') { throw new \InvalidArgumentException('Base URL must be absolute'); } @@ -653,7 +653,7 @@ public function withBase($baseUrl) */ public function withProtocolVersion($protocolVersion) { - if (!\in_array($protocolVersion, array('1.0', '1.1'), true)) { + if (!\in_array($protocolVersion, ['1.0', '1.1'], true)) { throw new InvalidArgumentException('Invalid HTTP protocol version, must be one of "1.1" or "1.0"'); } @@ -706,9 +706,9 @@ public function withProtocolVersion($protocolVersion) */ public function withResponseBuffer($maximumSize) { - return $this->withOptions(array( + return $this->withOptions([ 'maximumSize' => $maximumSize - )); + ]); } /** @@ -777,13 +777,13 @@ public function withoutHeader($header) * * ```php * // deprecated - * $newBrowser = $browser->withOptions(array( + * $newBrowser = $browser->withOptions([ * 'timeout' => null, // see withTimeout() instead * 'followRedirects' => true, // see withFollowRedirects() instead * 'maxRedirects' => 10, // see withFollowRedirects() instead * 'obeySuccessCode' => true, // see withRejectErrorResponse() instead * 'streaming' => false, // deprecated, see requestStreaming() instead - * )); + * ]); * ``` * * See also [timeouts](#timeouts), [redirects](#redirects) and @@ -814,7 +814,7 @@ private function withOptions(array $options) * @param string|ReadableStreamInterface $body * @return PromiseInterface */ - private function requestMayBeStreaming($method, $url, array $headers = array(), $body = '') + private function requestMayBeStreaming($method, $url, array $headers = [], $body = '') { if ($this->baseUrl !== null) { // ensure we're actually below the base URL diff --git a/src/HttpServer.php b/src/HttpServer.php index cd0874cc..24168cc5 100644 --- a/src/HttpServer.php +++ b/src/HttpServer.php @@ -27,9 +27,9 @@ * $http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { * return new React\Http\Message\Response( * React\Http\Message\Response::STATUS_OK, - * array( + * [ * 'Content-Type' => 'text/plain' - * ), + * ], * "Hello World!\n" * ); * }); @@ -222,7 +222,7 @@ public function __construct($requestHandlerOrLoop) } } - $middleware = array(); + $middleware = []; if (!$streaming) { $maxSize = $this->getMaxRequestSize(); $concurrency = $this->getConcurrentRequestsLimit(\ini_get('memory_limit'), $maxSize); @@ -253,9 +253,8 @@ public function __construct($requestHandlerOrLoop) $this->streamingServer = new StreamingServer($loop, new MiddlewareRunner($middleware)); - $that = $this; - $this->streamingServer->on('error', function ($error) use ($that) { - $that->emit('error', array($error)); + $this->streamingServer->on('error', function ($error) { + $this->emit('error', [$error]); }); } @@ -299,11 +298,11 @@ public function __construct($requestHandlerOrLoop) * ```php * $http = new React\Http\HttpServer($handler); * - * $socket = new React\Socket\SocketServer('tls://0.0.0.0:8443', array( - * 'tls' => array( + * $socket = new React\Socket\SocketServer('tls://0.0.0.0:8443', [ + * 'tls' => [ * 'local_cert' => __DIR__ . '/localhost.pem' - * ) - * )); + * ] + * ]); * $http->listen($socket); * ``` * @@ -340,7 +339,7 @@ private function getConcurrentRequestsLimit($memory_limit, $post_max_size) */ private function getMaxRequestSize($post_max_size = null) { - $maxSize = IniUtil::iniSizeToBytes($post_max_size === null ? \ini_get('post_max_size') : $post_max_size); + $maxSize = IniUtil::iniSizeToBytes($post_max_size ?? \ini_get('post_max_size')); return ($maxSize === 0 || $maxSize >= self::MAXIMUM_BUFFER_SIZE) ? self::MAXIMUM_BUFFER_SIZE : $maxSize; } diff --git a/src/Io/AbstractMessage.php b/src/Io/AbstractMessage.php index a0706bb1..232a5442 100644 --- a/src/Io/AbstractMessage.php +++ b/src/Io/AbstractMessage.php @@ -22,10 +22,10 @@ abstract class AbstractMessage implements MessageInterface const REGEX_HEADERS = '/^([^()<>@,;:\\\"\/\[\]?={}\x00-\x20\x7F]++):[\x20\x09]*+((?:[\x20\x09]*+[\x21-\x7E\x80-\xFF]++)*+)[\x20\x09]*+[\r]?+\n/m'; /** @var array */ - private $headers = array(); + private $headers = []; /** @var array */ - private $headerNamesLowerCase = array(); + private $headerNamesLowerCase = []; /** @var string */ private $protocolVersion; @@ -41,13 +41,13 @@ abstract class AbstractMessage implements MessageInterface protected function __construct($protocolVersion, array $headers, StreamInterface $body) { foreach ($headers as $name => $value) { - if ($value !== array()) { + if ($value !== []) { if (\is_array($value)) { foreach ($value as &$one) { $one = (string) $one; } } else { - $value = array((string) $value); + $value = [(string) $value]; } $lower = \strtolower($name); @@ -95,7 +95,7 @@ public function hasHeader($name) public function getHeader($name) { $lower = \strtolower($name); - return isset($this->headerNamesLowerCase[$lower]) ? $this->headers[$this->headerNamesLowerCase[$lower]] : array(); + return isset($this->headerNamesLowerCase[$lower]) ? $this->headers[$this->headerNamesLowerCase[$lower]] : []; } public function getHeaderLine($name) @@ -105,14 +105,14 @@ public function getHeaderLine($name) public function withHeader($name, $value) { - if ($value === array()) { + if ($value === []) { return $this->withoutHeader($name); } elseif (\is_array($value)) { foreach ($value as &$one) { $one = (string) $one; } } else { - $value = array((string) $value); + $value = [(string) $value]; } $lower = \strtolower($name); @@ -133,11 +133,11 @@ public function withHeader($name, $value) public function withAddedHeader($name, $value) { - if ($value === array()) { + if ($value === []) { return $this; } - return $this->withHeader($name, \array_merge($this->getHeader($name), \is_array($value) ? $value : array($value))); + return $this->withHeader($name, \array_merge($this->getHeader($name), \is_array($value) ? $value : [$value])); } public function withoutHeader($name) diff --git a/src/Io/AbstractRequest.php b/src/Io/AbstractRequest.php index f32307f7..1182f7ab 100644 --- a/src/Io/AbstractRequest.php +++ b/src/Io/AbstractRequest.php @@ -50,7 +50,7 @@ protected function __construct( $host = $uri->getHost(); if ($host !== '') { foreach ($headers as $name => $value) { - if (\strtolower($name) === 'host' && $value !== array()) { + if (\strtolower($name) === 'host' && $value !== []) { $host = ''; break; } @@ -61,7 +61,7 @@ protected function __construct( $host .= ':' . $port; } - $headers = array('Host' => $host) + $headers; + $headers = ['Host' => $host] + $headers; } } diff --git a/src/Io/BufferedBody.php b/src/Io/BufferedBody.php index 4a4d8393..9b1d9887 100644 --- a/src/Io/BufferedBody.php +++ b/src/Io/BufferedBody.php @@ -174,6 +174,6 @@ public function getContents() public function getMetadata($key = null) { - return $key === null ? array() : null; + return $key === null ? [] : null; } } diff --git a/src/Io/ChunkedDecoder.php b/src/Io/ChunkedDecoder.php index 2f58f42b..996484db 100644 --- a/src/Io/ChunkedDecoder.php +++ b/src/Io/ChunkedDecoder.php @@ -31,10 +31,10 @@ public function __construct(ReadableStreamInterface $input) { $this->input = $input; - $this->input->on('data', array($this, 'handleData')); - $this->input->on('end', array($this, 'handleEnd')); - $this->input->on('error', array($this, 'handleError')); - $this->input->on('close', array($this, 'close')); + $this->input->on('data', [$this, 'handleData']); + $this->input->on('end', [$this, 'handleEnd']); + $this->input->on('error', [$this, 'handleError']); + $this->input->on('close', [$this, 'close']); } public function isReadable() @@ -52,7 +52,7 @@ public function resume() $this->input->resume(); } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { Util::pipe($this, $dest, $options); @@ -86,7 +86,7 @@ public function handleEnd() /** @internal */ public function handleError(Exception $e) { - $this->emit('error', array($e)); + $this->emit('error', [$e]); $this->close(); } @@ -139,7 +139,7 @@ public function handleData($data) if ($chunk !== '') { $this->transferredSize += \strlen($chunk); - $this->emit('data', array($chunk)); + $this->emit('data', [$chunk]); $this->buffer = (string)\substr($this->buffer, \strlen($chunk)); } diff --git a/src/Io/ChunkedEncoder.php b/src/Io/ChunkedEncoder.php index c84ef54f..0bfe34f8 100644 --- a/src/Io/ChunkedEncoder.php +++ b/src/Io/ChunkedEncoder.php @@ -23,10 +23,10 @@ public function __construct(ReadableStreamInterface $input) { $this->input = $input; - $this->input->on('data', array($this, 'handleData')); - $this->input->on('end', array($this, 'handleEnd')); - $this->input->on('error', array($this, 'handleError')); - $this->input->on('close', array($this, 'close')); + $this->input->on('data', [$this, 'handleData']); + $this->input->on('end', [$this, 'handleEnd']); + $this->input->on('error', [$this, 'handleError']); + $this->input->on('close', [$this, 'close']); } public function isReadable() @@ -44,7 +44,7 @@ public function resume() $this->input->resume(); } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { return Util::pipe($this, $dest, $options); } @@ -66,23 +66,23 @@ public function close() public function handleData($data) { if ($data !== '') { - $this->emit('data', array( + $this->emit('data', [ \dechex(\strlen($data)) . "\r\n" . $data . "\r\n" - )); + ]); } } /** @internal */ public function handleError(\Exception $e) { - $this->emit('error', array($e)); + $this->emit('error', [$e]); $this->close(); } /** @internal */ public function handleEnd() { - $this->emit('data', array("0\r\n\r\n")); + $this->emit('data', ["0\r\n\r\n"]); if (!$this->closed) { $this->emit('end'); diff --git a/src/Io/ClientConnectionManager.php b/src/Io/ClientConnectionManager.php index faac98b6..794c0340 100644 --- a/src/Io/ClientConnectionManager.php +++ b/src/Io/ClientConnectionManager.php @@ -8,6 +8,8 @@ use React\Promise\PromiseInterface; use React\Socket\ConnectionInterface; use React\Socket\ConnectorInterface; +use function React\Promise\reject; +use function React\Promise\resolve; /** * [Internal] Manages outgoing HTTP connections for the HTTP client @@ -24,16 +26,16 @@ class ClientConnectionManager private $loop; /** @var string[] */ - private $idleUris = array(); + private $idleUris = []; /** @var ConnectionInterface[] */ - private $idleConnections = array(); + private $idleConnections = []; /** @var TimerInterface[] */ - private $idleTimers = array(); + private $idleTimers = []; /** @var \Closure[] */ - private $idleStreamHandlers = array(); + private $idleStreamHandlers = []; /** @var float */ private $maximumTimeToKeepAliveIdleConnection = 0.001; @@ -51,7 +53,7 @@ public function connect(UriInterface $uri) { $scheme = $uri->getScheme(); if ($scheme !== 'https' && $scheme !== 'http') { - return \React\Promise\reject(new \InvalidArgumentException( + return reject(new \InvalidArgumentException( 'Invalid request URL given' )); } @@ -74,7 +76,7 @@ public function connect(UriInterface $uri) $this->loop->cancelTimer($this->idleTimers[$id]); unset($this->idleUris[$id], $this->idleConnections[$id], $this->idleTimers[$id], $this->idleStreamHandlers[$id]); - return \React\Promise\resolve($connection); + return resolve($connection); } } @@ -100,10 +102,8 @@ public function keepAlive(UriInterface $uri, ConnectionInterface $connection) $this->idleUris[] = ($scheme === 'https' ? 'tls://' : '') . $uri->getHost() . ':' . $port; $this->idleConnections[] = $connection; - $that = $this; - $cleanUp = function () use ($connection, $that) { - // call public method to support legacy PHP 5.3 - $that->cleanUpConnection($connection); + $cleanUp = function () use ($connection) { + $this->cleanUpConnection($connection); }; // clean up and close connection when maximum time to keep-alive idle connection has passed @@ -116,11 +116,8 @@ public function keepAlive(UriInterface $uri, ConnectionInterface $connection) $connection->on('error', $cleanUp); } - /** - * @internal - * @return void - */ - public function cleanUpConnection(ConnectionInterface $connection) // private (PHP 5.4+) + /** @return void */ + private function cleanUpConnection(ConnectionInterface $connection) { $id = \array_search($connection, $this->idleConnections, true); if ($id === false) { diff --git a/src/Io/ClientRequestStream.php b/src/Io/ClientRequestStream.php index 3bdf9b1f..fb0cd3e5 100644 --- a/src/Io/ClientRequestStream.php +++ b/src/Io/ClientRequestStream.php @@ -74,38 +74,32 @@ private function writeHead() return; } - $connectionRef = &$this->connection; - $stateRef = &$this->state; - $pendingWrites = &$this->pendingWrites; - $that = $this; - $promise = $this->connectionManager->connect($this->request->getUri()); $promise->then( - function (ConnectionInterface $connection) use ($headers, &$connectionRef, &$stateRef, &$pendingWrites, $that) { - $connectionRef = $connection; - assert($connectionRef instanceof ConnectionInterface); + function (ConnectionInterface $connection) use ($headers) { + $this->connection = $connection; - $connection->on('drain', array($that, 'handleDrain')); - $connection->on('data', array($that, 'handleData')); - $connection->on('end', array($that, 'handleEnd')); - $connection->on('error', array($that, 'handleError')); - $connection->on('close', array($that, 'close')); + $connection->on('drain', [$this, 'handleDrain']); + $connection->on('data', [$this, 'handleData']); + $connection->on('end', [$this, 'handleEnd']); + $connection->on('error', [$this, 'handleError']); + $connection->on('close', [$this, 'close']); - $more = $connection->write($headers . "\r\n" . $pendingWrites); + $more = $connection->write($headers . "\r\n" . $this->pendingWrites); - assert($stateRef === ClientRequestStream::STATE_WRITING_HEAD); - $stateRef = ClientRequestStream::STATE_HEAD_WRITTEN; + assert($this->state === ClientRequestStream::STATE_WRITING_HEAD); + $this->state = ClientRequestStream::STATE_HEAD_WRITTEN; // clear pending writes if non-empty - if ($pendingWrites !== '') { - $pendingWrites = ''; + if ($this->pendingWrites !== '') { + $this->pendingWrites = ''; if ($more) { - $that->emit('drain'); + $this->emit('drain'); } } }, - array($this, 'closeError') + [$this, 'closeError'] ); $this->on('close', function() use ($promise) { @@ -179,29 +173,26 @@ public function handleData($data) // response headers successfully received => remove listeners for connection events $connection = $this->connection; assert($connection instanceof ConnectionInterface); - $connection->removeListener('drain', array($this, 'handleDrain')); - $connection->removeListener('data', array($this, 'handleData')); - $connection->removeListener('end', array($this, 'handleEnd')); - $connection->removeListener('error', array($this, 'handleError')); - $connection->removeListener('close', array($this, 'close')); + $connection->removeListener('drain', [$this, 'handleDrain']); + $connection->removeListener('data', [$this, 'handleData']); + $connection->removeListener('end', [$this, 'handleEnd']); + $connection->removeListener('error', [$this, 'handleError']); + $connection->removeListener('close', [$this, 'close']); $this->connection = null; $this->buffer = ''; // take control over connection handling and check if we can reuse the connection once response body closes - $that = $this; - $request = $this->request; - $connectionManager = $this->connectionManager; $successfulEndReceived = false; $input = $body = new CloseProtectionStream($connection); - $input->on('close', function () use ($connection, $that, $connectionManager, $request, $response, &$successfulEndReceived) { + $input->on('close', function () use ($connection, $response, &$successfulEndReceived) { // only reuse connection after successful response and both request and response allow keep alive - if ($successfulEndReceived && $connection->isReadable() && $that->hasMessageKeepAliveEnabled($response) && $that->hasMessageKeepAliveEnabled($request)) { - $connectionManager->keepAlive($request->getUri(), $connection); + if ($successfulEndReceived && $connection->isReadable() && $this->hasMessageKeepAliveEnabled($response) && $this->hasMessageKeepAliveEnabled($this->request)) { + $this->connectionManager->keepAlive($this->request->getUri(), $connection); } else { $connection->close(); } - $that->close(); + $this->close(); }); // determine length of response body @@ -220,7 +211,7 @@ public function handleData($data) }); // emit response with streaming response body (see `Sender`) - $this->emit('response', array($response, $body)); + $this->emit('response', [$response, $body]); // re-emit HTTP response body to trigger body parsing if parts of it are buffered if ($bodyChunk !== '') { @@ -255,7 +246,7 @@ public function closeError(\Exception $error) if (self::STATE_END <= $this->state) { return; } - $this->emit('error', array($error)); + $this->emit('error', [$error]); $this->close(); } diff --git a/src/Io/Clock.php b/src/Io/Clock.php index 92c1cb09..c2445a94 100644 --- a/src/Io/Clock.php +++ b/src/Io/Clock.php @@ -42,10 +42,9 @@ public function now() $this->now = \microtime(true); // remember clock for current loop tick only and update on next tick - $now =& $this->now; - $this->loop->futureTick(function () use (&$now) { - assert($now !== null); - $now = null; + $this->loop->futureTick(function () { + assert($this->now !== null); + $this->now = null; }); } diff --git a/src/Io/CloseProtectionStream.php b/src/Io/CloseProtectionStream.php index 2e1ed6e4..7fae08e7 100644 --- a/src/Io/CloseProtectionStream.php +++ b/src/Io/CloseProtectionStream.php @@ -28,10 +28,10 @@ public function __construct(ReadableStreamInterface $input) { $this->input = $input; - $this->input->on('data', array($this, 'handleData')); - $this->input->on('end', array($this, 'handleEnd')); - $this->input->on('error', array($this, 'handleError')); - $this->input->on('close', array($this, 'close')); + $this->input->on('data', [$this, 'handleData']); + $this->input->on('end', [$this, 'handleEnd']); + $this->input->on('error', [$this, 'handleError']); + $this->input->on('close', [$this, 'close']); } public function isReadable() @@ -59,7 +59,7 @@ public function resume() $this->input->resume(); } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { Util::pipe($this, $dest, $options); @@ -75,10 +75,10 @@ public function close() $this->closed = true; // stop listening for incoming events - $this->input->removeListener('data', array($this, 'handleData')); - $this->input->removeListener('error', array($this, 'handleError')); - $this->input->removeListener('end', array($this, 'handleEnd')); - $this->input->removeListener('close', array($this, 'close')); + $this->input->removeListener('data', [$this, 'handleData']); + $this->input->removeListener('error', [$this, 'handleError']); + $this->input->removeListener('end', [$this, 'handleEnd']); + $this->input->removeListener('close', [$this, 'close']); // resume the stream to ensure we discard everything from incoming connection if ($this->paused) { @@ -93,7 +93,7 @@ public function close() /** @internal */ public function handleData($data) { - $this->emit('data', array($data)); + $this->emit('data', [$data]); } /** @internal */ @@ -106,6 +106,6 @@ public function handleEnd() /** @internal */ public function handleError(\Exception $e) { - $this->emit('error', array($e)); + $this->emit('error', [$e]); } } diff --git a/src/Io/EmptyBodyStream.php b/src/Io/EmptyBodyStream.php index 5056219c..7f9c8ad0 100644 --- a/src/Io/EmptyBodyStream.php +++ b/src/Io/EmptyBodyStream.php @@ -44,7 +44,7 @@ public function resume() // NOOP } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { Util::pipe($this, $dest, $options); @@ -137,6 +137,6 @@ public function getContents() /** @ignore */ public function getMetadata($key = null) { - return ($key === null) ? array() : null; + return ($key === null) ? [] : null; } } diff --git a/src/Io/HttpBodyStream.php b/src/Io/HttpBodyStream.php index 25d15a18..8be9b854 100644 --- a/src/Io/HttpBodyStream.php +++ b/src/Io/HttpBodyStream.php @@ -39,10 +39,10 @@ public function __construct(ReadableStreamInterface $input, $size) $this->input = $input; $this->size = $size; - $this->input->on('data', array($this, 'handleData')); - $this->input->on('end', array($this, 'handleEnd')); - $this->input->on('error', array($this, 'handleError')); - $this->input->on('close', array($this, 'close')); + $this->input->on('data', [$this, 'handleData']); + $this->input->on('end', [$this, 'handleEnd']); + $this->input->on('error', [$this, 'handleError']); + $this->input->on('close', [$this, 'close']); } public function isReadable() @@ -60,7 +60,7 @@ public function resume() $this->input->resume(); } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { Util::pipe($this, $dest, $options); @@ -161,13 +161,13 @@ public function getMetadata($key = null) /** @internal */ public function handleData($data) { - $this->emit('data', array($data)); + $this->emit('data', [$data]); } /** @internal */ public function handleError(\Exception $e) { - $this->emit('error', array($e)); + $this->emit('error', [$e]); $this->close(); } diff --git a/src/Io/LengthLimitedStream.php b/src/Io/LengthLimitedStream.php index bc64c54b..c4a38b13 100644 --- a/src/Io/LengthLimitedStream.php +++ b/src/Io/LengthLimitedStream.php @@ -27,10 +27,10 @@ public function __construct(ReadableStreamInterface $stream, $maxLength) $this->stream = $stream; $this->maxLength = $maxLength; - $this->stream->on('data', array($this, 'handleData')); - $this->stream->on('end', array($this, 'handleEnd')); - $this->stream->on('error', array($this, 'handleError')); - $this->stream->on('close', array($this, 'close')); + $this->stream->on('data', [$this, 'handleData']); + $this->stream->on('end', [$this, 'handleEnd']); + $this->stream->on('error', [$this, 'handleError']); + $this->stream->on('close', [$this, 'close']); } public function isReadable() @@ -48,7 +48,7 @@ public function resume() $this->stream->resume(); } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { Util::pipe($this, $dest, $options); @@ -79,21 +79,21 @@ public function handleData($data) if ($data !== '') { $this->transferredLength += \strlen($data); - $this->emit('data', array($data)); + $this->emit('data', [$data]); } if ($this->transferredLength === $this->maxLength) { // 'Content-Length' reached, stream will end $this->emit('end'); $this->close(); - $this->stream->removeListener('data', array($this, 'handleData')); + $this->stream->removeListener('data', [$this, 'handleData']); } } /** @internal */ public function handleError(\Exception $e) { - $this->emit('error', array($e)); + $this->emit('error', [$e]); $this->close(); } diff --git a/src/Io/MiddlewareRunner.php b/src/Io/MiddlewareRunner.php index dedf6ff1..c05c5a1a 100644 --- a/src/Io/MiddlewareRunner.php +++ b/src/Io/MiddlewareRunner.php @@ -40,8 +40,7 @@ public function __invoke(ServerRequestInterface $request) return $this->call($request, 0); } - /** @internal */ - public function call(ServerRequestInterface $request, $position) + private function call(ServerRequestInterface $request, $position) { // final request handler will be invoked without a next handler if (!isset($this->middleware[$position + 1])) { @@ -49,9 +48,8 @@ public function call(ServerRequestInterface $request, $position) return $handler($request); } - $that = $this; - $next = function (ServerRequestInterface $request) use ($that, $position) { - return $that->call($request, $position + 1); + $next = function (ServerRequestInterface $request) use ($position) { + return $this->call($request, $position + 1); }; // invoke middleware request handler with next handler diff --git a/src/Io/MultipartParser.php b/src/Io/MultipartParser.php index c65bb655..cdfe189b 100644 --- a/src/Io/MultipartParser.php +++ b/src/Io/MultipartParser.php @@ -166,7 +166,7 @@ private function parsePart($chunk) $this->parseFile( $name, $filename, - isset($headers['content-type'][0]) ? $headers['content-type'][0] : null, + $headers['content-type'][0] ?? null, $body ); } else { @@ -268,7 +268,7 @@ private function parsePost($name, $value) private function parseHeaders($header) { - $headers = array(); + $headers = []; foreach (\explode("\r\n", \trim($header)) as $line) { $parts = \explode(':', $line, 2); @@ -315,12 +315,12 @@ private function extractPost($postFields, $key, $value) $previousChunkKey = $chunkKey; if ($previousChunkKey === '') { - $parent[] = array(); + $parent[] = []; \end($parent); $parent = &$parent[\key($parent)]; } else { if (!isset($parent[$previousChunkKey]) || !\is_array($parent[$previousChunkKey])) { - $parent[$previousChunkKey] = array(); + $parent[$previousChunkKey] = []; } $parent = &$parent[$previousChunkKey]; } diff --git a/src/Io/PauseBufferStream.php b/src/Io/PauseBufferStream.php index fb5ed456..b1132adc 100644 --- a/src/Io/PauseBufferStream.php +++ b/src/Io/PauseBufferStream.php @@ -36,10 +36,10 @@ public function __construct(ReadableStreamInterface $input) { $this->input = $input; - $this->input->on('data', array($this, 'handleData')); - $this->input->on('end', array($this, 'handleEnd')); - $this->input->on('error', array($this, 'handleError')); - $this->input->on('close', array($this, 'handleClose')); + $this->input->on('data', [$this, 'handleData']); + $this->input->on('end', [$this, 'handleEnd']); + $this->input->on('error', [$this, 'handleError']); + $this->input->on('close', [$this, 'handleClose']); } /** @@ -91,12 +91,12 @@ public function resume() $this->implicit = false; if ($this->dataPaused !== '') { - $this->emit('data', array($this->dataPaused)); + $this->emit('data', [$this->dataPaused]); $this->dataPaused = ''; } if ($this->errorPaused) { - $this->emit('error', array($this->errorPaused)); + $this->emit('error', [$this->errorPaused]); return $this->close(); } @@ -114,7 +114,7 @@ public function resume() $this->input->resume(); } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { Util::pipe($this, $dest, $options); @@ -146,7 +146,7 @@ public function handleData($data) return; } - $this->emit('data', array($data)); + $this->emit('data', [$data]); } /** @internal */ @@ -157,7 +157,7 @@ public function handleError(\Exception $e) return; } - $this->emit('error', array($e)); + $this->emit('error', [$e]); $this->close(); } diff --git a/src/Io/ReadableBodyStream.php b/src/Io/ReadableBodyStream.php index daef45f9..9a8bd105 100644 --- a/src/Io/ReadableBodyStream.php +++ b/src/Io/ReadableBodyStream.php @@ -23,22 +23,20 @@ public function __construct(ReadableStreamInterface $input, $size = null) $this->input = $input; $this->size = $size; - $that = $this; - $pos =& $this->position; - $input->on('data', function ($data) use ($that, &$pos, $size) { - $that->emit('data', array($data)); - - $pos += \strlen($data); - if ($size !== null && $pos >= $size) { - $that->handleEnd(); + $input->on('data', function ($data) use ($size) { + $this->emit('data', [$data]); + + $this->position += \strlen($data); + if ($size !== null && $this->position >= $size) { + $this->handleEnd(); } }); - $input->on('error', function ($error) use ($that) { - $that->emit('error', array($error)); - $that->close(); + $input->on('error', function ($error) { + $this->emit('error', [$error]); + $this->close(); }); - $input->on('end', array($that, 'handleEnd')); - $input->on('close', array($that, 'close')); + $input->on('end', [$this, 'handleEnd']); + $input->on('close', [$this, 'close']); } public function close() @@ -67,7 +65,7 @@ public function resume() $this->input->resume(); } - public function pipe(WritableStreamInterface $dest, array $options = array()) + public function pipe(WritableStreamInterface $dest, array $options = []) { Util::pipe($this, $dest, $options); @@ -136,14 +134,14 @@ public function getContents() public function getMetadata($key = null) { - return ($key === null) ? array() : null; + return ($key === null) ? [] : null; } /** @internal */ public function handleEnd() { if ($this->position !== $this->size && $this->size !== null) { - $this->emit('error', array(new \UnderflowException('Unexpected end of response body after ' . $this->position . '/' . $this->size . ' bytes'))); + $this->emit('error', [new \UnderflowException('Unexpected end of response body after ' . $this->position . '/' . $this->size . ' bytes')]); } else { $this->emit('end'); } diff --git a/src/Io/RequestHeaderParser.php b/src/Io/RequestHeaderParser.php index 8975ce57..403ab0cc 100644 --- a/src/Io/RequestHeaderParser.php +++ b/src/Io/RequestHeaderParser.php @@ -28,7 +28,7 @@ class RequestHeaderParser extends EventEmitter private $clock; /** @var array> */ - private $connectionParams = array(); + private $connectionParams = []; public function __construct(Clock $clock) { @@ -38,22 +38,20 @@ public function __construct(Clock $clock) public function handle(ConnectionInterface $conn) { $buffer = ''; - $maxSize = $this->maxSize; - $that = $this; - $conn->on('data', $fn = function ($data) use (&$buffer, &$fn, $conn, $maxSize, $that) { + $conn->on('data', $fn = function ($data) use (&$buffer, &$fn, $conn) { // append chunk of data to buffer and look for end of request headers $buffer .= $data; $endOfHeader = \strpos($buffer, "\r\n\r\n"); // reject request if buffer size is exceeded - if ($endOfHeader > $maxSize || ($endOfHeader === false && isset($buffer[$maxSize]))) { + if ($endOfHeader > $this->maxSize || ($endOfHeader === false && isset($buffer[$this->maxSize]))) { $conn->removeListener('data', $fn); $fn = null; - $that->emit('error', array( - new \OverflowException("Maximum header size of {$maxSize} exceeded.", Response::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE), + $this->emit('error', [ + new \OverflowException("Maximum header size of {$this->maxSize} exceeded.", Response::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE), $conn - )); + ]); return; } @@ -67,16 +65,16 @@ public function handle(ConnectionInterface $conn) $fn = null; try { - $request = $that->parseRequest( + $request = $this->parseRequest( (string)\substr($buffer, 0, $endOfHeader + 2), $conn ); } catch (Exception $exception) { $buffer = ''; - $that->emit('error', array( + $this->emit('error', [ $exception, $conn - )); + ]); return; } @@ -105,10 +103,10 @@ public function handle(ConnectionInterface $conn) $bodyBuffer = isset($buffer[$endOfHeader + 4]) ? \substr($buffer, $endOfHeader + 4) : ''; $buffer = ''; - $that->emit('headers', array($request, $conn)); + $this->emit('headers', [$request, $conn]); if ($bodyBuffer !== '') { - $conn->emit('data', array($bodyBuffer)); + $conn->emit('data', [$bodyBuffer]); } // happy path: request body is known to be empty => immediately end stream @@ -134,11 +132,11 @@ public function parseRequest($headers, ConnectionInterface $connection) $serverParams = $this->connectionParams[$cid]; } else { // assign new server params for new connection - $serverParams = array(); + $serverParams = []; // scheme is `http` unless TLS is used $localSocketUri = $connection->getLocalAddress(); - $localParts = $localSocketUri === null ? array() : \parse_url($localSocketUri); + $localParts = $localSocketUri === null ? [] : \parse_url($localSocketUri); if (isset($localParts['scheme']) && $localParts['scheme'] === 'tls') { $serverParams['HTTPS'] = 'on'; } @@ -162,10 +160,9 @@ public function parseRequest($headers, ConnectionInterface $connection) // remember server params for all requests from this connection, reset on connection close $this->connectionParams[$cid] = $serverParams; - $params =& $this->connectionParams; - $connection->on('close', function () use (&$params, $cid) { - assert(\is_array($params)); - unset($params[$cid]); + $connection->on('close', function () use ($cid) { + assert(\is_array($this->connectionParams[$cid])); + unset($this->connectionParams[$cid]); }); } diff --git a/src/Io/Sender.php b/src/Io/Sender.php index 1d563891..8ece2ee0 100644 --- a/src/Io/Sender.php +++ b/src/Io/Sender.php @@ -40,7 +40,7 @@ class Sender * settings. You can use this method manually like this: * * ```php - * $connector = new \React\Socket\Connector(array(), $loop); + * $connector = new \React\Socket\Connector([], $loop); * $sender = \React\Http\Io\Sender::createFromLoop($loop, $connector); * ``` * @@ -51,7 +51,7 @@ class Sender public static function createFromLoop(LoopInterface $loop, ConnectorInterface $connector = null) { if ($connector === null) { - $connector = new Connector(array(), $loop); + $connector = new Connector([], $loop); } return new self(new HttpClient(new ClientConnectionManager($connector, $loop))); @@ -79,7 +79,7 @@ public function __construct(HttpClient $http) public function send(RequestInterface $request) { // support HTTP/1.1 and HTTP/1.0 only, ensured by `Browser` already - assert(\in_array($request->getProtocolVersion(), array('1.0', '1.1'), true)); + assert(\in_array($request->getProtocolVersion(), ['1.0', '1.1'], true)); $body = $request->getBody(); $size = $body->getSize(); @@ -87,7 +87,7 @@ public function send(RequestInterface $request) if ($size !== null && $size !== 0) { // automatically assign a "Content-Length" request header if the body size is known and non-empty $request = $request->withHeader('Content-Length', (string)$size); - } elseif ($size === 0 && \in_array($request->getMethod(), array('POST', 'PUT', 'PATCH'))) { + } elseif ($size === 0 && \in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'])) { // only assign a "Content-Length: 0" request header if the body is expected for certain methods $request = $request->withHeader('Content-Length', '0'); } elseif ($body instanceof ReadableStreamInterface && $size !== 0 && $body->isReadable() && !$request->hasHeader('Content-Length')) { diff --git a/src/Io/StreamingServer.php b/src/Io/StreamingServer.php index eee9f900..6d12d359 100644 --- a/src/Io/StreamingServer.php +++ b/src/Io/StreamingServer.php @@ -8,12 +8,13 @@ use React\EventLoop\LoopInterface; use React\Http\Message\Response; use React\Http\Message\ServerRequest; -use React\Promise; use React\Promise\PromiseInterface; use React\Socket\ConnectionInterface; use React\Socket\ServerInterface; use React\Stream\ReadableStreamInterface; use React\Stream\WritableStreamInterface; +use function React\Promise\reject; +use function React\Promise\resolve; /** * The internal `StreamingServer` class is responsible for handling incoming connections and then @@ -31,9 +32,9 @@ * $server = new StreamingServer($loop, function (ServerRequestInterface $request) { * return new Response( * Response::STATUS_OK, - * array( + * [ * 'Content-Type' => 'text/plain' - * ), + * ], * "Hello World!\n" * ); * }); @@ -55,7 +56,7 @@ * ```php * $server = new StreamingServer($loop, $handler); * - * $socket = new React\Socket\SocketServer('0.0.0.0:8080', array(), $loop); + * $socket = new React\Socket\SocketServer('0.0.0.0:8080', [], $loop); * $server->listen($socket); * ``` * @@ -109,16 +110,15 @@ public function __construct(LoopInterface $loop, $requestHandler) $this->clock = new Clock($loop); $this->parser = new RequestHeaderParser($this->clock); - $that = $this; - $this->parser->on('headers', function (ServerRequestInterface $request, ConnectionInterface $conn) use ($that) { - $that->handleRequest($conn, $request); + $this->parser->on('headers', function (ServerRequestInterface $request, ConnectionInterface $conn) { + $this->handleRequest($conn, $request); }); - $this->parser->on('error', function(\Exception $e, ConnectionInterface $conn) use ($that) { - $that->emit('error', array($e)); + $this->parser->on('error', function(\Exception $e, ConnectionInterface $conn) { + $this->emit('error', [$e]); // parsing failed => assume dummy request and send appropriate error - $that->writeError( + $this->writeError( $conn, $e->getCode() !== 0 ? $e->getCode() : Response::STATUS_BAD_REQUEST, new ServerRequest('GET', '/') @@ -134,7 +134,7 @@ public function __construct(LoopInterface $loop, $requestHandler) */ public function listen(ServerInterface $socket) { - $socket->on('connection', array($this->parser, 'handle')); + $socket->on('connection', [$this->parser, 'handle']); } /** @internal */ @@ -145,15 +145,11 @@ public function handleRequest(ConnectionInterface $conn, ServerRequestInterface } // execute request handler callback - $callback = $this->callback; try { - $response = $callback($request); - } catch (\Exception $error) { + $response = ($this->callback)($request); + } catch (\Throwable $error) { // request handler callback throws an Exception - $response = Promise\reject($error); - } catch (\Throwable $error) { // @codeCoverageIgnoreStart - // request handler callback throws a PHP7+ Error - $response = Promise\reject($error); // @codeCoverageIgnoreEnd + $response = reject($error); } // cancel pending promise once connection closes @@ -177,23 +173,22 @@ public function handleRequest(ConnectionInterface $conn, ServerRequestInterface // did not return a promise? this is an error, convert into one for rejection below. if (!$response instanceof PromiseInterface) { - $response = Promise\resolve($response); + $response = resolve($response); } - $that = $this; $response->then( - function ($response) use ($that, $conn, $request) { + function ($response) use ($conn, $request) { if (!$response instanceof ResponseInterface) { $message = 'The response callback is expected to resolve with an object implementing Psr\Http\Message\ResponseInterface, but resolved with "%s" instead.'; $message = \sprintf($message, \is_object($response) ? \get_class($response) : \gettype($response)); $exception = new \RuntimeException($message); - $that->emit('error', array($exception)); - return $that->writeError($conn, Response::STATUS_INTERNAL_SERVER_ERROR, $request); + $this->emit('error', [$exception]); + return $this->writeError($conn, Response::STATUS_INTERNAL_SERVER_ERROR, $request); } - $that->handleResponse($conn, $request, $response); + $this->handleResponse($conn, $request, $response); }, - function ($error) use ($that, $conn, $request) { + function ($error) use ($conn, $request) { $message = 'The response callback is expected to resolve with an object implementing Psr\Http\Message\ResponseInterface, but rejected with "%s" instead.'; $message = \sprintf($message, \is_object($error) ? \get_class($error) : \gettype($error)); @@ -205,8 +200,8 @@ function ($error) use ($that, $conn, $request) { $exception = new \RuntimeException($message, 0, $previous); - $that->emit('error', array($exception)); - return $that->writeError($conn, Response::STATUS_INTERNAL_SERVER_ERROR, $request); + $this->emit('error', [$exception]); + return $this->writeError($conn, Response::STATUS_INTERNAL_SERVER_ERROR, $request); } )->then($connectionOnCloseResponseCancelerHandler, $connectionOnCloseResponseCancelerHandler); } @@ -216,10 +211,10 @@ public function writeError(ConnectionInterface $conn, $code, ServerRequestInterf { $response = new Response( $code, - array( + [ 'Content-Type' => 'text/plain', 'Connection' => 'close' // we do not want to keep the connection open after an error - ), + ], 'Error ' . $code ); @@ -347,7 +342,7 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt } if ($code < 100 || $code > 999 || \substr_count($headers, "\n") !== ($expected + 1) || \preg_match_all(AbstractMessage::REGEX_HEADERS, $headers) !== $expected) { - $this->emit('error', array(new \InvalidArgumentException('Unable to send response with invalid response headers'))); + $this->emit('error', [new \InvalidArgumentException('Unable to send response with invalid response headers')]); $this->writeError($connection, Response::STATUS_INTERNAL_SERVER_ERROR, $request); return; } @@ -387,15 +382,14 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt // Close response stream once connection closes. // Note that this TCP/IP close detection may take some time, // in particular this may only fire on a later read/write attempt. - $connection->on('close', array($body, 'close')); + $connection->on('close', [$body, 'close']); // write streaming body and then wait for next request over persistent connection if ($persist) { - $body->pipe($connection, array('end' => false)); - $parser = $this->parser; - $body->on('end', function () use ($connection, $parser, $body) { - $connection->removeListener('close', array($body, 'close')); - $parser->handle($connection); + $body->pipe($connection, ['end' => false]); + $body->on('end', function () use ($connection, $body) { + $connection->removeListener('close', [$body, 'close']); + $this->parser->handle($connection); }); } else { $body->pipe($connection); diff --git a/src/Io/Transaction.php b/src/Io/Transaction.php index 64738f56..6790cb45 100644 --- a/src/Io/Transaction.php +++ b/src/Io/Transaction.php @@ -13,6 +13,8 @@ use React\Promise\Promise; use React\Promise\PromiseInterface; use React\Stream\ReadableStreamInterface; +use function React\Promise\reject; +use function React\Promise\resolve; /** * @internal @@ -77,21 +79,20 @@ public function send(RequestInterface $request) }); // use timeout from options or default to PHP's default_socket_timeout (60) - $timeout = (float)($this->timeout !== null ? $this->timeout : ini_get("default_socket_timeout")); + $timeout = (float) ($this->timeout ?? ini_get("default_socket_timeout")); - $loop = $this->loop; $this->next($request, $deferred, $state)->then( - function (ResponseInterface $response) use ($state, $deferred, $loop, &$timeout) { + function (ResponseInterface $response) use ($state, $deferred, &$timeout) { if ($state->timeout !== null) { - $loop->cancelTimer($state->timeout); + $this->loop->cancelTimer($state->timeout); $state->timeout = null; } $timeout = -1; $deferred->resolve($response); }, - function ($e) use ($state, $deferred, $loop, &$timeout) { + function ($e) use ($state, $deferred, &$timeout) { if ($state->timeout !== null) { - $loop->cancelTimer($state->timeout); + $this->loop->cancelTimer($state->timeout); $state->timeout = null; } $timeout = -1; @@ -105,10 +106,9 @@ function ($e) use ($state, $deferred, $loop, &$timeout) { $body = $request->getBody(); if ($body instanceof ReadableStreamInterface && $body->isReadable()) { - $that = $this; - $body->on('close', function () use ($that, $deferred, $state, &$timeout) { + $body->on('close', function () use ($deferred, $state, &$timeout) { if ($timeout >= 0) { - $that->applyTimeout($deferred, $state, $timeout); + $this->applyTimeout($deferred, $state, $timeout); } }); } else { @@ -138,24 +138,23 @@ public function applyTimeout(Deferred $deferred, ClientRequestState $state, $tim private function next(RequestInterface $request, Deferred $deferred, ClientRequestState $state) { - $this->progress('request', array($request)); + $this->progress('request', [$request]); - $that = $this; ++$state->numRequests; $promise = $this->sender->send($request); if (!$this->streaming) { - $promise = $promise->then(function ($response) use ($deferred, $state, $that) { - return $that->bufferResponse($response, $deferred, $state); + $promise = $promise->then(function ($response) use ($deferred, $state) { + return $this->bufferResponse($response, $deferred, $state); }); } $state->pending = $promise; return $promise->then( - function (ResponseInterface $response) use ($request, $that, $deferred, $state) { - return $that->onResponse($response, $request, $deferred, $state); + function (ResponseInterface $response) use ($request, $deferred, $state) { + return $this->onResponse($response, $request, $deferred, $state); } ); } @@ -171,7 +170,7 @@ public function bufferResponse(ResponseInterface $response, Deferred $deferred, if ($size !== null && $size > $this->maximumSize) { $body->close(); - return \React\Promise\reject(new \OverflowException( + return reject(new \OverflowException( 'Response body size of ' . $size . ' bytes exceeds maximum of ' . $this->maximumSize . ' bytes', \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90 )); @@ -179,33 +178,32 @@ public function bufferResponse(ResponseInterface $response, Deferred $deferred, // body is not streaming => already buffered if (!$body instanceof ReadableStreamInterface) { - return \React\Promise\resolve($response); + return resolve($response); } /** @var ?\Closure $closer */ $closer = null; - $maximumSize = $this->maximumSize; - return $state->pending = new Promise(function ($resolve, $reject) use ($body, $maximumSize, $response, &$closer) { + return $state->pending = new Promise(function ($resolve, $reject) use ($body, $response, &$closer) { // resolve with current buffer when stream closes successfully $buffer = ''; - $body->on('close', $closer = function () use (&$buffer, $response, $maximumSize, $resolve, $reject) { + $body->on('close', $closer = function () use (&$buffer, $response, $resolve, $reject) { $resolve($response->withBody(new BufferedBody($buffer))); }); // buffer response body data in memory - $body->on('data', function ($data) use (&$buffer, $maximumSize, $body, $closer, $reject) { + $body->on('data', function ($data) use (&$buffer, $body, $closer, $reject) { $buffer .= $data; // close stream and reject promise if limit is exceeded - if (isset($buffer[$maximumSize])) { + if (isset($buffer[$this->maximumSize])) { $buffer = ''; assert($closer instanceof \Closure); $body->removeListener('close', $closer); $body->close(); $reject(new \OverflowException( - 'Response body size exceeds maximum of ' . $maximumSize . ' bytes', + 'Response body size exceeds maximum of ' . $this->maximumSize . ' bytes', \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90 )); } @@ -236,7 +234,7 @@ public function bufferResponse(ResponseInterface $response, Deferred $deferred, */ public function onResponse(ResponseInterface $response, RequestInterface $request, Deferred $deferred, ClientRequestState $state) { - $this->progress('response', array($response, $request)); + $this->progress('response', [$response, $request]); // follow 3xx (Redirection) response status codes if Location header is present and not explicitly disabled // @link https://tools.ietf.org/html/rfc7231#section-6.4 @@ -267,7 +265,7 @@ private function onResponseRedirect(ResponseInterface $response, RequestInterfac $location = Uri::resolve($request->getUri(), new Uri($response->getHeaderLine('Location'))); $request = $this->makeRedirectRequest($request, $location, $response->getStatusCode()); - $this->progress('redirect', array($request)); + $this->progress('redirect', [$request]); if ($state->numRequests >= $this->maxRedirects) { throw new \RuntimeException('Maximum number of redirects (' . $this->maxRedirects . ') exceeded'); @@ -308,7 +306,7 @@ private function makeRedirectRequest(RequestInterface $request, UriInterface $lo return $request; } - private function progress($name, array $args = array()) + private function progress($name, array $args = []) { return; diff --git a/src/Io/UploadedFile.php b/src/Io/UploadedFile.php index f2a6c9e7..b0d0dd98 100644 --- a/src/Io/UploadedFile.php +++ b/src/Io/UploadedFile.php @@ -57,7 +57,7 @@ public function __construct(StreamInterface $stream, $size, $error, $filename, $ $this->stream = $stream; $this->size = $size; - if (!\is_int($error) || !\in_array($error, array( + if (!\is_int($error) || !\in_array($error, [ \UPLOAD_ERR_OK, \UPLOAD_ERR_INI_SIZE, \UPLOAD_ERR_FORM_SIZE, @@ -66,7 +66,7 @@ public function __construct(StreamInterface $stream, $size, $error, $filename, $ \UPLOAD_ERR_NO_TMP_DIR, \UPLOAD_ERR_CANT_WRITE, \UPLOAD_ERR_EXTENSION, - ))) { + ])) { throw new InvalidArgumentException( 'Invalid error code, must be an UPLOAD_ERR_* constant' ); diff --git a/src/Message/Request.php b/src/Message/Request.php index 3de8c1b3..fdba39f5 100644 --- a/src/Message/Request.php +++ b/src/Message/Request.php @@ -40,7 +40,7 @@ final class Request extends AbstractRequest implements RequestInterface public function __construct( $method, $url, - array $headers = array(), + array $headers = [], $body = '', $version = '1.1' ) { diff --git a/src/Message/Response.php b/src/Message/Response.php index 107508a9..93557fab 100644 --- a/src/Message/Response.php +++ b/src/Message/Response.php @@ -16,9 +16,9 @@ * ```php * $response = new React\Http\Message\Response( * React\Http\Message\Response::STATUS_OK, - * array( + * [ * 'Content-Type' => 'text/html' - * ), + * ], * "Hello world!\n" * ); * ``` @@ -90,7 +90,7 @@ final class Response extends AbstractMessage implements ResponseInterface, Statu */ public static function html($html) { - return new self(self::STATUS_OK, array('Content-Type' => 'text/html; charset=utf-8'), $html); + return new self(self::STATUS_OK, ['Content-Type' => 'text/html; charset=utf-8'], $html); } /** @@ -124,10 +124,9 @@ public static function html($html) * fails, this method will throw an `InvalidArgumentException`. * * By default, the given structured data will be encoded with the flags as - * shown above. This includes pretty printing (PHP 5.4+) and preserving - * zero fractions for `float` values (PHP 5.6.6+) to ease debugging. It is - * assumed any additional data overhead is usually compensated by using HTTP - * response compression. + * shown above. This includes pretty printing and preserving zero fractions + * for `float` values to ease debugging. It is assumed any additional data + * overhead is usually compensated by using HTTP response compression. * * If you want to use a different status code or custom HTTP response * headers, you can manipulate the returned response object using the @@ -146,19 +145,19 @@ public static function html($html) */ public static function json($data) { - $json = @\json_encode( + $json = \json_encode( $data, - (\defined('JSON_PRETTY_PRINT') ? \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE : 0) | (\defined('JSON_PRESERVE_ZERO_FRACTION') ? \JSON_PRESERVE_ZERO_FRACTION : 0) + \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION ); if ($json === false) { throw new \InvalidArgumentException( - 'Unable to encode given data as JSON' . (\function_exists('json_last_error_msg') ? ': ' . \json_last_error_msg() : ''), + 'Unable to encode given data as JSON: ' . \json_last_error_msg(), \json_last_error() ); } - return new self(self::STATUS_OK, array('Content-Type' => 'application/json'), $json . "\n"); + return new self(self::STATUS_OK, ['Content-Type' => 'application/json'], $json . "\n"); } /** @@ -201,7 +200,7 @@ public static function json($data) */ public static function plaintext($text) { - return new self(self::STATUS_OK, array('Content-Type' => 'text/plain; charset=utf-8'), $text); + return new self(self::STATUS_OK, ['Content-Type' => 'text/plain; charset=utf-8'], $text); } /** @@ -253,7 +252,7 @@ public static function plaintext($text) */ public static function xml($xml) { - return new self(self::STATUS_OK, array('Content-Type' => 'application/xml'), $xml); + return new self(self::STATUS_OK, ['Content-Type' => 'application/xml'], $xml); } /** @@ -275,7 +274,7 @@ public static function xml($xml) * @see self::STATUS_* * @see self::getReasonPhraseForStatusCode() */ - private static $phrasesMap = array( + private static $phrasesMap = [ 200 => 'OK', 203 => 'Non-Authoritative Information', 207 => 'Multi-Status', @@ -283,7 +282,7 @@ public static function xml($xml) 414 => 'URI Too Large', 418 => 'I\'m a teapot', 505 => 'HTTP Version Not Supported' - ); + ]; /** @var int */ private $statusCode; @@ -301,7 +300,7 @@ public static function xml($xml) */ public function __construct( $status = self::STATUS_OK, - array $headers = array(), + array $headers = [], $body = '', $version = '1.1', $reason = null @@ -366,7 +365,7 @@ private static function getReasonPhraseForStatusCode($code) } } - return isset(self::$phrasesMap[$code]) ? self::$phrasesMap[$code] : ''; + return self::$phrasesMap[$code] ?? ''; } /** @@ -379,7 +378,7 @@ private static function getReasonPhraseForStatusCode($code) */ public static function parseMessage($message) { - $start = array(); + $start = []; if (!\preg_match('#^HTTP/(?\d\.\d) (?\d{3})(?: (?[^\r\n]*+))?[\r]?+\n#m', $message, $start)) { throw new \InvalidArgumentException('Unable to parse invalid status-line'); } @@ -390,14 +389,14 @@ public static function parseMessage($message) } // check number of valid header fields matches number of lines + status line - $matches = array(); + $matches = []; $n = \preg_match_all(self::REGEX_HEADERS, $message, $matches, \PREG_SET_ORDER); if (\substr_count($message, "\n") !== $n + 1) { throw new \InvalidArgumentException('Unable to parse invalid response header fields'); } // format all header fields into associative array - $headers = array(); + $headers = []; foreach ($matches as $match) { $headers[$match[1]][] = $match[2]; } @@ -407,7 +406,7 @@ public static function parseMessage($message) $headers, '', $start['version'], - isset($start['reason']) ? $start['reason'] : '' + $start['reason'] ?? '' ); } } diff --git a/src/Message/ServerRequest.php b/src/Message/ServerRequest.php index 32a0f62f..da0d76ab 100644 --- a/src/Message/ServerRequest.php +++ b/src/Message/ServerRequest.php @@ -31,12 +31,12 @@ */ final class ServerRequest extends AbstractRequest implements ServerRequestInterface { - private $attributes = array(); + private $attributes = []; private $serverParams; - private $fileParams = array(); - private $cookies = array(); - private $queryParams = array(); + private $fileParams = []; + private $cookies = []; + private $queryParams = []; private $parsedBody; /** @@ -51,10 +51,10 @@ final class ServerRequest extends AbstractRequest implements ServerRequestInterf public function __construct( $method, $url, - array $headers = array(), + array $headers = [], $body = '', $version = '1.1', - $serverParams = array() + $serverParams = [] ) { if (\is_string($body)) { $body = new BufferedBody($body); @@ -174,7 +174,7 @@ public function withoutAttribute($name) private function parseCookie($cookie) { $cookieArray = \explode(';', $cookie); - $result = array(); + $result = []; foreach ($cookieArray as $pair) { $pair = \trim($pair); @@ -202,7 +202,7 @@ private function parseCookie($cookie) public static function parseMessage($message, array $serverParams) { // parse request line like "GET /path HTTP/1.1" - $start = array(); + $start = []; if (!\preg_match('#^(?[^ ]+) (?[^ ]+) HTTP/(?\d\.\d)#m', $message, $start)) { throw new \InvalidArgumentException('Unable to parse invalid request-line'); } @@ -213,7 +213,7 @@ public static function parseMessage($message, array $serverParams) } // check number of valid header fields matches number of lines + request line - $matches = array(); + $matches = []; $n = \preg_match_all(self::REGEX_HEADERS, $message, $matches, \PREG_SET_ORDER); if (\substr_count($message, "\n") !== $n + 1) { throw new \InvalidArgumentException('Unable to parse invalid request header fields'); @@ -221,7 +221,7 @@ public static function parseMessage($message, array $serverParams) // format all header fields into associative array $host = null; - $headers = array(); + $headers = []; foreach ($matches as $match) { $headers[$match[1]][] = $match[2]; diff --git a/src/Message/Uri.php b/src/Message/Uri.php index 6b77d3e7..84fc38d8 100644 --- a/src/Message/Uri.php +++ b/src/Message/Uri.php @@ -54,8 +54,8 @@ public function __construct($uri) $this->scheme = \strtolower($parts['scheme']); } - if (isset($parts['user']) || isset($parts['pass'])) { - $this->userInfo = $this->encode(isset($parts['user']) ? $parts['user'] : '', \PHP_URL_USER) . (isset($parts['pass']) ? ':' . $this->encode($parts['pass'], \PHP_URL_PASS) : ''); + if (isset($parts['user'])) { + $this->userInfo = $this->encode($parts['user'], \PHP_URL_USER) . (isset($parts['pass']) ? ':' . $this->encode($parts['pass'], \PHP_URL_PASS) : ''); } if (isset($parts['host'])) { @@ -301,7 +301,7 @@ public static function resolve(UriInterface $base, UriInterface $rel) if ($rel->getAuthority() !== '') { $reset = true; $userInfo = \explode(':', $rel->getUserInfo(), 2); - $new = $base->withUserInfo($userInfo[0], isset($userInfo[1]) ? $userInfo[1]: null)->withHost($rel->getHost())->withPort($rel->getPort()); + $new = $base->withUserInfo($userInfo[0], $userInfo[1] ?? null)->withHost($rel->getHost())->withPort($rel->getPort()); } if ($reset && $rel->getPath() === '') { @@ -334,7 +334,7 @@ public static function resolve(UriInterface $base, UriInterface $rel) */ private static function removeDotSegments($path) { - $segments = array(); + $segments = []; foreach (\explode('/', $path) as $segment) { if ($segment === '..') { \array_pop($segments); diff --git a/src/Middleware/LimitConcurrentRequestsMiddleware.php b/src/Middleware/LimitConcurrentRequestsMiddleware.php index b1c00da0..41477f91 100644 --- a/src/Middleware/LimitConcurrentRequestsMiddleware.php +++ b/src/Middleware/LimitConcurrentRequestsMiddleware.php @@ -6,10 +6,11 @@ use Psr\Http\Message\ServerRequestInterface; use React\Http\Io\HttpBodyStream; use React\Http\Io\PauseBufferStream; -use React\Promise; use React\Promise\PromiseInterface; use React\Promise\Deferred; use React\Stream\ReadableStreamInterface; +use function React\Promise\reject; +use function React\Promise\resolve; /** * Limits how many next handlers can be executed concurrently. @@ -71,7 +72,7 @@ final class LimitConcurrentRequestsMiddleware { private $limit; private $pending = 0; - private $queue = array(); + private $queue = []; /** * @param int $limit Maximum amount of concurrent requests handled. @@ -92,13 +93,9 @@ public function __invoke(ServerRequestInterface $request, $next) try { $response = $next($request); - } catch (\Exception $e) { + } catch (\Throwable $e) { $this->processQueue(); throw $e; - } catch (\Throwable $e) { // @codeCoverageIgnoreStart - // handle Errors just like Exceptions (PHP 7+ only) - $this->processQueue(); - throw $e; // @codeCoverageIgnoreEnd } // happy path: if next request handler returned immediately, @@ -110,7 +107,7 @@ public function __invoke(ServerRequestInterface $request, $next) // if the next handler returns a pending promise, we have to // await its resolution before invoking next queued request - return $this->await(Promise\resolve($response)); + return $this->await(resolve($response)); } // if we reach this point, then this request will need to be queued @@ -130,36 +127,29 @@ public function __invoke(ServerRequestInterface $request, $next) } // get next queue position - $queue =& $this->queue; - $queue[] = null; - \end($queue); - $id = \key($queue); + $this->queue[] = null; + \end($this->queue); + $id = \key($this->queue); - $deferred = new Deferred(function ($_, $reject) use (&$queue, $id) { + $deferred = new Deferred(function ($_, $reject) use ($id) { // queued promise cancelled before its next handler is invoked // remove from queue and reject explicitly - unset($queue[$id]); + unset($this->queue[$id]); $reject(new \RuntimeException('Cancelled queued next handler')); }); // queue request and process queue if pending does not exceed limit - $queue[$id] = $deferred; + $this->queue[$id] = $deferred; - $pending = &$this->pending; - $that = $this; - return $deferred->promise()->then(function () use ($request, $next, $body, &$pending, $that) { + return $deferred->promise()->then(function () use ($request, $next, $body) { // invoke next request handler - ++$pending; + ++$this->pending; try { $response = $next($request); - } catch (\Exception $e) { - $that->processQueue(); + } catch (\Throwable $e) { + $this->processQueue(); throw $e; - } catch (\Throwable $e) { // @codeCoverageIgnoreStart - // handle Errors just like Exceptions (PHP 7+ only) - $that->processQueue(); - throw $e; // @codeCoverageIgnoreEnd } // resume readable stream and replay buffered events @@ -169,27 +159,24 @@ public function __invoke(ServerRequestInterface $request, $next) // if the next handler returns a pending promise, we have to // await its resolution before invoking next queued request - return $that->await(Promise\resolve($response)); + return $this->await(resolve($response)); }); } /** - * @internal * @param PromiseInterface $promise * @return PromiseInterface */ - public function await(PromiseInterface $promise) + private function await(PromiseInterface $promise) { - $that = $this; - - return $promise->then(function ($response) use ($that) { - $that->processQueue(); + return $promise->then(function ($response) { + $this->processQueue(); return $response; - }, function ($error) use ($that) { - $that->processQueue(); + }, function ($error) { + $this->processQueue(); - return Promise\reject($error); + return reject($error); }); } diff --git a/src/Middleware/RequestBodyBufferMiddleware.php b/src/Middleware/RequestBodyBufferMiddleware.php index ddb39f5e..ea889bd3 100644 --- a/src/Middleware/RequestBodyBufferMiddleware.php +++ b/src/Middleware/RequestBodyBufferMiddleware.php @@ -76,11 +76,8 @@ public function __invoke(ServerRequestInterface $request, $next) try { // resolve with result of next handler $resolve($next($request->withBody(new BufferedBody($buffer)))); - } catch (\Exception $e) { + } catch (\Throwable $e) { $reject($e); - } catch (\Throwable $e) { // @codeCoverageIgnoreStart - // reject Errors just like Exceptions (PHP 7+) - $reject($e); // @codeCoverageIgnoreEnd } }); diff --git a/src/Middleware/RequestBodyParserMiddleware.php b/src/Middleware/RequestBodyParserMiddleware.php index be5ba16f..63013337 100644 --- a/src/Middleware/RequestBodyParserMiddleware.php +++ b/src/Middleware/RequestBodyParserMiddleware.php @@ -21,7 +21,7 @@ public function __construct($uploadMaxFilesize = null, $maxFileUploads = null) public function __invoke(ServerRequestInterface $request, $next) { $type = \strtolower($request->getHeaderLine('Content-Type')); - list ($type) = \explode(';', $type); + [$type] = \explode(';', $type); if ($type === 'application/x-www-form-urlencoded') { return $next($this->parseFormUrlencoded($request)); @@ -38,7 +38,7 @@ private function parseFormUrlencoded(ServerRequestInterface $request) { // parse string into array structure // ignore warnings due to excessive data structures (max_input_vars and max_input_nesting_level) - $ret = array(); + $ret = []; @\parse_str((string)$request->getBody(), $ret); return $request->withParsedBody($ret); diff --git a/tests/BrowserTest.php b/tests/BrowserTest.php index fb1a1beb..a7188b2c 100644 --- a/tests/BrowserTest.php +++ b/tests/BrowserTest.php @@ -87,9 +87,8 @@ public function testConstructWithLoopAssignsGivenLoop() public function testGetSendsGetRequest() { - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('GET', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('GET', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -98,9 +97,8 @@ public function testGetSendsGetRequest() public function testPostSendsPostRequest() { - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('POST', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('POST', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -109,9 +107,8 @@ public function testPostSendsPostRequest() public function testHeadSendsHeadRequest() { - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('HEAD', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('HEAD', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -120,9 +117,8 @@ public function testHeadSendsHeadRequest() public function testPatchSendsPatchRequest() { - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('PATCH', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('PATCH', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -131,9 +127,8 @@ public function testPatchSendsPatchRequest() public function testPutSendsPutRequest() { - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('PUT', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('PUT', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -142,9 +137,8 @@ public function testPutSendsPutRequest() public function testDeleteSendsDeleteRequest() { - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('DELETE', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('DELETE', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -153,11 +147,10 @@ public function testDeleteSendsDeleteRequest() public function testRequestOptionsSendsPutRequestWithStreamingExplicitlyDisabled() { - $this->sender->expects($this->once())->method('withOptions')->with(array('streaming' => false))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['streaming' => false])->willReturnSelf(); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('OPTIONS', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('OPTIONS', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -166,11 +159,10 @@ public function testRequestOptionsSendsPutRequestWithStreamingExplicitlyDisabled public function testRequestStreamingGetSendsGetRequestWithStreamingExplicitlyEnabled() { - $this->sender->expects($this->once())->method('withOptions')->with(array('streaming' => true))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['streaming' => true])->willReturnSelf(); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('GET', $request->getMethod()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('GET', $request->getMethod()); return true; }))->willReturn(new Promise(function () { })); @@ -179,77 +171,77 @@ public function testRequestStreamingGetSendsGetRequestWithStreamingExplicitlyEna public function testWithTimeoutTrueSetsDefaultTimeoutOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('timeout' => null))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['timeout' => null])->willReturnSelf(); $this->browser->withTimeout(true); } public function testWithTimeoutFalseSetsNegativeTimeoutOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('timeout' => -1))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['timeout' => -1])->willReturnSelf(); $this->browser->withTimeout(false); } public function testWithTimeout10SetsTimeoutOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('timeout' => 10))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['timeout' => 10])->willReturnSelf(); $this->browser->withTimeout(10); } public function testWithTimeoutNegativeSetsZeroTimeoutOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('timeout' => null))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['timeout' => null])->willReturnSelf(); $this->browser->withTimeout(-10); } public function testWithFollowRedirectsTrueSetsSenderOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('followRedirects' => true, 'maxRedirects' => null))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['followRedirects' => true, 'maxRedirects' => null])->willReturnSelf(); $this->browser->withFollowRedirects(true); } public function testWithFollowRedirectsFalseSetsSenderOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('followRedirects' => false, 'maxRedirects' => null))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['followRedirects' => false, 'maxRedirects' => null])->willReturnSelf(); $this->browser->withFollowRedirects(false); } public function testWithFollowRedirectsTenSetsSenderOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('followRedirects' => true, 'maxRedirects' => 10))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['followRedirects' => true, 'maxRedirects' => 10])->willReturnSelf(); $this->browser->withFollowRedirects(10); } public function testWithFollowRedirectsZeroSetsSenderOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('followRedirects' => true, 'maxRedirects' => 0))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['followRedirects' => true, 'maxRedirects' => 0])->willReturnSelf(); $this->browser->withFollowRedirects(0); } public function testWithRejectErrorResponseTrueSetsSenderOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('obeySuccessCode' => true))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['obeySuccessCode' => true])->willReturnSelf(); $this->browser->withRejectErrorResponse(true); } public function testWithRejectErrorResponseFalseSetsSenderOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('obeySuccessCode' => false))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['obeySuccessCode' => false])->willReturnSelf(); $this->browser->withRejectErrorResponse(false); } public function testWithResponseBufferThousandSetsSenderOption() { - $this->sender->expects($this->once())->method('withOptions')->with(array('maximumSize' => 1000))->willReturnSelf(); + $this->sender->expects($this->once())->method('withOptions')->with(['maximumSize' => 1000])->willReturnSelf(); $this->browser->withResponseBuffer(1000); } @@ -264,103 +256,103 @@ public function testWithBase() public function provideOtherUris() { - return array( - 'empty returns base' => array( + return [ + 'empty returns base' => [ 'http://example.com/base', '', 'http://example.com/base', - ), - 'absolute same as base returns base' => array( + ], + 'absolute same as base returns base' => [ 'http://example.com/base', 'http://example.com/base', 'http://example.com/base', - ), - 'absolute below base returns absolute' => array( + ], + 'absolute below base returns absolute' => [ 'http://example.com/base', 'http://example.com/base/another', 'http://example.com/base/another', - ), - 'slash returns base without path' => array( + ], + 'slash returns base without path' => [ 'http://example.com/base', '/', 'http://example.com/', - ), - 'relative is added behind base' => array( + ], + 'relative is added behind base' => [ 'http://example.com/base/', 'test', 'http://example.com/base/test', - ), - 'relative is added behind base without path' => array( + ], + 'relative is added behind base without path' => [ 'http://example.com/base', 'test', 'http://example.com/test', - ), - 'relative level up is added behind parent path' => array( + ], + 'relative level up is added behind parent path' => [ 'http://example.com/base/foo/', '../bar', 'http://example.com/base/bar', - ), - 'absolute with slash is added behind base without path' => array( + ], + 'absolute with slash is added behind base without path' => [ 'http://example.com/base', '/test', 'http://example.com/test', - ), - 'query string is added behind base' => array( + ], + 'query string is added behind base' => [ 'http://example.com/base', '?key=value', 'http://example.com/base?key=value', - ), - 'query string is added behind base with slash' => array( + ], + 'query string is added behind base with slash' => [ 'http://example.com/base/', '?key=value', 'http://example.com/base/?key=value', - ), - 'query string with slash is added behind base without path' => array( + ], + 'query string with slash is added behind base without path' => [ 'http://example.com/base', '/?key=value', 'http://example.com/?key=value', - ), - 'absolute with query string below base is returned as-is' => array( + ], + 'absolute with query string below base is returned as-is' => [ 'http://example.com/base', 'http://example.com/base?test', 'http://example.com/base?test', - ), - 'urlencoded special chars will stay as-is' => array( + ], + 'urlencoded special chars will stay as-is' => [ 'http://example.com/%7Bversion%7D/', '', 'http://example.com/%7Bversion%7D/' - ), - 'special chars will be urlencoded' => array( + ], + 'special chars will be urlencoded' => [ 'http://example.com/{version}/', '', 'http://example.com/%7Bversion%7D/' - ), - 'other domain' => array( + ], + 'other domain' => [ 'http://example.com/base/', 'http://example.org/base/', 'http://example.org/base/' - ), - 'other scheme' => array( + ], + 'other scheme' => [ 'http://example.com/base/', 'https://example.com/base/', 'https://example.com/base/' - ), - 'other port' => array( + ], + 'other port' => [ 'http://example.com/base/', 'http://example.com:81/base/', 'http://example.com:81/base/' - ), - 'other path' => array( + ], + 'other path' => [ 'http://example.com/base/', 'http://example.com/other/', 'http://example.com/other/' - ), - 'other path due to missing slash' => array( + ], + 'other path due to missing slash' => [ 'http://example.com/base/', 'http://example.com/other', 'http://example.com/other' - ), - ); + ], + ]; } /** @@ -372,9 +364,8 @@ public function testResolveUriWithBaseEndsWithoutSlash($base, $uri, $expectedAbs { $browser = $this->browser->withBase($base); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($expectedAbsolute, $that) { - $that->assertEquals($expectedAbsolute, $request->getUri()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($expectedAbsolute) { + $this->assertEquals($expectedAbsolute, $request->getUri()); return true; }))->willReturn(new Promise(function () { })); @@ -397,9 +388,8 @@ public function testWithoutBaseFollowedByGetRequestTriesToSendIncompleteRequestU { $this->browser = $this->browser->withBase('http://example.com')->withBase(null); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('path', $request->getUri()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('path', $request->getUri()); return true; }))->willReturn(new Promise(function () { })); @@ -410,9 +400,8 @@ public function testWithProtocolVersionFollowedByGetRequestSendsRequestWithProto { $this->browser = $this->browser->withProtocolVersion('1.0'); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('1.0', $request->getProtocolVersion()); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals('1.0', $request->getProtocolVersion()); return true; }))->willReturn(new Promise(function () { })); @@ -443,9 +432,8 @@ public function testWithHeaderShouldOverwriteExistingHeader() $this->browser = $this->browser->withHeader('User-Agent', 'ACMC'); //should be overwritten $this->browser = $this->browser->withHeader('user-agent', 'ABC'); //should be the user-agent - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array('ABC'), $request->getHeader('UsEr-AgEnT')); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals(['ABC'], $request->getHeader('UsEr-AgEnT')); return true; }))->willReturn(new Promise(function () { })); @@ -456,13 +444,12 @@ public function testWithHeaderShouldBeOverwrittenByExplicitHeaderInGetMethod() { $this->browser = $this->browser->withHeader('User-Agent', 'ACMC'); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array('ABC'), $request->getHeader('UsEr-AgEnT')); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals(['ABC'], $request->getHeader('UsEr-AgEnT')); return true; }))->willReturn(new Promise(function () { })); - $this->browser->get('http://example.com/', array('user-Agent' => 'ABC')); //should win + $this->browser->get('http://example.com/', ['user-Agent' => 'ABC']); //should win } public function testWithMultipleHeadersShouldBeMergedCorrectlyWithMultipleDefaultHeaders() @@ -472,28 +459,27 @@ public function testWithMultipleHeadersShouldBeMergedCorrectlyWithMultipleDefaul $this->browser = $this->browser->withHeader('Custom-HEADER', 'custom'); $this->browser = $this->browser->withHeader('just-a-header', 'header-value'); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $expectedHeaders = array( - 'Host' => array('example.com'), + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $expectedHeaders = [ + 'Host' => ['example.com'], - 'User-Test' => array('Test'), - 'just-a-header' => array('header-value'), + 'User-Test' => ['Test'], + 'just-a-header' => ['header-value'], - 'user-Agent' => array('ABC'), - 'another-header' => array('value'), - 'custom-header' => array('data'), - ); + 'user-Agent' => ['ABC'], + 'another-header' => ['value'], + 'custom-header' => ['data'], + ]; - $that->assertEquals($expectedHeaders, $request->getHeaders()); + $this->assertEquals($expectedHeaders, $request->getHeaders()); return true; }))->willReturn(new Promise(function () { })); - $headers = array( + $headers = [ 'user-Agent' => 'ABC', //should overwrite: 'User-Agent', 'ACMC' 'another-header' => 'value', 'custom-header' => 'data', //should overwrite: 'Custom-header', 'custom' - ); + ]; $this->browser->get('http://example.com/', $headers); } @@ -502,9 +488,8 @@ public function testWithoutHeaderShouldRemoveExistingHeader() $this->browser = $this->browser->withHeader('User-Agent', 'ACMC'); $this->browser = $this->browser->withoutHeader('UsEr-AgEnT'); //should remove case-insensitive header - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array(), $request->getHeader('user-agent')); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals([], $request->getHeader('user-agent')); return true; }))->willReturn(new Promise(function () { })); @@ -515,9 +500,8 @@ public function testWithoutHeaderConnectionShouldRemoveDefaultConnectionHeader() { $this->browser = $this->browser->withoutHeader('Connection'); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array(), $request->getHeader('Connection')); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals([], $request->getHeader('Connection')); return true; }))->willReturn(new Promise(function () { })); @@ -528,9 +512,8 @@ public function testWithHeaderConnectionShouldOverwriteDefaultConnectionHeader() { $this->browser = $this->browser->withHeader('Connection', 'keep-alive'); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array('keep-alive'), $request->getHeader('Connection')); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals(['keep-alive'], $request->getHeader('Connection')); return true; }))->willReturn(new Promise(function () { })); @@ -539,9 +522,8 @@ public function testWithHeaderConnectionShouldOverwriteDefaultConnectionHeader() public function testBrowserShouldSendDefaultUserAgentHeader() { - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array(0 => 'ReactPHP/1'), $request->getHeader('user-agent')); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals([0 => 'ReactPHP/1'], $request->getHeader('user-agent')); return true; }))->willReturn(new Promise(function () { })); @@ -552,9 +534,8 @@ public function testBrowserShouldNotSendDefaultUserAgentHeaderIfWithoutHeaderRem { $this->browser = $this->browser->withoutHeader('UsEr-AgEnT'); - $that = $this; - $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array(), $request->getHeader('User-Agent')); + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) { + $this->assertEquals([], $request->getHeader('User-Agent')); return true; }))->willReturn(new Promise(function () { })); diff --git a/tests/Client/FunctionalIntegrationTest.php b/tests/Client/FunctionalIntegrationTest.php index 6c49c127..b727a334 100644 --- a/tests/Client/FunctionalIntegrationTest.php +++ b/tests/Client/FunctionalIntegrationTest.php @@ -7,14 +7,15 @@ use React\Http\Client\Client; use React\Http\Io\ClientConnectionManager; use React\Http\Message\Request; -use React\Promise\Deferred; use React\Promise\Promise; -use React\Promise\Stream; use React\Socket\ConnectionInterface; use React\Socket\Connector; use React\Socket\SocketServer; use React\Stream\ReadableStreamInterface; use React\Tests\Http\TestCase; +use function React\Async\await; +use function React\Promise\Stream\first; +use function React\Promise\Timer\timeout; class FunctionalIntegrationTest extends TestCase { @@ -49,12 +50,12 @@ public function testRequestToLocalhostEmitsSingleRemoteConnection() $port = parse_url($socket->getAddress(), PHP_URL_PORT); $client = new Client(new ClientConnectionManager(new Connector(), Loop::get())); - $request = $client->request(new Request('GET', 'http://localhost:' . $port, array(), '', '1.0')); + $request = $client->request(new Request('GET', 'http://localhost:' . $port, [], '', '1.0')); - $promise = Stream\first($request, 'close'); + $promise = first($request, 'close'); $request->end(); - \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT_LOCAL)); + await(timeout($promise, self::TIMEOUT_LOCAL)); } public function testRequestToLocalhostWillConnectAndCloseConnectionAfterResponseWhenKeepAliveTimesOut() @@ -74,11 +75,11 @@ public function testRequestToLocalhostWillConnectAndCloseConnectionAfterResponse $port = parse_url($socket->getAddress(), PHP_URL_PORT); $client = new Client(new ClientConnectionManager(new Connector(), Loop::get())); - $request = $client->request(new Request('GET', 'http://localhost:' . $port, array(), '', '1.1')); + $request = $client->request(new Request('GET', 'http://localhost:' . $port, [], '', '1.1')); $request->end(); - \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT_LOCAL)); + await(timeout($promise, self::TIMEOUT_LOCAL)); } public function testRequestToLocalhostWillReuseExistingConnectionForSecondRequest() @@ -96,17 +97,17 @@ public function testRequestToLocalhostWillReuseExistingConnectionForSecondReques $client = new Client(new ClientConnectionManager(new Connector(), Loop::get())); - $request = $client->request(new Request('GET', 'http://localhost:' . $port, array(), '', '1.1')); - $promise = Stream\first($request, 'close'); + $request = $client->request(new Request('GET', 'http://localhost:' . $port, [], '', '1.1')); + $promise = first($request, 'close'); $request->end(); - \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT_LOCAL)); + await(timeout($promise, self::TIMEOUT_LOCAL)); - $request = $client->request(new Request('GET', 'http://localhost:' . $port, array(), '', '1.1')); - $promise = Stream\first($request, 'close'); + $request = $client->request(new Request('GET', 'http://localhost:' . $port, [], '', '1.1')); + $promise = first($request, 'close'); $request->end(); - \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT_LOCAL)); + await(timeout($promise, self::TIMEOUT_LOCAL)); } public function testRequestLegacyHttpServerWithOnlyLineFeedReturnsSuccessfulResponse() @@ -118,17 +119,17 @@ public function testRequestLegacyHttpServerWithOnlyLineFeedReturnsSuccessfulResp }); $client = new Client(new ClientConnectionManager(new Connector(), Loop::get())); - $request = $client->request(new Request('GET', str_replace('tcp:', 'http:', $socket->getAddress()), array(), '', '1.0')); + $request = $client->request(new Request('GET', str_replace('tcp:', 'http:', $socket->getAddress()), [], '', '1.0')); $once = $this->expectCallableOnceWith('body'); $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($once) { $body->on('data', $once); }); - $promise = Stream\first($request, 'close'); + $promise = first($request, 'close'); $request->end(); - \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT_LOCAL)); + await(timeout($promise, self::TIMEOUT_LOCAL)); } /** @group internet */ @@ -136,17 +137,17 @@ public function testSuccessfulResponseEmitsEnd() { $client = new Client(new ClientConnectionManager(new Connector(), Loop::get())); - $request = $client->request(new Request('GET', 'http://www.google.com/', array(), '', '1.0')); + $request = $client->request(new Request('GET', 'http://www.google.com/', [], '', '1.0')); $once = $this->expectCallableOnce(); $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($once) { $body->on('end', $once); }); - $promise = Stream\first($request, 'close'); + $promise = first($request, 'close'); $request->end(); - \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT_REMOTE)); + await(timeout($promise, self::TIMEOUT_REMOTE)); } /** @group internet */ @@ -154,7 +155,7 @@ public function testCancelPendingConnectionEmitsClose() { $client = new Client(new ClientConnectionManager(new Connector(), Loop::get())); - $request = $client->request(new Request('GET', 'http://www.google.com/', array(), '', '1.0')); + $request = $client->request(new Request('GET', 'http://www.google.com/', [], '', '1.0')); $request->on('error', $this->expectCallableNever()); $request->on('close', $this->expectCallableOnce()); $request->end(); diff --git a/tests/FunctionalBrowserTest.php b/tests/FunctionalBrowserTest.php index 6a235703..92c873d1 100644 --- a/tests/FunctionalBrowserTest.php +++ b/tests/FunctionalBrowserTest.php @@ -10,12 +10,16 @@ use React\Http\Message\Response; use React\Http\Message\ResponseException; use React\Http\Middleware\StreamingRequestMiddleware; +use React\Promise\Deferred; use React\Promise\Promise; -use React\Promise\Stream; +use React\Socket\ConnectionInterface; use React\Socket\Connector; use React\Socket\SocketServer; use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use function React\Async\await; +use function React\Promise\Stream\buffer; +use function React\Promise\Timer\timeout; class FunctionalBrowserTest extends TestCase { @@ -35,7 +39,7 @@ public function setUpBrowserAndServer() $http = new HttpServer(new StreamingRequestMiddleware(), function (ServerRequestInterface $request) { $path = $request->getUri()->getPath(); - $headers = array(); + $headers = []; foreach ($request->getHeaders() as $name => $values) { $headers[$name] = implode(', ', $values); } @@ -43,7 +47,7 @@ public function setUpBrowserAndServer() if ($path === '/get') { return new Response( 200, - array(), + [], 'hello' ); } @@ -52,14 +56,14 @@ public function setUpBrowserAndServer() $params = $request->getQueryParams(); return new Response( 302, - array('Location' => $params['url']) + ['Location' => $params['url']] ); } if ($path === '/basic-auth/user/pass') { return new Response( $request->getHeaderLine('Authorization') === 'Basic dXNlcjpwYXNz' ? 200 : 401, - array(), + [], '' ); } @@ -67,7 +71,7 @@ public function setUpBrowserAndServer() if ($path === '/status/204') { return new Response( 204, - array(), + [], '' ); } @@ -75,7 +79,7 @@ public function setUpBrowserAndServer() if ($path === '/status/304') { return new Response( 304, - array(), + [], 'Not modified' ); } @@ -83,7 +87,7 @@ public function setUpBrowserAndServer() if ($path === '/status/404') { return new Response( 404, - array(), + [], '' ); } @@ -94,7 +98,7 @@ public function setUpBrowserAndServer() $timer = Loop::addTimer(10, function () use ($resolve) { $resolve(new Response( 200, - array(), + [], 'hello' )); }); @@ -116,11 +120,11 @@ public function setUpBrowserAndServer() $body->on('close', function () use (&$buffer, $resolve, $headers) { $resolve(new Response( 200, - array(), - json_encode(array( + [], + json_encode([ 'data' => $buffer, 'headers' => $headers - )) + ]) )); }); }); @@ -130,14 +134,14 @@ public function setUpBrowserAndServer() $stream = new ThroughStream(); Loop::futureTick(function () use ($stream, $headers) { - $stream->end(json_encode(array( + $stream->end(json_encode([ 'headers' => $headers - ))); + ])); }); return new Response( 200, - array(), + [], $stream ); } @@ -165,7 +169,7 @@ public function cleanUpSocketServer() */ public function testSimpleRequest() { - \React\Async\await($this->browser->get($this->base . 'get')); + await($this->browser->get($this->base . 'get')); } public function testGetRequestWithRelativeAddressRejects() @@ -173,7 +177,7 @@ public function testGetRequestWithRelativeAddressRejects() $promise = $this->browser->get('delay'); $this->setExpectedException('InvalidArgumentException', 'Invalid request URL given'); - \React\Async\await($promise); + await($promise); } /** @@ -181,7 +185,7 @@ public function testGetRequestWithRelativeAddressRejects() */ public function testGetRequestWithBaseAndRelativeAddressResolves() { - \React\Async\await($this->browser->withBase($this->base)->get('get')); + await($this->browser->withBase($this->base)->get('get')); } /** @@ -189,7 +193,7 @@ public function testGetRequestWithBaseAndRelativeAddressResolves() */ public function testGetRequestWithBaseAndFullAddressResolves() { - \React\Async\await($this->browser->withBase('http://example.com/')->get($this->base . 'get')); + await($this->browser->withBase('http://example.com/')->get($this->base . 'get')); } public function testCancelGetRequestWillRejectRequest() @@ -198,7 +202,7 @@ public function testCancelGetRequestWillRejectRequest() $promise->cancel(); $this->setExpectedException('RuntimeException'); - \React\Async\await($promise); + await($promise); } public function testCancelRequestWithPromiseFollowerWillRejectRequest() @@ -209,13 +213,13 @@ public function testCancelRequestWithPromiseFollowerWillRejectRequest() $promise->cancel(); $this->setExpectedException('RuntimeException'); - \React\Async\await($promise); + await($promise); } public function testRequestWithoutAuthenticationFails() { $this->setExpectedException('RuntimeException'); - \React\Async\await($this->browser->get($this->base . 'basic-auth/user/pass')); + await($this->browser->get($this->base . 'basic-auth/user/pass')); } /** @@ -225,7 +229,7 @@ public function testRequestWithAuthenticationSucceeds() { $base = str_replace('://', '://user:pass@', $this->base); - \React\Async\await($this->browser->get($base . 'basic-auth/user/pass')); + await($this->browser->get($base . 'basic-auth/user/pass')); } /** @@ -239,7 +243,7 @@ public function testRedirectToPageWithAuthenticationSendsAuthenticationFromLocat { $target = str_replace('://', '://user:pass@', $this->base) . 'basic-auth/user/pass'; - \React\Async\await($this->browser->get($this->base . 'redirect-to?url=' . urlencode($target))); + await($this->browser->get($this->base . 'redirect-to?url=' . urlencode($target))); } /** @@ -254,7 +258,7 @@ public function testRedirectFromPageWithInvalidAuthToPageWithCorrectAuthenticati $base = str_replace('://', '://unknown:invalid@', $this->base); $target = str_replace('://', '://user:pass@', $this->base) . 'basic-auth/user/pass'; - \React\Async\await($this->browser->get($base . 'redirect-to?url=' . urlencode($target))); + await($this->browser->get($base . 'redirect-to?url=' . urlencode($target))); } public function testCancelRedirectedRequestShouldReject() @@ -266,7 +270,7 @@ public function testCancelRedirectedRequestShouldReject() }); $this->setExpectedException('RuntimeException', 'Request cancelled'); - \React\Async\await($promise); + await($promise); } public function testTimeoutDelayedResponseShouldReject() @@ -274,17 +278,17 @@ public function testTimeoutDelayedResponseShouldReject() $promise = $this->browser->withTimeout(0.1)->get($this->base . 'delay/10'); $this->setExpectedException('RuntimeException', 'Request timed out after 0.1 seconds'); - \React\Async\await($promise); + await($promise); } public function testTimeoutDelayedResponseAfterStreamingRequestShouldReject() { $stream = new ThroughStream(); - $promise = $this->browser->withTimeout(0.1)->post($this->base . 'delay/10', array(), $stream); + $promise = $this->browser->withTimeout(0.1)->post($this->base . 'delay/10', [], $stream); $stream->end(); $this->setExpectedException('RuntimeException', 'Request timed out after 0.1 seconds'); - \React\Async\await($promise); + await($promise); } /** @@ -292,7 +296,7 @@ public function testTimeoutDelayedResponseAfterStreamingRequestShouldReject() */ public function testTimeoutFalseShouldResolveSuccessfully() { - \React\Async\await($this->browser->withTimeout(false)->get($this->base . 'get')); + await($this->browser->withTimeout(false)->get($this->base . 'get')); } /** @@ -300,7 +304,7 @@ public function testTimeoutFalseShouldResolveSuccessfully() */ public function testRedirectRequestRelative() { - \React\Async\await($this->browser->get($this->base . 'redirect-to?url=get')); + await($this->browser->get($this->base . 'redirect-to?url=get')); } /** @@ -308,7 +312,7 @@ public function testRedirectRequestRelative() */ public function testRedirectRequestAbsolute() { - \React\Async\await($this->browser->get($this->base . 'redirect-to?url=' . urlencode($this->base . 'get'))); + await($this->browser->get($this->base . 'redirect-to?url=' . urlencode($this->base . 'get'))); } /** @@ -318,7 +322,7 @@ public function testFollowingRedirectsFalseResolvesWithRedirectResult() { $browser = $this->browser->withFollowRedirects(false); - \React\Async\await($browser->get($this->base . 'redirect-to?url=get')); + await($browser->get($this->base . 'redirect-to?url=get')); } public function testFollowRedirectsZeroRejectsOnRedirect() @@ -326,12 +330,12 @@ public function testFollowRedirectsZeroRejectsOnRedirect() $browser = $this->browser->withFollowRedirects(0); $this->setExpectedException('RuntimeException'); - \React\Async\await($browser->get($this->base . 'redirect-to?url=get')); + await($browser->get($this->base . 'redirect-to?url=get')); } public function testResponseStatus204ShouldResolveWithEmptyBody() { - $response = \React\Async\await($this->browser->get($this->base . 'status/204')); + $response = await($this->browser->get($this->base . 'status/204')); $this->assertFalse($response->hasHeader('Content-Length')); $body = $response->getBody(); @@ -341,7 +345,7 @@ public function testResponseStatus204ShouldResolveWithEmptyBody() public function testResponseStatus304ShouldResolveWithEmptyBodyButContentLengthResponseHeader() { - $response = \React\Async\await($this->browser->get($this->base . 'status/304')); + $response = await($this->browser->get($this->base . 'status/304')); $this->assertEquals('12', $response->getHeaderLine('Content-Length')); $body = $response->getBody(); @@ -356,7 +360,7 @@ public function testGetRequestWithResponseBufferMatchedExactlyResolves() { $promise = $this->browser->withResponseBuffer(5)->get($this->base . 'get'); - \React\Async\await($promise); + await($promise); } public function testGetRequestWithResponseBufferExceededRejects() @@ -368,7 +372,7 @@ public function testGetRequestWithResponseBufferExceededRejects() 'Response body size of 5 bytes exceeds maximum of 4 bytes', defined('SOCKET_EMSGSIZE') ? SOCKET_EMSGSIZE : 0 ); - \React\Async\await($promise); + await($promise); } public function testGetRequestWithResponseBufferExceededDuringStreamingRejects() @@ -380,7 +384,7 @@ public function testGetRequestWithResponseBufferExceededDuringStreamingRejects() 'Response body size exceeds maximum of 4 bytes', defined('SOCKET_EMSGSIZE') ? SOCKET_EMSGSIZE : 0 ); - \React\Async\await($promise); + await($promise); } /** @@ -389,7 +393,7 @@ public function testGetRequestWithResponseBufferExceededDuringStreamingRejects() */ public function testCanAccessHttps() { - \React\Async\await($this->browser->get('https://www.google.com/')); + await($this->browser->get('https://www.google.com/')); } /** @@ -397,16 +401,16 @@ public function testCanAccessHttps() */ public function testVerifyPeerEnabledForBadSslRejects() { - $connector = new Connector(array( - 'tls' => array( + $connector = new Connector([ + 'tls' => [ 'verify_peer' => true - ) - )); + ] + ]); $browser = new Browser($connector); $this->setExpectedException('RuntimeException'); - \React\Async\await($browser->get('https://self-signed.badssl.com/')); + await($browser->get('https://self-signed.badssl.com/')); } /** @@ -415,15 +419,15 @@ public function testVerifyPeerEnabledForBadSslRejects() */ public function testVerifyPeerDisabledForBadSslResolves() { - $connector = new Connector(array( - 'tls' => array( + $connector = new Connector([ + 'tls' => [ 'verify_peer' => false - ) - )); + ] + ]); $browser = new Browser($connector); - \React\Async\await($browser->get('https://self-signed.badssl.com/')); + await($browser->get('https://self-signed.badssl.com/')); } /** @@ -432,13 +436,13 @@ public function testVerifyPeerDisabledForBadSslResolves() public function testInvalidPort() { $this->setExpectedException('RuntimeException'); - \React\Async\await($this->browser->get('http://www.google.com:443/')); + await($this->browser->get('http://www.google.com:443/')); } public function testErrorStatusCodeRejectsWithResponseException() { try { - \React\Async\await($this->browser->get($this->base . 'status/404')); + await($this->browser->get($this->base . 'status/404')); $this->fail(); } catch (ResponseException $e) { $this->assertEquals(404, $e->getCode()); @@ -450,14 +454,14 @@ public function testErrorStatusCodeRejectsWithResponseException() public function testErrorStatusCodeDoesNotRejectWithRejectErrorResponseFalse() { - $response = \React\Async\await($this->browser->withRejectErrorResponse(false)->get($this->base . 'status/404')); + $response = await($this->browser->withRejectErrorResponse(false)->get($this->base . 'status/404')); $this->assertEquals(404, $response->getStatusCode()); } public function testPostString() { - $response = \React\Async\await($this->browser->post($this->base . 'post', array(), 'hello world')); + $response = await($this->browser->post($this->base . 'post', [], 'hello world')); $data = json_decode((string)$response->getBody(), true); $this->assertEquals('hello world', $data['data']); @@ -465,7 +469,7 @@ public function testPostString() public function testRequestStreamReturnsResponseBodyUntilConnectionsEndsForHttp10() { - $response = \React\Async\await($this->browser->withProtocolVersion('1.0')->get($this->base . 'stream/1')); + $response = await($this->browser->withProtocolVersion('1.0')->get($this->base . 'stream/1')); $this->assertEquals('1.0', $response->getProtocolVersion()); $this->assertFalse($response->hasHeader('Transfer-Encoding')); @@ -476,7 +480,7 @@ public function testRequestStreamReturnsResponseBodyUntilConnectionsEndsForHttp1 public function testRequestStreamReturnsResponseWithTransferEncodingChunkedAndResponseBodyDecodedForHttp11() { - $response = \React\Async\await($this->browser->get($this->base . 'stream/1')); + $response = await($this->browser->get($this->base . 'stream/1')); $this->assertEquals('1.1', $response->getProtocolVersion()); @@ -488,7 +492,7 @@ public function testRequestStreamReturnsResponseWithTransferEncodingChunkedAndRe public function testRequestStreamWithHeadRequestReturnsEmptyResponseBodWithTransferEncodingChunkedForHttp11() { - $response = \React\Async\await($this->browser->head($this->base . 'stream/1')); + $response = await($this->browser->head($this->base . 'stream/1')); $this->assertEquals('1.1', $response->getProtocolVersion()); @@ -499,7 +503,7 @@ public function testRequestStreamWithHeadRequestReturnsEmptyResponseBodWithTrans public function testRequestStreamReturnsResponseWithResponseBodyUndecodedWhenResponseHasDoubleTransferEncoding() { $socket = new SocketServer('127.0.0.1:0'); - $socket->on('connection', function (\React\Socket\ConnectionInterface $connection) { + $socket->on('connection', function (ConnectionInterface $connection) { $connection->on('data', function () use ($connection) { $connection->end("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked, chunked\r\nConnection: close\r\n\r\nhello"); }); @@ -507,7 +511,7 @@ public function testRequestStreamReturnsResponseWithResponseBodyUndecodedWhenRes $this->base = str_replace('tcp:', 'http:', $socket->getAddress()) . '/'; - $response = \React\Async\await($this->browser->get($this->base . 'stream/1')); + $response = await($this->browser->get($this->base . 'stream/1')); $socket->close(); @@ -519,9 +523,9 @@ public function testRequestStreamReturnsResponseWithResponseBodyUndecodedWhenRes public function testReceiveStreamAndExplicitlyCloseConnectionEvenWhenServerKeepsConnectionOpen() { - $closed = new \React\Promise\Deferred(); + $closed = new Deferred(); $socket = new SocketServer('127.0.0.1:0'); - $socket->on('connection', function (\React\Socket\ConnectionInterface $connection) use ($closed) { + $socket->on('connection', function (ConnectionInterface $connection) use ($closed) { $connection->on('data', function () use ($connection) { $connection->write("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello"); }); @@ -532,10 +536,10 @@ public function testReceiveStreamAndExplicitlyCloseConnectionEvenWhenServerKeeps $this->base = str_replace('tcp:', 'http:', $socket->getAddress()) . '/'; - $response = \React\Async\await($this->browser->get($this->base . 'get', array())); + $response = await($this->browser->get($this->base . 'get', [])); $this->assertEquals('hello', (string)$response->getBody()); - $ret = \React\Async\await(\React\Promise\Timer\timeout($closed->promise(), 0.1)); + $ret = await(timeout($closed->promise(), 0.1)); $this->assertTrue($ret); $socket->close(); @@ -545,7 +549,7 @@ public function testRequestWithConnectionCloseHeaderWillCreateNewConnectionForSe { $twice = $this->expectCallableOnce(); $socket = new SocketServer('127.0.0.1:0'); - $socket->on('connection', function (\React\Socket\ConnectionInterface $connection) use ($socket, $twice) { + $socket->on('connection', function (ConnectionInterface $connection) use ($socket, $twice) { $connection->on('data', function () use ($connection) { $connection->write("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello"); }); @@ -561,11 +565,11 @@ public function testRequestWithConnectionCloseHeaderWillCreateNewConnectionForSe // add `Connection: close` request header to disable HTTP keep-alive $this->browser = $this->browser->withHeader('Connection', 'close'); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); } @@ -574,7 +578,7 @@ public function testRequestWithHttp10WillCreateNewConnectionForSecondRequestEven { $twice = $this->expectCallableOnce(); $socket = new SocketServer('127.0.0.1:0'); - $socket->on('connection', function (\React\Socket\ConnectionInterface $connection) use ($socket, $twice) { + $socket->on('connection', function (ConnectionInterface $connection) use ($socket, $twice) { $connection->on('data', function () use ($connection) { $connection->write("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello"); }); @@ -590,11 +594,11 @@ public function testRequestWithHttp10WillCreateNewConnectionForSecondRequestEven // use HTTP/1.0 to disable HTTP keep-alive $this->browser = $this->browser->withProtocolVersion('1.0'); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); } @@ -603,11 +607,11 @@ public function testRequestWillReuseExistingConnectionForSecondRequestByDefault( { $this->socket->on('connection', $this->expectCallableOnce()); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); } @@ -619,11 +623,11 @@ public function testRequestWithHttp10AndConnectionKeepAliveHeaderWillReuseExisti $this->browser = $this->browser->withProtocolVersion('1.0'); $this->browser = $this->browser->withHeader('Connection', 'keep-alive'); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); - $response = \React\Async\await($this->browser->get($this->base . 'get')); + $response = await($this->browser->get($this->base . 'get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); } @@ -635,7 +639,7 @@ public function testRequestWithoutConnectionHeaderWillReuseExistingConnectionFor // remove default `Connection: close` request header to enable keep-alive $this->browser = $this->browser->withoutHeader('Connection'); - $response = \React\Async\await($this->browser->get($this->base . 'redirect-to?url=get')); + $response = await($this->browser->get($this->base . 'redirect-to?url=get')); assert($response instanceof ResponseInterface); $this->assertEquals('hello', (string)$response->getBody()); } @@ -648,7 +652,7 @@ public function testPostStreamChunked() $stream->end('hello world'); }); - $response = \React\Async\await($this->browser->post($this->base . 'post', array(), $stream)); + $response = await($this->browser->post($this->base . 'post', [], $stream)); $data = json_decode((string)$response->getBody(), true); $this->assertEquals('hello world', $data['data']); @@ -664,7 +668,7 @@ public function testPostStreamKnownLength() $stream->end('hello world'); }); - $response = \React\Async\await($this->browser->post($this->base . 'post', array('Content-Length' => 11), $stream)); + $response = await($this->browser->post($this->base . 'post', ['Content-Length' => 11], $stream)); $data = json_decode((string)$response->getBody(), true); $this->assertEquals('hello world', $data['data']); @@ -684,7 +688,7 @@ public function testPostStreamWillStartSendingRequestEvenWhenBodyDoesNotEmitData $this->base = str_replace('tcp:', 'http:', $socket->getAddress()) . '/'; $stream = new ThroughStream(); - \React\Async\await($this->browser->post($this->base . 'post', array(), $stream)); + await($this->browser->post($this->base . 'post', [], $stream)); $socket->close(); } @@ -694,7 +698,7 @@ public function testPostStreamClosed() $stream = new ThroughStream(); $stream->close(); - $response = \React\Async\await($this->browser->post($this->base . 'post', array(), $stream)); + $response = await($this->browser->post($this->base . 'post', [], $stream)); $data = json_decode((string)$response->getBody(), true); $this->assertEquals('', $data['data']); @@ -705,7 +709,7 @@ public function testSendsHttp11ByDefault() $http = new HttpServer(function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], $request->getProtocolVersion() ); }); @@ -714,7 +718,7 @@ public function testSendsHttp11ByDefault() $this->base = str_replace('tcp:', 'http:', $socket->getAddress()) . '/'; - $response = \React\Async\await($this->browser->get($this->base)); + $response = await($this->browser->get($this->base)); $this->assertEquals('1.1', (string)$response->getBody()); $socket->close(); @@ -725,7 +729,7 @@ public function testSendsExplicitHttp10Request() $http = new HttpServer(function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], $request->getProtocolVersion() ); }); @@ -734,7 +738,7 @@ public function testSendsExplicitHttp10Request() $this->base = str_replace('tcp:', 'http:', $socket->getAddress()) . '/'; - $response = \React\Async\await($this->browser->withProtocolVersion('1.0')->get($this->base)); + $response = await($this->browser->withProtocolVersion('1.0')->get($this->base)); $this->assertEquals('1.0', (string)$response->getBody()); $socket->close(); @@ -742,7 +746,7 @@ public function testSendsExplicitHttp10Request() public function testHeadRequestReceivesResponseWithEmptyBodyButWithContentLengthResponseHeader() { - $response = \React\Async\await($this->browser->head($this->base . 'get')); + $response = await($this->browser->head($this->base . 'get')); $this->assertEquals('5', $response->getHeaderLine('Content-Length')); $body = $response->getBody(); @@ -752,7 +756,7 @@ public function testHeadRequestReceivesResponseWithEmptyBodyButWithContentLength public function testRequestStreamingGetReceivesResponseWithStreamingBodyAndKnownSize() { - $response = \React\Async\await($this->browser->requestStreaming('GET', $this->base . 'get')); + $response = await($this->browser->requestStreaming('GET', $this->base . 'get')); $this->assertEquals('5', $response->getHeaderLine('Content-Length')); $body = $response->getBody(); @@ -763,7 +767,7 @@ public function testRequestStreamingGetReceivesResponseWithStreamingBodyAndKnown public function testRequestStreamingGetReceivesResponseWithStreamingBodyAndUnknownSizeFromStreamingEndpoint() { - $response = \React\Async\await($this->browser->requestStreaming('GET', $this->base . 'stream/1')); + $response = await($this->browser->requestStreaming('GET', $this->base . 'stream/1')); $this->assertFalse($response->hasHeader('Content-Length')); $body = $response->getBody(); @@ -774,9 +778,9 @@ public function testRequestStreamingGetReceivesResponseWithStreamingBodyAndUnkno public function testRequestStreamingGetReceivesStreamingResponseBody() { - $buffer = \React\Async\await( + $buffer = await( $this->browser->requestStreaming('GET', $this->base . 'get')->then(function (ResponseInterface $response) { - return Stream\buffer($response->getBody()); + return buffer($response->getBody()); }) ); @@ -785,9 +789,9 @@ public function testRequestStreamingGetReceivesStreamingResponseBody() public function testRequestStreamingGetReceivesStreamingResponseBodyEvenWhenResponseBufferExceeded() { - $buffer = \React\Async\await( + $buffer = await( $this->browser->withResponseBuffer(4)->requestStreaming('GET', $this->base . 'get')->then(function (ResponseInterface $response) { - return Stream\buffer($response->getBody()); + return buffer($response->getBody()); }) ); diff --git a/tests/FunctionalHttpServerTest.php b/tests/FunctionalHttpServerTest.php index 6b153b81..c0fcfe83 100644 --- a/tests/FunctionalHttpServerTest.php +++ b/tests/FunctionalHttpServerTest.php @@ -10,12 +10,17 @@ use React\Http\Middleware\LimitConcurrentRequestsMiddleware; use React\Http\Middleware\RequestBodyBufferMiddleware; use React\Http\Middleware\StreamingRequestMiddleware; +use React\Promise\Promise; use React\Socket\ConnectionInterface; use React\Socket\Connector; use React\Socket\SocketServer; -use React\Promise; -use React\Promise\Stream; use React\Stream\ThroughStream; +use function React\Async\await; +use function React\Promise\all; +use function React\Promise\Stream\buffer; +use function React\Promise\Stream\first; +use function React\Promise\Timer\sleep; +use function React\Promise\Timer\timeout; class FunctionalHttpServerTest extends TestCase { @@ -24,7 +29,7 @@ public function testPlainHttpOnRandomPort() $connector = new Connector(); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $socket = new SocketServer('127.0.0.1:0'); @@ -33,10 +38,10 @@ public function testPlainHttpOnRandomPort() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('http://' . noScheme($socket->getAddress()) . '/', $response); @@ -60,10 +65,10 @@ function () { $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 404 Not Found", $response); @@ -75,7 +80,7 @@ public function testPlainHttpOnRandomPortWithoutHostHeaderUsesSocketUri() $connector = new Connector(); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $socket = new SocketServer('127.0.0.1:0'); @@ -84,10 +89,10 @@ public function testPlainHttpOnRandomPortWithoutHostHeaderUsesSocketUri() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('http://' . noScheme($socket->getAddress()) . '/', $response); @@ -100,7 +105,7 @@ public function testPlainHttpOnRandomPortWithOtherHostHeaderTakesPrecedence() $connector = new Connector(); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $socket = new SocketServer('127.0.0.1:0'); @@ -109,10 +114,10 @@ public function testPlainHttpOnRandomPortWithOtherHostHeaderTakesPrecedence() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: localhost:1000\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('http://localhost:1000/', $response); @@ -122,26 +127,28 @@ public function testPlainHttpOnRandomPortWithOtherHostHeaderTakesPrecedence() public function testSecureHttpsOnRandomPort() { - $connector = new Connector(array( - 'tls' => array('verify_peer' => false) - )); + $connector = new Connector([ + 'tls' => [ + 'verify_peer' => false + ] + ]); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); - $socket = new SocketServer('tls://127.0.0.1:0', array('tls' => array( + $socket = new SocketServer('tls://127.0.0.1:0', ['tls' => [ 'local_cert' => __DIR__ . '/../examples/localhost.pem' - ))); + ]]); $http->listen($socket); $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('https://' . noScheme($socket->getAddress()) . '/', $response); @@ -154,27 +161,25 @@ public function testSecureHttpsReturnsData() $http = new HttpServer(function (RequestInterface $request) { return new Response( 200, - array(), + [], str_repeat('.', 33000) ); }); - $socket = new SocketServer('tls://127.0.0.1:0', array('tls' => array( - 'local_cert' => __DIR__ . '/../examples/localhost.pem' - ))); + $socket = new SocketServer('tls://127.0.0.1:0', ['tls' => ['local_cert' => __DIR__ . '/../examples/localhost.pem']]); $http->listen($socket); - $connector = new Connector(array( - 'tls' => array('verify_peer' => false) - )); + $connector = new Connector(['tls' => [ + 'verify_peer' => false + ]]); $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString("\r\nContent-Length: 33000\r\n", $response); @@ -185,26 +190,26 @@ public function testSecureHttpsReturnsData() public function testSecureHttpsOnRandomPortWithoutHostHeaderUsesSocketUri() { - $connector = new Connector(array( - 'tls' => array('verify_peer' => false) - )); + $connector = new Connector([ + 'tls' => ['verify_peer' => false] + ]); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); - $socket = new SocketServer('tls://127.0.0.1:0', array('tls' => array( + $socket = new SocketServer('tls://127.0.0.1:0', ['tls' => [ 'local_cert' => __DIR__ . '/../examples/localhost.pem' - ))); + ]]); $http->listen($socket); $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('https://' . noScheme($socket->getAddress()) . '/', $response); @@ -222,7 +227,7 @@ public function testPlainHttpOnStandardPortReturnsUriWithNoPort() $connector = new Connector(); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $http->listen($socket); @@ -230,10 +235,10 @@ public function testPlainHttpOnStandardPortReturnsUriWithNoPort() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('http://127.0.0.1/', $response); @@ -251,7 +256,7 @@ public function testPlainHttpOnStandardPortWithoutHostHeaderReturnsUriWithNoPort $connector = new Connector(); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $http->listen($socket); @@ -259,10 +264,10 @@ public function testPlainHttpOnStandardPortWithoutHostHeaderReturnsUriWithNoPort $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('http://127.0.0.1/', $response); @@ -273,19 +278,19 @@ public function testPlainHttpOnStandardPortWithoutHostHeaderReturnsUriWithNoPort public function testSecureHttpsOnStandardPortReturnsUriWithNoPort() { try { - $socket = new SocketServer('tls://127.0.0.1:443', array('tls' => array( + $socket = new SocketServer('tls://127.0.0.1:443', ['tls' => [ 'local_cert' => __DIR__ . '/../examples/localhost.pem' - ))); + ]]); } catch (\RuntimeException $e) { $this->markTestSkipped('Listening on port 443 failed (root and unused?)'); } - $connector = new Connector(array( - 'tls' => array('verify_peer' => false) - )); + $connector = new Connector([ + 'tls' => ['verify_peer' => false] + ]); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $http->listen($socket); @@ -293,10 +298,10 @@ public function testSecureHttpsOnStandardPortReturnsUriWithNoPort() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('https://127.0.0.1/', $response); @@ -307,19 +312,19 @@ public function testSecureHttpsOnStandardPortReturnsUriWithNoPort() public function testSecureHttpsOnStandardPortWithoutHostHeaderUsesSocketUri() { try { - $socket = new SocketServer('tls://127.0.0.1:443', array('tls' => array( + $socket = new SocketServer('tls://127.0.0.1:443', ['tls' => [ 'local_cert' => __DIR__ . '/../examples/localhost.pem' - ))); + ]]); } catch (\RuntimeException $e) { $this->markTestSkipped('Listening on port 443 failed (root and unused?)'); } - $connector = new Connector(array( - 'tls' => array('verify_peer' => false) - )); + $connector = new Connector([ + 'tls' => ['verify_peer' => false] + ]); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $http->listen($socket); @@ -327,10 +332,10 @@ public function testSecureHttpsOnStandardPortWithoutHostHeaderUsesSocketUri() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('https://127.0.0.1/', $response); @@ -348,7 +353,7 @@ public function testPlainHttpOnHttpsStandardPortReturnsUriWithPort() $connector = new Connector(); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri()); + return new Response(200, [], (string)$request->getUri()); }); $http->listen($socket); @@ -356,10 +361,10 @@ public function testPlainHttpOnHttpsStandardPortReturnsUriWithPort() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('http://127.0.0.1:443/', $response); @@ -370,19 +375,19 @@ public function testPlainHttpOnHttpsStandardPortReturnsUriWithPort() public function testSecureHttpsOnHttpStandardPortReturnsUriWithPort() { try { - $socket = new SocketServer('tls://127.0.0.1:80', array('tls' => array( + $socket = new SocketServer('tls://127.0.0.1:80', ['tls' => [ 'local_cert' => __DIR__ . '/../examples/localhost.pem' - ))); + ]]); } catch (\RuntimeException $e) { $this->markTestSkipped('Listening on port 80 failed (root and unused?)'); } - $connector = new Connector(array( - 'tls' => array('verify_peer' => false) - )); + $connector = new Connector([ + 'tls' => ['verify_peer' => false] + ]); $http = new HttpServer(function (RequestInterface $request) { - return new Response(200, array(), (string)$request->getUri() . 'x' . $request->getHeaderLine('Host')); + return new Response(200, [], (string)$request->getUri() . 'x' . $request->getHeaderLine('Host')); }); $http->listen($socket); @@ -390,10 +395,10 @@ public function testSecureHttpsOnHttpStandardPortReturnsUriWithPort() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertContainsString("HTTP/1.0 200 OK", $response); $this->assertContainsString('https://127.0.0.1:80/', $response); @@ -409,7 +414,7 @@ public function testClosedStreamFromRequestHandlerWillSendEmptyBody() $stream->close(); $http = new HttpServer(function (RequestInterface $request) use ($stream) { - return new Response(200, array(), $stream); + return new Response(200, [], $stream); }); $socket = new SocketServer('127.0.0.1:0'); @@ -418,10 +423,10 @@ public function testClosedStreamFromRequestHandlerWillSendEmptyBody() $result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write("GET / HTTP/1.0\r\n\r\n"); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertStringStartsWith("HTTP/1.0 200 OK", $response); $this->assertStringEndsWith("\r\n\r\n", $response); @@ -452,7 +457,7 @@ function (RequestInterface $request) use ($once) { }); }); - \React\Async\await(\React\Promise\Timer\sleep(0.1)); + await(sleep(0.1)); $socket->close(); } @@ -466,7 +471,7 @@ public function testStreamFromRequestHandlerWillBeClosedIfConnectionClosesWhileS $http = new HttpServer( new StreamingRequestMiddleware(), function (RequestInterface $request) use ($stream) { - return new Response(200, array(), $stream); + return new Response(200, [], $stream); } ); @@ -482,7 +487,7 @@ function (RequestInterface $request) use ($stream) { }); // stream will be closed within 0.1s - $ret = \React\Async\await(\React\Promise\Timer\timeout(Stream\first($stream, 'close'), 0.1)); + $ret = await(timeout(first($stream, 'close'), 0.1)); $socket->close(); @@ -496,7 +501,7 @@ public function testStreamFromRequestHandlerWillBeClosedIfConnectionCloses() $stream = new ThroughStream(); $http = new HttpServer(function (RequestInterface $request) use ($stream) { - return new Response(200, array(), $stream); + return new Response(200, [], $stream); }); $socket = new SocketServer('127.0.0.1:0'); @@ -511,7 +516,7 @@ public function testStreamFromRequestHandlerWillBeClosedIfConnectionCloses() }); // await response stream to be closed - $ret = \React\Async\await(\React\Promise\Timer\timeout(Stream\first($stream, 'close'), 1.0)); + $ret = await(timeout(first($stream, 'close'), 1.0)); $socket->close(); @@ -529,7 +534,7 @@ public function testUpgradeWithThroughStreamReturnsDataAsGiven() $stream->end(); }); - return new Response(101, array('Upgrade' => 'echo'), $stream); + return new Response(101, ['Upgrade' => 'echo'], $stream); }); $socket = new SocketServer('127.0.0.1:0'); @@ -543,10 +548,10 @@ public function testUpgradeWithThroughStreamReturnsDataAsGiven() $conn->write('world'); }); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertStringStartsWith("HTTP/1.1 101 Switching Protocols\r\n", $response); $this->assertStringEndsWith("\r\n\r\nhelloworld", $response); @@ -565,7 +570,7 @@ public function testUpgradeWithRequestBodyAndThroughStreamReturnsDataAsGiven() $stream->end(); }); - return new Response(101, array('Upgrade' => 'echo'), $stream); + return new Response(101, ['Upgrade' => 'echo'], $stream); }); $socket = new SocketServer('127.0.0.1:0'); @@ -580,10 +585,10 @@ public function testUpgradeWithRequestBodyAndThroughStreamReturnsDataAsGiven() $conn->write('world'); }); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertStringStartsWith("HTTP/1.1 101 Switching Protocols\r\n", $response); $this->assertStringEndsWith("\r\n\r\nhelloworld", $response); @@ -602,7 +607,7 @@ public function testConnectWithThroughStreamReturnsDataAsGiven() $stream->end(); }); - return new Response(200, array(), $stream); + return new Response(200, [], $stream); }); $socket = new SocketServer('127.0.0.1:0'); @@ -616,10 +621,10 @@ public function testConnectWithThroughStreamReturnsDataAsGiven() $conn->write('world'); }); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertStringStartsWith("HTTP/1.1 200 OK\r\n", $response); $this->assertStringEndsWith("\r\n\r\nhelloworld", $response); @@ -638,9 +643,9 @@ public function testConnectWithThroughStreamReturnedFromPromiseReturnsDataAsGive $stream->end(); }); - return new Promise\Promise(function ($resolve) use ($stream) { + return new Promise(function ($resolve) use ($stream) { Loop::addTimer(0.001, function () use ($resolve, $stream) { - $resolve(new Response(200, array(), $stream)); + $resolve(new Response(200, [], $stream)); }); }); }); @@ -656,10 +661,10 @@ public function testConnectWithThroughStreamReturnedFromPromiseReturnsDataAsGive $conn->write('world'); }); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertStringStartsWith("HTTP/1.1 200 OK\r\n", $response); $this->assertStringEndsWith("\r\n\r\nhelloworld", $response); @@ -675,7 +680,7 @@ public function testConnectWithClosedThroughStreamReturnsNoData() $stream = new ThroughStream(); $stream->close(); - return new Response(200, array(), $stream); + return new Response(200, [], $stream); }); $socket = new SocketServer('127.0.0.1:0'); @@ -689,10 +694,10 @@ public function testConnectWithClosedThroughStreamReturnsNoData() $conn->write('world'); }); - return Stream\buffer($conn); + return buffer($conn); }); - $response = \React\Async\await(\React\Promise\Timer\timeout($result, 1.0)); + $response = await(timeout($result, 1.0)); $this->assertStringStartsWith("HTTP/1.1 200 OK\r\n", $response); $this->assertStringEndsWith("\r\n\r\n", $response); @@ -708,21 +713,21 @@ public function testLimitConcurrentRequestsMiddlewareRequestStreamPausing() new LimitConcurrentRequestsMiddleware(5), new RequestBodyBufferMiddleware(16 * 1024 * 1024), // 16 MiB function (ServerRequestInterface $request, $next) { - return new Promise\Promise(function ($resolve) use ($request, $next) { + return new Promise(function ($resolve) use ($request, $next) { Loop::addTimer(0.1, function () use ($request, $resolve, $next) { $resolve($next($request)); }); }); }, function (ServerRequestInterface $request) { - return new Response(200, array(), (string)strlen((string)$request->getBody())); + return new Response(200, [], (string)strlen((string)$request->getBody())); } ); $socket = new SocketServer('127.0.0.1:0'); $http->listen($socket); - $result = array(); + $result = []; for ($i = 0; $i < 6; $i++) { $result[] = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) { $conn->write( @@ -731,11 +736,11 @@ function (ServerRequestInterface $request) { "\r\n\r\n" ); - return Stream\buffer($conn); + return buffer($conn); }); } - $responses = \React\Async\await(\React\Promise\Timer\timeout(Promise\all($result), 1.0)); + $responses = await(timeout(all($result), 1.0)); foreach ($responses as $response) { $this->assertContainsString("HTTP/1.0 200 OK", $response, $response); diff --git a/tests/HttpServerTest.php b/tests/HttpServerTest.php index 606c50a6..fc977d9b 100644 --- a/tests/HttpServerTest.php +++ b/tests/HttpServerTest.php @@ -7,9 +7,10 @@ use React\Http\HttpServer; use React\Http\Io\IniUtil; use React\Http\Middleware\StreamingRequestMiddleware; -use React\Promise; use React\Promise\Deferred; use React\Stream\ReadableStreamInterface; +use function React\Async\await; +use function React\Promise\reject; final class HttpServerTest extends TestCase { @@ -27,7 +28,7 @@ public function setUpConnectionMockAndSocket() $this->connection = $this->getMockBuilder('React\Socket\Connection') ->disableOriginalConstructor() ->setMethods( - array( + [ 'write', 'end', 'close', @@ -38,7 +39,7 @@ public function setUpConnectionMockAndSocket() 'getRemoteAddress', 'getLocalAddress', 'pipe' - ) + ] ) ->getMock(); @@ -81,8 +82,8 @@ public function testSimpleRequestCallsRequestHandlerOnce() }); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); - $this->connection->emit('data', array("GET / HTTP/1.0\r\n\r\n")); + $this->socket->emit('connection', [$this->connection]); + $this->connection->emit('data', ["GET / HTTP/1.0\r\n\r\n"]); $this->assertSame(1, $called); } @@ -90,11 +91,11 @@ public function testSimpleRequestCallsRequestHandlerOnce() public function testSimpleRequestCallsArrayRequestHandlerOnce() { $this->called = null; - $http = new HttpServer(array($this, 'helperCallableOnce')); + $http = new HttpServer([$this, 'helperCallableOnce']); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); - $this->connection->emit('data', array("GET / HTTP/1.0\r\n\r\n")); + $this->socket->emit('connection', [$this->connection]); + $this->connection->emit('data', ["GET / HTTP/1.0\r\n\r\n"]); $this->assertSame(1, $this->called); } @@ -121,8 +122,8 @@ function (ServerRequestInterface $request) use (&$called) { ); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); - $this->connection->emit('data', array("GET / HTTP/1.0\r\n\r\n")); + $this->socket->emit('connection', [$this->connection]); + $this->connection->emit('data', ["GET / HTTP/1.0\r\n\r\n"]); $this->assertSame('beforeokafter', $called); } @@ -135,10 +136,10 @@ public function testPostFormData() }); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); - $this->connection->emit('data', array("POST / HTTP/1.0\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 7\r\n\r\nfoo=bar")); + $this->socket->emit('connection', [$this->connection]); + $this->connection->emit('data', ["POST / HTTP/1.0\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 7\r\n\r\nfoo=bar"]); - $request = \React\Async\await($deferred->promise()); + $request = await($deferred->promise()); assert($request instanceof ServerRequestInterface); $form = $request->getParsedBody(); @@ -146,7 +147,7 @@ public function testPostFormData() $this->assertTrue(isset($form['foo'])); $this->assertEquals('bar', $form['foo']); - $this->assertEquals(array(), $request->getUploadedFiles()); + $this->assertEquals([], $request->getUploadedFiles()); $body = $request->getBody(); @@ -163,20 +164,19 @@ public function testPostFileUpload() }); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); - $connection = $this->connection; $data = $this->createPostFileUploadRequest(); - Loop::addPeriodicTimer(0.01, function ($timer) use (&$data, $connection) { + Loop::addPeriodicTimer(0.01, function ($timer) use (&$data) { $line = array_shift($data); - $connection->emit('data', array($line)); + $this->connection->emit('data', [$line]); if (count($data) === 0) { Loop::cancelTimer($timer); } }); - $request = \React\Async\await($deferred->promise()); + $request = await($deferred->promise()); assert($request instanceof ServerRequestInterface); $this->assertEmpty($request->getParsedBody()); @@ -206,15 +206,15 @@ public function testPostJsonWillNotBeParsedByDefault() }); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); - $this->connection->emit('data', array("POST / HTTP/1.0\r\nContent-Type: application/json\r\nContent-Length: 6\r\n\r\n[true]")); + $this->socket->emit('connection', [$this->connection]); + $this->connection->emit('data', ["POST / HTTP/1.0\r\nContent-Type: application/json\r\nContent-Length: 6\r\n\r\n[true]"]); - $request = \React\Async\await($deferred->promise()); + $request = await($deferred->promise()); assert($request instanceof ServerRequestInterface); $this->assertNull($request->getParsedBody()); - $this->assertSame(array(), $request->getUploadedFiles()); + $this->assertSame([], $request->getUploadedFiles()); $body = $request->getBody(); @@ -231,8 +231,8 @@ public function testServerReceivesBufferedRequestByDefault() }); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); - $this->connection->emit('data', array("GET / HTTP/1.0\r\n\r\n")); + $this->socket->emit('connection', [$this->connection]); + $this->connection->emit('data', ["GET / HTTP/1.0\r\n\r\n"]); $this->assertEquals(false, $streaming); } @@ -248,8 +248,8 @@ function (ServerRequestInterface $request) use (&$streaming) { ); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); - $this->connection->emit('data', array("GET / HTTP/1.0\r\n\r\n")); + $this->socket->emit('connection', [$this->connection]); + $this->connection->emit('data', ["GET / HTTP/1.0\r\n\r\n"]); $this->assertEquals(true, $streaming); } @@ -259,17 +259,17 @@ public function testForwardErrors() $exception = new \Exception(); $capturedException = null; $http = new HttpServer(function () use ($exception) { - return Promise\reject($exception); + return reject($exception); }); $http->on('error', function ($error) use (&$capturedException) { $capturedException = $error; }); $http->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createPostFileUploadRequest(); - $this->connection->emit('data', array(implode('', $data))); + $this->connection->emit('data', [implode('', $data)]); $this->assertInstanceOf('RuntimeException', $capturedException); $this->assertInstanceOf('Exception', $capturedException->getPrevious()); @@ -280,7 +280,7 @@ private function createPostFileUploadRequest() { $boundary = "---------------------------5844729766471062541057622570"; - $data = array(); + $data = []; $data[] = "POST / HTTP/1.1\r\n"; $data[] = "Host: localhost\r\n"; $data[] = "Content-Type: multipart/form-data; boundary=" . $boundary . "\r\n"; @@ -299,23 +299,23 @@ private function createPostFileUploadRequest() public function provideIniSettingsForConcurrency() { - return array( - 'default settings' => array( + return [ + 'default settings' => [ '128M', '64K', // 8M capped at maximum 1024 - ), - 'unlimited memory_limit has no concurrency limit' => array( + ], + 'unlimited memory_limit has no concurrency limit' => [ '-1', '8M', null - ), - 'small post_max_size results in high concurrency' => array( + ], + 'small post_max_size results in high concurrency' => [ '128M', '1k', 65536 - ) - ); + ] + ]; } /** diff --git a/tests/Io/AbstractMessageTest.php b/tests/Io/AbstractMessageTest.php index 9e2c7d32..59c170ec 100644 --- a/tests/Io/AbstractMessageTest.php +++ b/tests/Io/AbstractMessageTest.php @@ -25,7 +25,7 @@ public function testWithProtocolVersionReturnsNewInstanceWhenProtocolVersionIsCh { $message = new MessageMock( '1.1', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() ); @@ -39,7 +39,7 @@ public function testWithProtocolVersionReturnsSameInstanceWhenProtocolVersionIsU { $message = new MessageMock( '1.1', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() ); @@ -52,16 +52,16 @@ public function testHeaderWithStringValue() { $message = new MessageMock( '1.1', - array( + [ 'Content-Type' => 'text/plain' - ), + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() ); - $this->assertEquals(array('Content-Type' => array('text/plain')), $message->getHeaders()); + $this->assertEquals(['Content-Type' => ['text/plain']], $message->getHeaders()); - $this->assertEquals(array('text/plain'), $message->getHeader('Content-Type')); - $this->assertEquals(array('text/plain'), $message->getHeader('CONTENT-type')); + $this->assertEquals(['text/plain'], $message->getHeader('Content-Type')); + $this->assertEquals(['text/plain'], $message->getHeader('CONTENT-type')); $this->assertEquals('text/plain', $message->getHeaderLine('Content-Type')); $this->assertEquals('text/plain', $message->getHeaderLine('CONTENT-Type')); @@ -72,50 +72,50 @@ public function testHeaderWithStringValue() $new = $message->withHeader('Content-Type', 'text/plain'); $this->assertSame($message, $new); - $new = $message->withHeader('Content-Type', array('text/plain')); + $new = $message->withHeader('Content-Type', ['text/plain']); $this->assertSame($message, $new); $new = $message->withHeader('content-type', 'text/plain'); $this->assertNotSame($message, $new); - $this->assertEquals(array('content-type' => array('text/plain')), $new->getHeaders()); - $this->assertEquals(array('Content-Type' => array('text/plain')), $message->getHeaders()); + $this->assertEquals(['content-type' => ['text/plain']], $new->getHeaders()); + $this->assertEquals(['Content-Type' => ['text/plain']], $message->getHeaders()); $new = $message->withHeader('Content-Type', 'text/html'); $this->assertNotSame($message, $new); - $this->assertEquals(array('Content-Type' => array('text/html')), $new->getHeaders()); - $this->assertEquals(array('Content-Type' => array('text/plain')), $message->getHeaders()); + $this->assertEquals(['Content-Type' => ['text/html']], $new->getHeaders()); + $this->assertEquals(['Content-Type' => ['text/plain']], $message->getHeaders()); - $new = $message->withHeader('Content-Type', array('text/html')); + $new = $message->withHeader('Content-Type', ['text/html']); $this->assertNotSame($message, $new); - $this->assertEquals(array('Content-Type' => array('text/html')), $new->getHeaders()); - $this->assertEquals(array('Content-Type' => array('text/plain')), $message->getHeaders()); + $this->assertEquals(['Content-Type' => ['text/html']], $new->getHeaders()); + $this->assertEquals(['Content-Type' => ['text/plain']], $message->getHeaders()); - $new = $message->withAddedHeader('Content-Type', array()); + $new = $message->withAddedHeader('Content-Type', []); $this->assertSame($message, $new); $new = $message->withoutHeader('Content-Type'); $this->assertNotSame($message, $new); - $this->assertEquals(array(), $new->getHeaders()); - $this->assertEquals(array('Content-Type' => array('text/plain')), $message->getHeaders()); + $this->assertEquals([], $new->getHeaders()); + $this->assertEquals(['Content-Type' => ['text/plain']], $message->getHeaders()); } public function testHeaderWithMultipleValues() { $message = new MessageMock( '1.1', - array( - 'Set-Cookie' => array( + [ + 'Set-Cookie' => [ 'a=1', 'b=2' - ) - ), + ] + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() ); - $this->assertEquals(array('Set-Cookie' => array('a=1', 'b=2')), $message->getHeaders()); + $this->assertEquals(['Set-Cookie' => ['a=1', 'b=2']], $message->getHeaders()); - $this->assertEquals(array('a=1', 'b=2'), $message->getHeader('Set-Cookie')); - $this->assertEquals(array('a=1', 'b=2'), $message->getHeader('Set-Cookie')); + $this->assertEquals(['a=1', 'b=2'], $message->getHeader('Set-Cookie')); + $this->assertEquals(['a=1', 'b=2'], $message->getHeader('Set-Cookie')); $this->assertEquals('a=1, b=2', $message->getHeaderLine('Set-Cookie')); $this->assertEquals('a=1, b=2', $message->getHeaderLine('Set-Cookie')); @@ -123,49 +123,49 @@ public function testHeaderWithMultipleValues() $this->assertTrue($message->hasHeader('Set-Cookie')); $this->assertTrue($message->hasHeader('Set-Cookie')); - $new = $message->withHeader('Set-Cookie', array('a=1', 'b=2')); + $new = $message->withHeader('Set-Cookie', ['a=1', 'b=2']); $this->assertSame($message, $new); - $new = $message->withHeader('Set-Cookie', array('a=1', 'b=2', 'c=3')); + $new = $message->withHeader('Set-Cookie', ['a=1', 'b=2', 'c=3']); $this->assertNotSame($message, $new); - $this->assertEquals(array('Set-Cookie' => array('a=1', 'b=2', 'c=3')), $new->getHeaders()); - $this->assertEquals(array('Set-Cookie' => array('a=1', 'b=2')), $message->getHeaders()); + $this->assertEquals(['Set-Cookie' => ['a=1', 'b=2', 'c=3']], $new->getHeaders()); + $this->assertEquals(['Set-Cookie' => ['a=1', 'b=2']], $message->getHeaders()); - $new = $message->withAddedHeader('Set-Cookie', array()); + $new = $message->withAddedHeader('Set-Cookie', []); $this->assertSame($message, $new); $new = $message->withAddedHeader('Set-Cookie', 'c=3'); $this->assertNotSame($message, $new); - $this->assertEquals(array('Set-Cookie' => array('a=1', 'b=2', 'c=3')), $new->getHeaders()); - $this->assertEquals(array('Set-Cookie' => array('a=1', 'b=2')), $message->getHeaders()); + $this->assertEquals(['Set-Cookie' => ['a=1', 'b=2', 'c=3']], $new->getHeaders()); + $this->assertEquals(['Set-Cookie' => ['a=1', 'b=2']], $message->getHeaders()); - $new = $message->withAddedHeader('Set-Cookie', array('c=3')); + $new = $message->withAddedHeader('Set-Cookie', ['c=3']); $this->assertNotSame($message, $new); - $this->assertEquals(array('Set-Cookie' => array('a=1', 'b=2', 'c=3')), $new->getHeaders()); - $this->assertEquals(array('Set-Cookie' => array('a=1', 'b=2')), $message->getHeaders()); + $this->assertEquals(['Set-Cookie' => ['a=1', 'b=2', 'c=3']], $new->getHeaders()); + $this->assertEquals(['Set-Cookie' => ['a=1', 'b=2']], $message->getHeaders()); } public function testHeaderWithEmptyValue() { $message = new MessageMock( '1.1', - array( - 'Content-Type' => array() - ), + [ + 'Content-Type' => [] + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() ); - $this->assertEquals(array(), $message->getHeaders()); + $this->assertEquals([], $message->getHeaders()); - $this->assertEquals(array(), $message->getHeader('Content-Type')); + $this->assertEquals([], $message->getHeader('Content-Type')); $this->assertEquals('', $message->getHeaderLine('Content-Type')); $this->assertFalse($message->hasHeader('Content-Type')); - $new = $message->withHeader('Empty', array()); + $new = $message->withHeader('Empty', []); $this->assertSame($message, $new); $this->assertFalse($new->hasHeader('Empty')); - $new = $message->withAddedHeader('Empty', array()); + $new = $message->withAddedHeader('Empty', []); $this->assertSame($message, $new); $this->assertFalse($new->hasHeader('Empty')); @@ -178,16 +178,16 @@ public function testHeaderWithMultipleValuesAcrossMixedCaseNamesInConstructorMer { $message = new MessageMock( '1.1', - array( + [ 'SET-Cookie' => 'a=1', - 'set-cookie' => array('b=2'), - 'set-COOKIE' => array() - ), + 'set-cookie' => ['b=2'], + 'set-COOKIE' => [] + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() ); - $this->assertEquals(array('set-cookie' => array('a=1', 'b=2')), $message->getHeaders()); - $this->assertEquals(array('a=1', 'b=2'), $message->getHeader('Set-Cookie')); + $this->assertEquals(['set-cookie' => ['a=1', 'b=2']], $message->getHeaders()); + $this->assertEquals(['a=1', 'b=2'], $message->getHeader('Set-Cookie')); } public function testWithBodyReturnsNewInstanceWhenBodyIsChanged() @@ -195,7 +195,7 @@ public function testWithBodyReturnsNewInstanceWhenBodyIsChanged() $body = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(); $message = new MessageMock( '1.1', - array(), + [], $body ); @@ -211,7 +211,7 @@ public function testWithBodyReturnsSameInstanceWhenBodyIsUnchanged() $body = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(); $message = new MessageMock( '1.1', - array(), + [], $body ); diff --git a/tests/Io/AbstractRequestTest.php b/tests/Io/AbstractRequestTest.php index 7ff4a9a5..24990622 100644 --- a/tests/Io/AbstractRequestTest.php +++ b/tests/Io/AbstractRequestTest.php @@ -36,7 +36,7 @@ public function testCtorWithInvalidUriThrows() new RequestMock( 'GET', null, - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -47,12 +47,12 @@ public function testGetHeadersReturnsHostHeaderFromUri() $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromUriWithCustomHttpPort() @@ -60,12 +60,12 @@ public function testGetHeadersReturnsHostHeaderFromUriWithCustomHttpPort() $request = new RequestMock( 'GET', 'http://example.com:8080/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com:8080')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com:8080']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromUriWithCustomPortHttpOnHttpsPort() @@ -73,12 +73,12 @@ public function testGetHeadersReturnsHostHeaderFromUriWithCustomPortHttpOnHttpsP $request = new RequestMock( 'GET', 'http://example.com:443/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com:443')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com:443']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromUriWithCustomPortHttpsOnHttpPort() @@ -86,12 +86,12 @@ public function testGetHeadersReturnsHostHeaderFromUriWithCustomPortHttpsOnHttpP $request = new RequestMock( 'GET', 'https://example.com:80/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com:80')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com:80']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromUriWithoutDefaultHttpPort() @@ -99,12 +99,12 @@ public function testGetHeadersReturnsHostHeaderFromUriWithoutDefaultHttpPort() $request = new RequestMock( 'GET', 'http://example.com:80/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromUriWithoutDefaultHttpsPort() @@ -112,12 +112,12 @@ public function testGetHeadersReturnsHostHeaderFromUriWithoutDefaultHttpsPort() $request = new RequestMock( 'GET', 'https://example.com:443/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromUriBeforeOtherHeadersExplicitlyGiven() @@ -125,14 +125,14 @@ public function testGetHeadersReturnsHostHeaderFromUriBeforeOtherHeadersExplicit $request = new RequestMock( 'GET', 'http://example.com/', - array( + [ 'User-Agent' => 'demo' - ), + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com'), 'User-Agent' => array('demo')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com'], 'User-Agent' => ['demo']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromHeadersExplicitlyGiven() @@ -140,14 +140,14 @@ public function testGetHeadersReturnsHostHeaderFromHeadersExplicitlyGiven() $request = new RequestMock( 'GET', 'http://localhost/', - array( + [ 'Host' => 'example.com:8080' - ), + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com:8080')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com:8080']], $request->getHeaders()); } public function testGetHeadersReturnsHostHeaderFromUriWhenHeadersExplicitlyGivenContainEmptyHostArray() @@ -155,14 +155,14 @@ public function testGetHeadersReturnsHostHeaderFromUriWhenHeadersExplicitlyGiven $request = new RequestMock( 'GET', 'https://example.com/', - array( - 'Host' => array() - ), + [ + 'Host' => [] + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); - $this->assertEquals(array('Host' => array('example.com')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com']], $request->getHeaders()); } public function testGetRequestTargetReturnsPathAndQueryFromUri() @@ -170,7 +170,7 @@ public function testGetRequestTargetReturnsPathAndQueryFromUri() $request = new RequestMock( 'GET', 'http://example.com/demo?name=Alice', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -183,7 +183,7 @@ public function testGetRequestTargetReturnsSlashOnlyIfUriHasNoPathOrQuery() $request = new RequestMock( 'GET', 'http://example.com', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -196,7 +196,7 @@ public function testGetRequestTargetReturnsRequestTargetInAbsoluteFormIfGivenExp $request = new RequestMock( 'GET', 'http://example.com/demo?name=Alice', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -210,7 +210,7 @@ public function testWithRequestTargetReturnsNewInstanceWhenRequestTargetIsChange $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -226,7 +226,7 @@ public function testWithRequestTargetReturnsSameInstanceWhenRequestTargetIsUncha $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -242,7 +242,7 @@ public function testWithMethodReturnsNewInstanceWhenMethodIsChanged() $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -258,7 +258,7 @@ public function testWithMethodReturnsSameInstanceWhenMethodIsUnchanged() $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -275,7 +275,7 @@ public function testGetUriReturnsUriInstanceGivenToCtor() $request = new RequestMock( 'GET', $uri, - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -288,7 +288,7 @@ public function testGetUriReturnsUriInstanceForUriStringGivenToCtor() $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -303,7 +303,7 @@ public function testWithUriReturnsNewInstanceWhenUriIsChanged() $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -323,7 +323,7 @@ public function testWithUriReturnsSameInstanceWhenUriIsUnchanged() $request = new RequestMock( 'GET', $uri, - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -338,7 +338,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderChangedIfUriContainsH $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -348,7 +348,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderChangedIfUriContainsH $this->assertNotSame($request, $new); $this->assertEquals('http://localhost/', (string) $new->getUri()); - $this->assertEquals(array('Host' => array('localhost')), $new->getHeaders()); + $this->assertEquals(['Host' => ['localhost']], $new->getHeaders()); } public function testWithUriReturnsNewInstanceWithHostHeaderChangedIfUriContainsHostWithCustomPort() @@ -356,7 +356,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderChangedIfUriContainsH $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -366,7 +366,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderChangedIfUriContainsH $this->assertNotSame($request, $new); $this->assertEquals('http://localhost:8080/', (string) $new->getUri()); - $this->assertEquals(array('Host' => array('localhost:8080')), $new->getHeaders()); + $this->assertEquals(['Host' => ['localhost:8080']], $new->getHeaders()); } public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderBeforeOthersIfUriContainsHost() @@ -374,9 +374,9 @@ public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderBef $request = new RequestMock( 'GET', 'http://example.com/', - array( + [ 'User-Agent' => 'test' - ), + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -387,7 +387,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderBef $this->assertNotSame($request, $new); $this->assertEquals('http://localhost/', (string) $new->getUri()); - $this->assertEquals(array('Host' => array('localhost'), 'User-Agent' => array('test')), $new->getHeaders()); + $this->assertEquals(['Host' => ['localhost'], 'User-Agent' => ['test']], $new->getHeaders()); } public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfUriContainsNoHost() @@ -395,7 +395,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfUriContain $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -405,7 +405,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfUriContain $this->assertNotSame($request, $new); $this->assertEquals('/path', (string) $new->getUri()); - $this->assertEquals(array('Host' => array('example.com')), $new->getHeaders()); + $this->assertEquals(['Host' => ['example.com']], $new->getHeaders()); } public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfPreserveHostIsTrue() @@ -413,7 +413,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfPreserveHo $request = new RequestMock( 'GET', 'http://example.com/', - array(), + [], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -423,7 +423,7 @@ public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfPreserveHo $this->assertNotSame($request, $new); $this->assertEquals('http://localhost/', (string) $new->getUri()); - $this->assertEquals(array('Host' => array('example.com')), $new->getHeaders()); + $this->assertEquals(['Host' => ['example.com']], $new->getHeaders()); } public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderNoMatterIfPreserveHostIsTrue() @@ -431,9 +431,9 @@ public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderNoM $request = new RequestMock( 'GET', 'http://example.com/', - array( + [ 'User-Agent' => 'test' - ), + ], $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), '1.1' ); @@ -444,6 +444,6 @@ public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderNoM $this->assertNotSame($request, $new); $this->assertEquals('http://example.com/', (string) $new->getUri()); - $this->assertEquals(array('Host' => array('example.com'), 'User-Agent' => array('test')), $new->getHeaders()); + $this->assertEquals(['Host' => ['example.com'], 'User-Agent' => ['test']], $new->getHeaders()); } } diff --git a/tests/Io/BufferedBodyTest.php b/tests/Io/BufferedBodyTest.php index 01154e71..4f5d042a 100644 --- a/tests/Io/BufferedBodyTest.php +++ b/tests/Io/BufferedBodyTest.php @@ -288,7 +288,7 @@ public function testGetMetadataWithoutKeyReturnsEmptyArray() { $stream = new BufferedBody('hello'); - $this->assertEquals(array(), $stream->getMetadata()); + $this->assertEquals([], $stream->getMetadata()); } public function testGetMetadataWithKeyReturnsNull() diff --git a/tests/Io/ChunkedDecoderTest.php b/tests/Io/ChunkedDecoderTest.php index 822ceaa6..5168f2d0 100644 --- a/tests/Io/ChunkedDecoderTest.php +++ b/tests/Io/ChunkedDecoderTest.php @@ -26,12 +26,12 @@ public function testSimpleChunk() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableNever()); - $this->input->emit('data', array("5\r\nhello\r\n")); + $this->input->emit('data', ["5\r\nhello\r\n"]); } public function testTwoChunks() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -39,9 +39,9 @@ public function testTwoChunks() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableNever()); - $this->input->emit('data', array("5\r\nhello\r\n3\r\nbla\r\n")); + $this->input->emit('data', ["5\r\nhello\r\n3\r\nbla\r\n"]); - $this->assertEquals(array('hello', 'bla'), $buffer); + $this->assertEquals(['hello', 'bla'], $buffer); } public function testEnd() @@ -50,12 +50,12 @@ public function testEnd() $this->parser->on('close', $this->expectCallableOnce()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("0\r\n\r\n")); + $this->input->emit('data', ["0\r\n\r\n"]); } public function testParameterWithEnd() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -64,9 +64,9 @@ public function testParameterWithEnd() $this->parser->on('close', $this->expectCallableOnce()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("5\r\nhello\r\n3\r\nbla\r\n0\r\n\r\n")); + $this->input->emit('data', ["5\r\nhello\r\n3\r\nbla\r\n0\r\n\r\n"]); - $this->assertEquals(array('hello', 'bla'), $buffer); + $this->assertEquals(['hello', 'bla'], $buffer); } public function testInvalidChunk() @@ -76,7 +76,7 @@ public function testInvalidChunk() $this->parser->on('close', $this->expectCallableOnce()); $this->parser->on('error', $this->expectCallableOnce()); - $this->input->emit('data', array("bla\r\n")); + $this->input->emit('data', ["bla\r\n"]); } public function testNeverEnd() @@ -85,7 +85,7 @@ public function testNeverEnd() $this->parser->on('close', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("0\r\n")); + $this->input->emit('data', ["0\r\n"]); } public function testWrongChunkHex() @@ -94,7 +94,7 @@ public function testWrongChunkHex() $this->parser->on('close', $this->expectCallableOnce()); $this->parser->on('end', $this->expectCallableNever()); - $this->input->emit('data', array("2\r\na\r\n5\r\nhello\r\n")); + $this->input->emit('data', ["2\r\na\r\n5\r\nhello\r\n"]); } public function testSplittedChunk() @@ -104,8 +104,8 @@ public function testSplittedChunk() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("4\r\n")); - $this->input->emit('data', array("welt\r\n")); + $this->input->emit('data', ["4\r\n"]); + $this->input->emit('data', ["welt\r\n"]); } public function testSplittedHeader() @@ -115,8 +115,8 @@ public function testSplittedHeader() $this->parser->on('end', $this->expectCallableNever());# $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("4")); - $this->input->emit('data', array("\r\nwelt\r\n")); + $this->input->emit('data', ["4"]); + $this->input->emit('data', ["\r\nwelt\r\n"]); } public function testSplittedBoth() @@ -126,14 +126,14 @@ public function testSplittedBoth() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("4")); - $this->input->emit('data', array("\r\n")); - $this->input->emit('data', array("welt\r\n")); + $this->input->emit('data', ["4"]); + $this->input->emit('data', ["\r\n"]); + $this->input->emit('data', ["welt\r\n"]); } public function testCompletlySplitted() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -142,17 +142,17 @@ public function testCompletlySplitted() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("4")); - $this->input->emit('data', array("\r\n")); - $this->input->emit('data', array("we")); - $this->input->emit('data', array("lt\r\n")); + $this->input->emit('data', ["4"]); + $this->input->emit('data', ["\r\n"]); + $this->input->emit('data', ["we"]); + $this->input->emit('data', ["lt\r\n"]); - $this->assertEquals(array('we', 'lt'), $buffer); + $this->assertEquals(['we', 'lt'], $buffer); } public function testMixed() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -161,17 +161,17 @@ public function testMixed() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("4")); - $this->input->emit('data', array("\r\n")); - $this->input->emit('data', array("welt\r\n")); - $this->input->emit('data', array("5\r\nhello\r\n")); + $this->input->emit('data', ["4"]); + $this->input->emit('data', ["\r\n"]); + $this->input->emit('data', ["welt\r\n"]); + $this->input->emit('data', ["5\r\nhello\r\n"]); - $this->assertEquals(array('welt', 'hello'), $buffer); + $this->assertEquals(['welt', 'hello'], $buffer); } public function testBigger() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -180,18 +180,18 @@ public function testBigger() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("1")); - $this->input->emit('data', array("0")); - $this->input->emit('data', array("\r\n")); - $this->input->emit('data', array("abcdeabcdeabcdea\r\n")); - $this->input->emit('data', array("5\r\nhello\r\n")); + $this->input->emit('data', ["1"]); + $this->input->emit('data', ["0"]); + $this->input->emit('data', ["\r\n"]); + $this->input->emit('data', ["abcdeabcdeabcdea\r\n"]); + $this->input->emit('data', ["5\r\nhello\r\n"]); - $this->assertEquals(array('abcdeabcdeabcdea', 'hello'), $buffer); + $this->assertEquals(['abcdeabcdeabcdea', 'hello'], $buffer); } public function testOneUnfinished() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -200,11 +200,11 @@ public function testOneUnfinished() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("3\r\n")); - $this->input->emit('data', array("bla\r\n")); - $this->input->emit('data', array("5\r\nhello")); + $this->input->emit('data', ["3\r\n"]); + $this->input->emit('data', ["bla\r\n"]); + $this->input->emit('data', ["5\r\nhello"]); - $this->assertEquals(array('bla', 'hello'), $buffer); + $this->assertEquals(['bla', 'hello'], $buffer); } public function testChunkIsBiggerThenExpected() @@ -214,8 +214,8 @@ public function testChunkIsBiggerThenExpected() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableOnce()); - $this->input->emit('data', array("5\r\n")); - $this->input->emit('data', array("hello world\r\n")); + $this->input->emit('data', ["5\r\n"]); + $this->input->emit('data', ["hello world\r\n"]); } public function testHandleUnexpectedEnd() @@ -235,7 +235,7 @@ public function testExtensionWillBeIgnored() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("3;hello=world;foo=bar\r\nbla")); + $this->input->emit('data', ["3;hello=world;foo=bar\r\nbla"]); } public function testChunkHeaderIsTooBig() @@ -249,7 +249,7 @@ public function testChunkHeaderIsTooBig() for ($i = 0; $i < 1025; $i++) { $data .= 'a'; } - $this->input->emit('data', array($data)); + $this->input->emit('data', [$data]); } public function testChunkIsMaximumSize() @@ -265,7 +265,7 @@ public function testChunkIsMaximumSize() } $data .= "\r\n"; - $this->input->emit('data', array($data)); + $this->input->emit('data', [$data]); } public function testLateCrlf() @@ -275,9 +275,9 @@ public function testLateCrlf() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("4\r\nlate")); - $this->input->emit('data', array("\r")); - $this->input->emit('data', array("\n")); + $this->input->emit('data', ["4\r\nlate"]); + $this->input->emit('data', ["\r"]); + $this->input->emit('data', ["\n"]); } public function testNoCrlfInChunk() @@ -287,7 +287,7 @@ public function testNoCrlfInChunk() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableOnce()); - $this->input->emit('data', array("2\r\nno crlf")); + $this->input->emit('data', ["2\r\nno crlf"]); } public function testNoCrlfInChunkSplitted() @@ -297,10 +297,10 @@ public function testNoCrlfInChunkSplitted() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableOnce()); - $this->input->emit('data', array("2\r\n")); - $this->input->emit('data', array("no")); - $this->input->emit('data', array("further")); - $this->input->emit('data', array("clrf")); + $this->input->emit('data', ["2\r\n"]); + $this->input->emit('data', ["no"]); + $this->input->emit('data', ["further"]); + $this->input->emit('data', ["clrf"]); } public function testEmitEmptyChunkBody() @@ -310,9 +310,9 @@ public function testEmitEmptyChunkBody() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("2\r\n")); - $this->input->emit('data', array("")); - $this->input->emit('data', array("")); + $this->input->emit('data', ["2\r\n"]); + $this->input->emit('data', [""]); + $this->input->emit('data', [""]); } public function testEmitCrlfAsChunkBody() @@ -322,9 +322,9 @@ public function testEmitCrlfAsChunkBody() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableNever()); - $this->input->emit('data', array("2\r\n")); - $this->input->emit('data', array("\r\n")); - $this->input->emit('data', array("\r\n")); + $this->input->emit('data', ["2\r\n"]); + $this->input->emit('data', ["\r\n"]); + $this->input->emit('data', ["\r\n"]); } public function testNegativeHeader() @@ -334,7 +334,7 @@ public function testNegativeHeader() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableOnce()); - $this->input->emit('data', array("-2\r\n")); + $this->input->emit('data', ["-2\r\n"]); } public function testHexDecimalInBodyIsPotentialThread() @@ -344,7 +344,7 @@ public function testHexDecimalInBodyIsPotentialThread() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableOnce()); - $this->input->emit('data', array("4\r\ntest5\r\nworld")); + $this->input->emit('data', ["4\r\ntest5\r\nworld"]); } public function testHexDecimalInBodyIsPotentialThreadSplitted() @@ -354,17 +354,17 @@ public function testHexDecimalInBodyIsPotentialThreadSplitted() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('error', $this->expectCallableOnce()); - $this->input->emit('data', array("4")); - $this->input->emit('data', array("\r\n")); - $this->input->emit('data', array("test")); - $this->input->emit('data', array("5")); - $this->input->emit('data', array("\r\n")); - $this->input->emit('data', array("world")); + $this->input->emit('data', ["4"]); + $this->input->emit('data', ["\r\n"]); + $this->input->emit('data', ["test"]); + $this->input->emit('data', ["5"]); + $this->input->emit('data', ["\r\n"]); + $this->input->emit('data', ["world"]); } public function testEmitSingleCharacter() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -375,10 +375,10 @@ public function testEmitSingleCharacter() $array = str_split("4\r\ntest\r\n0\r\n\r\n"); foreach ($array as $character) { - $this->input->emit('data', array($character)); + $this->input->emit('data', [$character]); } - $this->assertEquals(array('t', 'e', 's', 't'), $buffer); + $this->assertEquals(['t', 'e', 's', 't'], $buffer); } public function testHandleError() @@ -387,7 +387,7 @@ public function testHandleError() $this->parser->on('close', $this->expectCallableOnce()); $this->parser->on('end', $this->expectCallableNever()); - $this->input->emit('error', array(new \RuntimeException())); + $this->input->emit('error', [new \RuntimeException()]); $this->assertFalse($this->parser->isReadable()); } @@ -425,7 +425,7 @@ public function testHandleClose() $this->parser->on('close', $this->expectCallableOnce()); $this->input->close(); - $this->input->emit('end', array()); + $this->input->emit('end', []); $this->assertFalse($this->parser->isReadable()); } @@ -445,7 +445,7 @@ public function testOutputStreamCanCloseInputStream() public function testLeadingZerosWillBeIgnored() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -454,10 +454,10 @@ public function testLeadingZerosWillBeIgnored() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableNever()); - $this->input->emit('data', array("00005\r\nhello\r\n")); - $this->input->emit('data', array("0000b\r\nhello world\r\n")); + $this->input->emit('data', ["00005\r\nhello\r\n"]); + $this->input->emit('data', ["0000b\r\nhello world\r\n"]); - $this->assertEquals(array('hello', 'hello world'), $buffer); + $this->assertEquals(['hello', 'hello world'], $buffer); } public function testLeadingZerosInEndChunkWillBeIgnored() @@ -467,7 +467,7 @@ public function testLeadingZerosInEndChunkWillBeIgnored() $this->parser->on('end', $this->expectCallableOnce()); $this->parser->on('close', $this->expectCallableOnce()); - $this->input->emit('data', array("0000\r\n\r\n")); + $this->input->emit('data', ["0000\r\n\r\n"]); } public function testAdditionalWhitespaceInEndChunkWillBeIgnored() @@ -477,7 +477,7 @@ public function testAdditionalWhitespaceInEndChunkWillBeIgnored() $this->parser->on('end', $this->expectCallableOnce()); $this->parser->on('close', $this->expectCallableOnce()); - $this->input->emit('data', array(" 0 \r\n\r\n")); + $this->input->emit('data', [" 0 \r\n\r\n"]); } public function testEndChunkWithTrailersWillBeIgnored() @@ -487,7 +487,7 @@ public function testEndChunkWithTrailersWillBeIgnored() $this->parser->on('end', $this->expectCallableOnce()); $this->parser->on('close', $this->expectCallableOnce()); - $this->input->emit('data', array("0\r\nFoo: bar\r\n\r\n")); + $this->input->emit('data', ["0\r\nFoo: bar\r\n\r\n"]); } public function testEndChunkWithMultipleTrailersWillBeIgnored() @@ -497,7 +497,7 @@ public function testEndChunkWithMultipleTrailersWillBeIgnored() $this->parser->on('end', $this->expectCallableOnce()); $this->parser->on('close', $this->expectCallableOnce()); - $this->input->emit('data', array("0\r\nFoo: a\r\nBar: b\r\nBaz: c\r\n\r\n")); + $this->input->emit('data', ["0\r\nFoo: a\r\nBar: b\r\nBaz: c\r\n\r\n"]); } public function testLeadingZerosInInvalidChunk() @@ -507,7 +507,7 @@ public function testLeadingZerosInInvalidChunk() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableOnce()); - $this->input->emit('data', array("0000hello\r\n\r\n")); + $this->input->emit('data', ["0000hello\r\n\r\n"]); } public function testEmptyHeaderLeadsToError() @@ -517,7 +517,7 @@ public function testEmptyHeaderLeadsToError() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableOnce()); - $this->input->emit('data', array("\r\n\r\n")); + $this->input->emit('data', ["\r\n\r\n"]); } public function testEmptyHeaderAndFilledBodyLeadsToError() @@ -527,7 +527,7 @@ public function testEmptyHeaderAndFilledBodyLeadsToError() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableOnce()); - $this->input->emit('data', array("\r\nhello\r\n")); + $this->input->emit('data', ["\r\nhello\r\n"]); } public function testUpperCaseHexWillBeHandled() @@ -537,7 +537,7 @@ public function testUpperCaseHexWillBeHandled() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableNever()); - $this->input->emit('data', array("A\r\n0123456790\r\n")); + $this->input->emit('data', ["A\r\n0123456790\r\n"]); } public function testLowerCaseHexWillBeHandled() @@ -547,7 +547,7 @@ public function testLowerCaseHexWillBeHandled() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableNever()); - $this->input->emit('data', array("a\r\n0123456790\r\n")); + $this->input->emit('data', ["a\r\n0123456790\r\n"]); } public function testMixedUpperAndLowerCaseHexValuesInHeaderWillBeHandled() @@ -559,6 +559,6 @@ public function testMixedUpperAndLowerCaseHexValuesInHeaderWillBeHandled() $this->parser->on('end', $this->expectCallableNever()); $this->parser->on('close', $this->expectCallableNever()); - $this->input->emit('data', array("aA\r\n" . $data . "\r\n")); + $this->input->emit('data', ["aA\r\n" . $data . "\r\n"]); } } diff --git a/tests/Io/ChunkedEncoderTest.php b/tests/Io/ChunkedEncoderTest.php index 87ce44c4..96b97848 100644 --- a/tests/Io/ChunkedEncoderTest.php +++ b/tests/Io/ChunkedEncoderTest.php @@ -23,19 +23,19 @@ public function setUpChunkedStream() public function testChunked() { $this->chunkedStream->on('data', $this->expectCallableOnceWith("5\r\nhello\r\n")); - $this->input->emit('data', array('hello')); + $this->input->emit('data', ['hello']); } public function testEmptyString() { $this->chunkedStream->on('data', $this->expectCallableNever()); - $this->input->emit('data', array('')); + $this->input->emit('data', ['']); } public function testBiggerStringToCheckHexValue() { $this->chunkedStream->on('data', $this->expectCallableOnceWith("1a\r\nabcdefghijklmnopqrstuvwxyz\r\n")); - $this->input->emit('data', array('abcdefghijklmnopqrstuvwxyz')); + $this->input->emit('data', ['abcdefghijklmnopqrstuvwxyz']); } public function testHandleClose() @@ -52,7 +52,7 @@ public function testHandleError() $this->chunkedStream->on('error', $this->expectCallableOnce()); $this->chunkedStream->on('close', $this->expectCallableOnce()); - $this->input->emit('error', array(new \RuntimeException())); + $this->input->emit('error', [new \RuntimeException()]); $this->assertFalse($this->chunkedStream->isReadable()); } diff --git a/tests/Io/ClientConnectionManagerTest.php b/tests/Io/ClientConnectionManagerTest.php index 6aafa6db..88c5ff4f 100644 --- a/tests/Io/ClientConnectionManagerTest.php +++ b/tests/Io/ClientConnectionManagerTest.php @@ -7,6 +7,7 @@ use React\Promise\Promise; use React\Promise\PromiseInterface; use React\Tests\Http\TestCase; +use function React\Promise\resolve; class ClientConnectionManagerTest extends TestCase { @@ -100,51 +101,51 @@ public function testConnectReusesIdleConnectionFromPreviousKeepAliveCallWithoutU $streamHandler = null; $connectionToReuse->expects($this->exactly(3))->method('on')->withConsecutive( - array( + [ 'close', $this->callback(function ($cb) use (&$streamHandler) { $streamHandler = $cb; return true; }) - ), - array( + ], + [ 'data', $this->callback(function ($cb) use (&$streamHandler) { assert($streamHandler instanceof \Closure); return $cb === $streamHandler; }) - ), - array( + ], + [ 'error', $this->callback(function ($cb) use (&$streamHandler) { assert($streamHandler instanceof \Closure); return $cb === $streamHandler; }) - ) + ] ); $connectionToReuse->expects($this->exactly(3))->method('removeListener')->withConsecutive( - array( + [ 'close', $this->callback(function ($cb) use (&$streamHandler) { assert($streamHandler instanceof \Closure); return $cb === $streamHandler; }) - ), - array( + ], + [ 'data', $this->callback(function ($cb) use (&$streamHandler) { assert($streamHandler instanceof \Closure); return $cb === $streamHandler; }) - ), - array( + ], + [ 'error', $this->callback(function ($cb) use (&$streamHandler) { assert($streamHandler instanceof \Closure); return $cb === $streamHandler; }) - ) + ] ); $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); @@ -223,7 +224,7 @@ public function testConnectUsesConnectorForNewConnectionWhenPreviousConnectReuse $secondConnection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(\React\Promise\resolve($secondConnection)); + $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(resolve($secondConnection)); $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); @@ -297,7 +298,7 @@ public function testConnectUsesConnectorForNewConnectionWhenIdleConnectionFromPr $secondConnection->expects($this->never())->method('close'); $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(\React\Promise\resolve($secondConnection)); + $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(resolve($secondConnection)); $timerCallback = null; $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); @@ -334,34 +335,34 @@ public function testConnectUsesConnectorForNewConnectionWhenIdleConnectionFromPr $streamHandler = null; $firstConnection->expects($this->exactly(3))->method('on')->withConsecutive( - array( + [ 'close', $this->callback(function ($cb) use (&$streamHandler) { $streamHandler = $cb; return true; }) - ), - array( + ], + [ 'data', $this->callback(function ($cb) use (&$streamHandler) { assert($streamHandler instanceof \Closure); return $cb === $streamHandler; }) - ), - array( + ], + [ 'error', $this->callback(function ($cb) use (&$streamHandler) { assert($streamHandler instanceof \Closure); return $cb === $streamHandler; }) - ) + ] ); $secondConnection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $secondConnection->expects($this->never())->method('close'); $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(\React\Promise\resolve($secondConnection)); + $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(resolve($secondConnection)); $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); diff --git a/tests/Io/ClientRequestStreamTest.php b/tests/Io/ClientRequestStreamTest.php index 9a5373a1..0df92961 100644 --- a/tests/Io/ClientRequestStreamTest.php +++ b/tests/Io/ClientRequestStreamTest.php @@ -12,6 +12,8 @@ use React\Stream\DuplexResourceStream; use React\Stream\ReadableStreamInterface; use React\Tests\Http\TestCase; +use function React\Promise\reject; +use function React\Promise\resolve; class ClientRequestStreamTest extends TestCase { @@ -22,25 +24,25 @@ public function testRequestShouldUseConnectionManagerWithUriFromRequestAndBindTo $uri = new Uri('http://www.example.com'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->with($uri)->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->with($uri)->willReturn(resolve($connection)); $requestData = new Request('GET', $uri); $request = new ClientRequestStream($connectionManager, $requestData); $connection->expects($this->atLeast(5))->method('on')->withConsecutive( - array('drain', $this->identicalTo(array($request, 'handleDrain'))), - array('data', $this->identicalTo(array($request, 'handleData'))), - array('end', $this->identicalTo(array($request, 'handleEnd'))), - array('error', $this->identicalTo(array($request, 'handleError'))), - array('close', $this->identicalTo(array($request, 'close'))) + ['drain', $this->identicalTo([$request, 'handleDrain'])], + ['data', $this->identicalTo([$request, 'handleData'])], + ['end', $this->identicalTo([$request, 'handleEnd'])], + ['error', $this->identicalTo([$request, 'handleError'])], + ['close', $this->identicalTo([$request, 'close'])] ); $connection->expects($this->exactly(5))->method('removeListener')->withConsecutive( - array('drain', $this->identicalTo(array($request, 'handleDrain'))), - array('data', $this->identicalTo(array($request, 'handleData'))), - array('end', $this->identicalTo(array($request, 'handleEnd'))), - array('error', $this->identicalTo(array($request, 'handleError'))), - array('close', $this->identicalTo(array($request, 'close'))) + ['drain', $this->identicalTo([$request, 'handleDrain'])], + ['data', $this->identicalTo([$request, 'handleData'])], + ['end', $this->identicalTo([$request, 'handleEnd'])], + ['error', $this->identicalTo([$request, 'handleError'])], + ['close', $this->identicalTo([$request, 'close'])] ); $request->end(); @@ -54,7 +56,7 @@ public function testRequestShouldUseConnectionManagerWithUriFromRequestAndBindTo public function requestShouldEmitErrorIfConnectionFails() { $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\reject(new \RuntimeException())); + $connectionManager->expects($this->once())->method('connect')->willReturn(reject(new \RuntimeException())); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -71,7 +73,7 @@ public function requestShouldEmitErrorIfConnectionClosesBeforeResponseIsParsed() $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -89,7 +91,7 @@ public function requestShouldEmitErrorIfConnectionEmitsError() $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -105,44 +107,44 @@ public static function provideInvalidRequest() { $request = new Request('GET' , "http://localhost/"); - return array( - array( + return [ + [ $request->withMethod("INVA\r\nLID", '') - ), - array( + ], + [ $request->withRequestTarget('/inva lid') - ), - array( + ], + [ $request->withHeader('Invalid', "Yes\r\n") - ), - array( + ], + [ $request->withHeader('Invalid', "Yes\n") - ), - array( + ], + [ $request->withHeader('Invalid', "Yes\r") - ), - array( + ], + [ $request->withHeader("Inva\r\nlid", 'Yes') - ), - array( + ], + [ $request->withHeader("Inva\nlid", 'Yes') - ), - array( + ], + [ $request->withHeader("Inva\rlid", 'Yes') - ), - array( + ], + [ $request->withHeader('Inva Lid', 'Yes') - ), - array( + ], + [ $request->withHeader('Inva:Lid', 'Yes') - ), - array( + ], + [ $request->withHeader('Invalid', "Val\0ue") - ), - array( + ], + [ $request->withHeader("Inva\0lid", 'Yes') - ) - ); + ] + ]; } /** @@ -168,7 +170,7 @@ public function requestShouldEmitErrorIfRequestParserThrowsException() $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -187,9 +189,9 @@ public function getRequestShouldSendAGetRequest() $connection->expects($this->once())->method('write')->with("GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n"); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.0'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $request->end(); @@ -202,9 +204,9 @@ public function getHttp11RequestShouldSendAGetRequestWithGivenConnectionCloseHea $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->end(); @@ -217,9 +219,9 @@ public function getOptionsAsteriskShouldSendAOptionsRequestAsteriskRequestTarget $connection->expects($this->once())->method('write')->with("OPTIONS * HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('OPTIONS', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('OPTIONS', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $requestData = $requestData->withRequestTarget('*'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -233,16 +235,15 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsCon $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableNever()); - $body->on('end', $that->expectCallableOnce()); - $body->on('close', $that->expectCallableOnce()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableNever()); + $body->on('end', $this->expectCallableOnce()); + $body->on('close', $this->expectCallableOnce()); }); $request->on('close', $this->expectCallableOnce()); @@ -258,16 +259,15 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsSta $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableNever()); - $body->on('end', $that->expectCallableOnce()); - $body->on('close', $that->expectCallableOnce()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableNever()); + $body->on('end', $this->expectCallableOnce()); + $body->on('close', $this->expectCallableOnce()); }); $request->on('close', $this->expectCallableOnce()); @@ -283,16 +283,15 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsSta $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableNever()); - $body->on('end', $that->expectCallableOnce()); - $body->on('close', $that->expectCallableOnce()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableNever()); + $body->on('end', $this->expectCallableOnce()); + $body->on('close', $this->expectCallableOnce()); }); $request->on('close', $this->expectCallableOnce()); @@ -308,16 +307,15 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenRequestMethodIsHead $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('HEAD', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('HEAD', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableNever()); - $body->on('end', $that->expectCallableOnce()); - $body->on('close', $that->expectCallableOnce()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableNever()); + $body->on('end', $this->expectCallableOnce()); + $body->on('close', $this->expectCallableOnce()); }); $request->on('close', $this->expectCallableOnce()); @@ -333,16 +331,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenRespons $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableOnceWith('OK')); - $body->on('end', $that->expectCallableOnce()); - $body->on('close', $that->expectCallableOnce()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableOnceWith('OK')); + $body->on('end', $this->expectCallableOnce()); + $body->on('close', $this->expectCallableOnce()); }); $request->on('close', $this->expectCallableOnce()); @@ -358,16 +355,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithoutDataWhenResp $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableNever()); - $body->on('end', $that->expectCallableNever()); - $body->on('close', $that->expectCallableNever()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableNever()); + $body->on('end', $this->expectCallableNever()); + $body->on('close', $this->expectCallableNever()); }); $request->on('close', $this->expectCallableNever()); @@ -383,16 +379,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndW $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableOnce('O')); - $body->on('end', $that->expectCallableNever()); - $body->on('close', $that->expectCallableNever()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableOnce('O')); + $body->on('end', $this->expectCallableNever()); + $body->on('close', $this->expectCallableNever()); }); $request->on('close', $this->expectCallableNever()); @@ -408,16 +403,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenRespons $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableOnceWith('OK')); - $body->on('end', $that->expectCallableOnce()); - $body->on('close', $that->expectCallableOnce()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableOnceWith('OK')); + $body->on('end', $this->expectCallableOnce()); + $body->on('close', $this->expectCallableOnce()); }); $request->on('close', $this->expectCallableOnce()); @@ -433,16 +427,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithoutDataWhenResp $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableNever()); - $body->on('end', $that->expectCallableNever()); - $body->on('close', $that->expectCallableNever()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableNever()); + $body->on('end', $this->expectCallableNever()); + $body->on('close', $this->expectCallableNever()); }); $request->on('close', $this->expectCallableNever()); @@ -458,16 +451,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndW $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableOnceWith('O')); - $body->on('end', $that->expectCallableNever()); - $body->on('close', $that->expectCallableNever()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableOnceWith('O')); + $body->on('end', $this->expectCallableNever()); + $body->on('close', $this->expectCallableNever()); }); $request->on('close', $this->expectCallableNever()); @@ -483,16 +475,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndW $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableOnce('O')); - $body->on('end', $that->expectCallableNever()); - $body->on('close', $that->expectCallableNever()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableOnce('O')); + $body->on('end', $this->expectCallableNever()); + $body->on('close', $this->expectCallableNever()); }); $request->on('close', $this->expectCallableNever()); @@ -520,16 +511,15 @@ public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenRespons })); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'close'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'close'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); - $that = $this; - $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($that) { - $body->on('data', $that->expectCallableOnce('OK')); - $body->on('end', $that->expectCallableOnce()); - $body->on('close', $that->expectCallableOnce()); + $request->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) { + $body->on('data', $this->expectCallableOnce('OK')); + $body->on('end', $this->expectCallableOnce()); + $body->on('close', $this->expectCallableOnce()); }); $request->on('close', $this->expectCallableOnce()); @@ -549,10 +539,10 @@ public function testStreamShouldReuseConnectionForHttp11ByDefault() $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $connectionManager->expects($this->once())->method('keepAlive')->with(new Uri('http://www.example.com'), $connection); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -570,9 +560,9 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsConnection $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -590,9 +580,9 @@ public function testStreamShouldNotReuseConnectionWhenRequestContainsConnectionC $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'FOO, CLOSE, BAR'), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'FOO, CLOSE, BAR'], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -610,9 +600,9 @@ public function testStreamShouldNotReuseConnectionForHttp10ByDefault() $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.0'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -630,10 +620,10 @@ public function testStreamShouldReuseConnectionForHttp10WhenBothRequestAndRespon $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $connectionManager->expects($this->once())->method('keepAlive')->with(new Uri('http://www.example.com'), $connection); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'keep-alive'), '', '1.0'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'keep-alive'], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -651,10 +641,10 @@ public function testStreamShouldReuseConnectionForHttp10WhenBothRequestAndRespon $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $connectionManager->expects($this->once())->method('keepAlive')->with(new Uri('http://www.example.com'), $connection); - $requestData = new Request('GET', 'http://www.example.com', array('Connection' => 'FOO, KEEP-ALIVE, BAR'), '', '1.0'); + $requestData = new Request('GET', 'http://www.example.com', ['Connection' => 'FOO, KEEP-ALIVE, BAR'], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -684,9 +674,9 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsNoContentL })); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -719,9 +709,9 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsContentLen })); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -742,10 +732,10 @@ public function testStreamShouldReuseConnectionWhenResponseContainsTransferEncod $connection->expects($this->never())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $connectionManager->expects($this->once())->method('keepAlive')->with(new Uri('http://www.example.com'), $connection); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -763,9 +753,9 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsTransferEn $connection->expects($this->once())->method('close'); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('GET', 'http://www.example.com', array(), '', '1.1'); + $requestData = new Request('GET', 'http://www.example.com', [], '', '1.1'); $request = new ClientRequestStream($connectionManager, $requestData); $request->on('close', $this->expectCallableOnce()); @@ -782,9 +772,9 @@ public function postRequestShouldSendAPostRequest() $connection->expects($this->once())->method('write')->with($this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsome post data$#")); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('POST', 'http://www.example.com', array(), '', '1.0'); + $requestData = new Request('POST', 'http://www.example.com', [], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $request->end('some post data'); @@ -799,15 +789,15 @@ public function writeWithAPostRequestShouldSendToTheStream() { $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connection->expects($this->exactly(3))->method('write')->withConsecutive( - array($this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsome$#")), - array($this->identicalTo("post")), - array($this->identicalTo("data")) + [$this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsome$#")], + [$this->identicalTo("post")], + [$this->identicalTo("data")] ); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('POST', 'http://www.example.com', array(), '', '1.0'); + $requestData = new Request('POST', 'http://www.example.com', [], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $request->write("some"); @@ -824,8 +814,8 @@ public function writeWithAPostRequestShouldSendBodyAfterHeadersAndEmitDrainEvent { $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connection->expects($this->exactly(2))->method('write')->withConsecutive( - array($this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsomepost$#")), - array($this->identicalTo("data")) + [$this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsomepost$#")], + [$this->identicalTo("data")] )->willReturn( true ); @@ -834,7 +824,7 @@ public function writeWithAPostRequestShouldSendBodyAfterHeadersAndEmitDrainEvent $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); $connectionManager->expects($this->once())->method('connect')->willReturn($deferred->promise()); - $requestData = new Request('POST', 'http://www.example.com', array(), '', '1.0'); + $requestData = new Request('POST', 'http://www.example.com', [], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $this->assertFalse($request->write("some")); @@ -858,12 +848,12 @@ public function writeWithAPostRequestShouldForwardDrainEventIfFirstChunkExceedsB { $connection = $this->getMockBuilder('React\Socket\Connection') ->disableOriginalConstructor() - ->setMethods(array('write')) + ->setMethods(['write']) ->getMock(); $connection->expects($this->exactly(2))->method('write')->withConsecutive( - array($this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsomepost$#")), - array($this->identicalTo("data")) + [$this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsomepost$#")], + [$this->identicalTo("data")] )->willReturn( false ); @@ -872,7 +862,7 @@ public function writeWithAPostRequestShouldForwardDrainEventIfFirstChunkExceedsB $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); $connectionManager->expects($this->once())->method('connect')->willReturn($deferred->promise()); - $requestData = new Request('POST', 'http://www.example.com', array(), '', '1.0'); + $requestData = new Request('POST', 'http://www.example.com', [], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $this->assertFalse($request->write("some")); @@ -897,15 +887,15 @@ public function pipeShouldPipeDataIntoTheRequestBody() { $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connection->expects($this->exactly(3))->method('write')->withConsecutive( - array($this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsome$#")), - array($this->identicalTo("post")), - array($this->identicalTo("data")) + [$this->matchesRegularExpression("#^POST / HTTP/1\.0\r\nHost: www.example.com\r\n\r\nsome$#")], + [$this->identicalTo("post")], + [$this->identicalTo("data")] ); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); - $requestData = new Request('POST', 'http://www.example.com', array(), '', '1.0'); + $requestData = new Request('POST', 'http://www.example.com', [], '', '1.0'); $request = new ClientRequestStream($connectionManager, $requestData); $loop = $this @@ -916,9 +906,9 @@ public function pipeShouldPipeDataIntoTheRequestBody() $stream = new DuplexResourceStream($stream, $loop); $stream->pipe($request); - $stream->emit('data', array('some')); - $stream->emit('data', array('post')); - $stream->emit('data', array('data')); + $stream->emit('data', ['some']); + $stream->emit('data', ['post']); + $stream->emit('data', ['data']); $request->handleData("HTTP/1.0 200 OK\r\n"); $request->handleData("Content-Type: text/plain\r\n"); @@ -1044,7 +1034,7 @@ public function multivalueHeader() $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); diff --git a/tests/Io/CloseProtectionStreamTest.php b/tests/Io/CloseProtectionStreamTest.php index 8490daff..4f3d35ca 100644 --- a/tests/Io/CloseProtectionStreamTest.php +++ b/tests/Io/CloseProtectionStreamTest.php @@ -27,7 +27,7 @@ public function testErrorWontCloseStream() $protection->on('error', $this->expectCallableOnce()); $protection->on('close', $this->expectCallableNever()); - $input->emit('error', array(new \RuntimeException())); + $input->emit('error', [new \RuntimeException()]); $this->assertTrue($protection->isReadable()); $this->assertTrue($input->isReadable()); @@ -91,7 +91,7 @@ public function testStopEmittingDataAfterClose() $protection->close(); - $input->emit('data', array('hello')); + $input->emit('data', ['hello']); $this->assertFalse($protection->isReadable()); $this->assertTrue($input->isReadable()); @@ -108,7 +108,7 @@ public function testErrorIsNeverCalledAfterClose() $protection->close(); - $input->emit('error', array(new \Exception())); + $input->emit('error', [new \Exception()]); $this->assertFalse($protection->isReadable()); $this->assertTrue($input->isReadable()); @@ -124,7 +124,7 @@ public function testEndWontBeEmittedAfterClose() $protection->close(); - $input->emit('end', array()); + $input->emit('end', []); $this->assertFalse($protection->isReadable()); $this->assertTrue($input->isReadable()); diff --git a/tests/Io/EmptyBodyStreamTest.php b/tests/Io/EmptyBodyStreamTest.php index 8430239d..3633ff81 100644 --- a/tests/Io/EmptyBodyStreamTest.php +++ b/tests/Io/EmptyBodyStreamTest.php @@ -65,7 +65,7 @@ public function testCloseTwiceEmitsCloseEventAndClearsListeners() $this->bodyStream->close(); $this->bodyStream->close(); - $this->assertEquals(array(), $this->bodyStream->listeners('close')); + $this->assertEquals([], $this->bodyStream->listeners('close')); } public function testTell() @@ -104,7 +104,7 @@ public function testGetContentsReturnsEmpy() public function testGetMetaDataWithoutKeyReturnsEmptyArray() { - $this->assertSame(array(), $this->bodyStream->getMetadata()); + $this->assertSame([], $this->bodyStream->getMetadata()); } public function testGetMetaDataWithKeyReturnsNull() diff --git a/tests/Io/HttpBodyStreamTest.php b/tests/Io/HttpBodyStreamTest.php index db21dcf8..1fd269b1 100644 --- a/tests/Io/HttpBodyStreamTest.php +++ b/tests/Io/HttpBodyStreamTest.php @@ -22,8 +22,8 @@ public function setUpBodyStream() public function testDataEmit() { - $this->bodyStream->on('data', $this->expectCallableOnce(array("hello"))); - $this->input->emit('data', array("hello")); + $this->bodyStream->on('data', $this->expectCallableOnce(["hello"])); + $this->input->emit('data', ["hello"]); } public function testPauseStream() @@ -58,7 +58,7 @@ public function testHandleClose() $this->bodyStream->on('close', $this->expectCallableOnce()); $this->input->close(); - $this->input->emit('end', array()); + $this->input->emit('end', []); $this->assertFalse($this->bodyStream->isReadable()); } @@ -67,11 +67,11 @@ public function testStopDataEmittingAfterClose() { $bodyStream = new HttpBodyStream($this->input, null); $bodyStream->on('close', $this->expectCallableOnce()); - $this->bodyStream->on('data', $this->expectCallableOnce(array("hello"))); + $this->bodyStream->on('data', $this->expectCallableOnce(["hello"])); - $this->input->emit('data', array("hello")); + $this->input->emit('data', ["hello"]); $bodyStream->close(); - $this->input->emit('data', array("world")); + $this->input->emit('data', ["world"]); } public function testHandleError() @@ -79,7 +79,7 @@ public function testHandleError() $this->bodyStream->on('error', $this->expectCallableOnce()); $this->bodyStream->on('close', $this->expectCallableOnce()); - $this->input->emit('error', array(new \RuntimeException())); + $this->input->emit('error', [new \RuntimeException()]); $this->assertFalse($this->bodyStream->isReadable()); } diff --git a/tests/Io/IniUtilTest.php b/tests/Io/IniUtilTest.php index 155c6ed2..0bc9a249 100644 --- a/tests/Io/IniUtilTest.php +++ b/tests/Io/IniUtilTest.php @@ -9,40 +9,40 @@ class IniUtilTest extends TestCase { public function provideIniSizes() { - return array( - array( + return [ + [ '1', 1, - ), - array( + ], + [ '10', 10, - ), - array( + ], + [ '1024', 1024, - ), - array( + ], + [ '1K', 1024, - ), - array( + ], + [ '1.5M', 1572864, - ), - array( + ], + [ '64M', 67108864, - ), - array( + ], + [ '8G', 8589934592, - ), - array( + ], + [ '1T', 1099511627776, - ), - ); + ], + ]; } /** @@ -60,14 +60,14 @@ public function testIniSizeToBytesWithInvalidSuffixReturnsNumberWithoutSuffix() public function provideInvalidInputIniSizeToBytes() { - return array( - array('-1G'), - array('0G'), - array('foo'), - array('fooK'), - array('1ooL'), - array('1ooL'), - ); + return [ + ['-1G'], + ['0G'], + ['foo'], + ['fooK'], + ['1ooL'], + ['1ooL'], + ]; } /** diff --git a/tests/Io/LengthLimitedStreamTest.php b/tests/Io/LengthLimitedStreamTest.php index b415269c..f1761a0b 100644 --- a/tests/Io/LengthLimitedStreamTest.php +++ b/tests/Io/LengthLimitedStreamTest.php @@ -24,7 +24,7 @@ public function testSimpleChunk() $stream = new LengthLimitedStream($this->input, 5); $stream->on('data', $this->expectCallableOnceWith('hello')); $stream->on('end', $this->expectCallableOnce()); - $this->input->emit('data', array("hello world")); + $this->input->emit('data', ["hello world"]); } public function testInputStreamKeepsEmitting() @@ -33,9 +33,9 @@ public function testInputStreamKeepsEmitting() $stream->on('data', $this->expectCallableOnceWith('hello')); $stream->on('end', $this->expectCallableOnce()); - $this->input->emit('data', array("hello world")); - $this->input->emit('data', array("world")); - $this->input->emit('data', array("world")); + $this->input->emit('data', ["hello world"]); + $this->input->emit('data', ["world"]); + $this->input->emit('data', ["world"]); } public function testZeroLengthInContentLengthWillIgnoreEmittedDataEvents() @@ -43,7 +43,7 @@ public function testZeroLengthInContentLengthWillIgnoreEmittedDataEvents() $stream = new LengthLimitedStream($this->input, 0); $stream->on('data', $this->expectCallableNever()); $stream->on('end', $this->expectCallableOnce()); - $this->input->emit('data', array("hello world")); + $this->input->emit('data', ["hello world"]); } public function testHandleError() @@ -52,7 +52,7 @@ public function testHandleError() $stream->on('error', $this->expectCallableOnce()); $stream->on('close', $this->expectCallableOnce()); - $this->input->emit('error', array(new \RuntimeException())); + $this->input->emit('error', [new \RuntimeException()]); $this->assertFalse($stream->isReadable()); } @@ -92,7 +92,7 @@ public function testHandleClose() $stream->on('close', $this->expectCallableOnce()); $this->input->close(); - $this->input->emit('end', array()); + $this->input->emit('end', []); $this->assertFalse($stream->isReadable()); } diff --git a/tests/Io/MiddlewareRunnerTest.php b/tests/Io/MiddlewareRunnerTest.php index e742ef6d..e46039bf 100644 --- a/tests/Io/MiddlewareRunnerTest.php +++ b/tests/Io/MiddlewareRunnerTest.php @@ -8,17 +8,19 @@ use React\Http\Io\MiddlewareRunner; use React\Http\Message\Response; use React\Http\Message\ServerRequest; -use React\Promise; +use React\Promise\Promise; use React\Promise\PromiseInterface; use React\Tests\Http\Middleware\ProcessStack; use React\Tests\Http\TestCase; +use function React\Async\await; +use function React\Promise\reject; final class MiddlewareRunnerTest extends TestCase { public function testEmptyMiddlewareStackThrowsException() { $request = new ServerRequest('GET', 'https://example.com/'); - $middlewares = array(); + $middlewares = []; $middlewareStack = new MiddlewareRunner($middlewares); $this->setExpectedException('RuntimeException', 'No middleware to run'); @@ -28,7 +30,7 @@ public function testEmptyMiddlewareStackThrowsException() public function testMiddlewareHandlerReceivesTwoArguments() { $args = null; - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (ServerRequestInterface $request, $next) use (&$args) { $args = func_num_args(); return $next($request); @@ -36,7 +38,7 @@ function (ServerRequestInterface $request, $next) use (&$args) { function (ServerRequestInterface $request) { return null; } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); @@ -48,12 +50,12 @@ function (ServerRequestInterface $request) { public function testFinalHandlerReceivesOneArgument() { $args = null; - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (ServerRequestInterface $request) use (&$args) { $args = func_num_args(); return null; } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); @@ -64,11 +66,11 @@ function (ServerRequestInterface $request) use (&$args) { public function testThrowsIfHandlerThrowsException() { - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (ServerRequestInterface $request) { throw new \RuntimeException('hello'); } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); @@ -78,11 +80,11 @@ function (ServerRequestInterface $request) { public function testThrowsIfHandlerThrowsThrowable() { - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (ServerRequestInterface $request) { throw new \Error('hello'); } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); @@ -99,42 +101,42 @@ public function provideProcessStackMiddlewares() $responseMiddleware = function () { return new Response(200); }; - return array( - array( - array( + return [ + [ + [ $processStackA, $responseMiddleware, - ), + ], 1, - ), - array( - array( + ], + [ + [ $processStackB, $processStackB, $responseMiddleware, - ), + ], 2, - ), - array( - array( + ], + [ + [ $processStackC, $processStackC, $processStackC, $responseMiddleware, - ), + ], 3, - ), - array( - array( + ], + [ + [ $processStackD, $processStackD, $processStackD, $processStackD, $responseMiddleware, - ), + ], 4, - ), - ); + ], + ]; } /** @@ -156,7 +158,7 @@ public function testProcessStack(array $middlewares, $expectedCallCount) $response = $middlewareStack($request); $this->assertTrue($response instanceof PromiseInterface); - $response = \React\Async\await($response); + $response = await($response); $this->assertTrue($response instanceof ResponseInterface); $this->assertSame(200, $response->getStatusCode()); @@ -172,18 +174,18 @@ public function testProcessStack(array $middlewares, $expectedCallCount) public function provideErrorHandler() { - return array( - array( + return [ + [ function (\Exception $e) { throw $e; } - ), - array( + ], + [ function (\Exception $e) { - return Promise\reject($e); + return reject($e); } - ) - ); + ] + ]; } /** @@ -195,7 +197,7 @@ public function testNextCanBeRunMoreThanOnceWithoutCorruptingTheMiddlewareStack( $retryCalled = 0; $error = null; $retry = function ($request, $next) use (&$error, &$retryCalled) { - $promise = new \React\Promise\Promise(function ($resolve) use ($request, $next) { + $promise = new Promise(function ($resolve) use ($request, $next) { $resolve($next($request)); }); @@ -209,7 +211,7 @@ public function testNextCanBeRunMoreThanOnceWithoutCorruptingTheMiddlewareStack( $response = new Response(); $called = 0; - $runner = new MiddlewareRunner(array( + $runner = new MiddlewareRunner([ $retry, function () use ($errorHandler, &$called, $response, $exception) { $called++; @@ -219,11 +221,11 @@ function () use ($errorHandler, &$called, $response, $exception) { return $response; } - )); + ]); $request = new ServerRequest('GET', 'https://example.com/'); - $this->assertSame($response, \React\Async\await($runner($request))); + $this->assertSame($response, await($runner($request))); $this->assertSame(1, $retryCalled); $this->assertSame(2, $called); $this->assertSame($exception, $error); @@ -231,15 +233,15 @@ function () use ($errorHandler, &$called, $response, $exception) { public function testMultipleRunsInvokeAllMiddlewareInCorrectOrder() { - $requests = array( + $requests = [ new ServerRequest('GET', 'https://example.com/1'), new ServerRequest('GET', 'https://example.com/2'), new ServerRequest('GET', 'https://example.com/3') - ); + ]; - $receivedRequests = array(); + $receivedRequests = []; - $middlewareRunner = new MiddlewareRunner(array( + $middlewareRunner = new MiddlewareRunner([ function (ServerRequestInterface $request, $next) use (&$receivedRequests) { $receivedRequests[] = 'middleware1: ' . $request->getUri(); return $next($request); @@ -250,16 +252,16 @@ function (ServerRequestInterface $request, $next) use (&$receivedRequests) { }, function (ServerRequestInterface $request) use (&$receivedRequests) { $receivedRequests[] = 'middleware3: ' . $request->getUri(); - return new \React\Promise\Promise(function () { }); + return new Promise(function () { }); } - )); + ]); foreach ($requests as $request) { $middlewareRunner($request); } $this->assertEquals( - array( + [ 'middleware1: https://example.com/1', 'middleware2: https://example.com/1', 'middleware3: https://example.com/1', @@ -269,20 +271,20 @@ function (ServerRequestInterface $request) use (&$receivedRequests) { 'middleware1: https://example.com/3', 'middleware2: https://example.com/3', 'middleware3: https://example.com/3' - ), + ], $receivedRequests ); } public function provideUncommonMiddlewareArrayFormats() { - return array( - array( + return [ + [ function () { $sequence = ''; // Numeric index gap - return array( + return [ 0 => function (ServerRequestInterface $request, $next) use (&$sequence) { $sequence .= 'A'; @@ -294,18 +296,18 @@ function () { return $next($request); }, 3 => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); + return new Response(200, [], $sequence . 'C'); }, - ); + ]; }, 'ABC', - ), - array( + ], + [ function () { $sequence = ''; // Reversed numeric indexes - return array( + return [ 2 => function (ServerRequestInterface $request, $next) use (&$sequence) { $sequence .= 'A'; @@ -317,18 +319,18 @@ function () { return $next($request); }, 0 => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); + return new Response(200, [], $sequence . 'C'); }, - ); + ]; }, 'ABC', - ), - array( + ], + [ function () { $sequence = ''; // Associative array - return array( + return [ 'middleware1' => function (ServerRequestInterface $request, $next) use (&$sequence) { $sequence .= 'A'; @@ -340,18 +342,18 @@ function () { return $next($request); }, 'middleware3' => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); + return new Response(200, [], $sequence . 'C'); }, - ); + ]; }, 'ABC', - ), - array( + ], + [ function () { $sequence = ''; // Associative array with empty or trimmable string keys - return array( + return [ '' => function (ServerRequestInterface $request, $next) use (&$sequence) { $sequence .= 'A'; @@ -363,18 +365,18 @@ function () { return $next($request); }, ' ' => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); + return new Response(200, [], $sequence . 'C'); }, - ); + ]; }, 'ABC', - ), - array( + ], + [ function () { $sequence = ''; // Mixed array keys - return array( + return [ '' => function (ServerRequestInterface $request, $next) use (&$sequence) { $sequence .= 'A'; @@ -391,13 +393,13 @@ function () { return $next($request); }, 2 => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'D'); + return new Response(200, [], $sequence . 'D'); }, - ); + ]; }, 'ABCD', - ), - ); + ], + ]; } /** @@ -417,7 +419,7 @@ public function testUncommonMiddlewareArrayFormats($middlewareFactory, $expected public function testPendingNextRequestHandlersCanBeCalledConcurrently() { $called = 0; - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (RequestInterface $request, $next) { $first = $next($request); $second = $next($request); @@ -427,9 +429,9 @@ function (RequestInterface $request, $next) { function (RequestInterface $request) use (&$called) { ++$called; - return new Promise\Promise(function () { }); + return new Promise(function () { }); } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); @@ -442,7 +444,7 @@ function (RequestInterface $request) use (&$called) { public function testCancelPendingNextHandler() { $once = $this->expectCallableOnce(); - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (RequestInterface $request, $next) { $ret = $next($request); $ret->cancel(); @@ -450,9 +452,9 @@ function (RequestInterface $request, $next) { return $ret; }, function (RequestInterface $request) use ($once) { - return new Promise\Promise(function () { }, $once); + return new Promise(function () { }, $once); } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); @@ -462,14 +464,14 @@ function (RequestInterface $request) use ($once) { public function testCancelResultingPromiseWillCancelPendingNextHandler() { $once = $this->expectCallableOnce(); - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (RequestInterface $request, $next) { return $next($request); }, function (RequestInterface $request) use ($once) { - return new Promise\Promise(function () { }, $once); + return new Promise(function () { }, $once); } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); diff --git a/tests/Io/MultipartParserTest.php b/tests/Io/MultipartParserTest.php index 7f1ec667..ba439760 100644 --- a/tests/Io/MultipartParserTest.php +++ b/tests/Io/MultipartParserTest.php @@ -22,9 +22,9 @@ public function testDoesNotParseWithoutMultipartFormDataContentType() $data .= "second\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data', - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -47,21 +47,21 @@ public function testPostKey() $data .= "second\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'users' => array( + [ + 'users' => [ 'one' => 'single', 'two' => 'second', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); } @@ -80,21 +80,21 @@ public function testPostWithQuotationMarkEncapsulatedBoundary() $data .= "second\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary="' . $boundary . '"', - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'users' => array( + [ + 'users' => [ 'one' => 'single', 'two' => 'second', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); } @@ -113,21 +113,21 @@ public function testPostFormDataNamesWithoutQuotationMark() $data .= "second\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary="' . $boundary . '"', - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'users' => array( + [ + 'users' => [ 'one' => 'single', 'two' => 'second', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); } @@ -146,18 +146,18 @@ public function testPostStringOverwritesMap() $data .= "2\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( + [ 'users' => '2' - ), + ], $parsedRequest->getParsedBody() ); } @@ -176,20 +176,20 @@ public function testPostMapOverwritesString() $data .= "2\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'users' => array( + [ + 'users' => [ 'two' => '2', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); } @@ -208,20 +208,20 @@ public function testPostVectorOverwritesString() $data .= "2\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'users' => array( + [ + 'users' => [ '2', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); } @@ -240,25 +240,25 @@ public function testPostDeeplyNestedArray() $data .= "2\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'users' => array( - array( + [ + 'users' => [ + [ '1' - ), - array( + ], + [ '2' - ) - ), - ), + ] + ], + ], $parsedRequest->getParsedBody() ); } @@ -273,18 +273,18 @@ public function testEmptyPostValue() $data .= "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( + [ 'key' => '' - ), + ], $parsedRequest->getParsedBody() ); } @@ -299,18 +299,18 @@ public function testEmptyPostKey() $data .= "value\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( + [ '' => 'value' - ), + ], $parsedRequest->getParsedBody() ); } @@ -325,22 +325,22 @@ public function testNestedPostKeyAssoc() $data .= "value\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'a' => array( - 'b' => array( + [ + 'a' => [ + 'b' => [ 'c' => 'value' - ) - ) - ), + ] + ] + ], $parsedRequest->getParsedBody() ); } @@ -355,22 +355,22 @@ public function testNestedPostKeyVector() $data .= "value\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( - 'a' => array( - array( + [ + 'a' => [ + [ 'value' - ) - ) - ), + ] + ] + ], $parsedRequest->getParsedBody() ); } @@ -436,25 +436,25 @@ public function testFileUpload() $data .= "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertSame( - array( + [ 'MAX_FILE_SIZE' => '12000', - 'users' => array( + 'users' => [ 'one' => 'single', 'two' => 'second', 0 => 'first in array', 1 => 'second in array', - ), + ], 'user' => 'single', 'user2' => 'second', - ), + ], $parsedRequest->getParsedBody() ); @@ -491,18 +491,18 @@ public function testInvalidDoubleContentDispositionUsesLast() $data .= "value\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); $this->assertEmpty($parsedRequest->getUploadedFiles()); $this->assertSame( - array( + [ 'key' => 'value' - ), + ], $parsedRequest->getParsedBody() ); } @@ -517,9 +517,9 @@ public function testInvalidMissingNewlineAfterValueWillBeIgnored() $data .= "value"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -537,9 +537,9 @@ public function testInvalidMissingValueWillBeIgnored() $data .= "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -555,9 +555,9 @@ public function testInvalidMissingValueAndEndBoundaryWillBeIgnored() $data = "--$boundary\r\n"; $data .= "Content-Disposition: form-data; name=\"key\"\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -576,9 +576,9 @@ public function testInvalidContentDispositionMissingWillBeIgnored() $data .= "hello\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -597,9 +597,9 @@ public function testInvalidContentDispositionMissingValueWillBeIgnored() $data .= "value\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -618,9 +618,9 @@ public function testInvalidContentDispositionWithoutNameWillBeIgnored() $data .= "value\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -638,9 +638,9 @@ public function testInvalidMissingEndBoundaryWillBeIgnored() $data .= "\r\n"; $data .= "value\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -662,9 +662,9 @@ public function testInvalidUploadFileWithoutContentTypeUsesNullValue() $data .= "world\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -697,9 +697,9 @@ public function testInvalidUploadFileWithoutMultipleContentTypeUsesLastValue() $data .= "world\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -731,9 +731,9 @@ public function testUploadEmptyFile() $data .= "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -765,9 +765,9 @@ public function testUploadTooLargeFile() $data .= "world\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(4); $parsedRequest = $parser->parse($request); @@ -798,9 +798,9 @@ public function testUploadTooLargeFileWithIniLikeSize() $data .= str_repeat('world', 1024) . "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser('1K'); $parsedRequest = $parser->parse($request); @@ -831,9 +831,9 @@ public function testUploadNoFile() $data .= "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -869,9 +869,9 @@ public function testUploadTooManyFilesReturnsTruncatedList() $data .= "world\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(100, 1); $parsedRequest = $parser->parse($request); @@ -910,9 +910,9 @@ public function testUploadTooManyFilesIgnoresEmptyFilesAndIncludesThemDespiteTru $data .= "world\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(100, 1); $parsedRequest = $parser->parse($request); @@ -953,9 +953,9 @@ public function testPostMaxFileSize() $data .= "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -1008,9 +1008,9 @@ public function testPostMaxFileSizeIgnoredByFilesComingBeforeIt() $data .= "\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); $parsedRequest = $parser->parse($request); @@ -1040,9 +1040,9 @@ public function testWeOnlyParseTheAmountOfMultiPartChunksWeConfigured() $data .= str_repeat($chunk, $chunkCount); $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( + $request = new ServerRequest('POST', 'http://example.com/', [ 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + ], $data, 1.1); $parser = new MultipartParser(); diff --git a/tests/Io/PauseBufferStreamTest.php b/tests/Io/PauseBufferStreamTest.php index a9678a78..05bf3ee3 100644 --- a/tests/Io/PauseBufferStreamTest.php +++ b/tests/Io/PauseBufferStreamTest.php @@ -156,7 +156,7 @@ public function testErrorEventWillBePassedThroughAsIs() $stream->on('error', $this->expectCallableOnce()); $stream->on('close', $this->expectCallableOnce()); - $input->emit('error', array(new \RuntimeException())); + $input->emit('error', [new \RuntimeException()]); } public function testPausedStreamWillNotPassThroughErrorEvent() @@ -167,7 +167,7 @@ public function testPausedStreamWillNotPassThroughErrorEvent() $stream->pause(); $stream->on('error', $this->expectCallableNever()); $stream->on('close', $this->expectCallableNever()); - $input->emit('error', array(new \RuntimeException())); + $input->emit('error', [new \RuntimeException()]); } public function testPausedStreamWillPassThroughErrorEventOnResume() @@ -176,7 +176,7 @@ public function testPausedStreamWillPassThroughErrorEventOnResume() $stream = new PauseBufferStream($input); $stream->pause(); - $input->emit('error', array(new \RuntimeException())); + $input->emit('error', [new \RuntimeException()]); $stream->on('error', $this->expectCallableOnce()); $stream->on('close', $this->expectCallableOnce()); @@ -191,7 +191,7 @@ public function testPausedStreamWillNotPassThroughErrorEventOnExplicitClose() $stream->pause(); $stream->on('error', $this->expectCallableNever()); $stream->on('close', $this->expectCallableOnce()); - $input->emit('error', array(new \RuntimeException())); + $input->emit('error', [new \RuntimeException()]); $stream->close(); } diff --git a/tests/Io/ReadableBodyStreamTest.php b/tests/Io/ReadableBodyStreamTest.php index d89199ff..8ece6791 100644 --- a/tests/Io/ReadableBodyStreamTest.php +++ b/tests/Io/ReadableBodyStreamTest.php @@ -250,6 +250,6 @@ public function testPointlessGetMetadataReturnsNullWhenKeyIsGiven() public function testPointlessGetMetadataReturnsEmptyArrayWhenNoKeyIsGiven() { - $this->assertEquals(array(), $this->stream->getMetadata()); + $this->assertEquals([], $this->stream->getMetadata()); } } diff --git a/tests/Io/RequestHeaderParserTest.php b/tests/Io/RequestHeaderParserTest.php index 1ed994b7..d15d4e7f 100644 --- a/tests/Io/RequestHeaderParserTest.php +++ b/tests/Io/RequestHeaderParserTest.php @@ -19,14 +19,14 @@ public function testSplitShouldHappenOnDoubleCrlf() $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\n")); - $connection->emit('data', array("Host: example.com:80\r\n")); - $connection->emit('data', array("Connection: close\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\n"]); + $connection->emit('data', ["Host: example.com:80\r\n"]); + $connection->emit('data', ["Connection: close\r\n"]); $parser->removeAllListeners(); $parser->on('headers', $this->expectCallableOnce()); - $connection->emit('data', array("\r\n")); + $connection->emit('data', ["\r\n"]); } public function testFeedInOneGo() @@ -40,7 +40,7 @@ public function testFeedInOneGo() $parser->handle($connection); $data = $this->createGetRequest(); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); } public function testFeedTwoRequestsOnSeparateConnections() @@ -60,8 +60,8 @@ public function testFeedTwoRequestsOnSeparateConnections() $parser->handle($connection2); $data = $this->createGetRequest(); - $connection1->emit('data', array($data)); - $connection2->emit('data', array($data)); + $connection1->emit('data', [$data]); + $connection2->emit('data', [$data]); $this->assertEquals(2, $called); } @@ -83,13 +83,13 @@ public function testHeadersEventShouldEmitRequestAndConnection() $parser->handle($connection); $data = $this->createGetRequest(); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $request); $this->assertSame('GET', $request->getMethod()); $this->assertEquals('http://example.com/', $request->getUri()); $this->assertSame('1.1', $request->getProtocolVersion()); - $this->assertSame(array('Host' => array('example.com'), 'Connection' => array('close')), $request->getHeaders()); + $this->assertSame(['Host' => ['example.com'], 'Connection' => ['close']], $request->getHeaders()); $this->assertSame($connection, $conn); } @@ -101,10 +101,9 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitEndForStreamingB $parser = new RequestHeaderParser($clock); $ended = false; - $that = $this; - $parser->on('headers', function (ServerRequestInterface $request) use (&$ended, $that) { + $parser->on('headers', function (ServerRequestInterface $request) use (&$ended) { $body = $request->getBody(); - $that->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); $body->on('end', function () use (&$ended) { $ended = true; @@ -115,7 +114,7 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitEndForStreamingB $parser->handle($connection); $data = "GET / HTTP/1.0\r\n\r\n"; - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertTrue($ended); } @@ -127,10 +126,9 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyDat $parser = new RequestHeaderParser($clock); $buffer = ''; - $that = $this; - $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer, $that) { + $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer) { $body = $request->getBody(); - $that->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; @@ -145,7 +143,7 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyDat $data = "POST / HTTP/1.0\r\nContent-Length: 11\r\n\r\n"; $data .= 'RANDOM DATA'; - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertSame('RANDOM DATA.', $buffer); } @@ -157,10 +155,9 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyWit $parser = new RequestHeaderParser($clock); $buffer = ''; - $that = $this; - $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer, $that) { + $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer) { $body = $request->getBody(); - $that->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; @@ -173,7 +170,7 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyWit $size = 10000; $data = "POST / HTTP/1.0\r\nContent-Length: $size\r\n\r\n"; $data .= str_repeat('x', $size); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertSame($size, strlen($buffer)); } @@ -185,10 +182,9 @@ public function testHeadersEventShouldEmitRequestWhichShouldNotEmitStreamingBody $parser = new RequestHeaderParser($clock); $buffer = ''; - $that = $this; - $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer, $that) { + $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer) { $body = $request->getBody(); - $that->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; @@ -200,7 +196,7 @@ public function testHeadersEventShouldEmitRequestWhichShouldNotEmitStreamingBody $data = "POST / HTTP/1.0\r\n\r\n"; $data .= 'RANDOM DATA'; - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertSame('', $buffer); } @@ -212,10 +208,9 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyDat $parser = new RequestHeaderParser($clock); $buffer = ''; - $that = $this; - $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer, $that) { + $parser->on('headers', function (ServerRequestInterface $request) use (&$buffer) { $body = $request->getBody(); - $that->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; @@ -227,7 +222,7 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyDat $data = "POST / HTTP/1.0\r\nContent-Length: 6\r\n\r\n"; $data .= 'RANDOM DATA'; - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertSame('RANDOM', $buffer); } @@ -247,17 +242,17 @@ public function testHeadersEventShouldParsePathAndQueryString() $parser->handle($connection); $data = $this->createAdvancedPostRequest(); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $request); $this->assertSame('POST', $request->getMethod()); $this->assertEquals('http://example.com/foo?bar=baz', $request->getUri()); $this->assertSame('1.1', $request->getProtocolVersion()); - $headers = array( - 'Host' => array('example.com'), - 'User-Agent' => array('react/alpha'), - 'Connection' => array('close'), - ); + $headers = [ + 'Host' => ['example.com'], + 'User-Agent' => ['react/alpha'], + 'Connection' => ['close'] + ]; $this->assertSame($headers, $request->getHeaders()); } @@ -272,11 +267,11 @@ public function testHeaderEventWithShouldApplyDefaultAddressFromLocalConnectionA $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress'))->getMock(); + $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(['getLocalAddress'])->getMock(); $connection->expects($this->once())->method('getLocalAddress')->willReturn('tcp://127.1.1.1:8000'); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\n\r\n"]); $this->assertEquals('http://127.1.1.1:8000/foo', $request->getUri()); $this->assertFalse($request->hasHeader('Host')); @@ -293,11 +288,11 @@ public function testHeaderEventViaHttpsShouldApplyHttpsSchemeFromLocalTlsConnect $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress'))->getMock(); + $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(['getLocalAddress'])->getMock(); $connection->expects($this->once())->method('getLocalAddress')->willReturn('tls://127.1.1.1:8000'); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $this->assertEquals('https://example.com/foo', $request->getUri()); $this->assertEquals('example.com', $request->getHeaderLine('Host')); @@ -321,7 +316,7 @@ public function testHeaderOverflowShouldEmitError() $parser->handle($connection); $data = str_repeat('A', 8193); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertInstanceOf('OverflowException', $error); $this->assertSame('Maximum header size of 8192 exceeded.', $error->getMessage()); @@ -343,7 +338,7 @@ public function testInvalidEmptyRequestHeadersParseException() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("\r\n\r\n")); + $connection->emit('data', ["\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Unable to parse invalid request-line', $error->getMessage()); @@ -364,7 +359,7 @@ public function testInvalidMalformedRequestLineParseException() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET /\r\n\r\n")); + $connection->emit('data', ["GET /\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Unable to parse invalid request-line', $error->getMessage()); @@ -385,7 +380,7 @@ public function testInvalidMalformedRequestHeadersThrowsParseException() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\nHost : yes\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\nHost : yes\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Unable to parse invalid request header fields', $error->getMessage()); @@ -406,7 +401,7 @@ public function testInvalidMalformedRequestHeadersWhitespaceThrowsParseException $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\nHost: yes\rFoo: bar\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\nHost: yes\rFoo: bar\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Unable to parse invalid request header fields', $error->getMessage()); @@ -427,7 +422,7 @@ public function testInvalidAbsoluteFormSchemeEmitsError() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET tcp://example.com:80/ HTTP/1.0\r\n\r\n")); + $connection->emit('data', ["GET tcp://example.com:80/ HTTP/1.0\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Invalid absolute-form request-target', $error->getMessage()); @@ -448,15 +443,15 @@ public function testOriginFormWithSchemeSeparatorInParam() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET /somepath?param=http://example.com HTTP/1.1\r\nHost: localhost\r\n\r\n")); + $connection->emit('data', ["GET /somepath?param=http://example.com HTTP/1.1\r\nHost: localhost\r\n\r\n"]); $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $request); $this->assertSame('GET', $request->getMethod()); $this->assertEquals('http://localhost/somepath?param=http://example.com', $request->getUri()); $this->assertSame('1.1', $request->getProtocolVersion()); - $headers = array( - 'Host' => array('localhost') - ); + $headers = [ + 'Host' => ['localhost'] + ]; $this->assertSame($headers, $request->getHeaders()); } @@ -475,7 +470,7 @@ public function testUriStartingWithColonSlashSlashFails() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET ://example.com:80/ HTTP/1.0\r\n\r\n")); + $connection->emit('data', ["GET ://example.com:80/ HTTP/1.0\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Invalid absolute-form request-target', $error->getMessage()); @@ -496,7 +491,7 @@ public function testInvalidAbsoluteFormWithFragmentEmitsError() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET http://example.com:80/#home HTTP/1.0\r\n\r\n")); + $connection->emit('data', ["GET http://example.com:80/#home HTTP/1.0\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Invalid absolute-form request-target', $error->getMessage()); @@ -517,7 +512,7 @@ public function testInvalidHeaderContainsFullUri() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\nHost: http://user:pass@host/\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\nHost: http://user:pass@host/\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Invalid Host header value', $error->getMessage()); @@ -538,7 +533,7 @@ public function testInvalidAbsoluteFormWithHostHeaderEmpty() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET http://example.com/ HTTP/1.1\r\nHost: \r\n\r\n")); + $connection->emit('data', ["GET http://example.com/ HTTP/1.1\r\nHost: \r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('Invalid Host header value', $error->getMessage()); @@ -559,7 +554,7 @@ public function testInvalidConnectRequestWithNonAuthorityForm() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("CONNECT http://example.com:8080/ HTTP/1.1\r\nHost: example.com:8080\r\n\r\n")); + $connection->emit('data', ["CONNECT http://example.com:8080/ HTTP/1.1\r\nHost: example.com:8080\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame('CONNECT method MUST use authority-form request target', $error->getMessage()); @@ -580,7 +575,7 @@ public function testInvalidHttpVersion() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.2\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.2\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame(505, $error->getCode()); @@ -602,7 +597,7 @@ public function testInvalidContentLengthRequestHeaderWillEmitError() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: foo\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: foo\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame(400, $error->getCode()); @@ -624,7 +619,7 @@ public function testInvalidRequestWithMultipleContentLengthRequestHeadersWillEmi $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 4\r\nContent-Length: 5\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 4\r\nContent-Length: 5\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame(400, $error->getCode()); @@ -646,7 +641,7 @@ public function testInvalidTransferEncodingRequestHeaderWillEmitError() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: foo\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: foo\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame(501, $error->getCode()); @@ -668,7 +663,7 @@ public function testInvalidRequestWithBothTransferEncodingAndContentLengthWillEm $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\nContent-Length: 0\r\n\r\n")); + $connection->emit('data', ["GET / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\nContent-Length: 0\r\n\r\n"]); $this->assertInstanceOf('InvalidArgumentException', $error); $this->assertSame(400, $error->getCode()); @@ -688,12 +683,12 @@ public function testServerParamsWillBeSetOnHttpsRequest() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(['getLocalAddress', 'getRemoteAddress'])->getMock(); $connection->expects($this->once())->method('getLocalAddress')->willReturn('tls://127.1.1.1:8000'); $connection->expects($this->once())->method('getRemoteAddress')->willReturn('tls://192.168.1.1:8001'); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $serverParams = $request->getServerParams(); @@ -721,12 +716,12 @@ public function testServerParamsWillBeSetOnHttpRequest() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(['getLocalAddress', 'getRemoteAddress'])->getMock(); $connection->expects($this->once())->method('getLocalAddress')->willReturn('tcp://127.1.1.1:8000'); $connection->expects($this->once())->method('getRemoteAddress')->willReturn('tcp://192.168.1.1:8001'); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $serverParams = $request->getServerParams(); @@ -754,12 +749,12 @@ public function testServerParamsWillNotSetRemoteAddressForUnixDomainSockets() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(['getLocalAddress', 'getRemoteAddress'])->getMock(); $connection->expects($this->once())->method('getLocalAddress')->willReturn('unix://./server.sock'); $connection->expects($this->once())->method('getRemoteAddress')->willReturn(null); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $serverParams = $request->getServerParams(); @@ -790,7 +785,7 @@ public function testServerParamsWontBeSetOnMissingUrls() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $serverParams = $request->getServerParams(); @@ -811,12 +806,12 @@ public function testServerParamsWillBeReusedForMultipleRequestsFromSameConnectio $parser = new RequestHeaderParser($clock); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(['getLocalAddress', 'getRemoteAddress'])->getMock(); $connection->expects($this->once())->method('getLocalAddress')->willReturn('tcp://127.1.1.1:8000'); $connection->expects($this->once())->method('getRemoteAddress')->willReturn('tcp://192.168.1.1:8001'); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $request = null; $parser->on('headers', function ($parsedRequest) use (&$request) { @@ -824,7 +819,7 @@ public function testServerParamsWillBeReusedForMultipleRequestsFromSameConnectio }); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); assert($request instanceof ServerRequestInterface); $serverParams = $request->getServerParams(); @@ -846,10 +841,10 @@ public function testServerParamsWillBeRememberedUntilConnectionIsClosed() $parser = new RequestHeaderParser($clock); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(['getLocalAddress', 'getRemoteAddress'])->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $ref = new \ReflectionProperty($parser, 'connectionParams'); $ref->setAccessible(true); @@ -857,7 +852,7 @@ public function testServerParamsWillBeRememberedUntilConnectionIsClosed() $this->assertCount(1, $ref->getValue($parser)); $connection->emit('close'); - $this->assertEquals(array(), $ref->getValue($parser)); + $this->assertEquals([], $ref->getValue($parser)); } public function testQueryParmetersWillBeSet() @@ -875,7 +870,7 @@ public function testQueryParmetersWillBeSet() $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); - $connection->emit('data', array("GET /foo.php?hello=world&test=this HTTP/1.0\r\nHost: example.com\r\n\r\n")); + $connection->emit('data', ["GET /foo.php?hello=world&test=this HTTP/1.0\r\nHost: example.com\r\n\r\n"]); $queryParams = $request->getQueryParams(); diff --git a/tests/Io/SenderTest.php b/tests/Io/SenderTest.php index 03a9b56e..59bb9719 100644 --- a/tests/Io/SenderTest.php +++ b/tests/Io/SenderTest.php @@ -9,13 +9,15 @@ use React\Http\Io\ReadableBodyStream; use React\Http\Io\Sender; use React\Http\Message\Request; -use React\Promise; +use React\Promise\Promise; use React\Stream\ThroughStream; use React\Tests\Http\TestCase; +use function React\Promise\reject; +use function React\Promise\resolve; class SenderTest extends TestCase { - /** @var \React\EventLoop\LoopInterface */ + /** @var LoopInterface */ private $loop; /** @@ -55,7 +57,7 @@ public function testSenderRejectsInvalidUri() public function testSenderConnectorRejection() { $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->willReturn(Promise\reject(new \RuntimeException('Rejected'))); + $connector->expects($this->once())->method('connect')->willReturn(reject(new \RuntimeException('Rejected'))); $sender = new Sender(new HttpClient(new ClientConnectionManager($connector, $this->loop))); @@ -80,7 +82,7 @@ public function testSendPostWillAutomaticallySendContentLengthHeader() $sender = new Sender($client); - $request = new Request('POST', 'http://www.google.com/', array(), 'hello'); + $request = new Request('POST', 'http://www.google.com/', [], 'hello'); $sender->send($request); } @@ -93,7 +95,7 @@ public function testSendPostWillAutomaticallySendContentLengthZeroHeaderForEmpty $sender = new Sender($client); - $request = new Request('POST', 'http://www.google.com/', array(), ''); + $request = new Request('POST', 'http://www.google.com/', [], ''); $sender->send($request); } @@ -110,7 +112,7 @@ public function testSendPostStreamWillAutomaticallySendTransferEncodingChunked() $sender = new Sender($client); $stream = new ThroughStream(); - $request = new Request('POST', 'http://www.google.com/', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://www.google.com/', [], new ReadableBodyStream($stream)); $sender->send($request); } @@ -118,7 +120,7 @@ public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForWriteAn { $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); $outgoing->expects($this->once())->method('isWritable')->willReturn(true); - $outgoing->expects($this->exactly(2))->method('write')->withConsecutive(array(""), array("5\r\nhello\r\n"))->willReturn(false); + $outgoing->expects($this->exactly(2))->method('write')->withConsecutive([""], ["5\r\nhello\r\n"])->willReturn(false); $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); $client->expects($this->once())->method('request')->willReturn($outgoing); @@ -126,7 +128,7 @@ public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForWriteAn $sender = new Sender($client); $stream = new ThroughStream(); - $request = new Request('POST', 'http://www.google.com/', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://www.google.com/', [], new ReadableBodyStream($stream)); $sender->send($request); $ret = $stream->write('hello'); @@ -137,7 +139,7 @@ public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForEnd() { $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); $outgoing->expects($this->once())->method('isWritable')->willReturn(true); - $outgoing->expects($this->exactly(2))->method('write')->withConsecutive(array(""), array("0\r\n\r\n"))->willReturn(false); + $outgoing->expects($this->exactly(2))->method('write')->withConsecutive([""], ["0\r\n\r\n"])->willReturn(false); $outgoing->expects($this->once())->method('end')->with(null); $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); @@ -146,7 +148,7 @@ public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForEnd() $sender = new Sender($client); $stream = new ThroughStream(); - $request = new Request('POST', 'http://www.google.com/', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://www.google.com/', [], new ReadableBodyStream($stream)); $sender->send($request); $stream->end(); @@ -167,10 +169,10 @@ public function testSendPostStreamWillRejectWhenRequestBodyEmitsErrorEvent() $expected = new \RuntimeException(); $stream = new ThroughStream(); - $request = new Request('POST', 'http://www.google.com/', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://www.google.com/', [], new ReadableBodyStream($stream)); $promise = $sender->send($request); - $stream->emit('error', array($expected)); + $stream->emit('error', [$expected]); $exception = null; $promise->then(null, function ($e) use (&$exception) { @@ -196,7 +198,7 @@ public function testSendPostStreamWillRejectWhenRequestBodyClosesWithoutEnd() $sender = new Sender($client); $stream = new ThroughStream(); - $request = new Request('POST', 'http://www.google.com/', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://www.google.com/', [], new ReadableBodyStream($stream)); $promise = $sender->send($request); $stream->close(); @@ -214,7 +216,7 @@ public function testSendPostStreamWillNotRejectWhenRequestBodyClosesAfterEnd() { $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); $outgoing->expects($this->once())->method('isWritable')->willReturn(true); - $outgoing->expects($this->exactly(2))->method('write')->withConsecutive(array(""), array("0\r\n\r\n"))->willReturn(false); + $outgoing->expects($this->exactly(2))->method('write')->withConsecutive([""], ["0\r\n\r\n"])->willReturn(false); $outgoing->expects($this->once())->method('end'); $outgoing->expects($this->never())->method('close'); @@ -224,7 +226,7 @@ public function testSendPostStreamWillNotRejectWhenRequestBodyClosesAfterEnd() $sender = new Sender($client); $stream = new ThroughStream(); - $request = new Request('POST', 'http://www.google.com/', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://www.google.com/', [], new ReadableBodyStream($stream)); $promise = $sender->send($request); $stream->end(); @@ -248,7 +250,7 @@ public function testSendPostStreamWithExplicitContentLengthWillSendHeaderAsIs() $sender = new Sender($client); $stream = new ThroughStream(); - $request = new Request('POST', 'http://www.google.com/', array('Content-Length' => '100'), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://www.google.com/', ['Content-Length' => '100'], new ReadableBodyStream($stream)); $sender->send($request); } @@ -275,7 +277,7 @@ public function testSendGetWithEmptyBodyStreamWillNotPassContentLengthOrTransfer $sender = new Sender($client); $body = new EmptyBodyStream(); - $request = new Request('GET', 'http://www.google.com/', array(), $body); + $request = new Request('GET', 'http://www.google.com/', [], $body); $sender->send($request); } @@ -302,7 +304,7 @@ public function testSendCustomMethodWithExplicitContentLengthZeroWillBePassedAsI $sender = new Sender($client); - $request = new Request('CUSTOM', 'http://www.google.com/', array('Content-Length' => '0')); + $request = new Request('CUSTOM', 'http://www.google.com/', ['Content-Length' => '0']); $sender->send($request); } @@ -330,13 +332,13 @@ public function getRequestWithUserAndPassShouldSendAGetRequestWithGivenAuthoriza $sender = new Sender($client); - $request = new Request('GET', 'http://john:dummy@www.example.com', array('Authorization' => 'bearer abc123')); + $request = new Request('GET', 'http://john:dummy@www.example.com', ['Authorization' => 'bearer abc123']); $sender->send($request); } public function testCancelRequestWillCancelConnector() { - $promise = new \React\Promise\Promise(function () { }, function () { + $promise = new Promise(function () { }, function () { throw new \RuntimeException(); }); @@ -364,7 +366,7 @@ public function testCancelRequestWillCloseConnection() $connection->expects($this->once())->method('close'); $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->willReturn(Promise\resolve($connection)); + $connector->expects($this->once())->method('connect')->willReturn(resolve($connection)); $sender = new Sender(new HttpClient(new ClientConnectionManager($connector, $this->loop))); diff --git a/tests/Io/StreamingServerTest.php b/tests/Io/StreamingServerTest.php index 152fece6..3b5f28f4 100644 --- a/tests/Io/StreamingServerTest.php +++ b/tests/Io/StreamingServerTest.php @@ -12,6 +12,7 @@ use React\Stream\ThroughStream; use React\Tests\Http\SocketServerStub; use React\Tests\Http\TestCase; +use function React\Promise\resolve; class StreamingServerTest extends TestCase { @@ -37,7 +38,7 @@ private function mockConnection(array $additionalMethods = null) $connection = $this->getMockBuilder('React\Socket\Connection') ->disableOriginalConstructor() ->setMethods(array_merge( - array( + [ 'write', 'end', 'close', @@ -48,8 +49,8 @@ private function mockConnection(array $additionalMethods = null) 'getRemoteAddress', 'getLocalAddress', 'pipe' - ), - (is_array($additionalMethods) ? $additionalMethods : array()) + ], + (is_array($additionalMethods) ? $additionalMethods : []) )) ->getMock(); @@ -64,11 +65,11 @@ public function testRequestEventWillNotBeEmittedForIncompleteHeaders() $server = new StreamingServer(Loop::get(), $this->expectCallableNever()); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = ''; $data .= "GET / HTTP/1.1\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestEventIsEmitted() @@ -76,22 +77,22 @@ public function testRequestEventIsEmitted() $server = new StreamingServer(Loop::get(), $this->expectCallableOnce()); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestEventIsEmittedForArrayCallable() { $this->called = null; - $server = new StreamingServer(Loop::get(), array($this, 'helperCallableOnce')); + $server = new StreamingServer(Loop::get(), [$this, 'helperCallableOnce']); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals(1, $this->called); } @@ -116,10 +117,10 @@ public function testRequestEvent() ->willReturn('127.0.0.1:8080'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $serverParams = $requestAssertion->getServerParams(); @@ -128,7 +129,7 @@ public function testRequestEvent() $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('/', $requestAssertion->getRequestTarget()); $this->assertSame('/', $requestAssertion->getUri()->getPath()); - $this->assertSame(array(), $requestAssertion->getQueryParams()); + $this->assertSame([], $requestAssertion->getQueryParams()); $this->assertSame('http://example.com/', (string)$requestAssertion->getUri()); $this->assertSame('example.com', $requestAssertion->getHeaderLine('Host')); $this->assertSame('127.0.0.1', $serverParams['REMOTE_ADDR']); @@ -149,10 +150,10 @@ public function testRequestEventWithSingleRequestHandlerArray() ->willReturn('127.0.0.1:8080'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $serverParams = $requestAssertion->getServerParams(); @@ -161,7 +162,7 @@ public function testRequestEventWithSingleRequestHandlerArray() $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('/', $requestAssertion->getRequestTarget()); $this->assertSame('/', $requestAssertion->getUri()->getPath()); - $this->assertSame(array(), $requestAssertion->getQueryParams()); + $this->assertSame([], $requestAssertion->getQueryParams()); $this->assertSame('http://example.com/', (string)$requestAssertion->getUri()); $this->assertSame('example.com', $requestAssertion->getHeaderLine('Host')); $this->assertSame('127.0.0.1', $serverParams['REMOTE_ADDR']); @@ -175,10 +176,10 @@ public function testRequestGetWithHostAndCustomPort() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: example.com:8080\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); @@ -197,10 +198,10 @@ public function testRequestGetWithHostAndHttpsPort() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: example.com:443\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); @@ -219,10 +220,10 @@ public function testRequestGetWithHostAndDefaultPortWillBeIgnored() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); @@ -241,10 +242,10 @@ public function testRequestGetHttp10WithoutHostWillBeIgnored() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); @@ -262,10 +263,10 @@ public function testRequestGetHttp11WithoutHostWillReject() $server->on('error', $this->expectCallableOnce()); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestOptionsAsterisk() @@ -276,10 +277,10 @@ public function testRequestOptionsAsterisk() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "OPTIONS * HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('OPTIONS', $requestAssertion->getMethod()); @@ -295,10 +296,10 @@ public function testRequestNonOptionsWithAsteriskRequestTargetWillReject() $server->on('error', $this->expectCallableOnce()); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET * HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestConnectAuthorityForm() @@ -309,10 +310,10 @@ public function testRequestConnectAuthorityForm() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); @@ -331,10 +332,10 @@ public function testRequestConnectWithoutHostWillBePassesAsIs() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "CONNECT example.com:443 HTTP/1.1\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); @@ -353,10 +354,10 @@ public function testRequestConnectAuthorityFormWithDefaultPortWillBePassedAsIs() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); @@ -375,10 +376,10 @@ public function testRequestConnectAuthorityFormNonMatchingHostWillBePassedAsIs() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "CONNECT example.com:80 HTTP/1.1\r\nHost: other.example.org\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); @@ -395,10 +396,10 @@ public function testRequestConnectOriginFormRequestTargetWillReject() $server->on('error', $this->expectCallableOnce()); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "CONNECT / HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestNonConnectWithAuthorityRequestTargetWillReject() @@ -407,10 +408,10 @@ public function testRequestNonConnectWithAuthorityRequestTargetWillReject() $server->on('error', $this->expectCallableOnce()); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET example.com:80 HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestWithoutHostEventUsesSocketAddress() @@ -427,10 +428,10 @@ public function testRequestWithoutHostEventUsesSocketAddress() ->willReturn('127.0.0.1:80'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET /test HTTP/1.0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); @@ -448,10 +449,10 @@ public function testRequestAbsoluteEvent() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET http://example.com/test HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); @@ -470,10 +471,10 @@ public function testRequestAbsoluteNonMatchingHostWillBePassedAsIs() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET http://example.com/test HTTP/1.1\r\nHost: other.example.org\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); @@ -489,10 +490,10 @@ public function testRequestAbsoluteWithoutHostWillReject() $server->on('error', $this->expectCallableOnce()); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET http://example.com:8080/test HTTP/1.1\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestOptionsAsteriskEvent() @@ -504,10 +505,10 @@ public function testRequestOptionsAsteriskEvent() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "OPTIONS * HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('OPTIONS', $requestAssertion->getMethod()); @@ -526,10 +527,10 @@ public function testRequestOptionsAbsoluteEvent() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "OPTIONS http://example.com HTTP/1.1\r\nHost: example.com\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); $this->assertSame('OPTIONS', $requestAssertion->getMethod()); @@ -548,7 +549,7 @@ public function testRequestPauseWillBeForwardedToConnection() $this->connection->expects($this->once())->method('pause'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -556,7 +557,7 @@ public function testRequestPauseWillBeForwardedToConnection() $data .= "Content-Length: 5\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestResumeWillBeForwardedToConnection() @@ -568,7 +569,7 @@ public function testRequestResumeWillBeForwardedToConnection() $this->connection->expects($this->once())->method('resume'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -576,7 +577,7 @@ public function testRequestResumeWillBeForwardedToConnection() $data .= "Content-Length: 5\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestCloseWillNotCloseConnection() @@ -588,10 +589,10 @@ public function testRequestCloseWillNotCloseConnection() $this->connection->expects($this->never())->method('close'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestPauseAfterCloseWillNotBeForwarded() @@ -605,10 +606,10 @@ public function testRequestPauseAfterCloseWillNotBeForwarded() $this->connection->expects($this->never())->method('pause'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestResumeAfterCloseWillNotBeForwarded() @@ -622,10 +623,10 @@ public function testRequestResumeAfterCloseWillNotBeForwarded() $this->connection->expects($this->never())->method('resume'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestEventWithoutBodyWillNotEmitData() @@ -637,10 +638,10 @@ public function testRequestEventWithoutBodyWillNotEmitData() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestEventWithSecondDataEventWillEmitBodyData() @@ -652,7 +653,7 @@ public function testRequestEventWithSecondDataEventWillEmitBodyData() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = ''; $data .= "POST / HTTP/1.1\r\n"; @@ -660,7 +661,7 @@ public function testRequestEventWithSecondDataEventWillEmitBodyData() $data .= "Content-Length: 100\r\n"; $data .= "\r\n"; $data .= "incomplete"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestEventWithPartialBodyWillEmitData() @@ -672,18 +673,18 @@ public function testRequestEventWithPartialBodyWillEmitData() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = ''; $data .= "POST / HTTP/1.1\r\n"; $data .= "Host: localhost\r\n"; $data .= "Content-Length: 100\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $data = ''; $data .= "incomplete"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testResponseContainsServerHeader() @@ -706,10 +707,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("\r\nServer: ReactPHP/1\r\n", $buffer); } @@ -736,10 +737,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals('', $buffer); } @@ -766,10 +767,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->connection->emit('close'); $this->assertEquals('', $buffer); @@ -783,7 +784,7 @@ public function testResponseBodyStreamAlreadyClosedWillSendEmptyBodyChunkedEncod $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -802,10 +803,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertStringStartsWith("HTTP/1.1 200 OK\r\n", $buffer); $this->assertStringEndsWith("\r\n\r\n0\r\n\r\n", $buffer); @@ -818,7 +819,7 @@ public function testResponseBodyStreamEndingWillSendEmptyBodyChunkedEncoded() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -837,10 +838,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $stream->end(); @@ -856,7 +857,7 @@ public function testResponseBodyStreamAlreadyClosedWillSendEmptyBodyPlainHttp10( $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -875,10 +876,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertStringStartsWith("HTTP/1.0 200 OK\r\n", $buffer); $this->assertStringEndsWith("\r\n\r\n", $buffer); @@ -892,7 +893,7 @@ public function testResponseStreamWillBeClosedIfConnectionIsAlreadyClosed() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -913,7 +914,7 @@ function ($data) use (&$buffer) { $this->connection = $this->getMockBuilder('React\Socket\Connection') ->disableOriginalConstructor() ->setMethods( - array( + [ 'write', 'end', 'close', @@ -924,7 +925,7 @@ function ($data) use (&$buffer) { 'getRemoteAddress', 'getLocalAddress', 'pipe' - ) + ] ) ->getMock(); @@ -933,10 +934,10 @@ function ($data) use (&$buffer) { $this->connection->expects($this->never())->method('write'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testResponseBodyStreamWillBeClosedIfConnectionEmitsCloseEvent() @@ -947,16 +948,16 @@ public function testResponseBodyStreamWillBeClosedIfConnectionEmitsCloseEvent() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->connection->emit('close'); } @@ -965,11 +966,11 @@ public function testResponseUpgradeInResponseCanBeUsedToAdvertisePossibleUpgrade $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array( + [ 'date' => '', 'server' => '', 'Upgrade' => 'demo' - ), + ], 'foo' ); }); @@ -988,10 +989,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals("HTTP/1.1 200 OK\r\nUpgrade: demo\r\nContent-Length: 3\r\n\r\nfoo", $buffer); } @@ -1001,10 +1002,10 @@ public function testResponseUpgradeWishInRequestCanBeIgnoredByReturningNormalRes $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array( + [ 'date' => '', 'server' => '' - ), + ], 'foo' ); }); @@ -1023,10 +1024,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: demo\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nfoo", $buffer); } @@ -1036,11 +1037,11 @@ public function testResponseUpgradeSwitchingProtocolIncludesConnectionUpgradeHea $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 101, - array( + [ 'date' => '', 'server' => '', 'Upgrade' => 'demo' - ), + ], 'foo' ); }); @@ -1061,10 +1062,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: demo\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals("HTTP/1.1 101 Switching Protocols\r\nUpgrade: demo\r\nConnection: upgrade\r\n\r\nfoo", $buffer); } @@ -1076,11 +1077,11 @@ public function testResponseUpgradeSwitchingProtocolWithStreamWillPipeDataToConn $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 101, - array( + [ 'date' => '', 'server' => '', 'Upgrade' => 'demo' - ), + ], $stream ); }); @@ -1099,10 +1100,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: demo\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $stream->write('hello'); $stream->write('world'); @@ -1117,7 +1118,7 @@ public function testResponseConnectMethodStreamWillPipeDataToConnection() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -1136,10 +1137,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $stream->write('hello'); $stream->write('world'); @@ -1155,18 +1156,18 @@ public function testResponseConnectMethodStreamWillPipeDataFromConnection() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->once())->method('pipe')->with($stream); $data = "CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testResponseContainsSameRequestProtocolVersionAndChunkedBodyForHttp11() @@ -1174,7 +1175,7 @@ public function testResponseContainsSameRequestProtocolVersionAndChunkedBodyForH $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], 'bye' ); }); @@ -1193,10 +1194,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("bye", $buffer); @@ -1207,7 +1208,7 @@ public function testResponseContainsSameRequestProtocolVersionAndRawBodyForHttp1 $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], 'bye' ); }); @@ -1226,10 +1227,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.0 200 OK\r\n", $buffer); $this->assertContainsString("\r\n\r\n", $buffer); @@ -1241,7 +1242,7 @@ public function testResponseContainsNoResponseBodyForHeadRequest() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], 'bye' ); }); @@ -1259,10 +1260,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "HEAD / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1277,7 +1278,7 @@ public function testResponseContainsNoResponseBodyForHeadRequestWithStreamingRes $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array('Content-Length' => '3'), + ['Content-Length' => '3'], $stream ); }); @@ -1295,10 +1296,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "HEAD / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1309,7 +1310,7 @@ public function testResponseContainsNoResponseBodyAndNoContentLengthForNoContent $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 204, - array(), + [], 'bye' ); }); @@ -1327,10 +1328,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 204 No Content\r\n", $buffer); $this->assertNotContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1345,7 +1346,7 @@ public function testResponseContainsNoResponseBodyAndNoContentLengthForNoContent $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 204, - array('Content-Length' => '3'), + ['Content-Length' => '3'], $stream ); }); @@ -1363,10 +1364,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "HEAD / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 204 No Content\r\n", $buffer); $this->assertNotContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1377,7 +1378,7 @@ public function testResponseContainsNoContentLengthHeaderForNotModifiedStatus() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 304, - array(), + [], '' ); }); @@ -1395,10 +1396,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); $this->assertNotContainsString("\r\nContent-Length: 0\r\n", $buffer); @@ -1409,7 +1410,7 @@ public function testResponseContainsExplicitContentLengthHeaderForNotModifiedSta $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 304, - array('Content-Length' => 3), + ['Content-Length' => 3], '' ); }); @@ -1427,10 +1428,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); $this->assertContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1441,7 +1442,7 @@ public function testResponseContainsExplicitContentLengthHeaderForHeadRequests() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array('Content-Length' => 3), + ['Content-Length' => 3], '' ); }); @@ -1459,10 +1460,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "HEAD / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1473,7 +1474,7 @@ public function testResponseContainsNoResponseBodyForNotModifiedStatus() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 304, - array(), + [], 'bye' ); }); @@ -1491,10 +1492,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); $this->assertContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1509,7 +1510,7 @@ public function testResponseContainsNoResponseBodyForNotModifiedStatusWithStream $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 304, - array('Content-Length' => '3'), + ['Content-Length' => '3'], $stream ); }); @@ -1527,10 +1528,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); $this->assertContainsString("\r\nContent-Length: 3\r\n", $buffer); @@ -1558,10 +1559,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.2\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('InvalidArgumentException', $error); @@ -1592,11 +1593,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\nX-DATA: "; $data .= str_repeat('A', 8193 - strlen($data)) . "\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('OverflowException', $error); @@ -1626,10 +1627,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "bad request\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('InvalidArgumentException', $error); @@ -1652,7 +1653,7 @@ public function testRequestContentLengthBodyDataWillEmitDataEventOnRequestStream }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1661,7 +1662,7 @@ public function testRequestContentLengthBodyDataWillEmitDataEventOnRequestStream $data .= "\r\n"; $data .= "hello"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestChunkedTransferEncodingRequestWillEmitDecodedDataEventOnRequestStream() @@ -1681,7 +1682,7 @@ public function testRequestChunkedTransferEncodingRequestWillEmitDecodedDataEven }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1691,7 +1692,7 @@ public function testRequestChunkedTransferEncodingRequestWillEmitDecodedDataEven $data .= "5\r\nhello\r\n"; $data .= "0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals('chunked', $requestValidation->getHeaderLine('Transfer-Encoding')); } @@ -1711,7 +1712,7 @@ public function testRequestChunkedTransferEncodingWithAdditionalDataWontBeEmitte }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1722,7 +1723,7 @@ public function testRequestChunkedTransferEncodingWithAdditionalDataWontBeEmitte $data .= "0\r\n\r\n"; $data .= "2\r\nhi\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestChunkedTransferEncodingEmpty() @@ -1740,7 +1741,7 @@ public function testRequestChunkedTransferEncodingEmpty() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1749,7 +1750,7 @@ public function testRequestChunkedTransferEncodingEmpty() $data .= "\r\n"; $data .= "0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestChunkedTransferEncodingHeaderCanBeUpperCase() @@ -1769,7 +1770,7 @@ public function testRequestChunkedTransferEncodingHeaderCanBeUpperCase() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1779,7 +1780,7 @@ public function testRequestChunkedTransferEncodingHeaderCanBeUpperCase() $data .= "5\r\nhello\r\n"; $data .= "0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals('CHUNKED', $requestValidation->getHeaderLine('Transfer-Encoding')); } @@ -1798,7 +1799,7 @@ public function testRequestChunkedTransferEncodingCanBeMixedUpperAndLowerCase() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1807,7 +1808,7 @@ public function testRequestChunkedTransferEncodingCanBeMixedUpperAndLowerCase() $data .= "\r\n"; $data .= "5\r\nhello\r\n"; $data .= "0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditionalDataWillBeIgnored() @@ -1823,11 +1824,11 @@ public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditiona $request->getBody()->on('close', $closeEvent); $request->getBody()->on('error', $errorEvent); - return \React\Promise\resolve(new Response()); + return resolve(new Response()); }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1837,7 +1838,7 @@ public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditiona $data .= "hello"; $data .= "world"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditionalDataWillBeIgnoredSplitted() @@ -1856,7 +1857,7 @@ public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditiona }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1865,11 +1866,11 @@ public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditiona $data .= "\r\n"; $data .= "hello"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $data = "world"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestZeroContentLengthWillEmitEndEvent() @@ -1888,7 +1889,7 @@ public function testRequestZeroContentLengthWillEmitEndEvent() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1896,7 +1897,7 @@ public function testRequestZeroContentLengthWillEmitEndEvent() $data .= "Content-Length: 0\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIgnored() @@ -1914,7 +1915,7 @@ public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIg }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1923,7 +1924,7 @@ public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIg $data .= "\r\n"; $data .= "hello"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIgnoredSplitted() @@ -1941,7 +1942,7 @@ public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIg }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1949,11 +1950,11 @@ public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIg $data .= "Content-Length: 0\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $data = "hello"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestInvalidChunkHeaderTooLongWillEmitErrorOnRequestStream() @@ -1961,13 +1962,13 @@ public function testRequestInvalidChunkHeaderTooLongWillEmitErrorOnRequestStream $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf('Exception')); $server = new StreamingServer(Loop::get(), function ($request) use ($errorEvent){ $request->getBody()->on('error', $errorEvent); - return \React\Promise\resolve(new Response()); + return resolve(new Response()); }); $this->connection->expects($this->never())->method('close'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -1978,7 +1979,7 @@ public function testRequestInvalidChunkHeaderTooLongWillEmitErrorOnRequestStream $data .= 'a'; } - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestInvalidChunkBodyTooLongWillEmitErrorOnRequestStream() @@ -1991,7 +1992,7 @@ public function testRequestInvalidChunkBodyTooLongWillEmitErrorOnRequestStream() $this->connection->expects($this->never())->method('close'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -2000,7 +2001,7 @@ public function testRequestInvalidChunkBodyTooLongWillEmitErrorOnRequestStream() $data .= "\r\n"; $data .= "5\r\nhello world\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestUnexpectedEndOfRequestWithChunkedTransferConnectionWillEmitErrorOnRequestStream() @@ -2013,7 +2014,7 @@ public function testRequestUnexpectedEndOfRequestWithChunkedTransferConnectionWi $this->connection->expects($this->never())->method('close'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -2022,7 +2023,7 @@ public function testRequestUnexpectedEndOfRequestWithChunkedTransferConnectionWi $data .= "\r\n"; $data .= "5\r\nhello\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->connection->emit('end'); } @@ -2036,7 +2037,7 @@ public function testRequestInvalidChunkHeaderWillEmitErrorOnRequestStream() $this->connection->expects($this->never())->method('close'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -2045,7 +2046,7 @@ public function testRequestInvalidChunkHeaderWillEmitErrorOnRequestStream() $data .= "\r\n"; $data .= "hello\r\nhello\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestUnexpectedEndOfRequestWithContentLengthWillEmitErrorOnRequestStream() @@ -2058,7 +2059,7 @@ public function testRequestUnexpectedEndOfRequestWithContentLengthWillEmitErrorO $this->connection->expects($this->never())->method('close'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -2067,7 +2068,7 @@ public function testRequestUnexpectedEndOfRequestWithContentLengthWillEmitErrorO $data .= "\r\n"; $data .= "incomplete"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->connection->emit('end'); } @@ -2088,11 +2089,11 @@ public function testRequestWithoutBodyWillEmitEndOnRequestStream() $this->connection->expects($this->never())->method('close'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestWithoutDefinedLengthWillIgnoreDataEvent() @@ -2110,12 +2111,12 @@ public function testRequestWithoutDefinedLengthWillIgnoreDataEvent() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); $data .= "hello world"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testResponseWithBodyStreamWillUseChunkedTransferEncodingByDefault() @@ -2124,7 +2125,7 @@ public function testResponseWithBodyStreamWillUseChunkedTransferEncodingByDefaul $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -2142,12 +2143,12 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); - $stream->emit('data', array('hello')); + $this->connection->emit('data', [$data]); + $stream->emit('data', ['hello']); $this->assertContainsString("Transfer-Encoding: chunked", $buffer); $this->assertContainsString("hello", $buffer); @@ -2158,10 +2159,10 @@ public function testResponseWithBodyStringWillOverwriteExplicitContentLengthAndT $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array( + [ 'Content-Length' => 1000, 'Transfer-Encoding' => 'chunked' - ), + ], 'hello' ); }); @@ -2179,11 +2180,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertNotContainsString("Transfer-Encoding: chunked", $buffer); $this->assertContainsString("Content-Length: 5", $buffer); @@ -2199,7 +2200,7 @@ public function testResponseContainsResponseBodyWithTransferEncodingChunkedForBo $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($body) { return new Response( 200, - array(), + [], $body ); }); @@ -2217,10 +2218,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("Transfer-Encoding: chunked", $buffer); $this->assertNotContainsString("Content-Length:", $buffer); @@ -2236,7 +2237,7 @@ public function testResponseContainsResponseBodyWithPlainBodyWithUnknownSizeForL $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($body) { return new Response( 200, - array(), + [], $body ); }); @@ -2254,10 +2255,10 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertNotContainsString("Transfer-Encoding: chunked", $buffer); $this->assertNotContainsString("Content-Length:", $buffer); @@ -2270,9 +2271,9 @@ public function testResponseWithCustomTransferEncodingWillBeIgnoredAndUseChunked $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array( + [ 'Transfer-Encoding' => 'custom' - ), + ], $stream ); }); @@ -2290,12 +2291,12 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); - $stream->emit('data', array('hello')); + $this->connection->emit('data', [$data]); + $stream->emit('data', ['hello']); $this->assertContainsString('Transfer-Encoding: chunked', $buffer); $this->assertNotContainsString('Transfer-Encoding: custom', $buffer); @@ -2329,11 +2330,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("Date: Thu, 19 May 2022 14:54:51 GMT\r\n", $buffer); @@ -2345,7 +2346,7 @@ public function testResponseWithCustomDateHeaderOverwritesDefault() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array("Date" => "Tue, 15 Nov 1994 08:12:31 GMT") + ["Date" => "Tue, 15 Nov 1994 08:12:31 GMT"] ); }); @@ -2362,11 +2363,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("Date: Tue, 15 Nov 1994 08:12:31 GMT\r\n", $buffer); @@ -2378,7 +2379,7 @@ public function testResponseWithEmptyDateHeaderRemovesDateHeader() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array('Date' => '') + ['Date' => ''] ); }); @@ -2395,11 +2396,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertNotContainsString("Date:", $buffer); @@ -2411,14 +2412,14 @@ public function testResponseCanContainMultipleCookieHeaders() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array( - 'Set-Cookie' => array( + [ + 'Set-Cookie' => [ 'name=test', 'session=abc' - ), + ], 'Date' => '', 'Server' => '' - ) + ] ); }); @@ -2435,11 +2436,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertEquals("HTTP/1.1 200 OK\r\nSet-Cookie: name=test\r\nSet-Cookie: session=abc\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", $buffer); } @@ -2463,7 +2464,7 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -2471,7 +2472,7 @@ function ($data) use (&$buffer) { $data .= "Expect: 100-continue\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 100 Continue\r\n", $buffer); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); } @@ -2495,13 +2496,13 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.0\r\n"; $data .= "Expect: 100-continue\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.0 200 OK\r\n", $buffer); $this->assertNotContainsString("HTTP/1.1 100 Continue\r\n\r\n", $buffer); } @@ -2519,7 +2520,7 @@ public function testResponseBodyStreamWillStreamDataWithChunkedTransferEncoding( $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($input) { return new Response( 200, - array(), + [], $input ); }); @@ -2537,13 +2538,13 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); - $input->emit('data', array('1')); - $input->emit('data', array('23')); + $this->connection->emit('data', [$data]); + $input->emit('data', ['1']); + $input->emit('data', ['23']); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("\r\n\r\n", $buffer); @@ -2558,7 +2559,7 @@ public function testResponseBodyStreamWithContentLengthWillStreamTillLengthWitho $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($input) { return new Response( 200, - array('Content-Length' => 5), + ['Content-Length' => 5], $input ); }); @@ -2576,13 +2577,13 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); - $input->emit('data', array('hel')); - $input->emit('data', array('lo')); + $this->connection->emit('data', [$data]); + $input->emit('data', ['hel']); + $input->emit('data', ['lo']); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("Content-Length: 5\r\n", $buffer); @@ -2594,7 +2595,7 @@ function ($data) use (&$buffer) { public function testResponseWithResponsePromise() { $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { - return \React\Promise\resolve(new Response()); + return resolve(new Response()); }); $buffer = ''; @@ -2610,11 +2611,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("\r\n\r\n", $buffer); } @@ -2643,11 +2644,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); $this->assertInstanceOf('RuntimeException', $exception); @@ -2656,7 +2657,7 @@ function ($data) use (&$buffer) { public function testResponseResolveWrongTypeInPromiseWillResultInError() { $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { - return \React\Promise\resolve("invalid"); + return resolve("invalid"); }); $buffer = ''; @@ -2672,11 +2673,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); } @@ -2703,11 +2704,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); } @@ -2734,11 +2735,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); } @@ -2748,7 +2749,7 @@ public function testResponseWithContentLengthHeaderForStringBodyOverwritesTransf $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array('Transfer-Encoding' => 'chunked'), + ['Transfer-Encoding' => 'chunked'], 'hello' ); }); @@ -2766,11 +2767,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); $this->assertContainsString("Content-Length: 5\r\n", $buffer); @@ -2798,11 +2799,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); } @@ -2831,11 +2832,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertInstanceOf('RuntimeException', $exception); $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); @@ -2866,12 +2867,12 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); try { - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } catch (\Error $e) { $this->markTestSkipped( 'A \Throwable bubbled out of the request callback. ' . @@ -2911,11 +2912,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); $this->assertInstanceOf('RuntimeException', $exception); @@ -2923,49 +2924,49 @@ function ($data) use (&$buffer) { public static function provideInvalidResponse() { - $response = new Response(200, array(), '', '1.1', 'OK'); + $response = new Response(200, [], '', '1.1', 'OK'); - return array( - array( + return [ + [ $response->withStatus(99, 'OK') - ), - array( + ], + [ $response->withStatus(1000, 'OK') - ), - array( + ], + [ $response->withStatus(200, "Invald\r\nReason: Yes") - ), - array( + ], + [ $response->withHeader('Invalid', "Yes\r\n") - ), - array( + ], + [ $response->withHeader('Invalid', "Yes\n") - ), - array( + ], + [ $response->withHeader('Invalid', "Yes\r") - ), - array( + ], + [ $response->withHeader("Inva\r\nlid", 'Yes') - ), - array( + ], + [ $response->withHeader("Inva\nlid", 'Yes') - ), - array( + ], + [ $response->withHeader("Inva\rlid", 'Yes') - ), - array( + ], + [ $response->withHeader('Inva Lid', 'Yes') - ), - array( + ], + [ $response->withHeader('Inva:Lid', 'Yes') - ), - array( + ], + [ $response->withHeader('Invalid', "Val\0ue") - ), - array( + ], + [ $response->withHeader("Inva\0lid", 'Yes') - ) - ); + ] + ]; } /** @@ -2996,11 +2997,11 @@ function ($data) use (&$buffer) { ); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); $this->assertInstanceOf('InvalidArgumentException', $exception); @@ -3024,11 +3025,11 @@ public function testRequestServerRequestParams() ->willReturn('127.0.0.1:8080'); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = $this->createGetRequest(); - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $serverParams = $requestValidation->getServerParams(); @@ -3048,11 +3049,11 @@ public function testRequestQueryParametersWillBeAddedToRequest() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET /foo.php?hello=world&test=bar HTTP/1.0\r\n\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $queryParams = $requestValidation->getQueryParams(); @@ -3068,7 +3069,7 @@ public function testRequestCookieWillBeAddedToServerRequest() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -3076,9 +3077,9 @@ public function testRequestCookieWillBeAddedToServerRequest() $data .= "Cookie: hello=world\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); - $this->assertEquals(array('hello' => 'world'), $requestValidation->getCookieParams()); + $this->assertEquals(['hello' => 'world'], $requestValidation->getCookieParams()); } public function testRequestInvalidMultipleCookiesWontBeAddedToServerRequest() @@ -3089,7 +3090,7 @@ public function testRequestInvalidMultipleCookiesWontBeAddedToServerRequest() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -3098,8 +3099,8 @@ public function testRequestInvalidMultipleCookiesWontBeAddedToServerRequest() $data .= "Cookie: test=failed\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); - $this->assertEquals(array(), $requestValidation->getCookieParams()); + $this->connection->emit('data', [$data]); + $this->assertEquals([], $requestValidation->getCookieParams()); } public function testRequestCookieWithSeparatorWillBeAddedToServerRequest() @@ -3110,7 +3111,7 @@ public function testRequestCookieWithSeparatorWillBeAddedToServerRequest() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -3118,8 +3119,8 @@ public function testRequestCookieWithSeparatorWillBeAddedToServerRequest() $data .= "Cookie: hello=world; test=abc\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); - $this->assertEquals(array('hello' => 'world', 'test' => 'abc'), $requestValidation->getCookieParams()); + $this->connection->emit('data', [$data]); + $this->assertEquals(['hello' => 'world', 'test' => 'abc'], $requestValidation->getCookieParams()); } public function testRequestCookieWithCommaValueWillBeAddedToServerRequest() @@ -3130,7 +3131,7 @@ public function testRequestCookieWithCommaValueWillBeAddedToServerRequest() }); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $data = "GET / HTTP/1.1\r\n"; $data .= "Host: example.com\r\n"; @@ -3138,8 +3139,8 @@ public function testRequestCookieWithCommaValueWillBeAddedToServerRequest() $data .= "Cookie: test=abc,def; hello=world\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); - $this->assertEquals(array('test' => 'abc,def', 'hello' => 'world'), $requestValidation->getCookieParams()); + $this->connection->emit('data', [$data]); + $this->assertEquals(['test' => 'abc,def', 'hello' => 'world'], $requestValidation->getCookieParams()); } public function testNewConnectionWillInvokeParserOnce() @@ -3154,12 +3155,12 @@ public function testNewConnectionWillInvokeParserOnce() $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); } public function testNewConnectionWillInvokeParserOnceAndInvokeRequestHandlerWhenParserIsDoneForHttp10() { - $request = new ServerRequest('GET', 'http://localhost/', array(), '', '1.0'); + $request = new ServerRequest('GET', 'http://localhost/', [], '', '1.0'); $server = new StreamingServer(Loop::get(), $this->expectCallableOnceWith($request)); @@ -3171,7 +3172,7 @@ public function testNewConnectionWillInvokeParserOnceAndInvokeRequestHandlerWhen $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->once())->method('write'); $this->connection->expects($this->once())->method('end'); @@ -3182,7 +3183,7 @@ public function testNewConnectionWillInvokeParserOnceAndInvokeRequestHandlerWhen public function testNewConnectionWillInvokeParserOnceAndInvokeRequestHandlerWhenParserIsDoneForHttp11ConnectionClose() { - $request = new ServerRequest('GET', 'http://localhost/', array('Connection' => 'close')); + $request = new ServerRequest('GET', 'http://localhost/', ['Connection' => 'close']); $server = new StreamingServer(Loop::get(), $this->expectCallableOnceWith($request)); @@ -3194,7 +3195,7 @@ public function testNewConnectionWillInvokeParserOnceAndInvokeRequestHandlerWhen $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->once())->method('write'); $this->connection->expects($this->once())->method('end'); @@ -3208,7 +3209,7 @@ public function testNewConnectionWillInvokeParserOnceAndInvokeRequestHandlerWhen $request = new ServerRequest('GET', 'http://localhost/'); $server = new StreamingServer(Loop::get(), function () { - return new Response(200, array('Connection' => 'close')); + return new Response(200, ['Connection' => 'close']); }); $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); @@ -3219,7 +3220,7 @@ public function testNewConnectionWillInvokeParserOnceAndInvokeRequestHandlerWhen $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->once())->method('write'); $this->connection->expects($this->once())->method('end'); @@ -3244,7 +3245,7 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->once())->method('write'); $this->connection->expects($this->never())->method('end'); @@ -3255,7 +3256,7 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandlerWhenConnectionCanBeKeptAliveForHttp10ConnectionKeepAlive() { - $request = new ServerRequest('GET', 'http://localhost/', array('Connection' => 'keep-alive'), '', '1.0'); + $request = new ServerRequest('GET', 'http://localhost/', ['Connection' => 'keep-alive'], '', '1.0'); $server = new StreamingServer(Loop::get(), function () { return new Response(); @@ -3269,7 +3270,7 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->once())->method('write'); $this->connection->expects($this->never())->method('end'); @@ -3284,7 +3285,7 @@ public function testNewConnectionWillInvokeParserOnceAfterInvokingRequestHandler $body = new ThroughStream(); $server = new StreamingServer(Loop::get(), function () use ($body) { - return new Response(200, array(), $body); + return new Response(200, [], $body); }); $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); @@ -3295,7 +3296,7 @@ public function testNewConnectionWillInvokeParserOnceAfterInvokingRequestHandler $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->once())->method('write'); $this->connection->expects($this->never())->method('end'); @@ -3310,7 +3311,7 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle $body = new ThroughStream(); $server = new StreamingServer(Loop::get(), function () use ($body) { - return new Response(200, array(), $body); + return new Response(200, [], $body); }); $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); @@ -3321,7 +3322,7 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle $ref->setValue($server, $parser); $server->listen($this->socket); - $this->socket->emit('connection', array($this->connection)); + $this->socket->emit('connection', [$this->connection]); $this->connection->expects($this->exactly(2))->method('write'); $this->connection->expects($this->never())->method('end'); @@ -3336,16 +3337,16 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle public function testCompletingARequestWillRemoveConnectionOnCloseListener() { - $connection = $this->mockConnection(array('removeListener')); + $connection = $this->mockConnection(['removeListener']); $request = new ServerRequest('GET', 'http://localhost/'); $server = new StreamingServer(Loop::get(), function () { - return \React\Promise\resolve(new Response()); + return resolve(new Response()); }); $server->listen($this->socket); - $this->socket->emit('connection', array($connection)); + $this->socket->emit('connection', [$connection]); $connection->expects($this->once())->method('removeListener'); diff --git a/tests/Io/TransactionTest.php b/tests/Io/TransactionTest.php index 284d059f..b4825024 100644 --- a/tests/Io/TransactionTest.php +++ b/tests/Io/TransactionTest.php @@ -11,10 +11,13 @@ use React\Http\Message\Response; use React\Http\Message\ResponseException; use React\EventLoop\Loop; -use React\Promise; use React\Promise\Deferred; +use React\Promise\Promise; use React\Stream\ThroughStream; use React\Tests\Http\TestCase; +use function React\Async\await; +use function React\Promise\reject; +use function React\Promise\resolve; class TransactionTest extends TestCase { @@ -24,7 +27,7 @@ public function testWithOptionsReturnsNewInstanceWithChangedOption() $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); $transaction = new Transaction($sender, $loop); - $new = $transaction->withOptions(array('followRedirects' => false)); + $new = $transaction->withOptions(['followRedirects' => false]); $this->assertInstanceOf('React\Http\Io\Transaction', $new); $this->assertNotSame($transaction, $new); @@ -41,7 +44,7 @@ public function testWithOptionsDoesNotChangeOriginalInstance() $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); $transaction = new Transaction($sender, $loop); - $transaction->withOptions(array('followRedirects' => false)); + $transaction->withOptions(['followRedirects' => false]); $ref = new \ReflectionProperty($transaction, 'followRedirects'); $ref->setAccessible(true); @@ -55,8 +58,8 @@ public function testWithOptionsNullValueReturnsNewInstanceWithDefaultOption() $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('followRedirects' => false)); - $transaction = $transaction->withOptions(array('followRedirects' => null)); + $transaction = $transaction->withOptions(['followRedirects' => false]); + $transaction = $transaction->withOptions(['followRedirects' => null]); $ref = new \ReflectionProperty($transaction, 'followRedirects'); $ref->setAccessible(true); @@ -74,10 +77,10 @@ public function testTimeoutExplicitOptionWillStartTimeoutTimer() $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); @@ -93,7 +96,7 @@ public function testTimeoutImplicitFromIniWillStartTimeoutTimer() $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); @@ -119,10 +122,10 @@ public function testTimeoutExplicitOptionWillRejectWhenTimerFires() $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $this->assertNotNull($timeout); @@ -143,13 +146,13 @@ public function testTimeoutExplicitOptionWillNotStartTimeoutWhenSenderResolvesIm $loop->expects($this->never())->method('addTimer'); $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), ''); + $response = new Response(200, [], ''); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(resolve($response)); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 0.001)); + $transaction = $transaction->withOptions(['timeout' => 0.001]); $promise = $transaction->send($request); $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); @@ -164,14 +167,14 @@ public function testTimeoutExplicitOptionWillCancelTimeoutTimerWhenSenderResolve $loop->expects($this->once())->method('cancelTimer')->with($timer); $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), ''); + $response = new Response(200, [], ''); $deferred = new Deferred(); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn($deferred->promise()); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 0.001)); + $transaction = $transaction->withOptions(['timeout' => 0.001]); $promise = $transaction->send($request); $deferred->resolve($response); @@ -189,10 +192,10 @@ public function testTimeoutExplicitOptionWillNotStartTimeoutWhenSenderRejectsImm $exception = new \RuntimeException(); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\reject($exception)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(reject($exception)); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 0.001)); + $transaction = $transaction->withOptions(['timeout' => 0.001]); $promise = $transaction->send($request); $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); @@ -213,7 +216,7 @@ public function testTimeoutExplicitOptionWillCancelTimeoutTimerWhenSenderRejects $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn($deferred->promise()); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 0.001)); + $transaction = $transaction->withOptions(['timeout' => 0.001]); $promise = $transaction->send($request); $exception = new \RuntimeException(); @@ -231,10 +234,10 @@ public function testTimeoutExplicitNegativeWillNotStartTimeoutTimer() $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => -1)); + $transaction = $transaction->withOptions(['timeout' => -1]); $promise = $transaction->send($request); $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); @@ -246,13 +249,13 @@ public function testTimeoutExplicitOptionWillNotStartTimeoutTimerWhenRequestBody $loop->expects($this->never())->method('addTimer'); $stream = new ThroughStream(); - $request = new Request('POST', 'http://example.com', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://example.com', [], new ReadableBodyStream($stream)); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); @@ -267,13 +270,13 @@ public function testTimeoutExplicitOptionWillStartTimeoutTimerWhenStreamingReque $stream = new ThroughStream(); $stream->close(); - $request = new Request('POST', 'http://example.com', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://example.com', [], new ReadableBodyStream($stream)); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); @@ -287,13 +290,13 @@ public function testTimeoutExplicitOptionWillStartTimeoutTimerWhenStreamingReque $loop->expects($this->never())->method('cancelTimer'); $stream = new ThroughStream(); - $request = new Request('POST', 'http://example.com', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://example.com', [], new ReadableBodyStream($stream)); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $stream->close(); @@ -307,14 +310,14 @@ public function testTimeoutExplicitOptionWillNotStartTimeoutTimerWhenStreamingRe $loop->expects($this->never())->method('addTimer'); $stream = new ThroughStream(); - $request = new Request('POST', 'http://example.com', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://example.com', [], new ReadableBodyStream($stream)); $deferred = new Deferred(); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn($deferred->promise()); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $deferred->reject(new \RuntimeException('Request failed')); @@ -337,13 +340,13 @@ public function testTimeoutExplicitOptionWillRejectWhenTimerFiresAfterStreamingR $loop->expects($this->never())->method('cancelTimer'); $stream = new ThroughStream(); - $request = new Request('POST', 'http://example.com', array(), new ReadableBodyStream($stream)); + $request = new Request('POST', 'http://example.com', [], new ReadableBodyStream($stream)); $sender = $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new \React\Promise\Promise(function () { })); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $stream->close(); @@ -368,10 +371,10 @@ public function testReceivingErrorResponseWillRejectWithResponseException() // mock sender to resolve promise with the given $response in response to the given $request $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(resolve($response)); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => -1)); + $transaction = $transaction->withOptions(['timeout' => -1]); $promise = $transaction->send($request); $exception = null; @@ -388,21 +391,21 @@ public function testReceivingStreamingBodyWillResolveWithBufferedResponseByDefau { $stream = new ThroughStream(); Loop::addTimer(0.001, function () use ($stream) { - $stream->emit('data', array('hello world')); + $stream->emit('data', ['hello world']); $stream->close(); }); $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($stream)); + $response = new Response(200, [], new ReadableBodyStream($stream)); // mock sender to resolve promise with the given $response in response to the given $request $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(resolve($response)); $transaction = new Transaction($sender, Loop::get()); $promise = $transaction->send($request); - $response = \React\Async\await($promise); + $response = await($promise); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('hello world', (string)$response->getBody()); @@ -415,11 +418,11 @@ public function testReceivingStreamingBodyWithContentLengthExceedingMaximumRespo $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array('Content-Length' => '100000000'), new ReadableBodyStream($stream, 100000000)); + $response = new Response(200, ['Content-Length' => '100000000'], new ReadableBodyStream($stream, 100000000)); // mock sender to resolve promise with the given $response in response to the given $request $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(resolve($response)); $transaction = new Transaction($sender, Loop::get()); @@ -446,14 +449,14 @@ public function testReceivingStreamingBodyWithContentsExceedingMaximumResponseBu $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($stream)); + $response = new Response(200, [], new ReadableBodyStream($stream)); // mock sender to resolve promise with the given $response in response to the given $request $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(resolve($response)); $transaction = new Transaction($sender, Loop::get()); - $transaction = $transaction->withOptions(array('maximumSize' => 10)); + $transaction = $transaction->withOptions(['maximumSize' => 10]); $promise = $transaction->send($request); $exception = null; @@ -479,11 +482,11 @@ public function testReceivingStreamingBodyWillRejectWhenStreamEmitsError() }); $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($stream)); + $response = new Response(200, [], new ReadableBodyStream($stream)); // mock sender to resolve promise with the given $response in response to the given $request $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(resolve($response)); $transaction = new Transaction($sender, Loop::get()); $promise = $transaction->send($request); @@ -511,7 +514,7 @@ public function testCancelBufferingResponseWillCloseStreamAndReject() $stream->expects($this->once())->method('close'); $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($stream)); + $response = new Response(200, [], new ReadableBodyStream($stream)); // mock sender to resolve promise with the given $response in response to the given $request $deferred = new Deferred(); @@ -541,14 +544,14 @@ public function testReceivingStreamingBodyWillResolveWithStreamingResponseIfStre $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock())); + $response = new Response(200, [], new ReadableBodyStream($this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock())); // mock sender to resolve promise with the given $response in response to the given $request $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn(resolve($response)); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('streaming' => true, 'timeout' => -1)); + $transaction = $transaction->withOptions(['streaming' => true, 'timeout' => -1]); $promise = $transaction->send($request); $response = null; @@ -566,13 +569,13 @@ public function testResponseCode304WithoutLocationWillResolveWithResponseAsIs() $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); // conditional GET request will respond with 304 (Not Modified - $request = new Request('GET', 'http://example.com', array('If-None-Match' => '"abc"')); - $response = new Response(304, array('ETag' => '"abc"')); + $request = new Request('GET', 'http://example.com', ['If-None-Match' => '"abc"']); + $response = new Response(304, ['ETag' => '"abc"']); $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($request)->willReturn(Promise\resolve($response)); + $sender->expects($this->once())->method('send')->with($request)->willReturn(resolve($response)); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => -1)); + $transaction = $transaction->withOptions(['timeout' => -1]); $promise = $transaction->send($request); $promise->then($this->expectCallableOnceWith($response)); @@ -584,16 +587,16 @@ public function testCustomRedirectResponseCode333WillFollowLocationHeaderAndSend // original GET request will respond with custom 333 redirect status code and follow location header $requestOriginal = new Request('GET', 'http://example.com'); - $response = new Response(333, array('Location' => 'foo')); + $response = new Response(333, ['Location' => 'foo']); $sender = $this->makeSenderMock(); $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($requestOriginal), - array($this->callback(function (RequestInterface $request) { + [$requestOriginal], + [$this->callback(function (RequestInterface $request) { return $request->getMethod() === 'GET' && (string)$request->getUri() === 'http://example.com/foo'; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($response), - new \React\Promise\Promise(function () { }) + resolve($response), + new Promise(function () { }) ); $transaction = new Transaction($sender, $loop); @@ -604,27 +607,26 @@ public function testFollowingRedirectWithSpecifiedHeaders() { $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $customHeaders = array('User-Agent' => 'Chrome'); + $customHeaders = ['User-Agent' => 'Chrome']; $requestWithUserAgent = new Request('GET', 'http://example.com', $customHeaders); $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in // response to the given $requestWithUserAgent - $redirectResponse = new Response(301, array('Location' => 'http://redirect.com')); + $redirectResponse = new Response(301, ['Location' => 'http://redirect.com']); // mock sender to resolve promise with the given $okResponse in // response to the given $requestWithUserAgent $okResponse = new Response(200); - $that = $this; $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array('Chrome'), $request->getHeader('User-Agent')); + [$this->anything()], + [$this->callback(function (RequestInterface $request) { + $this->assertEquals(['Chrome'], $request->getHeader('User-Agent')); return true; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), - Promise\resolve($okResponse) + resolve($redirectResponse), + resolve($okResponse) ); $transaction = new Transaction($sender, $loop); @@ -635,27 +637,26 @@ public function testRemovingAuthorizationHeaderWhenChangingHostnamesDuringRedire { $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $customHeaders = array('Authorization' => 'secret'); + $customHeaders = ['Authorization' => 'secret']; $requestWithAuthorization = new Request('GET', 'http://example.com', $customHeaders); $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in // response to the given $requestWithAuthorization - $redirectResponse = new Response(301, array('Location' => 'http://redirect.com')); + $redirectResponse = new Response(301, ['Location' => 'http://redirect.com']); // mock sender to resolve promise with the given $okResponse in // response to the given $requestWithAuthorization $okResponse = new Response(200); - $that = $this; $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->callback(function (RequestInterface $request) use ($that) { - $that->assertFalse($request->hasHeader('Authorization')); + [$this->anything()], + [$this->callback(function (RequestInterface $request) { + $this->assertFalse($request->hasHeader('Authorization')); return true; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), - Promise\resolve($okResponse) + resolve($redirectResponse), + resolve($okResponse) ); $transaction = new Transaction($sender, $loop); @@ -666,27 +667,26 @@ public function testAuthorizationHeaderIsForwardedWhenRedirectingToSameDomain() { $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $customHeaders = array('Authorization' => 'secret'); + $customHeaders = ['Authorization' => 'secret']; $requestWithAuthorization = new Request('GET', 'http://example.com', $customHeaders); $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in // response to the given $requestWithAuthorization - $redirectResponse = new Response(301, array('Location' => 'http://example.com/new')); + $redirectResponse = new Response(301, ['Location' => 'http://example.com/new']); // mock sender to resolve promise with the given $okResponse in // response to the given $requestWithAuthorization $okResponse = new Response(200); - $that = $this; $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals(array('secret'), $request->getHeader('Authorization')); + [$this->anything()], + [$this->callback(function (RequestInterface $request) { + $this->assertEquals(['secret'], $request->getHeader('Authorization')); return true; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), - Promise\resolve($okResponse) + resolve($redirectResponse), + resolve($okResponse) ); $transaction = new Transaction($sender, $loop); @@ -702,22 +702,21 @@ public function testAuthorizationHeaderIsForwardedWhenLocationContainsAuthentica // mock sender to resolve promise with the given $redirectResponse in // response to the given $requestWithAuthorization - $redirectResponse = new Response(301, array('Location' => 'http://user:pass@example.com/new')); + $redirectResponse = new Response(301, ['Location' => 'http://user:pass@example.com/new']); // mock sender to resolve promise with the given $okResponse in // response to the given $requestWithAuthorization $okResponse = new Response(200); - $that = $this; $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('user:pass', $request->getUri()->getUserInfo()); - $that->assertFalse($request->hasHeader('Authorization')); + [$this->anything()], + [$this->callback(function (RequestInterface $request) { + $this->assertEquals('user:pass', $request->getUri()->getUserInfo()); + $this->assertFalse($request->hasHeader('Authorization')); return true; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), - Promise\resolve($okResponse) + resolve($redirectResponse), + resolve($okResponse) ); $transaction = new Transaction($sender, $loop); @@ -728,32 +727,31 @@ public function testSomeRequestHeadersShouldBeRemovedWhenRedirecting() { $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $customHeaders = array( + $customHeaders = [ 'Content-Type' => 'text/html; charset=utf-8', - 'Content-Length' => '111', - ); + 'Content-Length' => '111' + ]; $requestWithCustomHeaders = new Request('GET', 'http://example.com', $customHeaders); $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in // response to the given $requestWithCustomHeaders - $redirectResponse = new Response(301, array('Location' => 'http://example.com/new')); + $redirectResponse = new Response(301, ['Location' => 'http://example.com/new']); // mock sender to resolve promise with the given $okResponse in // response to the given $requestWithCustomHeaders $okResponse = new Response(200); - $that = $this; $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->callback(function (RequestInterface $request) use ($that) { - $that->assertFalse($request->hasHeader('Content-Type')); - $that->assertFalse($request->hasHeader('Content-Length')); + [$this->anything()], + [$this->callback(function (RequestInterface $request) { + $this->assertFalse($request->hasHeader('Content-Type')); + $this->assertFalse($request->hasHeader('Content-Length')); return true; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), - Promise\resolve($okResponse) + resolve($redirectResponse), + resolve($okResponse) ); $transaction = new Transaction($sender, $loop); @@ -764,33 +762,32 @@ public function testRequestMethodShouldBeChangedWhenRedirectingWithSeeOther() { $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $customHeaders = array( + $customHeaders = [ 'Content-Type' => 'text/html; charset=utf-8', - 'Content-Length' => '111', - ); + 'Content-Length' => '111' + ]; $request = new Request('POST', 'http://example.com', $customHeaders); $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in // response to the given $request - $redirectResponse = new Response(303, array('Location' => 'http://example.com/new')); + $redirectResponse = new Response(303, ['Location' => 'http://example.com/new']); // mock sender to resolve promise with the given $okResponse in // response to the given $request $okResponse = new Response(200); - $that = $this; $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('GET', $request->getMethod()); - $that->assertFalse($request->hasHeader('Content-Type')); - $that->assertFalse($request->hasHeader('Content-Length')); + [$this->anything()], + [$this->callback(function (RequestInterface $request) { + $this->assertEquals('GET', $request->getMethod()); + $this->assertFalse($request->hasHeader('Content-Type')); + $this->assertFalse($request->hasHeader('Content-Length')); return true; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), - Promise\resolve($okResponse) + resolve($redirectResponse), + resolve($okResponse) ); $transaction = new Transaction($sender, $loop); @@ -801,40 +798,39 @@ public function testRequestMethodAndBodyShouldNotBeChangedWhenRedirectingWith307 { $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $customHeaders = array( + $customHeaders = [ 'Content-Type' => 'text/html; charset=utf-8', - 'Content-Length' => '111', - ); + 'Content-Length' => '111' + ]; $request = new Request('POST', 'http://example.com', $customHeaders, '{"key":"value"}'); $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in // response to the given $request - $redirectResponse = new Response(307, array('Location' => 'http://example.com/new')); + $redirectResponse = new Response(307, ['Location' => 'http://example.com/new']); // mock sender to resolve promise with the given $okResponse in // response to the given $request $okResponse = new Response(200); - $that = $this; $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->callback(function (RequestInterface $request) use ($that) { - $that->assertEquals('POST', $request->getMethod()); - $that->assertEquals('{"key":"value"}', (string)$request->getBody()); - $that->assertEquals( - array( - 'Content-Type' => array('text/html; charset=utf-8'), - 'Content-Length' => array('111'), - 'Host' => array('example.com') - ), + [$this->anything()], + [$this->callback(function (RequestInterface $request) { + $this->assertEquals('POST', $request->getMethod()); + $this->assertEquals('{"key":"value"}', (string)$request->getBody()); + $this->assertEquals( + [ + 'Content-Type' => ['text/html; charset=utf-8'], + 'Content-Length' => ['111'], + 'Host' => ['example.com'] + ], $request->getHeaders() ); return true; - })) + })] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), - Promise\resolve($okResponse) + resolve($redirectResponse), + resolve($okResponse) ); $transaction = new Transaction($sender, $loop); @@ -845,10 +841,10 @@ public function testRedirectingStreamingBodyWith307Or308ShouldThrowCantRedirectS { $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $customHeaders = array( + $customHeaders = [ 'Content-Type' => 'text/html; charset=utf-8', - 'Content-Length' => '111', - ); + 'Content-Length' => '111' + ]; $stream = new ThroughStream(); $request = new Request('POST', 'http://example.com', $customHeaders, new ReadableBodyStream($stream)); @@ -856,12 +852,12 @@ public function testRedirectingStreamingBodyWith307Or308ShouldThrowCantRedirectS // mock sender to resolve promise with the given $redirectResponse in // response to the given $request - $redirectResponse = new Response(307, array('Location' => 'http://example.com/new')); + $redirectResponse = new Response(307, ['Location' => 'http://example.com/new']); $sender->expects($this->once())->method('send')->withConsecutive( - array($this->anything()) + [$this->anything()] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse) + resolve($redirectResponse) ); $transaction = new Transaction($sender, $loop); @@ -883,7 +879,7 @@ public function testCancelTransactionWillCancelRequest() $request = new Request('GET', 'http://example.com'); $sender = $this->makeSenderMock(); - $pending = new \React\Promise\Promise(function () { }, $this->expectCallableOnce()); + $pending = new Promise(function () { }, $this->expectCallableOnce()); // mock sender to return pending promise which should be cancelled when cancelling result $sender->expects($this->once())->method('send')->willReturn($pending); @@ -904,13 +900,13 @@ public function testCancelTransactionWillCancelTimeoutTimer() $request = new Request('GET', 'http://example.com'); $sender = $this->makeSenderMock(); - $pending = new \React\Promise\Promise(function () { }, function () { throw new \RuntimeException(); }); + $pending = new Promise(function () { }, function () { throw new \RuntimeException(); }); // mock sender to return pending promise which should be cancelled when cancelling result $sender->expects($this->once())->method('send')->willReturn($pending); $transaction = new Transaction($sender, $loop); - $transaction = $transaction->withOptions(array('timeout' => 2)); + $transaction = $transaction->withOptions(['timeout' => 2]); $promise = $transaction->send($request); $promise->cancel(); @@ -924,16 +920,16 @@ public function testCancelTransactionWillCancelRedirectedRequest() $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in - $redirectResponse = new Response(301, array('Location' => 'http://example.com/new')); + $redirectResponse = new Response(301, ['Location' => 'http://example.com/new']); - $pending = new \React\Promise\Promise(function () { }, $this->expectCallableOnce()); + $pending = new Promise(function () { }, $this->expectCallableOnce()); // mock sender to return pending promise which should be cancelled when cancelling result $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->anything()) + [$this->anything()], + [$this->anything()] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), + resolve($redirectResponse), $pending ); @@ -953,12 +949,12 @@ public function testCancelTransactionWillCancelRedirectedRequestAgain() // mock sender to resolve promise with the given $redirectResponse in $first = new Deferred(); - $second = new \React\Promise\Promise(function () { }, $this->expectCallableOnce()); + $second = new Promise(function () { }, $this->expectCallableOnce()); // mock sender to return pending promise which should be cancelled when cancelling result $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->anything()) + [$this->anything()], + [$this->anything()] )->willReturnOnConsecutiveCalls( $first->promise(), $second @@ -968,7 +964,7 @@ public function testCancelTransactionWillCancelRedirectedRequestAgain() $promise = $transaction->send($request); // mock sender to resolve promise with the given $redirectResponse in - $first->resolve(new Response(301, array('Location' => 'http://example.com/new'))); + $first->resolve(new Response(301, ['Location' => 'http://example.com/new'])); $promise->cancel(); } @@ -990,7 +986,7 @@ public function testCancelTransactionWillCloseBufferingStream() $transaction = new Transaction($sender, $loop); $promise = $transaction->send($request); - $redirectResponse = new Response(301, array('Location' => 'http://example.com/new'), new ReadableBodyStream($body)); + $redirectResponse = new Response(301, ['Location' => 'http://example.com/new'], new ReadableBodyStream($body)); $deferred->resolve($redirectResponse); $promise->cancel(); @@ -1013,7 +1009,7 @@ public function testCancelTransactionWillCloseBufferingStreamAgain() $body->on('close', $this->expectCallableOnce()); // mock sender to resolve promise with the given $redirectResponse in - $first->resolve(new Response(301, array('Location' => 'http://example.com/new'), new ReadableBodyStream($body))); + $first->resolve(new Response(301, ['Location' => 'http://example.com/new'], new ReadableBodyStream($body))); $promise->cancel(); } @@ -1025,16 +1021,16 @@ public function testCancelTransactionShouldCancelSendingPromise() $sender = $this->makeSenderMock(); // mock sender to resolve promise with the given $redirectResponse in - $redirectResponse = new Response(301, array('Location' => 'http://example.com/new')); + $redirectResponse = new Response(301, ['Location' => 'http://example.com/new']); - $pending = new \React\Promise\Promise(function () { }, $this->expectCallableOnce()); + $pending = new Promise(function () { }, $this->expectCallableOnce()); // mock sender to return pending promise which should be cancelled when cancelling result $sender->expects($this->exactly(2))->method('send')->withConsecutive( - array($this->anything()), - array($this->anything()) + [$this->anything()], + [$this->anything()] )->willReturnOnConsecutiveCalls( - Promise\resolve($redirectResponse), + resolve($redirectResponse), $pending ); diff --git a/tests/Io/UploadedFileTest.php b/tests/Io/UploadedFileTest.php index 4e9c0dd5..adbed51c 100644 --- a/tests/Io/UploadedFileTest.php +++ b/tests/Io/UploadedFileTest.php @@ -10,12 +10,12 @@ class UploadedFileTest extends TestCase { public function failtyErrorProvider() { - return array( - array('a'), - array(null), - array(-1), - array(9), - ); + return [ + ['a'], + [null], + [-1], + [9] + ]; } /** diff --git a/tests/Message/RequestTest.php b/tests/Message/RequestTest.php index 29baf8a7..543ddb88 100644 --- a/tests/Message/RequestTest.php +++ b/tests/Message/RequestTest.php @@ -14,7 +14,7 @@ public function testConstructWithStringRequestBodyReturnsStringBodyWithAutomatic $request = new Request( 'GET', 'http://localhost', - array(), + [], 'foo' ); @@ -28,7 +28,7 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWhichImplementsR $request = new Request( 'GET', 'http://localhost', - array(), + [], new ThroughStream() ); @@ -43,7 +43,7 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() $request = new Request( 'GET', 'http://localhost', - array(), + [], $body = new HttpBodyStream(new ThroughStream(), 100) ); @@ -56,7 +56,7 @@ public function testConstructWithNullBodyThrows() new Request( 'GET', 'http://localhost', - array(), + [], null ); } diff --git a/tests/Message/ResponseTest.php b/tests/Message/ResponseTest.php index 1c70ae3a..61acf19e 100644 --- a/tests/Message/ResponseTest.php +++ b/tests/Message/ResponseTest.php @@ -11,7 +11,7 @@ class ResponseTest extends TestCase { public function testConstructWithStringBodyWillReturnStreamInstance() { - $response = new Response(200, array(), 'hello'); + $response = new Response(200, [], 'hello'); $body = $response->getBody(); /** @var \Psr\Http\Message\StreamInterface $body */ @@ -21,7 +21,7 @@ public function testConstructWithStringBodyWillReturnStreamInstance() public function testConstructWithStreamingBodyWillReturnReadableBodyStream() { - $response = new Response(200, array(), new ThroughStream()); + $response = new Response(200, [], new ThroughStream()); $body = $response->getBody(); /** @var \Psr\Http\Message\StreamInterface $body */ @@ -35,7 +35,7 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() { $response = new Response( 200, - array(), + [], $body = new HttpBodyStream(new ThroughStream(), 100) ); @@ -45,13 +45,13 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() public function testFloatBodyWillThrow() { $this->setExpectedException('InvalidArgumentException'); - new Response(200, array(), 1.0); + new Response(200, [], 1.0); } public function testResourceBodyWillThrow() { $this->setExpectedException('InvalidArgumentException'); - new Response(200, array(), tmpfile()); + new Response(200, [], tmpfile()); } public function testWithStatusReturnsNewInstanceWhenStatusIsChanged() @@ -99,7 +99,7 @@ public function testHtmlMethodReturnsHtmlResponse() public function testJsonMethodReturnsPrettyPrintedJsonResponse() { - $response = Response::json(array('text' => 'Hello wörld!')); + $response = Response::json(['text' => 'Hello wörld!']); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('application/json', $response->getHeaderLine('Content-Type')); @@ -155,7 +155,7 @@ public function testParseMessageWithMinimalOkResponse() $this->assertEquals('1.1', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); - $this->assertEquals(array(), $response->getHeaders()); + $this->assertEquals([], $response->getHeaders()); } public function testParseMessageWithSimpleOkResponse() @@ -165,7 +165,7 @@ public function testParseMessageWithSimpleOkResponse() $this->assertEquals('1.1', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); - $this->assertEquals(array('Server' => array('demo')), $response->getHeaders()); + $this->assertEquals(['Server' => ['demo']], $response->getHeaders()); } public function testParseMessageWithSimpleOkResponseWithCustomReasonPhrase() @@ -175,7 +175,7 @@ public function testParseMessageWithSimpleOkResponseWithCustomReasonPhrase() $this->assertEquals('1.1', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('Mostly Okay', $response->getReasonPhrase()); - $this->assertEquals(array('Server' => array('demo')), $response->getHeaders()); + $this->assertEquals(['Server' => ['demo']], $response->getHeaders()); } public function testParseMessageWithSimpleOkResponseWithEmptyReasonPhraseAppliesDefault() @@ -185,7 +185,7 @@ public function testParseMessageWithSimpleOkResponseWithEmptyReasonPhraseApplies $this->assertEquals('1.1', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); - $this->assertEquals(array('Server' => array('demo')), $response->getHeaders()); + $this->assertEquals(['Server' => ['demo']], $response->getHeaders()); } public function testParseMessageWithSimpleOkResponseWithoutReasonPhraseAndWhitespaceSeparatorAppliesDefault() @@ -195,7 +195,7 @@ public function testParseMessageWithSimpleOkResponseWithoutReasonPhraseAndWhites $this->assertEquals('1.1', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); - $this->assertEquals(array('Server' => array('demo')), $response->getHeaders()); + $this->assertEquals(['Server' => ['demo']], $response->getHeaders()); } public function testParseMessageWithHttp10SimpleOkResponse() @@ -205,7 +205,7 @@ public function testParseMessageWithHttp10SimpleOkResponse() $this->assertEquals('1.0', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); - $this->assertEquals(array('Server' => array('demo')), $response->getHeaders()); + $this->assertEquals(['Server' => ['demo']], $response->getHeaders()); } public function testParseMessageWithHttp10SimpleOkResponseWithLegacyNewlines() @@ -215,7 +215,7 @@ public function testParseMessageWithHttp10SimpleOkResponseWithLegacyNewlines() $this->assertEquals('1.0', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); - $this->assertEquals(array('Server' => array('demo')), $response->getHeaders()); + $this->assertEquals(['Server' => ['demo']], $response->getHeaders()); } public function testParseMessageWithInvalidHttpProtocolVersion12Throws() diff --git a/tests/Message/ServerRequestTest.php b/tests/Message/ServerRequestTest.php index f82d60f8..36d20bfa 100644 --- a/tests/Message/ServerRequestTest.php +++ b/tests/Message/ServerRequestTest.php @@ -21,7 +21,7 @@ public function setUpRequest() public function testGetNoAttributes() { - $this->assertEquals(array(), $this->request->getAttributes()); + $this->assertEquals([], $this->request->getAttributes()); } public function testWithAttribute() @@ -29,7 +29,7 @@ public function testWithAttribute() $request = $this->request->withAttribute('hello', 'world'); $this->assertNotSame($request, $this->request); - $this->assertEquals(array('hello' => 'world'), $request->getAttributes()); + $this->assertEquals(['hello' => 'world'], $request->getAttributes()); } public function testGetAttribute() @@ -56,61 +56,61 @@ public function testWithoutAttribute() $request = $request->withoutAttribute('hello'); $this->assertNotSame($request, $this->request); - $this->assertEquals(array('test' => 'nice'), $request->getAttributes()); + $this->assertEquals(['test' => 'nice'], $request->getAttributes()); } public function testGetQueryParamsFromConstructorUri() { $this->request = new ServerRequest('GET', 'http://localhost/?test=world'); - $this->assertEquals(array('test' => 'world'), $this->request->getQueryParams()); + $this->assertEquals(['test' => 'world'], $this->request->getQueryParams()); } public function testWithCookieParams() { - $request = $this->request->withCookieParams(array('test' => 'world')); + $request = $this->request->withCookieParams(['test' => 'world']); $this->assertNotSame($request, $this->request); - $this->assertEquals(array('test' => 'world'), $request->getCookieParams()); + $this->assertEquals(['test' => 'world'], $request->getCookieParams()); } public function testGetQueryParamsFromConstructorUriUrlencoded() { $this->request = new ServerRequest('GET', 'http://localhost/?test=hello+world%21'); - $this->assertEquals(array('test' => 'hello world!'), $this->request->getQueryParams()); + $this->assertEquals(['test' => 'hello world!'], $this->request->getQueryParams()); } public function testWithQueryParams() { - $request = $this->request->withQueryParams(array('test' => 'world')); + $request = $this->request->withQueryParams(['test' => 'world']); $this->assertNotSame($request, $this->request); - $this->assertEquals(array('test' => 'world'), $request->getQueryParams()); + $this->assertEquals(['test' => 'world'], $request->getQueryParams()); } public function testWithQueryParamsWithoutSpecialEncoding() { - $request = $this->request->withQueryParams(array('test' => 'hello world!')); + $request = $this->request->withQueryParams(['test' => 'hello world!']); $this->assertNotSame($request, $this->request); - $this->assertEquals(array('test' => 'hello world!'), $request->getQueryParams()); + $this->assertEquals(['test' => 'hello world!'], $request->getQueryParams()); } public function testWithUploadedFiles() { - $request = $this->request->withUploadedFiles(array('test' => 'world')); + $request = $this->request->withUploadedFiles(['test' => 'world']); $this->assertNotSame($request, $this->request); - $this->assertEquals(array('test' => 'world'), $request->getUploadedFiles()); + $this->assertEquals(['test' => 'world'], $request->getUploadedFiles()); } public function testWithParsedBody() { - $request = $this->request->withParsedBody(array('test' => 'world')); + $request = $this->request->withParsedBody(['test' => 'world']); $this->assertNotSame($request, $this->request); - $this->assertEquals(array('test' => 'world'), $request->getParsedBody()); + $this->assertEquals(['test' => 'world'], $request->getParsedBody()); } public function testServerRequestParameter() @@ -119,10 +119,10 @@ public function testServerRequestParameter() $request = new ServerRequest( 'POST', 'http://127.0.0.1', - array('Content-Length' => strlen($body)), + ['Content-Length' => strlen($body)], $body, '1.0', - array('SERVER_ADDR' => '127.0.0.1') + ['SERVER_ADDR' => '127.0.0.1'] ); $serverParams = $request->getServerParams(); @@ -139,11 +139,11 @@ public function testParseSingleCookieNameValuePairWillReturnValidArray() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'hello=world') + ['Cookie' => 'hello=world'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('hello' => 'world'), $cookies); + $this->assertEquals(['hello' => 'world'], $cookies); } public function testParseMultipleCookieNameValuePairWillReturnValidArray() @@ -151,11 +151,11 @@ public function testParseMultipleCookieNameValuePairWillReturnValidArray() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'hello=world; test=abc') + ['Cookie' => 'hello=world; test=abc'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('hello' => 'world', 'test' => 'abc'), $cookies); + $this->assertEquals(['hello' => 'world', 'test' => 'abc'], $cookies); } public function testParseMultipleCookieHeadersAreNotAllowedAndWillReturnEmptyArray() @@ -163,11 +163,11 @@ public function testParseMultipleCookieHeadersAreNotAllowedAndWillReturnEmptyArr $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => array('hello=world', 'test=abc')) + ['Cookie' => ['hello=world', 'test=abc']] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array(), $cookies); + $this->assertEquals([], $cookies); } public function testMultipleCookiesWithSameNameWillReturnLastValue() @@ -175,11 +175,11 @@ public function testMultipleCookiesWithSameNameWillReturnLastValue() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'hello=world; hello=abc') + ['Cookie' => 'hello=world; hello=abc'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('hello' => 'abc'), $cookies); + $this->assertEquals(['hello' => 'abc'], $cookies); } public function testOtherEqualSignsWillBeAddedToValueAndWillReturnValidArray() @@ -187,11 +187,11 @@ public function testOtherEqualSignsWillBeAddedToValueAndWillReturnValidArray() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'hello=world=test=php') + ['Cookie' => 'hello=world=test=php'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('hello' => 'world=test=php'), $cookies); + $this->assertEquals(['hello' => 'world=test=php'], $cookies); } public function testSingleCookieValueInCookiesReturnsEmptyArray() @@ -199,11 +199,11 @@ public function testSingleCookieValueInCookiesReturnsEmptyArray() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'world') + ['Cookie' => 'world'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array(), $cookies); + $this->assertEquals([], $cookies); } public function testSingleMutlipleCookieValuesReturnsEmptyArray() @@ -211,11 +211,11 @@ public function testSingleMutlipleCookieValuesReturnsEmptyArray() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'world; test') + ['Cookie' => 'world; test'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array(), $cookies); + $this->assertEquals([], $cookies); } public function testSingleValueIsValidInMultipleValueCookieWillReturnValidArray() @@ -223,11 +223,11 @@ public function testSingleValueIsValidInMultipleValueCookieWillReturnValidArray( $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'world; test=php') + ['Cookie' => 'world; test=php'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('test' => 'php'), $cookies); + $this->assertEquals(['test' => 'php'], $cookies); } public function testUrlEncodingForValueWillReturnValidArray() @@ -235,11 +235,11 @@ public function testUrlEncodingForValueWillReturnValidArray() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'hello=world%21; test=100%25%20coverage') + ['Cookie' => 'hello=world%21; test=100%25%20coverage'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('hello' => 'world!', 'test' => '100% coverage'), $cookies); + $this->assertEquals(['hello' => 'world!', 'test' => '100% coverage'], $cookies); } public function testUrlEncodingForKeyWillReturnValidArray() @@ -247,11 +247,11 @@ public function testUrlEncodingForKeyWillReturnValidArray() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'react%3Bphp=is%20great') + ['Cookie' => 'react%3Bphp=is%20great'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('react%3Bphp' => 'is great'), $cookies); + $this->assertEquals(['react%3Bphp' => 'is great'], $cookies); } public function testCookieWithoutSpaceAfterSeparatorWillBeAccepted() @@ -259,11 +259,11 @@ public function testCookieWithoutSpaceAfterSeparatorWillBeAccepted() $this->request = new ServerRequest( 'GET', 'http://localhost', - array('Cookie' => 'hello=world;react=php') + ['Cookie' => 'hello=world;react=php'] ); $cookies = $this->request->getCookieParams(); - $this->assertEquals(array('hello' => 'world', 'react' => 'php'), $cookies); + $this->assertEquals(['hello' => 'world', 'react' => 'php'], $cookies); } public function testConstructWithStringRequestBodyReturnsStringBodyWithAutomaticSize() @@ -271,7 +271,7 @@ public function testConstructWithStringRequestBodyReturnsStringBodyWithAutomatic $request = new ServerRequest( 'GET', 'http://localhost', - array(), + [], 'foo' ); @@ -285,7 +285,7 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() $request = new ServerRequest( 'GET', 'http://localhost', - array(), + [], $body = new HttpBodyStream(new ThroughStream(), 100) ); @@ -297,7 +297,7 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWhichImplementsR $request = new ServerRequest( 'GET', 'http://localhost', - array(), + [], new ThroughStream() ); @@ -312,9 +312,9 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWithSizeFromCont $request = new ServerRequest( 'GET', 'http://localhost', - array( + [ 'Content-Length' => 100 - ), + ], new ThroughStream() ); @@ -329,9 +329,9 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWithSizeUnknownF $request = new ServerRequest( 'GET', 'http://localhost', - array( + [ 'Transfer-Encoding' => 'Chunked' - ), + ], new ThroughStream() ); @@ -347,7 +347,7 @@ public function testConstructWithFloatRequestBodyThrows() new ServerRequest( 'GET', 'http://localhost', - array(), + [], 1.0 ); } @@ -358,14 +358,14 @@ public function testConstructWithResourceRequestBodyThrows() new ServerRequest( 'GET', 'http://localhost', - array(), + [], tmpfile() ); } public function testParseMessageWithSimpleGetRequest() { - $request = ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: example.com\r\n", array()); + $request = ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: example.com\r\n", []); $this->assertEquals('GET', $request->getMethod()); $this->assertEquals('http://example.com/', (string) $request->getUri()); @@ -374,7 +374,7 @@ public function testParseMessageWithSimpleGetRequest() public function testParseMessageWithHttp10RequestWithoutHost() { - $request = ServerRequest::parseMessage("GET / HTTP/1.0\r\n", array()); + $request = ServerRequest::parseMessage("GET / HTTP/1.0\r\n", []); $this->assertEquals('GET', $request->getMethod()); $this->assertEquals('http://127.0.0.1/', (string) $request->getUri()); @@ -383,7 +383,7 @@ public function testParseMessageWithHttp10RequestWithoutHost() public function testParseMessageWithOptionsMethodWithAsteriskFormRequestTarget() { - $request = ServerRequest::parseMessage("OPTIONS * HTTP/1.1\r\nHost: example.com\r\n", array()); + $request = ServerRequest::parseMessage("OPTIONS * HTTP/1.1\r\nHost: example.com\r\n", []); $this->assertEquals('OPTIONS', $request->getMethod()); $this->assertEquals('*', $request->getRequestTarget()); @@ -393,7 +393,7 @@ public function testParseMessageWithOptionsMethodWithAsteriskFormRequestTarget() public function testParseMessageWithConnectMethodWithAuthorityFormRequestTarget() { - $request = ServerRequest::parseMessage("CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\n", array()); + $request = ServerRequest::parseMessage("CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\n", []); $this->assertEquals('CONNECT', $request->getMethod()); $this->assertEquals('example.com:80', $request->getRequestTarget()); @@ -404,84 +404,84 @@ public function testParseMessageWithConnectMethodWithAuthorityFormRequestTarget( public function testParseMessageWithInvalidHttp11RequestWithoutHostThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\n", []); } public function testParseMessageWithInvalidHttpProtocolVersionThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.2\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.2\r\n", []); } public function testParseMessageWithInvalidProtocolThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / CUSTOM/1.1\r\n", array()); + ServerRequest::parseMessage("GET / CUSTOM/1.1\r\n", []); } public function testParseMessageWithInvalidHostHeaderWithoutValueThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost\r\n", []); } public function testParseMessageWithInvalidHostHeaderSyntaxThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: ///\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: ///\r\n", []); } public function testParseMessageWithInvalidHostHeaderWithSchemeThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: http://localhost\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: http://localhost\r\n", []); } public function testParseMessageWithInvalidHostHeaderWithQueryThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost?foo\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost?foo\r\n", []); } public function testParseMessageWithInvalidHostHeaderWithFragmentThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost#foo\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost#foo\r\n", []); } public function testParseMessageWithInvalidContentLengthHeaderThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length:\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length:\r\n", []); } public function testParseMessageWithInvalidTransferEncodingHeaderThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding:\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding:\r\n", []); } public function testParseMessageWithInvalidBothContentLengthHeaderAndTransferEncodingHeaderThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nTransfer-Encoding: chunked\r\n", array()); + ServerRequest::parseMessage("GET / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nTransfer-Encoding: chunked\r\n", []); } public function testParseMessageWithInvalidEmptyHostHeaderWithAbsoluteFormRequestTargetThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET http://example.com/ HTTP/1.1\r\nHost: \r\n", array()); + ServerRequest::parseMessage("GET http://example.com/ HTTP/1.1\r\nHost: \r\n", []); } public function testParseMessageWithInvalidConnectMethodNotUsingAuthorityFormThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("CONNECT / HTTP/1.1\r\nHost: localhost\r\n", array()); + ServerRequest::parseMessage("CONNECT / HTTP/1.1\r\nHost: localhost\r\n", []); } public function testParseMessageWithInvalidRequestTargetAsteriskFormThrows() { $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET * HTTP/1.1\r\nHost: localhost\r\n", array()); + ServerRequest::parseMessage("GET * HTTP/1.1\r\nHost: localhost\r\n", []); } } diff --git a/tests/Message/UriTest.php b/tests/Message/UriTest.php index 10f355df..cdbc5a87 100644 --- a/tests/Message/UriTest.php +++ b/tests/Message/UriTest.php @@ -33,95 +33,95 @@ public function testCtorWithInvalidPortThrows() public static function provideValidUris() { - return array( - array( + return [ + [ 'http://localhost' - ), - array( + ], + [ 'http://localhost/' - ), - array( + ], + [ 'http://localhost:8080/' - ), - array( + ], + [ 'http://127.0.0.1/' - ), - array( + ], + [ 'http://[::1]:8080/' - ), - array( + ], + [ 'http://localhost/path' - ), - array( + ], + [ 'http://localhost/sub/path' - ), - array( + ], + [ 'http://localhost/with%20space' - ), - array( + ], + [ 'http://localhost/with%2fslash' - ), - array( + ], + [ 'http://localhost/?name=Alice' - ), - array( + ], + [ 'http://localhost/?name=John+Doe' - ), - array( + ], + [ 'http://localhost/?name=John%20Doe' - ), - array( + ], + [ 'http://localhost/?name=Alice&age=42' - ), - array( + ], + [ 'http://localhost/?name=Alice&' - ), - array( + ], + [ 'http://localhost/?choice=A%26B' - ), - array( + ], + [ 'http://localhost/?safe=Yes!?' - ), - array( + ], + [ 'http://localhost/?alias=@home' - ), - array( + ], + [ 'http://localhost/?assign:=true' - ), - array( + ], + [ 'http://localhost/?name=' - ), - array( + ], + [ 'http://localhost/?name' - ), - array( + ], + [ '' - ), - array( + ], + [ '/' - ), - array( + ], + [ '/path' - ), - array( + ], + [ 'path' - ), - array( + ], + [ 'http://user@localhost/' - ), - array( + ], + [ 'http://user:@localhost/' - ), - array( + ], + [ 'http://:pass@localhost/' - ), - array( + ], + [ 'http://user:pass@localhost/path?query#fragment' - ), - array( + ], + [ 'http://user%20name:pass%20word@localhost/path%20name?query%20name#frag%20ment' - ) - ); + ] + ]; } /** @@ -137,36 +137,36 @@ public function testToStringReturnsOriginalUriGivenToCtor($string) public static function provideValidUrisThatWillBeTransformed() { - return array( - array( + return [ + [ 'http://localhost:8080/?', 'http://localhost:8080/' - ), - array( + ], + [ 'http://localhost:8080/#', 'http://localhost:8080/' - ), - array( + ], + [ 'http://localhost:8080/?#', 'http://localhost:8080/' - ), - array( + ], + [ 'http://@localhost:8080/', 'http://localhost:8080/' - ), - array( + ], + [ 'http://localhost:8080/?percent=50%', 'http://localhost:8080/?percent=50%25' - ), - array( + ], + [ 'http://user name:pass word@localhost/path name?query name#frag ment', 'http://user%20name:pass%20word@localhost/path%20name?query%20name#frag%20ment' - ), - array( + ], + [ 'HTTP://USER:PASS@LOCALHOST:8080/PATH?QUERY#FRAGMENT', 'http://USER:PASS@localhost:8080/PATH?QUERY#FRAGMENT' - ) - ); + ] + ]; } /** @@ -576,113 +576,113 @@ public function testWithFragmentReturnsSameInstanceWhenFragmentIsUnchangedEncode public static function provideResolveUris() { - return array( - array( + return [ + [ 'http://localhost/', '', 'http://localhost/' - ), - array( + ], + [ 'http://localhost/', 'http://example.com/', 'http://example.com/' - ), - array( + ], + [ 'http://localhost/', 'path', 'http://localhost/path' - ), - array( + ], + [ 'http://localhost/', 'path/', 'http://localhost/path/' - ), - array( + ], + [ 'http://localhost/', 'path//', 'http://localhost/path/' - ), - array( + ], + [ 'http://localhost', 'path', 'http://localhost/path' - ), - array( + ], + [ 'http://localhost/a/b', '/path', 'http://localhost/path' - ), - array( + ], + [ 'http://localhost/', '/a/b/c', 'http://localhost/a/b/c' - ), - array( + ], + [ 'http://localhost/a/path', 'b/c', 'http://localhost/a/b/c' - ), - array( + ], + [ 'http://localhost/a/path', '/b/c', 'http://localhost/b/c' - ), - array( + ], + [ 'http://localhost/a/path/', 'b/c', 'http://localhost/a/path/b/c' - ), - array( + ], + [ 'http://localhost/a/path/', '../b/c', 'http://localhost/a/b/c' - ), - array( + ], + [ 'http://localhost', '../../../a/b', 'http://localhost/a/b' - ), - array( + ], + [ 'http://localhost/path', '?query', 'http://localhost/path?query' - ), - array( + ], + [ 'http://localhost/path', '#fragment', 'http://localhost/path#fragment' - ), - array( + ], + [ 'http://localhost/path', 'http://localhost', 'http://localhost' - ), - array( + ], + [ 'http://localhost/path', 'http://localhost/?query#fragment', 'http://localhost/?query#fragment' - ), - array( + ], + [ 'http://localhost/path/?a#fragment', '?b', 'http://localhost/path/?b' - ), - array( + ], + [ 'http://localhost/path', '//localhost', 'http://localhost' - ), - array( + ], + [ 'http://localhost/path', '//localhost/a?query', 'http://localhost/a?query' - ), - array( + ], + [ 'http://localhost/path', '//LOCALHOST', 'http://localhost' - ) - ); + ] + ]; } /** diff --git a/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php b/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php index 23455e6c..b79826d6 100644 --- a/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php +++ b/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php @@ -163,7 +163,7 @@ public function testStreamDoesNotPauseOrResumeWhenBelowLimit() $body->expects($this->never())->method('pause'); $body->expects($this->never())->method('resume'); $limitHandlers = new LimitConcurrentRequestsMiddleware(1); - $limitHandlers(new ServerRequest('GET', 'https://example.com/', array(), $body), function () {}); + $limitHandlers(new ServerRequest('GET', 'https://example.com/', [], $body), function () {}); } public function testStreamDoesPauseWhenAboveLimit() @@ -177,7 +177,7 @@ public function testStreamDoesPauseWhenAboveLimit() return new Promise(function () { }); }); - $limitHandlers(new ServerRequest('GET', 'https://example.com/', array(), $body), function () {}); + $limitHandlers(new ServerRequest('GET', 'https://example.com/', [], $body), function () {}); } public function testStreamDoesPauseAndThenResumeWhenDequeued() @@ -195,7 +195,7 @@ public function testStreamDoesPauseAndThenResumeWhenDequeued() assert($promise instanceof PromiseInterface); $promise->then(null, $this->expectCallableOnce()); // avoid reporting unhandled rejection - $limitHandlers(new ServerRequest('GET', 'https://example.com/', array(), $body), function () {}); + $limitHandlers(new ServerRequest('GET', 'https://example.com/', [], $body), function () {}); $deferred->reject(new \RuntimeException()); } @@ -205,7 +205,7 @@ public function testReceivesBufferedRequestSameInstance() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -224,7 +224,7 @@ public function testReceivesStreamingBodyRequestSameInstanceWhenBelowLimit() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 5) ); @@ -246,7 +246,7 @@ public function testReceivesRequestsSequentially() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -261,7 +261,7 @@ public function testDoesNotReceiveNextRequestIfHandlerIsPending() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -280,7 +280,7 @@ public function testReceivesNextRequestAfterPreviousHandlerIsSettled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -303,7 +303,7 @@ public function testReceivesNextRequestWhichThrowsAfterPreviousHandlerIsSettled( $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -331,7 +331,7 @@ public function testPendingRequestCanBeCancelledAndForwardsCancellationToInnerPr $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -354,7 +354,7 @@ public function testQueuedRequestCanBeCancelledBeforeItStartsProcessing() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -376,7 +376,7 @@ public function testReceivesNextRequestAfterPreviousHandlerIsCancelled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -400,7 +400,7 @@ public function testRejectsWhenQueuedPromiseIsCancelled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -422,7 +422,7 @@ public function testDoesNotInvokeNextHandlersWhenQueuedPromiseIsCancelled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -445,7 +445,7 @@ public function testReceivesStreamingBodyChangesInstanceWithCustomBodyButSameDat $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 5) ); @@ -494,7 +494,7 @@ public function testReceivesNextStreamingBodyWithBufferedDataAfterPreviousHandle $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 10) ); @@ -524,7 +524,7 @@ public function testReceivesNextStreamingBodyAndDoesNotEmitDataIfExplicitlyClose $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 10) ); @@ -555,7 +555,7 @@ public function testReceivesNextStreamingBodyAndDoesNotEmitDataIfExplicitlyPause $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 10) ); @@ -586,7 +586,7 @@ public function testReceivesNextStreamingBodyAndDoesEmitDataImmediatelyIfExplici $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 10) ); diff --git a/tests/Middleware/ProcessStack.php b/tests/Middleware/ProcessStack.php index 69bf34a8..22904310 100644 --- a/tests/Middleware/ProcessStack.php +++ b/tests/Middleware/ProcessStack.php @@ -3,7 +3,7 @@ namespace React\Tests\Http\Middleware; use Psr\Http\Message\ServerRequestInterface; -use React\Promise; +use function React\Promise\resolve; final class ProcessStack { @@ -15,7 +15,7 @@ final class ProcessStack public function __invoke(ServerRequestInterface $request, $stack) { $this->callCount++; - return Promise\resolve($stack($request)); + return resolve($stack($request)); } /** diff --git a/tests/Middleware/RequestBodyBufferMiddlewareTest.php b/tests/Middleware/RequestBodyBufferMiddlewareTest.php index 1c3b0b33..262ad9ca 100644 --- a/tests/Middleware/RequestBodyBufferMiddlewareTest.php +++ b/tests/Middleware/RequestBodyBufferMiddlewareTest.php @@ -11,6 +11,7 @@ use React\Http\Middleware\RequestBodyBufferMiddleware; use React\Stream\ThroughStream; use React\Tests\Http\TestCase; +use function React\Async\await; final class RequestBodyBufferMiddlewareTest extends TestCase { @@ -20,7 +21,7 @@ public function testBufferingResolvesWhenStreamEnds() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, 11) ); @@ -49,7 +50,7 @@ public function testAlreadyBufferedResolvesImmediately() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], $stream ); @@ -72,7 +73,7 @@ public function testEmptyStreamingResolvesImmediatelyWithEmptyBufferedBody() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], $body = new HttpBodyStream($stream, 0) ); @@ -95,7 +96,7 @@ public function testEmptyBufferedResolvesImmediatelyWithSameBody() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], '' ); $body = $serverRequest->getBody(); @@ -122,7 +123,7 @@ public function testClosedStreamResolvesImmediatelyWithEmptyBody() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, 2) ); @@ -145,7 +146,7 @@ public function testKnownExcessiveSizedBodyIsDiscardedAndRequestIsPassedDownToTh $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, 2) ); @@ -154,13 +155,13 @@ public function testKnownExcessiveSizedBodyIsDiscardedAndRequestIsPassedDownToTh $promise = $buffer( $serverRequest, function (ServerRequestInterface $request) { - return new Response(200, array(), $request->getBody()->getContents()); + return new Response(200, [], $request->getBody()->getContents()); } ); $stream->end('aa'); - $response = \React\Async\await($promise); + $response = await($promise); $this->assertSame(200, $response->getStatusCode()); $this->assertSame('', $response->getBody()->getContents()); @@ -175,15 +176,15 @@ public function testKnownExcessiveSizedWithIniLikeSize() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, 2048) ); $buffer = new RequestBodyBufferMiddleware('1K'); - $response = \React\Async\await($buffer( + $response = await($buffer( $serverRequest, function (ServerRequestInterface $request) { - return new Response(200, array(), $request->getBody()->getContents()); + return new Response(200, [], $request->getBody()->getContents()); } )); @@ -196,7 +197,7 @@ public function testAlreadyBufferedExceedingSizeResolvesImmediatelyWithEmptyBody $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], 'hello' ); @@ -219,7 +220,7 @@ public function testExcessiveSizeBodyIsDiscardedAndTheRequestIsPassedDownToTheNe $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -227,13 +228,13 @@ public function testExcessiveSizeBodyIsDiscardedAndTheRequestIsPassedDownToTheNe $promise = $buffer( $serverRequest, function (ServerRequestInterface $request) { - return new Response(200, array(), $request->getBody()->getContents()); + return new Response(200, [], $request->getBody()->getContents()); } ); $stream->end('aa'); - $exposedResponse = \React\Async\await($promise->then( + $exposedResponse = await($promise->then( null, $this->expectCallableNever() )); @@ -249,7 +250,7 @@ public function testBufferingRejectsWhenNextHandlerThrowsWhenStreamEnds() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -284,7 +285,7 @@ public function testBufferingRejectsWhenNextHandlerThrowsErrorWhenStreamEnds() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -321,7 +322,7 @@ public function testBufferingRejectsWhenStreamEmitsError() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -355,7 +356,7 @@ public function testFullBodyStreamedBeforeCallingNextMiddleware() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -381,7 +382,7 @@ public function testCancelBufferingClosesStreamAndRejectsPromise() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, 2) ); diff --git a/tests/Middleware/RequestBodyParserMiddlewareTest.php b/tests/Middleware/RequestBodyParserMiddlewareTest.php index b588bdd5..b601b478 100644 --- a/tests/Middleware/RequestBodyParserMiddlewareTest.php +++ b/tests/Middleware/RequestBodyParserMiddlewareTest.php @@ -15,9 +15,9 @@ public function testFormUrlencodedParsing() $request = new ServerRequest( 'POST', 'https://example.com/', - array( - 'Content-Type' => 'application/x-www-form-urlencoded', - ), + [ + 'Content-Type' => 'application/x-www-form-urlencoded' + ], 'hello=world' ); @@ -30,7 +30,7 @@ function (ServerRequestInterface $request) { ); $this->assertSame( - array('hello' => 'world'), + ['hello' => 'world'], $parsedRequest->getParsedBody() ); $this->assertSame('hello=world', (string)$parsedRequest->getBody()); @@ -42,9 +42,9 @@ public function testFormUrlencodedParsingIgnoresCaseForHeadersButRespectsContent $request = new ServerRequest( 'POST', 'https://example.com/', - array( - 'CONTENT-TYPE' => 'APPLICATION/X-WWW-Form-URLEncoded', - ), + [ + 'CONTENT-TYPE' => 'APPLICATION/X-WWW-Form-URLEncoded' + ], 'Hello=World' ); @@ -57,7 +57,7 @@ function (ServerRequestInterface $request) { ); $this->assertSame( - array('Hello' => 'World'), + ['Hello' => 'World'], $parsedRequest->getParsedBody() ); $this->assertSame('Hello=World', (string)$parsedRequest->getBody()); @@ -69,9 +69,9 @@ public function testFormUrlencodedParsingNestedStructure() $request = new ServerRequest( 'POST', 'https://example.com/', - array( - 'Content-Type' => 'application/x-www-form-urlencoded', - ), + [ + 'Content-Type' => 'application/x-www-form-urlencoded' + ], 'foo=bar&baz[]=cheese&bar[]=beer&bar[]=wine&market[fish]=salmon&market[meat][]=beef&market[meat][]=chicken&market[]=bazaar' ); @@ -84,24 +84,24 @@ function (ServerRequestInterface $request) { ); $this->assertSame( - array( + [ 'foo' => 'bar', - 'baz' => array( + 'baz' => [ 'cheese', - ), - 'bar' => array( + ], + 'bar' => [ 'beer', 'wine', - ), - 'market' => array( + ], + 'market' => [ 'fish' => 'salmon', - 'meat' => array( + 'meat' => [ 'beef', 'chicken', - ), + ], 0 => 'bazaar', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); $this->assertSame('foo=bar&baz[]=cheese&bar[]=beer&bar[]=wine&market[fish]=salmon&market[meat][]=beef&market[meat][]=chicken&market[]=bazaar', (string)$parsedRequest->getBody()); @@ -115,9 +115,9 @@ public function testFormUrlencodedIgnoresBodyWithExcessiveNesting() $request = new ServerRequest( 'POST', 'https://example.com/', - array( - 'Content-Type' => 'application/x-www-form-urlencoded', - ), + [ + 'Content-Type' => 'application/x-www-form-urlencoded' + ], 'hello' . str_repeat('[]', $allowed + 1) . '=world' ); @@ -130,7 +130,7 @@ function (ServerRequestInterface $request) { ); $this->assertSame( - array(), + [], $parsedRequest->getParsedBody() ); } @@ -143,9 +143,9 @@ public function testFormUrlencodedTruncatesBodyWithExcessiveLength() $request = new ServerRequest( 'POST', 'https://example.com/', - array( - 'Content-Type' => 'application/x-www-form-urlencoded', - ), + [ + 'Content-Type' => 'application/x-www-form-urlencoded' + ], str_repeat('a[]=b&', $allowed + 1) ); @@ -170,9 +170,9 @@ public function testDoesNotParseJsonByDefault() $request = new ServerRequest( 'POST', 'https://example.com/', - array( - 'Content-Type' => 'application/json', - ), + [ + 'Content-Type' => 'application/json' + ], '{"hello":"world"}' ); @@ -204,9 +204,9 @@ public function testMultipartFormDataParsing() $data .= "second\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( - 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + $request = new ServerRequest('POST', 'http://example.com/', [ + 'Content-Type' => 'multipart/form-data; boundary=' . $boundary + ], $data, 1.1); /** @var ServerRequestInterface $parsedRequest */ $parsedRequest = $middleware( @@ -217,12 +217,12 @@ function (ServerRequestInterface $request) { ); $this->assertSame( - array( - 'users' => array( + [ + 'users' => [ 'one' => 'single', 'two' => 'second', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); $this->assertSame($data, (string)$parsedRequest->getBody()); @@ -242,9 +242,9 @@ public function testMultipartFormDataIgnoresFieldWithExcessiveNesting() $data .= "world\r\n"; $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( - 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + $request = new ServerRequest('POST', 'http://example.com/', [ + 'Content-Type' => 'multipart/form-data; boundary=' . $boundary + ], $data, 1.1); /** @var ServerRequestInterface $parsedRequest */ $parsedRequest = $middleware( @@ -274,9 +274,9 @@ public function testMultipartFormDataTruncatesBodyWithExcessiveLength() } $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( - 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + $request = new ServerRequest('POST', 'http://example.com/', [ + 'Content-Type' => 'multipart/form-data; boundary=' . $boundary + ], $data, 1.1); /** @var ServerRequestInterface $parsedRequest */ $parsedRequest = $middleware( @@ -310,9 +310,9 @@ public function testMultipartFormDataTruncatesExcessiveNumberOfEmptyFileUploads( } $data .= "--$boundary--\r\n"; - $request = new ServerRequest('POST', 'http://example.com/', array( - 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ), $data, 1.1); + $request = new ServerRequest('POST', 'http://example.com/', [ + 'Content-Type' => 'multipart/form-data; boundary=' . $boundary + ], $data, 1.1); /** @var ServerRequestInterface $parsedRequest */ $parsedRequest = $middleware( diff --git a/tests/TestCase.php b/tests/TestCase.php index 88d8a3df..fa6fcd1c 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -6,7 +6,7 @@ class TestCase extends BaseTestCase { - public function expectCallableOnce() // protected (PHP 5.4+) + protected function expectCallableOnce() { $mock = $this->createCallableMock(); $mock @@ -16,7 +16,7 @@ public function expectCallableOnce() // protected (PHP 5.4+) return $mock; } - public function expectCallableOnceWith($value) // protected (PHP 5.4+) + protected function expectCallableOnceWith($value) { $mock = $this->createCallableMock(); $mock @@ -27,7 +27,7 @@ public function expectCallableOnceWith($value) // protected (PHP 5.4+) return $mock; } - public function expectCallableNever() // protected (PHP 5.4+) + protected function expectCallableNever() { $mock = $this->createCallableMock(); $mock @@ -41,10 +41,10 @@ protected function createCallableMock() { if (method_exists('PHPUnit\Framework\MockObject\MockBuilder', 'addMethods')) { // PHPUnit 9+ - return $this->getMockBuilder('stdClass')->addMethods(array('__invoke'))->getMock(); + return $this->getMockBuilder('stdClass')->addMethods(['__invoke'])->getMock(); } else { // legacy PHPUnit 4 - PHPUnit 8 - return $this->getMockBuilder('stdClass')->setMethods(array('__invoke'))->getMock(); + return $this->getMockBuilder('stdClass')->setMethods(['__invoke'])->getMock(); } } diff --git a/tests/benchmark-middleware-runner.php b/tests/benchmark-middleware-runner.php index 3f1dacaf..d330a1b0 100644 --- a/tests/benchmark-middleware-runner.php +++ b/tests/benchmark-middleware-runner.php @@ -13,7 +13,7 @@ $middleware = function (ServerRequestInterface $request, $next) { return $next($request); }; -$middlewareList = array(); +$middlewareList = []; for ($i = 0; $i < MIDDLEWARE_COUNT; $i++) { $middlewareList[] = $middleware; }