diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3666cd47..6f9cfb41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,11 +19,6 @@ jobs: - 7.3 - 7.2 - 7.1 - - 7.0 - - 5.6 - - 5.5 - - 5.4 - - 5.3 steps: - uses: actions/checkout@v4 - uses: shivammathur/setup-php@v2 @@ -36,19 +31,3 @@ jobs: if: ${{ matrix.php >= 7.3 }} - run: vendor/bin/phpunit --coverage-text -c phpunit.xml.legacy if: ${{ matrix.php < 7.3 }} - - PHPUnit-hhvm: - name: PHPUnit (HHVM) - runs-on: ubuntu-22.04 - continue-on-error: true - steps: - - uses: actions/checkout@v4 - - run: cp "$(which composer)" composer.phar && ./composer.phar self-update --2.2 # downgrade Composer for HHVM - - name: Run hhvm composer.phar install - uses: docker://hhvm/hhvm:3.30-lts-latest - with: - args: hhvm composer.phar install - - name: Run hhvm vendor/bin/phpunit - uses: docker://hhvm/hhvm:3.30-lts-latest - with: - args: hhvm vendor/bin/phpunit diff --git a/README.md b/README.md index 46da303d..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 ); }; @@ -2990,8 +2989,7 @@ composer require react/http:^3@dev See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. This project aims to run on any platform and thus does not require any PHP -extensions and supports running on legacy PHP 5.3 through current PHP 8+ and -HHVM. +extensions and supports running on PHP 7.1 through current PHP 8+. It's *highly recommended to use the latest supported PHP version* for this project. ## Tests diff --git a/composer.json b/composer.json index 23783c0c..2fe67da0 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,7 @@ } ], "require": { - "php": ">=5.3.0", + "php": ">=7.1", "evenement/evenement": "^3.0 || ^2.0 || ^1.0", "fig/http-message-util": "^1.1", "psr/http-message": "^1.0", @@ -39,8 +39,8 @@ "clue/http-proxy-react": "^1.8", "clue/reactphp-ssh-proxy": "^1.4", "clue/socks-react": "^1.4", - "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", - "react/async": "^4 || ^3 || ^2", + "phpunit/phpunit": "^9.6 || ^7.5", + "react/async": "^4 || ^3", "react/promise-stream": "^1.4", "react/promise-timer": "^1.9" }, 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/phpunit.xml.legacy b/phpunit.xml.legacy index 89161168..00868603 100644 --- a/phpunit.xml.legacy +++ b/phpunit.xml.legacy @@ -2,7 +2,7 @@ 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 ff9bf2d4..fb0cd3e5 100644 --- a/src/Io/ClientRequestStream.php +++ b/src/Io/ClientRequestStream.php @@ -69,44 +69,37 @@ private function writeHead() } } - /** @var array $m legacy PHP 5.3 only */ - if (!\preg_match('#^\S+ \S+ HTTP/1\.[01]\r\n#m', $headers) || \substr_count($headers, "\n") !== ($expected + 1) || (\PHP_VERSION_ID >= 50400 ? \preg_match_all(AbstractMessage::REGEX_HEADERS, $headers) : \preg_match_all(AbstractMessage::REGEX_HEADERS, $headers, $m)) !== $expected) { + if (!\preg_match('#^\S+ \S+ HTTP/1\.[01]\r\n#m', $headers) || \substr_count($headers, "\n") !== ($expected + 1) || \preg_match_all(AbstractMessage::REGEX_HEADERS, $headers) !== $expected) { $this->closeError(new \InvalidArgumentException('Unable to send request with invalid request headers')); 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) { @@ -180,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 @@ -221,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 !== '') { @@ -256,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 539107ae..cdfe189b 100644 --- a/src/Io/MultipartParser.php +++ b/src/Io/MultipartParser.php @@ -36,7 +36,7 @@ final class MultipartParser /** * ini setting "max_input_vars" * - * Does not exist in PHP < 5.3.9 or HHVM, so assume PHP's default 1000 here. + * Assume PHP' default of 1000 here. * * @var int * @link http://php.net/manual/en/info.configuration.php#ini.max-input-vars @@ -46,7 +46,7 @@ final class MultipartParser /** * ini setting "max_input_nesting_level" * - * Does not exist in HHVM, but assumes hard coded to 64 (PHP's default). + * Assume PHP's default of 64 here. * * @var int * @link http://php.net/manual/en/info.configuration.php#ini.max-input-nesting-level @@ -81,14 +81,8 @@ final class MultipartParser */ public function __construct($uploadMaxFilesize = null, $maxFileUploads = null) { - $var = \ini_get('max_input_vars'); - if ($var !== false) { - $this->maxInputVars = (int)$var; - } - $var = \ini_get('max_input_nesting_level'); - if ($var !== false) { - $this->maxInputNestingLevel = (int)$var; - } + $this->maxInputVars = (int) \ini_get('max_input_vars'); + $this->maxInputNestingLevel = (int) \ini_get('max_input_nesting_level'); if ($uploadMaxFilesize === null) { $uploadMaxFilesize = \ini_get('upload_max_filesize'); @@ -172,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 { @@ -274,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); @@ -321,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 143edaa8..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 ); @@ -346,9 +341,8 @@ public function handleResponse(ConnectionInterface $connection, ServerRequestInt } } - /** @var array $m legacy PHP 5.3 only */ - if ($code < 100 || $code > 999 || \substr_count($headers, "\n") !== ($expected + 1) || (\PHP_VERSION_ID >= 50400 ? \preg_match_all(AbstractMessage::REGEX_HEADERS, $headers) : \preg_match_all(AbstractMessage::REGEX_HEADERS, $headers, $m)) !== $expected) { - $this->emit('error', array(new \InvalidArgumentException('Unable to send response with invalid response headers'))); + if ($code < 100 || $code > 999 || \substr_count($headers, "\n") !== ($expected + 1) || \preg_match_all(AbstractMessage::REGEX_HEADERS, $headers) !== $expected) { + $this->emit('error', [new \InvalidArgumentException('Unable to send response with invalid response headers')]); $this->writeError($connection, Response::STATUS_INTERNAL_SERVER_ERROR, $request); return; } @@ -388,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 fa6366ed..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,20 +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 ); - // throw on error, now `false` but used to be `(string) "null"` before PHP 5.5 - if ($json === false || (\PHP_VERSION_ID < 50500 && \json_last_error() !== \JSON_ERROR_NONE)) { + 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"); } /** @@ -202,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); } /** @@ -254,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); } /** @@ -276,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', @@ -284,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; @@ -302,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 @@ -367,7 +365,7 @@ private static function getReasonPhraseForStatusCode($code) } } - return isset(self::$phrasesMap[$code]) ? self::$phrasesMap[$code] : ''; + return self::$phrasesMap[$code] ?? ''; } /** @@ -380,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'); } @@ -391,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]; } @@ -408,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 4309bbed..84fc38d8 100644 --- a/src/Message/Uri.php +++ b/src/Message/Uri.php @@ -45,16 +45,7 @@ final class Uri implements UriInterface */ public function __construct($uri) { - // @codeCoverageIgnoreStart - if (\PHP_VERSION_ID < 50407 && \strpos($uri, '//') === 0) { - // @link https://3v4l.org/UrAQP - $parts = \parse_url('http:' . $uri); - unset($parts['schema']); - } else { - $parts = \parse_url($uri); - } - // @codeCoverageIgnoreEnd - + $parts = \parse_url($uri); if ($parts === false || (isset($parts['scheme']) && !\preg_match('#^[a-z]+$#i', $parts['scheme'])) || (isset($parts['host']) && \preg_match('#[\s_%+]#', $parts['host']))) { throw new \InvalidArgumentException('Invalid URI given'); } @@ -63,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'])) { @@ -310,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() === '') { @@ -343,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..8f3e10bd 100644 --- a/tests/BrowserTest.php +++ b/tests/BrowserTest.php @@ -3,8 +3,11 @@ namespace React\Tests\Http; use Psr\Http\Message\RequestInterface; +use React\EventLoop\LoopInterface; +use React\Http\Io\Transaction; use React\Http\Browser; use React\Promise\Promise; +use React\Socket\ConnectorInterface; class BrowserTest extends TestCase { @@ -17,8 +20,8 @@ class BrowserTest extends TestCase */ public function setUpBrowser() { - $this->loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); - $this->sender = $this->getMockBuilder('React\Http\Io\Transaction')->disableOriginalConstructor()->getMock(); + $this->loop = $this->createMock(LoopInterface::class); + $this->sender = $this->createMock(Transaction::class); $this->browser = new Browser(null, $this->loop); $ref = new \ReflectionProperty($this->browser, 'transaction'); @@ -38,12 +41,12 @@ public function testConstructWithoutLoopAssignsLoopAutomatically() $ref->setAccessible(true); $loop = $ref->getValue($transaction); - $this->assertInstanceOf('React\EventLoop\LoopInterface', $loop); + $this->assertInstanceOf(LoopInterface::class, $loop); } public function testConstructWithConnectorAssignsGivenConnector() { - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $browser = new Browser($connector); @@ -87,9 +90,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 +100,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 +110,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 +120,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 +130,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 +140,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 +150,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 +162,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 +174,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); } @@ -258,109 +253,107 @@ public function testWithBase() { $browser = $this->browser->withBase('http://example.com/root'); - $this->assertInstanceOf('React\Http\Browser', $browser); + $this->assertInstanceOf(Browser::class, $browser); $this->assertNotSame($this->browser, $browser); } - public function provideOtherUris() - { - return array( - 'empty returns base' => array( - 'http://example.com/base', - '', - 'http://example.com/base', - ), - 'absolute same as base returns base' => array( - 'http://example.com/base', - 'http://example.com/base', - 'http://example.com/base', - ), - 'absolute below base returns absolute' => array( - 'http://example.com/base', - 'http://example.com/base/another', - 'http://example.com/base/another', - ), - 'slash returns base without path' => array( - 'http://example.com/base', - '/', - 'http://example.com/', - ), - 'relative is added behind base' => array( - 'http://example.com/base/', - 'test', - 'http://example.com/base/test', - ), - 'relative is added behind base without path' => array( - 'http://example.com/base', - 'test', - 'http://example.com/test', - ), - 'relative level up is added behind parent path' => array( - 'http://example.com/base/foo/', - '../bar', - 'http://example.com/base/bar', - ), - 'absolute with slash is added behind base without path' => array( - 'http://example.com/base', - '/test', - 'http://example.com/test', - ), - 'query string is added behind base' => array( - 'http://example.com/base', - '?key=value', - 'http://example.com/base?key=value', - ), - 'query string is added behind base with slash' => array( - 'http://example.com/base/', - '?key=value', - 'http://example.com/base/?key=value', - ), - 'query string with slash is added behind base without path' => array( - 'http://example.com/base', - '/?key=value', - 'http://example.com/?key=value', - ), - 'absolute with query string below base is returned as-is' => array( - 'http://example.com/base', - 'http://example.com/base?test', - 'http://example.com/base?test', - ), - 'urlencoded special chars will stay as-is' => array( - 'http://example.com/%7Bversion%7D/', - '', - 'http://example.com/%7Bversion%7D/' - ), - 'special chars will be urlencoded' => array( - 'http://example.com/{version}/', - '', - 'http://example.com/%7Bversion%7D/' - ), - 'other domain' => array( - 'http://example.com/base/', - 'http://example.org/base/', - 'http://example.org/base/' - ), - 'other scheme' => array( - 'http://example.com/base/', - 'https://example.com/base/', - 'https://example.com/base/' - ), - 'other port' => array( - 'http://example.com/base/', - 'http://example.com:81/base/', - 'http://example.com:81/base/' - ), - 'other path' => array( - 'http://example.com/base/', - 'http://example.com/other/', - 'http://example.com/other/' - ), - 'other path due to missing slash' => array( - 'http://example.com/base/', - 'http://example.com/other', - 'http://example.com/other' - ), - ); + public static function provideOtherUris() + { + yield 'empty returns base' => [ + 'http://example.com/base', + '', + 'http://example.com/base', + ]; + yield 'absolute same as base returns base' => [ + 'http://example.com/base', + 'http://example.com/base', + 'http://example.com/base', + ]; + yield 'absolute below base returns absolute' => [ + 'http://example.com/base', + 'http://example.com/base/another', + 'http://example.com/base/another', + ]; + yield 'slash returns base without path' => [ + 'http://example.com/base', + '/', + 'http://example.com/', + ]; + yield 'relative is added behind base' => [ + 'http://example.com/base/', + 'test', + 'http://example.com/base/test', + ]; + yield 'relative is added behind base without path' => [ + 'http://example.com/base', + 'test', + 'http://example.com/test', + ]; + yield 'relative level up is added behind parent path' => [ + 'http://example.com/base/foo/', + '../bar', + 'http://example.com/base/bar', + ]; + yield 'absolute with slash is added behind base without path' => [ + 'http://example.com/base', + '/test', + 'http://example.com/test', + ]; + yield 'query string is added behind base' => [ + 'http://example.com/base', + '?key=value', + 'http://example.com/base?key=value', + ]; + yield 'query string is added behind base with slash' => [ + 'http://example.com/base/', + '?key=value', + 'http://example.com/base/?key=value', + ]; + yield 'query string with slash is added behind base without path' => [ + 'http://example.com/base', + '/?key=value', + 'http://example.com/?key=value', + ]; + yield 'absolute with query string below base is returned as-is' => [ + 'http://example.com/base', + 'http://example.com/base?test', + 'http://example.com/base?test', + ]; + yield 'urlencoded special chars will stay as-is' => [ + 'http://example.com/%7Bversion%7D/', + '', + 'http://example.com/%7Bversion%7D/' + ]; + yield 'special chars will be urlencoded' => [ + 'http://example.com/{version}/', + '', + 'http://example.com/%7Bversion%7D/' + ]; + yield 'other domain' => [ + 'http://example.com/base/', + 'http://example.org/base/', + 'http://example.org/base/' + ]; + yield 'other scheme' => [ + 'http://example.com/base/', + 'https://example.com/base/', + 'https://example.com/base/' + ]; + yield 'other port' => [ + 'http://example.com/base/', + 'http://example.com:81/base/', + 'http://example.com:81/base/' + ]; + yield 'other path' => [ + 'http://example.com/base/', + 'http://example.com/other/', + 'http://example.com/other/' + ]; + yield 'other path due to missing slash' => [ + 'http://example.com/base/', + 'http://example.com/other', + 'http://example.com/other' + ]; } /** @@ -372,9 +365,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 () { })); @@ -383,13 +375,13 @@ public function testResolveUriWithBaseEndsWithoutSlash($base, $uri, $expectedAbs public function testWithBaseUrlNotAbsoluteFails() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $this->browser->withBase('hello'); } public function testWithBaseUrlInvalidSchemeFails() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $this->browser->withBase('ftp://example.com'); } @@ -397,9 +389,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 +401,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 () { })); @@ -421,7 +411,7 @@ public function testWithProtocolVersionFollowedByGetRequestSendsRequestWithProto public function testWithProtocolVersionInvalidThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $this->browser->withProtocolVersion('1.2'); } @@ -429,7 +419,7 @@ public function testCancelGetRequestShouldCancelUnderlyingSocketConnection() { $pending = new Promise(function () { }, $this->expectCallableOnce()); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->once())->method('connect')->with('example.com:80')->willReturn($pending); $this->browser = new Browser($connector, $this->loop); @@ -443,9 +433,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 +445,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 +460,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 +489,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 +501,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 +513,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 +523,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 +535,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 5405874e..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,49 +119,43 @@ 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 */ public function testSuccessfulResponseEmitsEnd() { - // max_nesting_level was set to 100 for PHP Versions < 5.4 which resulted in failing test for legacy PHP - ini_set('xdebug.max_nesting_level', 256); - $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 */ public function testCancelPendingConnectionEmitsClose() { - // max_nesting_level was set to 100 for PHP Versions < 5.4 which resulted in failing test for legacy PHP - ini_set('xdebug.max_nesting_level', 256); - $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 7b8ff84b..d89d92e9 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,15 +169,16 @@ 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() { $promise = $this->browser->get('delay'); - $this->setExpectedException('InvalidArgumentException', 'Invalid request URL given'); - \React\Async\await($promise); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid request URL given'); + await($promise); } /** @@ -181,7 +186,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 +194,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() @@ -197,8 +202,8 @@ public function testCancelGetRequestWillRejectRequest() $promise = $this->browser->get($this->base . 'get'); $promise->cancel(); - $this->setExpectedException('RuntimeException'); - \React\Async\await($promise); + $this->expectException(\RuntimeException::class); + await($promise); } public function testCancelRequestWithPromiseFollowerWillRejectRequest() @@ -208,14 +213,14 @@ public function testCancelRequestWithPromiseFollowerWillRejectRequest() }); $promise->cancel(); - $this->setExpectedException('RuntimeException'); - \React\Async\await($promise); + $this->expectException(\RuntimeException::class); + await($promise); } public function testRequestWithoutAuthenticationFails() { - $this->setExpectedException('RuntimeException'); - \React\Async\await($this->browser->get($this->base . 'basic-auth/user/pass')); + $this->expectException(\RuntimeException::class); + await($this->browser->get($this->base . 'basic-auth/user/pass')); } /** @@ -225,7 +230,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 +244,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 +259,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() @@ -265,26 +270,29 @@ public function testCancelRedirectedRequestShouldReject() $promise->cancel(); }); - $this->setExpectedException('RuntimeException', 'Request cancelled'); - \React\Async\await($promise); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Request cancelled'); + await($promise); } 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); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Request timed out after 0.1 seconds'); + 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); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Request timed out after 0.1 seconds'); + await($promise); } /** @@ -292,7 +300,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 +308,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 +316,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,20 +326,20 @@ 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() { $browser = $this->browser->withFollowRedirects(0); - $this->setExpectedException('RuntimeException'); - \React\Async\await($browser->get($this->base . 'redirect-to?url=get')); + $this->expectException(\RuntimeException::class); + 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 +349,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,31 +364,27 @@ public function testGetRequestWithResponseBufferMatchedExactlyResolves() { $promise = $this->browser->withResponseBuffer(5)->get($this->base . 'get'); - \React\Async\await($promise); + await($promise); } public function testGetRequestWithResponseBufferExceededRejects() { $promise = $this->browser->withResponseBuffer(4)->get($this->base . 'get'); - $this->setExpectedException( - 'OverflowException', - 'Response body size of 5 bytes exceeds maximum of 4 bytes', - defined('SOCKET_EMSGSIZE') ? SOCKET_EMSGSIZE : 0 - ); - \React\Async\await($promise); + $this->expectException(\OverflowException::class); + $this->expectExceptionMessage('Response body size of 5 bytes exceeds maximum of 4 bytes'); + $this->expectExceptionCode(defined('SOCKET_EMSGSIZE') ? SOCKET_EMSGSIZE : 0); + await($promise); } public function testGetRequestWithResponseBufferExceededDuringStreamingRejects() { $promise = $this->browser->withResponseBuffer(4)->get($this->base . 'stream/1'); - $this->setExpectedException( - 'OverflowException', - 'Response body size exceeds maximum of 4 bytes', - defined('SOCKET_EMSGSIZE') ? SOCKET_EMSGSIZE : 0 - ); - \React\Async\await($promise); + $this->expectException(\OverflowException::class); + $this->expectExceptionMessage('Response body size exceeds maximum of 4 bytes'); + $this->expectExceptionCode(defined('SOCKET_EMSGSIZE') ? SOCKET_EMSGSIZE : 0); + await($promise); } /** @@ -389,11 +393,7 @@ public function testGetRequestWithResponseBufferExceededDuringStreamingRejects() */ public function testCanAccessHttps() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - - \React\Async\await($this->browser->get('https://www.google.com/')); + await($this->browser->get('https://www.google.com/')); } /** @@ -401,20 +401,16 @@ public function testCanAccessHttps() */ public function testVerifyPeerEnabledForBadSslRejects() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - - $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/')); + $this->expectException(\RuntimeException::class); + await($browser->get('https://self-signed.badssl.com/')); } /** @@ -423,19 +419,15 @@ public function testVerifyPeerEnabledForBadSslRejects() */ public function testVerifyPeerDisabledForBadSslResolves() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - - $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/')); } /** @@ -443,33 +435,33 @@ public function testVerifyPeerDisabledForBadSslResolves() */ public function testInvalidPort() { - $this->setExpectedException('RuntimeException'); - \React\Async\await($this->browser->get('http://www.google.com:443/')); + $this->expectException(\RuntimeException::class); + 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()); - $this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $e->getResponse()); + $this->assertInstanceOf(ResponseInterface::class, $e->getResponse()); $this->assertEquals(404, $e->getResponse()->getStatusCode()); } } 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']); @@ -477,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')); @@ -488,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()); @@ -500,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()); @@ -511,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"); }); @@ -519,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(); @@ -531,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"); }); @@ -544,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(); @@ -557,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"); }); @@ -573,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()); } @@ -586,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"); }); @@ -602,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()); } @@ -615,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()); } @@ -631,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()); } @@ -647,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()); } @@ -660,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']); @@ -676,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']); @@ -696,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(); } @@ -706,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']); @@ -717,7 +709,7 @@ public function testSendsHttp11ByDefault() $http = new HttpServer(function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], $request->getProtocolVersion() ); }); @@ -726,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(); @@ -737,7 +729,7 @@ public function testSendsExplicitHttp10Request() $http = new HttpServer(function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], $request->getProtocolVersion() ); }); @@ -746,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(); @@ -754,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(); @@ -764,31 +756,31 @@ 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(); $this->assertEquals(5, $body->getSize()); $this->assertEquals('', (string) $body); - $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf(ReadableStreamInterface::class, $body); } 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(); $this->assertNull($body->getSize()); $this->assertEquals('', (string) $body); - $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf(ReadableStreamInterface::class, $body); } 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()); }) ); @@ -797,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 dcd79b3e..dc0bd276 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,13 +38,13 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('http://' . noScheme($socket->getAddress()) . '/', $response); $socket->close(); } @@ -60,12 +65,12 @@ 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); + $this->assertStringContainsString("HTTP/1.0 404 Not Found", $response); $socket->close(); } @@ -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,13 +89,13 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('http://' . noScheme($socket->getAddress()) . '/', $response); $socket->close(); } @@ -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,83 +114,75 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('http://localhost:1000/', $response); $socket->close(); } public function testSecureHttpsOnRandomPort() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - - $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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('https://' . noScheme($socket->getAddress()) . '/', $response); $socket->close(); } public function testSecureHttpsReturnsData() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - $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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString("\r\nContent-Length: 33000\r\n", $response); $this->assertStringEndsWith("\r\n". str_repeat('.', 33000), $response); $socket->close(); @@ -193,33 +190,29 @@ public function testSecureHttpsReturnsData() public function testSecureHttpsOnRandomPortWithoutHostHeaderUsesSocketUri() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - - $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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('https://' . noScheme($socket->getAddress()) . '/', $response); $socket->close(); } @@ -234,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); @@ -242,13 +235,13 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('http://127.0.0.1/', $response); $socket->close(); } @@ -263,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); @@ -271,37 +264,33 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('http://127.0.0.1/', $response); $socket->close(); } public function testSecureHttpsOnStandardPortReturnsUriWithNoPort() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - 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); @@ -309,37 +298,33 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('https://127.0.0.1/', $response); $socket->close(); } public function testSecureHttpsOnStandardPortWithoutHostHeaderUsesSocketUri() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - 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); @@ -347,13 +332,13 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('https://127.0.0.1/', $response); $socket->close(); } @@ -368,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); @@ -376,37 +361,33 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('http://127.0.0.1:443/', $response); $socket->close(); } public function testSecureHttpsOnHttpStandardPortReturnsUriWithPort() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - 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); @@ -414,13 +395,13 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response); + $this->assertStringContainsString('https://127.0.0.1:80/', $response); $socket->close(); } @@ -433,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'); @@ -442,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); @@ -476,7 +457,7 @@ function (RequestInterface $request) use ($once) { }); }); - \React\Async\await(\React\Promise\Timer\sleep(0.1)); + await(sleep(0.1)); $socket->close(); } @@ -490,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); } ); @@ -506,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(); @@ -520,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'); @@ -535,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(); @@ -553,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'); @@ -567,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); @@ -589,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'); @@ -604,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); @@ -626,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'); @@ -640,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); @@ -662,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)); }); }); }); @@ -680,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); @@ -699,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'); @@ -713,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); @@ -726,31 +707,27 @@ public function testConnectWithClosedThroughStreamReturnsNoData() public function testLimitConcurrentRequestsMiddlewareRequestStreamPausing() { - if (defined('HHVM_VERSION') && !interface_exists('React\Promise\PromisorInterface')) { - $this->markTestSkipped('Not supported on legacy HHVM with Promise v3'); - } - $connector = new Connector(); $http = new HttpServer( 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( @@ -759,14 +736,14 @@ 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); + $this->assertStringContainsString("HTTP/1.0 200 OK", $response, $response); $this->assertTrue(substr($response, -4) == 1024, $response); } diff --git a/tests/HttpServerTest.php b/tests/HttpServerTest.php index 72d48468..a62e5fbd 100644 --- a/tests/HttpServerTest.php +++ b/tests/HttpServerTest.php @@ -4,12 +4,17 @@ use Psr\Http\Message\ServerRequestInterface; use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; use React\Http\HttpServer; use React\Http\Io\IniUtil; +use React\Http\Middleware\LimitConcurrentRequestsMiddleware; +use React\Http\Middleware\RequestBodyBufferMiddleware; use React\Http\Middleware\StreamingRequestMiddleware; -use React\Promise; use React\Promise\Deferred; +use React\Socket\Connection; use React\Stream\ReadableStreamInterface; +use function React\Async\await; +use function React\Promise\reject; final class HttpServerTest extends TestCase { @@ -24,10 +29,10 @@ final class HttpServerTest extends TestCase */ public function setUpConnectionMockAndSocket() { - $this->connection = $this->getMockBuilder('React\Socket\Connection') + $this->connection = $this->getMockBuilder(Connection::class) ->disableOriginalConstructor() ->setMethods( - array( + [ 'write', 'end', 'close', @@ -38,7 +43,7 @@ public function setUpConnectionMockAndSocket() 'getRemoteAddress', 'getLocalAddress', 'pipe' - ) + ] ) ->getMock(); @@ -64,12 +69,12 @@ public function testConstructWithoutLoopAssignsLoopAutomatically() $ref->setAccessible(true); $loop = $ref->getValue($clock); - $this->assertInstanceOf('React\EventLoop\LoopInterface', $loop); + $this->assertInstanceOf(LoopInterface::class, $loop); } public function testInvalidCallbackFunctionLeadsToException() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new HttpServer('invalid'); } @@ -81,23 +86,20 @@ 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); } - /** - * @requires PHP 5.4 - */ 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); } @@ -124,8 +126,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); } @@ -138,10 +140,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(); @@ -149,7 +151,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(); @@ -166,20 +168,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()); @@ -209,15 +210,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(); @@ -234,8 +235,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); } @@ -251,8 +252,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); } @@ -262,20 +263,20 @@ 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()); + $this->assertInstanceOf(\RuntimeException::class, $capturedException); + $this->assertInstanceOf(\Exception::class, $capturedException->getPrevious()); $this->assertSame($exception, $capturedException->getPrevious()); } @@ -283,7 +284,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"; @@ -300,25 +301,23 @@ private function createPostFileUploadRequest() return $data; } - public function provideIniSettingsForConcurrency() + public static function provideIniSettingsForConcurrency() { - return array( - 'default settings' => array( - '128M', - '64K', // 8M capped at maximum - 1024 - ), - 'unlimited memory_limit has no concurrency limit' => array( - '-1', - '8M', - null - ), - 'small post_max_size results in high concurrency' => array( - '128M', - '1k', - 65536 - ) - ); + yield 'default settings' => [ + '128M', + '64K', // 8M capped at maximum + 1024 + ]; + yield 'unlimited memory_limit has no concurrency limit' => [ + '-1', + '8M', + null + ]; + yield 'small post_max_size results in high concurrency' => [ + '128M', + '1k', + 65536 + ]; } /** @@ -404,7 +403,7 @@ public function testConstructServerWithUnlimitedMemoryLimitDoesNotLimitConcurren $middleware = $ref->getValue($middlewareRunner); $this->assertTrue(is_array($middleware)); - $this->assertInstanceOf('React\Http\Middleware\RequestBodyBufferMiddleware', $middleware[0]); + $this->assertInstanceOf(RequestBodyBufferMiddleware::class, $middleware[0]); } public function testConstructServerWithMemoryLimitDoesLimitConcurrency() @@ -434,7 +433,7 @@ public function testConstructServerWithMemoryLimitDoesLimitConcurrency() $middleware = $ref->getValue($middlewareRunner); $this->assertTrue(is_array($middleware)); - $this->assertInstanceOf('React\Http\Middleware\LimitConcurrentRequestsMiddleware', $middleware[0]); + $this->assertInstanceOf(LimitConcurrentRequestsMiddleware::class, $middleware[0]); } public function testConstructFiltersOutConfigurationMiddlewareBefore() diff --git a/tests/Io/AbstractMessageTest.php b/tests/Io/AbstractMessageTest.php index 9e2c7d32..5451281a 100644 --- a/tests/Io/AbstractMessageTest.php +++ b/tests/Io/AbstractMessageTest.php @@ -25,8 +25,8 @@ public function testWithProtocolVersionReturnsNewInstanceWhenProtocolVersionIsCh { $message = new MessageMock( '1.1', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() + [], + $this->createMock(StreamInterface::class) ); $new = $message->withProtocolVersion('1.0'); @@ -39,8 +39,8 @@ public function testWithProtocolVersionReturnsSameInstanceWhenProtocolVersionIsU { $message = new MessageMock( '1.1', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() + [], + $this->createMock(StreamInterface::class) ); $new = $message->withProtocolVersion('1.1'); @@ -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->createMock(StreamInterface::class) ); - $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->createMock(StreamInterface::class) ); - $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() - ), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() + [ + 'Content-Type' => [] + ], + $this->createMock(StreamInterface::class) ); - $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,28 +178,28 @@ public function testHeaderWithMultipleValuesAcrossMixedCaseNamesInConstructorMer { $message = new MessageMock( '1.1', - array( + [ 'SET-Cookie' => 'a=1', - 'set-cookie' => array('b=2'), - 'set-COOKIE' => array() - ), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock() + 'set-cookie' => ['b=2'], + 'set-COOKIE' => [] + ], + $this->createMock(StreamInterface::class) ); - $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() { - $body = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(); + $body = $this->createMock(StreamInterface::class); $message = new MessageMock( '1.1', - array(), + [], $body ); - $body2 = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(); + $body2 = $this->createMock(StreamInterface::class); $new = $message->withBody($body2); $this->assertNotSame($message, $new); $this->assertSame($body2, $new->getBody()); @@ -208,10 +208,10 @@ public function testWithBodyReturnsNewInstanceWhenBodyIsChanged() public function testWithBodyReturnsSameInstanceWhenBodyIsUnchanged() { - $body = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(); + $body = $this->createMock(StreamInterface::class); $message = new MessageMock( '1.1', - array(), + [], $body ); diff --git a/tests/Io/AbstractRequestTest.php b/tests/Io/AbstractRequestTest.php index 7ff4a9a5..5d41369b 100644 --- a/tests/Io/AbstractRequestTest.php +++ b/tests/Io/AbstractRequestTest.php @@ -32,12 +32,12 @@ class AbstractRequestTest extends TestCase { public function testCtorWithInvalidUriThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new RequestMock( 'GET', null, - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); } @@ -47,12 +47,12 @@ public function testGetHeadersReturnsHostHeaderFromUri() $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '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(), + [], + $this->createMock(StreamInterface::class), '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(), + [], + $this->createMock(StreamInterface::class), '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(), + [], + $this->createMock(StreamInterface::class), '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(), + [], + $this->createMock(StreamInterface::class), '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(), + [], + $this->createMock(StreamInterface::class), '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(), + ], + $this->createMock(StreamInterface::class), '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(), + ], + $this->createMock(StreamInterface::class), '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() - ), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [ + 'Host' => [] + ], + $this->createMock(StreamInterface::class), '1.1' ); - $this->assertEquals(array('Host' => array('example.com')), $request->getHeaders()); + $this->assertEquals(['Host' => ['example.com']], $request->getHeaders()); } public function testGetRequestTargetReturnsPathAndQueryFromUri() @@ -170,8 +170,8 @@ public function testGetRequestTargetReturnsPathAndQueryFromUri() $request = new RequestMock( 'GET', 'http://example.com/demo?name=Alice', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); @@ -183,8 +183,8 @@ public function testGetRequestTargetReturnsSlashOnlyIfUriHasNoPathOrQuery() $request = new RequestMock( 'GET', 'http://example.com', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); @@ -196,8 +196,8 @@ public function testGetRequestTargetReturnsRequestTargetInAbsoluteFormIfGivenExp $request = new RequestMock( 'GET', 'http://example.com/demo?name=Alice', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); $request = $request->withRequestTarget('http://example.com/demo?name=Alice'); @@ -210,8 +210,8 @@ public function testWithRequestTargetReturnsNewInstanceWhenRequestTargetIsChange $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); @@ -226,8 +226,8 @@ public function testWithRequestTargetReturnsSameInstanceWhenRequestTargetIsUncha $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); $request = $request->withRequestTarget('/'); @@ -242,8 +242,8 @@ public function testWithMethodReturnsNewInstanceWhenMethodIsChanged() $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); @@ -258,8 +258,8 @@ public function testWithMethodReturnsSameInstanceWhenMethodIsUnchanged() $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); @@ -270,13 +270,13 @@ public function testWithMethodReturnsSameInstanceWhenMethodIsUnchanged() public function testGetUriReturnsUriInstanceGivenToCtor() { - $uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock(); + $uri = $this->createMock(UriInterface::class); $request = new RequestMock( 'GET', $uri, - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); @@ -288,13 +288,13 @@ public function testGetUriReturnsUriInstanceForUriStringGivenToCtor() $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); $uri = $request->getUri(); - $this->assertInstanceOf('Psr\Http\Message\UriInterface', $uri); + $this->assertInstanceOf(UriInterface::class, $uri); $this->assertEquals('http://example.com/', (string) $uri); } @@ -303,12 +303,12 @@ public function testWithUriReturnsNewInstanceWhenUriIsChanged() $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); - $uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock(); + $uri = $this->createMock(UriInterface::class); $new = $request->withUri($uri); $this->assertNotSame($request, $new); @@ -318,13 +318,13 @@ public function testWithUriReturnsNewInstanceWhenUriIsChanged() public function testWithUriReturnsSameInstanceWhenUriIsUnchanged() { - $uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock(); + $uri = $this->createMock(UriInterface::class); $request = new RequestMock( 'GET', $uri, - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '1.1' ); @@ -338,8 +338,8 @@ public function testWithUriReturnsNewInstanceWithHostHeaderChangedIfUriContainsH $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '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,8 +356,8 @@ public function testWithUriReturnsNewInstanceWithHostHeaderChangedIfUriContainsH $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '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,10 +374,10 @@ public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderBef $request = new RequestMock( 'GET', 'http://example.com/', - array( + [ 'User-Agent' => 'test' - ), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + ], + $this->createMock(StreamInterface::class), '1.1' ); $request = $request->withoutHeader('Host'); @@ -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,8 +395,8 @@ public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfUriContain $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '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,8 +413,8 @@ public function testWithUriReturnsNewInstanceWithHostHeaderUnchangedIfPreserveHo $request = new RequestMock( 'GET', 'http://example.com/', - array(), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + [], + $this->createMock(StreamInterface::class), '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,10 +431,10 @@ public function testWithUriReturnsNewInstanceWithHostHeaderAddedAsFirstHeaderNoM $request = new RequestMock( 'GET', 'http://example.com/', - array( + [ 'User-Agent' => 'test' - ), - $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(), + ], + $this->createMock(StreamInterface::class), '1.1' ); $request = $request->withoutHeader('Host'); @@ -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..c8534d50 100644 --- a/tests/Io/BufferedBodyTest.php +++ b/tests/Io/BufferedBodyTest.php @@ -91,7 +91,7 @@ public function testSeekBeforeStartThrows() } catch (\RuntimeException $e) { $this->assertSame(0, $stream->tell()); - $this->setExpectedException('RuntimeException'); + $this->expectException(\RuntimeException::class); throw $e; } } @@ -100,7 +100,7 @@ public function testSeekWithInvalidModeThrows() { $stream = new BufferedBody('hello'); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $stream->seek(1, 12345); } @@ -109,7 +109,7 @@ public function testSeekAfterCloseThrows() $stream = new BufferedBody('hello'); $stream->close(); - $this->setExpectedException('RuntimeException'); + $this->expectException(\RuntimeException::class); $stream->seek(0); } @@ -118,7 +118,7 @@ public function testTellAfterCloseThrows() $stream = new BufferedBody('hello'); $stream->close(); - $this->setExpectedException('RuntimeException'); + $this->expectException(\RuntimeException::class); $stream->tell(); } @@ -136,7 +136,7 @@ public function testRewindAfterCloseThrows() $stream = new BufferedBody('hello'); $stream->close(); - $this->setExpectedException('RuntimeException'); + $this->expectException(\RuntimeException::class); $stream->rewind(); } @@ -180,7 +180,7 @@ public function testReadZeroThrows() { $stream = new BufferedBody('hello'); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $stream->read(0); } @@ -189,7 +189,7 @@ public function testReadAfterCloseThrows() $stream = new BufferedBody('hello'); $stream->close(); - $this->setExpectedException('RuntimeException'); + $this->expectException(\RuntimeException::class); $stream->read(10); } @@ -218,7 +218,7 @@ public function testGetContentsAfterCloseThrows() $stream = new BufferedBody('hello'); $stream->close(); - $this->setExpectedException('RuntimeException'); + $this->expectException(\RuntimeException::class); $stream->getContents(); } @@ -280,7 +280,7 @@ public function testWriteAfterCloseThrows() $stream = new BufferedBody('hello'); $stream->close(); - $this->setExpectedException('RuntimeException'); + $this->expectException(\RuntimeException::class); $stream->write('foo'); } @@ -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..3ae8c742 100644 --- a/tests/Io/ChunkedDecoderTest.php +++ b/tests/Io/ChunkedDecoderTest.php @@ -3,7 +3,9 @@ namespace React\Tests\Http\Io; use React\Http\Io\ChunkedDecoder; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use React\Stream\WritableStreamInterface; use React\Tests\Http\TestCase; class ChunkedDecoderTest extends TestCase @@ -26,12 +28,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 +41,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 +52,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 +66,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 +78,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 +87,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 +96,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 +106,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 +117,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 +128,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 +144,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 +163,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 +182,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 +202,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 +216,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 +237,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 +251,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 +267,7 @@ public function testChunkIsMaximumSize() } $data .= "\r\n"; - $this->input->emit('data', array($data)); + $this->input->emit('data', [$data]); } public function testLateCrlf() @@ -275,9 +277,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 +289,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 +299,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 +312,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 +324,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 +336,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 +346,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 +356,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 +377,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,14 +389,14 @@ 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()); } public function testPauseStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $parser = new ChunkedDecoder($input); @@ -403,7 +405,7 @@ public function testPauseStream() public function testResumeStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $parser = new ChunkedDecoder($input); @@ -413,7 +415,7 @@ public function testResumeStream() public function testPipeStream() { - $dest = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $dest = $this->createMock(WritableStreamInterface::class); $ret = $this->parser->pipe($dest); @@ -425,7 +427,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 +447,7 @@ public function testOutputStreamCanCloseInputStream() public function testLeadingZerosWillBeIgnored() { - $buffer = array(); + $buffer = []; $this->parser->on('data', function ($data) use (&$buffer) { $buffer[] = $data; }); @@ -454,10 +456,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 +469,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 +479,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 +489,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 +499,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 +509,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 +519,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 +529,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 +539,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 +549,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 +561,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..cbb3e7ad 100644 --- a/tests/Io/ChunkedEncoderTest.php +++ b/tests/Io/ChunkedEncoderTest.php @@ -3,7 +3,9 @@ namespace React\Tests\Http\Io; use React\Http\Io\ChunkedEncoder; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use React\Stream\WritableStreamInterface; use React\Tests\Http\TestCase; class ChunkedEncoderTest extends TestCase @@ -23,19 +25,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,14 +54,14 @@ 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()); } public function testPauseStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $parser = new ChunkedEncoder($input); @@ -68,7 +70,7 @@ public function testPauseStream() public function testResumeStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $parser = new ChunkedEncoder($input); @@ -78,7 +80,7 @@ public function testResumeStream() public function testPipeStream() { - $dest = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $dest = $this->createMock(WritableStreamInterface::class); $ret = $this->chunkedStream->pipe($dest); diff --git a/tests/Io/ClientConnectionManagerTest.php b/tests/Io/ClientConnectionManagerTest.php index 6aafa6db..c4b3a07e 100644 --- a/tests/Io/ClientConnectionManagerTest.php +++ b/tests/Io/ClientConnectionManagerTest.php @@ -2,21 +2,26 @@ namespace React\Tests\Http\Io; +use React\EventLoop\LoopInterface; +use React\EventLoop\TimerInterface; use React\Http\Io\ClientConnectionManager; use React\Http\Message\Uri; use React\Promise\Promise; use React\Promise\PromiseInterface; +use React\Socket\ConnectionInterface; +use React\Socket\ConnectorInterface; use React\Tests\Http\TestCase; +use function React\Promise\resolve; class ClientConnectionManagerTest extends TestCase { public function testConnectWithHttpsUriShouldConnectToTlsWithDefaultPort() { $promise = new Promise(function () { }); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn($promise); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $connectionManager = new ClientConnectionManager($connector, $loop); @@ -29,10 +34,10 @@ public function testConnectWithHttpsUriShouldConnectToTlsWithDefaultPort() public function testConnectWithHttpUriShouldConnectToTcpWithDefaultPort() { $promise = new Promise(function () { }); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->once())->method('connect')->with('reactphp.org:80')->willReturn($promise); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $connectionManager = new ClientConnectionManager($connector, $loop); @@ -43,10 +48,10 @@ public function testConnectWithHttpUriShouldConnectToTcpWithDefaultPort() public function testConnectWithExplicitPortShouldConnectWithGivenPort() { $promise = new Promise(function () { }); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->once())->method('connect')->with('reactphp.org:8080')->willReturn($promise); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $connectionManager = new ClientConnectionManager($connector, $loop); @@ -56,10 +61,10 @@ public function testConnectWithExplicitPortShouldConnectWithGivenPort() public function testConnectWithInvalidSchemeShouldRejectWithException() { - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->never())->method('connect'); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $connectionManager = new ClientConnectionManager($connector, $loop); @@ -70,16 +75,16 @@ public function testConnectWithInvalidSchemeShouldRejectWithException() $exception = $reason; }); - $this->assertInstanceOf('InvalidArgumentException', $exception); + $this->assertInstanceOf(\InvalidArgumentException::class, $exception); $this->assertEquals('Invalid request URL given', $exception->getMessage()); } public function testConnectWithoutSchemeShouldRejectWithException() { - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->never())->method('connect'); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $connectionManager = new ClientConnectionManager($connector, $loop); @@ -90,68 +95,68 @@ public function testConnectWithoutSchemeShouldRejectWithException() $exception = $reason; }); - $this->assertInstanceOf('InvalidArgumentException', $exception); + $this->assertInstanceOf(\InvalidArgumentException::class, $exception); $this->assertEquals('Invalid request URL given', $exception->getMessage()); } public function testConnectReusesIdleConnectionFromPreviousKeepAliveCallWithoutUsingConnectorAndWillAddAndRemoveStreamEventsAndAddAndCancelIdleTimer() { - $connectionToReuse = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connectionToReuse = $this->createMock(ConnectionInterface::class); $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(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->never())->method('connect'); - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->willReturn($timer); $loop->expects($this->once())->method('cancelTimer')->with($timer); @@ -172,13 +177,13 @@ public function testConnectReusesIdleConnectionFromPreviousKeepAliveCallWithoutU public function testConnectReusesIdleConnectionFromPreviousKeepAliveCallWithoutUsingConnectorAlsoWhenUriPathAndQueryAndFragmentIsDifferent() { - $connectionToReuse = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connectionToReuse = $this->createMock(ConnectionInterface::class); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->never())->method('connect'); - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->willReturn($timer); $loop->expects($this->once())->method('cancelTimer')->with($timer); @@ -199,13 +204,13 @@ public function testConnectReusesIdleConnectionFromPreviousKeepAliveCallWithoutU public function testConnectUsesConnectorWithSameUriAndReturnsPromiseForNewConnectionFromConnectorWhenPreviousKeepAliveCallUsedDifferentUri() { - $connectionToReuse = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connectionToReuse = $this->createMock(ConnectionInterface::class); $promise = new Promise(function () { }); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn($promise); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $connectionManager = new ClientConnectionManager($connector, $loop); @@ -219,14 +224,14 @@ public function testConnectUsesConnectorWithSameUriAndReturnsPromiseForNewConnec public function testConnectUsesConnectorForNewConnectionWhenPreviousConnectReusedIdleConnectionFromPreviousKeepAliveCall() { - $firstConnection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); - $secondConnection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $firstConnection = $this->createMock(ConnectionInterface::class); + $secondConnection = $this->createMock(ConnectionInterface::class); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(\React\Promise\resolve($secondConnection)); + $connector = $this->createMock(ConnectorInterface::class); + $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(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->willReturn($timer); $loop->expects($this->once())->method('cancelTimer')->with($timer); @@ -250,12 +255,12 @@ public function testConnectUsesConnectorForNewConnectionWhenPreviousConnectReuse public function testKeepAliveAddsTimerAndDoesNotCloseConnectionImmediately() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->never())->method('close'); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with(0.001, $this->anything()); $connectionManager = new ClientConnectionManager($connector, $loop); @@ -265,14 +270,14 @@ public function testKeepAliveAddsTimerAndDoesNotCloseConnectionImmediately() public function testKeepAliveClosesConnectionAfterIdleTimeout() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('close'); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $timerCallback = null; - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with($this->anything(), $this->callback(function ($cb) use (&$timerCallback) { $timerCallback = $cb; return true; @@ -290,18 +295,18 @@ public function testKeepAliveClosesConnectionAfterIdleTimeout() public function testConnectUsesConnectorForNewConnectionWhenIdleConnectionFromPreviousKeepAliveCallHasAlreadyTimedOut() { - $firstConnection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $firstConnection = $this->createMock(ConnectionInterface::class); $firstConnection->expects($this->once())->method('close'); - $secondConnection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $secondConnection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ConnectorInterface::class); + $connector->expects($this->once())->method('connect')->with('tls://reactphp.org:443')->willReturn(resolve($secondConnection)); $timerCallback = null; - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with($this->anything(), $this->callback(function ($cb) use (&$timerCallback) { $timerCallback = $cb; return true; @@ -329,42 +334,42 @@ public function testConnectUsesConnectorForNewConnectionWhenIdleConnectionFromPr public function testConnectUsesConnectorForNewConnectionWhenIdleConnectionFromPreviousKeepAliveCallHasAlreadyFiredUnexpectedStreamEventBeforeIdleTimeoutThatClosesConnection() { - $firstConnection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $firstConnection = $this->createMock(ConnectionInterface::class); $firstConnection->expects($this->once())->method('close'); $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 = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ConnectorInterface::class); + $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(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->willReturn($timer); $loop->expects($this->once())->method('cancelTimer')->with($timer); diff --git a/tests/Io/ClientRequestStreamTest.php b/tests/Io/ClientRequestStreamTest.php index 9a5373a1..a20cda61 100644 --- a/tests/Io/ClientRequestStreamTest.php +++ b/tests/Io/ClientRequestStreamTest.php @@ -4,43 +4,49 @@ use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +use React\EventLoop\LoopInterface; +use React\Http\Io\ClientConnectionManager; use React\Http\Io\ClientRequestStream; use React\Http\Message\Request; use React\Http\Message\Uri; use React\Promise\Deferred; use React\Promise\Promise; +use React\Socket\Connection; +use React\Socket\ConnectionInterface; 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 { /** @test */ public function testRequestShouldUseConnectionManagerWithUriFromRequestAndBindToStreamEvents() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ClientConnectionManager::class); + $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(); @@ -53,13 +59,13 @@ public function testRequestShouldUseConnectionManagerWithUriFromRequestAndBindTo /** @test */ 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 = $this->createMock(ClientConnectionManager::class); + $connectionManager->expects($this->once())->method('connect')->willReturn(reject(new \RuntimeException())); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); - $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf('RuntimeException'))); + $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf(\RuntimeException::class))); $request->on('close', $this->expectCallableOnce()); $request->end(); @@ -68,15 +74,15 @@ public function requestShouldEmitErrorIfConnectionFails() /** @test */ public function requestShouldEmitErrorIfConnectionClosesBeforeResponseIsParsed() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager = $this->createMock(ClientConnectionManager::class); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); - $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf('RuntimeException'))); + $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf(\RuntimeException::class))); $request->on('close', $this->expectCallableOnce()); $request->end(); @@ -86,15 +92,15 @@ public function requestShouldEmitErrorIfConnectionClosesBeforeResponseIsParsed() /** @test */ public function requestShouldEmitErrorIfConnectionEmitsError() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager = $this->createMock(ClientConnectionManager::class); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); - $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf('Exception'))); + $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf(\Exception::class))); $request->on('close', $this->expectCallableOnce()); $request->end(); @@ -105,44 +111,42 @@ public static function provideInvalidRequest() { $request = new Request('GET' , "http://localhost/"); - return array( - array( - $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') - ) - ); + yield [ + $request->withMethod("INVA\r\nLID", '') + ]; + yield [ + $request->withRequestTarget('/inva lid') + ]; + yield [ + $request->withHeader('Invalid', "Yes\r\n") + ]; + yield [ + $request->withHeader('Invalid', "Yes\n") + ]; + yield [ + $request->withHeader('Invalid', "Yes\r") + ]; + yield [ + $request->withHeader("Inva\r\nlid", 'Yes') + ]; + yield [ + $request->withHeader("Inva\nlid", 'Yes') + ]; + yield [ + $request->withHeader("Inva\rlid", 'Yes') + ]; + yield [ + $request->withHeader('Inva Lid', 'Yes') + ]; + yield [ + $request->withHeader('Inva:Lid', 'Yes') + ]; + yield [ + $request->withHeader('Invalid', "Val\0ue") + ]; + yield [ + $request->withHeader("Inva\0lid", 'Yes') + ]; } /** @@ -151,12 +155,12 @@ public static function provideInvalidRequest() */ public function testStreamShouldEmitErrorBeforeCreatingConnectionWhenRequestIsInvalid(RequestInterface $request) { - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $connectionManager->expects($this->never())->method('connect'); $stream = new ClientRequestStream($connectionManager, $request); - $stream->on('error', $this->expectCallableOnceWith($this->isInstanceOf('InvalidArgumentException'))); + $stream->on('error', $this->expectCallableOnceWith($this->isInstanceOf(\InvalidArgumentException::class))); $stream->on('close', $this->expectCallableOnce()); $stream->end(); @@ -165,15 +169,15 @@ public function testStreamShouldEmitErrorBeforeCreatingConnectionWhenRequestIsIn /** @test */ public function requestShouldEmitErrorIfRequestParserThrowsException() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager = $this->createMock(ClientConnectionManager::class); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); - $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf('InvalidArgumentException'))); + $request->on('error', $this->expectCallableOnceWith($this->isInstanceOf(\InvalidArgumentException::class))); $request->on('close', $this->expectCallableOnce()); $request->end(); @@ -183,13 +187,13 @@ public function requestShouldEmitErrorIfRequestParserThrowsException() /** @test */ public function getRequestShouldSendAGetRequest() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ClientConnectionManager::class); + $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(); @@ -198,13 +202,13 @@ public function getRequestShouldSendAGetRequest() /** @test */ public function getHttp11RequestShouldSendAGetRequestWithGivenConnectionCloseHeader() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ClientConnectionManager::class); + $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(); @@ -213,13 +217,13 @@ public function getHttp11RequestShouldSendAGetRequestWithGivenConnectionCloseHea /** @test */ public function getOptionsAsteriskShouldSendAOptionsRequestAsteriskRequestTarget() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ClientConnectionManager::class); + $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); @@ -228,21 +232,20 @@ public function getOptionsAsteriskShouldSendAOptionsRequestAsteriskRequestTarget public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsContentLengthZero() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -253,21 +256,20 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsCon public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsStatusNoContent() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -278,21 +280,20 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsSta public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsStatusNotModifiedWithContentLengthGiven() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -303,21 +304,20 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenResponseContainsSta public function testStreamShouldEmitResponseWithEmptyBodyWhenRequestMethodIsHead() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("HEAD / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -328,21 +328,20 @@ public function testStreamShouldEmitResponseWithEmptyBodyWhenRequestMethodIsHead public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenResponseContainsContentLengthAndResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -353,21 +352,20 @@ public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenRespons public function testStreamShouldEmitResponseWithStreamingBodyWithoutDataWhenResponseContainsContentLengthWithoutResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -378,21 +376,20 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithoutDataWhenResp public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndWhenResponseContainsContentLengthWithIncompleteResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -403,21 +400,20 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndW public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenResponseContainsTransferEncodingChunkedAndResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -428,21 +424,20 @@ public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenRespons public function testStreamShouldEmitResponseWithStreamingBodyWithoutDataWhenResponseContainsTransferEncodingChunkedWithoutResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -453,21 +448,20 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithoutDataWhenResp public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndWhenResponseContainsTransferEncodingChunkedWithIncompleteResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -478,21 +472,20 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndW public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndWhenResponseContainsNoContentLengthAndIncompleteResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -503,7 +496,7 @@ public function testStreamShouldEmitResponseWithStreamingBodyWithDataWithoutEndW public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenResponseContainsNoContentLengthAndResponseBodyTerminatedByConnectionEndEvent() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n"); $connection->expects($this->once())->method('close'); @@ -519,17 +512,16 @@ public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenRespons return true; })); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager = $this->createMock(ClientConnectionManager::class); + $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()); @@ -543,16 +535,16 @@ public function testStreamShouldEmitResponseWithStreamingBodyUntilEndWhenRespons public function testStreamShouldReuseConnectionForHttp11ByDefault() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -564,15 +556,15 @@ public function testStreamShouldReuseConnectionForHttp11ByDefault() public function testStreamShouldNotReuseConnectionWhenResponseContainsConnectionClose() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -584,15 +576,15 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsConnection public function testStreamShouldNotReuseConnectionWhenRequestContainsConnectionCloseWithAdditionalOptions() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: FOO, CLOSE, BAR\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -604,15 +596,15 @@ public function testStreamShouldNotReuseConnectionWhenRequestContainsConnectionC public function testStreamShouldNotReuseConnectionForHttp10ByDefault() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -624,16 +616,16 @@ public function testStreamShouldNotReuseConnectionForHttp10ByDefault() public function testStreamShouldReuseConnectionForHttp10WhenBothRequestAndResponseContainConnectionKeepAlive() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.0\r\nHost: www.example.com\r\nConnection: keep-alive\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -645,16 +637,16 @@ public function testStreamShouldReuseConnectionForHttp10WhenBothRequestAndRespon public function testStreamShouldReuseConnectionForHttp10WhenBothRequestAndResponseContainConnectionKeepAliveWithAdditionalOptions() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.0\r\nHost: www.example.com\r\nConnection: FOO, KEEP-ALIVE, BAR\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -666,7 +658,7 @@ public function testStreamShouldReuseConnectionForHttp10WhenBothRequestAndRespon public function testStreamShouldNotReuseConnectionWhenResponseContainsNoContentLengthAndResponseBodyTerminatedByConnectionEndEvent() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(false); $connection->expects($this->once())->method('close'); @@ -683,10 +675,10 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsNoContentL return true; })); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager = $this->createMock(ClientConnectionManager::class); + $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()); @@ -701,7 +693,7 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsNoContentL public function testStreamShouldNotReuseConnectionWhenResponseContainsContentLengthButIsTerminatedByUnexpectedCloseEvent() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"); $connection->expects($this->atMost(1))->method('isReadable')->willReturn(false); $connection->expects($this->once())->method('close'); @@ -718,10 +710,10 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsContentLen return true; })); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager = $this->createMock(ClientConnectionManager::class); + $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()); @@ -736,16 +728,16 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsContentLen public function testStreamShouldReuseConnectionWhenResponseContainsTransferEncodingChunkedAndResponseBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"); $connection->expects($this->once())->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -757,15 +749,15 @@ public function testStreamShouldReuseConnectionWhenResponseContainsTransferEncod public function testStreamShouldNotReuseConnectionWhenResponseContainsTransferEncodingChunkedAndResponseBodyContainsInvalidData() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('write')->with("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"); $connection->expects($this->atMost(1))->method('isReadable')->willReturn(true); $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 = $this->createMock(ClientConnectionManager::class); + $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()); @@ -778,13 +770,13 @@ public function testStreamShouldNotReuseConnectionWhenResponseContainsTransferEn /** @test */ public function postRequestShouldSendAPostRequest() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ClientConnectionManager::class); + $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'); @@ -797,17 +789,17 @@ public function postRequestShouldSendAPostRequest() /** @test */ public function writeWithAPostRequestShouldSendToTheStream() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ClientConnectionManager::class); + $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"); @@ -822,19 +814,19 @@ public function writeWithAPostRequestShouldSendToTheStream() /** @test */ public function writeWithAPostRequestShouldSendBodyAfterHeadersAndEmitDrainEvent() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 ); $deferred = new Deferred(); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $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")); @@ -856,23 +848,23 @@ public function writeWithAPostRequestShouldSendBodyAfterHeadersAndEmitDrainEvent /** @test */ public function writeWithAPostRequestShouldForwardDrainEventIfFirstChunkExceedsBuffer() { - $connection = $this->getMockBuilder('React\Socket\Connection') + $connection = $this->getMockBuilder(Connection::class) ->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 ); $deferred = new Deferred(); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $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")); @@ -895,30 +887,28 @@ public function writeWithAPostRequestShouldForwardDrainEventIfFirstChunkExceedsB /** @test */ public function pipeShouldPipeDataIntoTheRequestBody() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $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 = $this->createMock(ClientConnectionManager::class); + $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 - ->getMockBuilder('React\EventLoop\LoopInterface') - ->getMock(); + $loop = $this->createMock(LoopInterface::class); $stream = fopen('php://memory', 'r+'); $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"); @@ -930,7 +920,7 @@ public function pipeShouldPipeDataIntoTheRequestBody() */ public function writeShouldStartConnecting() { - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $connectionManager->expects($this->once())->method('connect')->willReturn(new Promise(function () { })); $requestData = new Request('POST', 'http://www.example.com'); @@ -944,7 +934,7 @@ public function writeShouldStartConnecting() */ public function endShouldStartConnectingAndChangeStreamIntoNonWritableMode() { - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $connectionManager->expects($this->once())->method('connect')->willReturn(new Promise(function () { })); $requestData = new Request('POST', 'http://www.example.com'); @@ -960,7 +950,7 @@ public function endShouldStartConnectingAndChangeStreamIntoNonWritableMode() */ public function closeShouldEmitCloseEvent() { - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $requestData = new Request('POST', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -974,7 +964,7 @@ public function closeShouldEmitCloseEvent() */ public function writeAfterCloseReturnsFalse() { - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $requestData = new Request('POST', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -990,7 +980,7 @@ public function writeAfterCloseReturnsFalse() */ public function endAfterCloseIsNoOp() { - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $connectionManager->expects($this->never())->method('connect'); $requestData = new Request('POST', 'http://www.example.com'); @@ -1008,7 +998,7 @@ public function closeShouldCancelPendingConnectionAttempt() $promise = new Promise(function () {}, function () { throw new \RuntimeException(); }); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $connectionManager->expects($this->once())->method('connect')->willReturn($promise); $requestData = new Request('POST', 'http://www.example.com'); @@ -1026,7 +1016,7 @@ public function closeShouldCancelPendingConnectionAttempt() /** @test */ public function requestShouldRemoveAllListenerAfterClosed() { - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); + $connectionManager = $this->createMock(ClientConnectionManager::class); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -1041,10 +1031,10 @@ public function requestShouldRemoveAllListenerAfterClosed() /** @test */ public function multivalueHeader() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); - $connectionManager = $this->getMockBuilder('React\Http\Io\ClientConnectionManager')->disableOriginalConstructor()->getMock(); - $connectionManager->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection)); + $connectionManager = $this->createMock(ClientConnectionManager::class); + $connectionManager->expects($this->once())->method('connect')->willReturn(resolve($connection)); $requestData = new Request('GET', 'http://www.example.com'); $request = new ClientRequestStream($connectionManager, $requestData); @@ -1064,7 +1054,7 @@ public function multivalueHeader() $request->handleData("\r\nbody"); /** @var \Psr\Http\Message\ResponseInterface $response */ - $this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response); + $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertEquals('1.0', $response->getProtocolVersion()); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('OK', $response->getReasonPhrase()); diff --git a/tests/Io/ClockTest.php b/tests/Io/ClockTest.php index 8f4b90fa..318fa7ef 100644 --- a/tests/Io/ClockTest.php +++ b/tests/Io/ClockTest.php @@ -3,13 +3,14 @@ namespace React\Tests\Http\Io; use PHPUnit\Framework\TestCase; +use React\EventLoop\LoopInterface; use React\Http\Io\Clock; class ClockTest extends TestCase { public function testNowReturnsSameTimestampMultipleTimesInSameTick() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $clock = new Clock($loop); @@ -21,7 +22,7 @@ public function testNowReturnsSameTimestampMultipleTimesInSameTick() public function testNowResetsMemoizedTimestampOnFutureTick() { $tick = null; - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('futureTick')->with($this->callback(function ($cb) use (&$tick) { $tick = $cb; return true; diff --git a/tests/Io/CloseProtectionStreamTest.php b/tests/Io/CloseProtectionStreamTest.php index 8490daff..f3aa346d 100644 --- a/tests/Io/CloseProtectionStreamTest.php +++ b/tests/Io/CloseProtectionStreamTest.php @@ -3,14 +3,16 @@ namespace React\Tests\Http\Io; use React\Http\Io\CloseProtectionStream; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use React\Stream\WritableStreamInterface; use React\Tests\Http\TestCase; class CloseProtectionStreamTest extends TestCase { public function testCloseDoesNotCloseTheInputStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->disableOriginalConstructor()->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->never())->method('pause'); $input->expects($this->never())->method('resume'); $input->expects($this->never())->method('close'); @@ -27,7 +29,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()); @@ -35,7 +37,7 @@ public function testErrorWontCloseStream() public function testResumeStreamWillResumeInputStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $input->expects($this->once())->method('resume'); @@ -46,7 +48,7 @@ public function testResumeStreamWillResumeInputStream() public function testCloseResumesInputStreamIfItWasPreviouslyPaused() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $input->expects($this->once())->method('resume'); @@ -73,7 +75,7 @@ public function testPipeStream() $input = new ThroughStream(); $protection = new CloseProtectionStream($input); - $dest = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $dest = $this->createMock(WritableStreamInterface::class); $ret = $protection->pipe($dest); @@ -91,7 +93,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 +110,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 +126,7 @@ public function testEndWontBeEmittedAfterClose() $protection->close(); - $input->emit('end', array()); + $input->emit('end', []); $this->assertFalse($protection->isReadable()); $this->assertTrue($input->isReadable()); @@ -132,7 +134,7 @@ public function testEndWontBeEmittedAfterClose() public function testPauseAfterCloseHasNoEffect() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->never())->method('pause'); $input->expects($this->never())->method('resume'); @@ -146,7 +148,7 @@ public function testPauseAfterCloseHasNoEffect() public function testResumeAfterCloseHasNoEffect() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->never())->method('pause'); $input->expects($this->never())->method('resume'); diff --git a/tests/Io/EmptyBodyStreamTest.php b/tests/Io/EmptyBodyStreamTest.php index 8430239d..4ee92364 100644 --- a/tests/Io/EmptyBodyStreamTest.php +++ b/tests/Io/EmptyBodyStreamTest.php @@ -3,6 +3,7 @@ namespace React\Tests\Http\Io; use React\Http\Io\EmptyBodyStream; +use React\Stream\WritableStreamInterface; use React\Tests\Http\TestCase; class EmptyBodyStreamTest extends TestCase @@ -36,7 +37,7 @@ public function testResumeIsNoop() public function testPipeStreamReturnsDestinationStream() { - $dest = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $dest = $this->createMock(WritableStreamInterface::class); $ret = $this->bodyStream->pipe($dest); @@ -65,18 +66,18 @@ 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() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->tell(); } public function testEof() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->eof(); } @@ -87,13 +88,13 @@ public function testIsSeekable() public function testWrite() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->write(''); } public function testRead() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->read(1); } @@ -104,7 +105,7 @@ public function testGetContentsReturnsEmpy() public function testGetMetaDataWithoutKeyReturnsEmptyArray() { - $this->assertSame(array(), $this->bodyStream->getMetadata()); + $this->assertSame([], $this->bodyStream->getMetadata()); } public function testGetMetaDataWithKeyReturnsNull() @@ -126,13 +127,13 @@ public function testIsReadableReturnsFalseWhenAlreadyClosed() public function testSeek() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->seek(''); } public function testRewind() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->rewind(); } diff --git a/tests/Io/HttpBodyStreamTest.php b/tests/Io/HttpBodyStreamTest.php index db21dcf8..c246bd96 100644 --- a/tests/Io/HttpBodyStreamTest.php +++ b/tests/Io/HttpBodyStreamTest.php @@ -3,7 +3,9 @@ namespace React\Tests\Http\Io; use React\Http\Io\HttpBodyStream; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use React\Stream\WritableStreamInterface; use React\Tests\Http\TestCase; class HttpBodyStreamTest extends TestCase @@ -22,13 +24,13 @@ 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() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $bodyStream = new HttpBodyStream($input, null); @@ -37,7 +39,7 @@ public function testPauseStream() public function testResumeStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('resume'); $bodyStream = new HttpBodyStream($input, null); @@ -46,7 +48,7 @@ public function testResumeStream() public function testPipeStream() { - $dest = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $dest = $this->createMock(WritableStreamInterface::class); $ret = $this->bodyStream->pipe($dest); @@ -58,7 +60,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 +69,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 +81,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()); } @@ -107,13 +109,13 @@ public function testGetSizeCustom() public function testTell() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->tell(); } public function testEof() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->eof(); } @@ -124,13 +126,13 @@ public function testIsSeekable() public function testWrite() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->write(''); } public function testRead() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->read(''); } @@ -151,13 +153,13 @@ public function testIsReadable() public function testSeek() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->seek(''); } public function testRewind() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->bodyStream->rewind(); } diff --git a/tests/Io/IniUtilTest.php b/tests/Io/IniUtilTest.php index 155c6ed2..2e9f99c9 100644 --- a/tests/Io/IniUtilTest.php +++ b/tests/Io/IniUtilTest.php @@ -7,42 +7,40 @@ class IniUtilTest extends TestCase { - public function provideIniSizes() + public static function provideIniSizes() { - return array( - array( - '1', - 1, - ), - array( - '10', - 10, - ), - array( - '1024', - 1024, - ), - array( - '1K', - 1024, - ), - array( - '1.5M', - 1572864, - ), - array( - '64M', - 67108864, - ), - array( - '8G', - 8589934592, - ), - array( - '1T', - 1099511627776, - ), - ); + yield [ + '1', + 1, + ]; + yield [ + '10', + 10, + ]; + yield [ + '1024', + 1024, + ]; + yield [ + '1K', + 1024, + ]; + yield [ + '1.5M', + 1572864, + ]; + yield [ + '64M', + 67108864, + ]; + yield [ + '8G', + 8589934592, + ]; + yield [ + '1T', + 1099511627776, + ]; } /** @@ -58,16 +56,14 @@ public function testIniSizeToBytesWithInvalidSuffixReturnsNumberWithoutSuffix() $this->assertEquals('2', IniUtil::iniSizeToBytes('2x')); } - public function provideInvalidInputIniSizeToBytes() + public static function provideInvalidInputIniSizeToBytes() { - return array( - array('-1G'), - array('0G'), - array('foo'), - array('fooK'), - array('1ooL'), - array('1ooL'), - ); + yield ['-1G']; + yield ['0G']; + yield ['foo']; + yield ['fooK']; + yield ['1ooL']; + yield ['1ooL']; } /** @@ -75,7 +71,7 @@ public function provideInvalidInputIniSizeToBytes() */ public function testInvalidInputIniSizeToBytes($input) { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); IniUtil::iniSizeToBytes($input); } } diff --git a/tests/Io/LengthLimitedStreamTest.php b/tests/Io/LengthLimitedStreamTest.php index b415269c..b841257a 100644 --- a/tests/Io/LengthLimitedStreamTest.php +++ b/tests/Io/LengthLimitedStreamTest.php @@ -3,7 +3,9 @@ namespace React\Tests\Http\Io; use React\Http\Io\LengthLimitedStream; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use React\Stream\WritableStreamInterface; use React\Tests\Http\TestCase; class LengthLimitedStreamTest extends TestCase @@ -24,7 +26,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 +35,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 +45,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,14 +54,14 @@ 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()); } public function testPauseStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $stream = new LengthLimitedStream($input, 0); @@ -68,7 +70,7 @@ public function testPauseStream() public function testResumeStream() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $stream = new LengthLimitedStream($input, 0); @@ -79,7 +81,7 @@ public function testResumeStream() public function testPipeStream() { $stream = new LengthLimitedStream($this->input, 0); - $dest = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $dest = $this->createMock(WritableStreamInterface::class); $ret = $stream->pipe($dest); @@ -92,7 +94,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 762d7bdb..a2344d3a 100644 --- a/tests/Io/MiddlewareRunnerTest.php +++ b/tests/Io/MiddlewareRunnerTest.php @@ -8,27 +8,30 @@ 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'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('No middleware to run'); $middlewareStack($request); } 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 +39,7 @@ function (ServerRequestInterface $request, $next) use (&$args) { function (ServerRequestInterface $request) { return null; } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); @@ -48,12 +51,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,36 +67,35 @@ 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/'); - $this->setExpectedException('RuntimeException', 'hello'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('hello'); $middleware($request); } - /** - * @requires PHP 7 - */ public function testThrowsIfHandlerThrowsThrowable() { - $middleware = new MiddlewareRunner(array( + $middleware = new MiddlewareRunner([ function (ServerRequestInterface $request) { throw new \Error('hello'); } - )); + ]); $request = new ServerRequest('GET', 'http://example.com/'); - $this->setExpectedException('Throwable', 'hello'); + $this->expectException(\Throwable::class); + $this->expectExceptionMessage('hello'); $middleware($request); } - public function provideProcessStackMiddlewares() + public static function provideProcessStackMiddlewares() { $processStackA = new ProcessStack(); $processStackB = new ProcessStack(); @@ -102,42 +104,40 @@ public function provideProcessStackMiddlewares() $responseMiddleware = function () { return new Response(200); }; - return array( - array( - array( - $processStackA, - $responseMiddleware, - ), - 1, - ), - array( - array( - $processStackB, - $processStackB, - $responseMiddleware, - ), - 2, - ), - array( - array( - $processStackC, - $processStackC, - $processStackC, - $responseMiddleware, - ), - 3, - ), - array( - array( - $processStackD, - $processStackD, - $processStackD, - $processStackD, - $responseMiddleware, - ), - 4, - ), - ); + yield [ + [ + $processStackA, + $responseMiddleware, + ], + 1, + ]; + yield [ + [ + $processStackB, + $processStackB, + $responseMiddleware, + ], + 2, + ]; + yield [ + [ + $processStackC, + $processStackC, + $processStackC, + $responseMiddleware, + ], + 3, + ]; + yield [ + [ + $processStackD, + $processStackD, + $processStackD, + $processStackD, + $responseMiddleware, + ], + 4, + ]; } /** @@ -159,7 +159,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()); @@ -173,20 +173,18 @@ public function testProcessStack(array $middlewares, $expectedCallCount) } } - public function provideErrorHandler() + public static function provideErrorHandler() { - return array( - array( - function (\Exception $e) { - throw $e; - } - ), - array( - function (\Exception $e) { - return Promise\reject($e); - } - ) - ); + yield [ + function (\Exception $e) { + throw $e; + } + ]; + yield [ + function (\Exception $e) { + return reject($e); + } + ]; } /** @@ -194,11 +192,11 @@ function (\Exception $e) { */ public function testNextCanBeRunMoreThanOnceWithoutCorruptingTheMiddlewareStack($errorHandler) { - $exception = new \RuntimeException('exception'); + $exception = new \RuntimeException(\exception::class); $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)); }); @@ -212,7 +210,7 @@ public function testNextCanBeRunMoreThanOnceWithoutCorruptingTheMiddlewareStack( $response = new Response(); $called = 0; - $runner = new MiddlewareRunner(array( + $runner = new MiddlewareRunner([ $retry, function () use ($errorHandler, &$called, $response, $exception) { $called++; @@ -222,11 +220,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); @@ -234,15 +232,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); @@ -253,16 +251,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', @@ -272,135 +270,133 @@ function (ServerRequestInterface $request) use (&$receivedRequests) { 'middleware1: https://example.com/3', 'middleware2: https://example.com/3', 'middleware3: https://example.com/3' - ), + ], $receivedRequests ); } - public function provideUncommonMiddlewareArrayFormats() + public static function provideUncommonMiddlewareArrayFormats() { - return array( - array( - function () { - $sequence = ''; - - // Numeric index gap - return array( - 0 => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'A'; - - return $next($request); - }, - 2 => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'B'; - - return $next($request); - }, - 3 => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); - }, - ); - }, - 'ABC', - ), - array( - function () { - $sequence = ''; - - // Reversed numeric indexes - return array( - 2 => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'A'; - - return $next($request); - }, - 1 => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'B'; - - return $next($request); - }, - 0 => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); - }, - ); - }, - 'ABC', - ), - array( - function () { - $sequence = ''; - - // Associative array - return array( - 'middleware1' => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'A'; - - return $next($request); - }, - 'middleware2' => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'B'; - - return $next($request); - }, - 'middleware3' => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); - }, - ); - }, - 'ABC', - ), - array( - function () { - $sequence = ''; - - // Associative array with empty or trimmable string keys - return array( - '' => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'A'; - - return $next($request); - }, - ' ' => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'B'; - - return $next($request); - }, - ' ' => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'C'); - }, - ); - }, - 'ABC', - ), - array( - function () { - $sequence = ''; - - // Mixed array keys - return array( - '' => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'A'; - - return $next($request); - }, - 0 => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'B'; - - return $next($request); - }, - 'foo' => function (ServerRequestInterface $request, $next) use (&$sequence) { - $sequence .= 'C'; - - return $next($request); - }, - 2 => function () use (&$sequence) { - return new Response(200, array(), $sequence . 'D'); - }, - ); - }, - 'ABCD', - ), - ); + yield [ + function () { + $sequence = ''; + + // Numeric index gap + return [ + 0 => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'A'; + + return $next($request); + }, + 2 => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'B'; + + return $next($request); + }, + 3 => function () use (&$sequence) { + return new Response(200, [], $sequence . 'C'); + }, + ]; + }, + 'ABC', + ]; + yield [ + function () { + $sequence = ''; + + // Reversed numeric indexes + return [ + 2 => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'A'; + + return $next($request); + }, + 1 => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'B'; + + return $next($request); + }, + 0 => function () use (&$sequence) { + return new Response(200, [], $sequence . 'C'); + }, + ]; + }, + 'ABC', + ]; + yield [ + function () { + $sequence = ''; + + // Associative array + return [ + 'middleware1' => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'A'; + + return $next($request); + }, + 'middleware2' => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'B'; + + return $next($request); + }, + 'middleware3' => function () use (&$sequence) { + return new Response(200, [], $sequence . 'C'); + }, + ]; + }, + 'ABC', + ]; + yield [ + function () { + $sequence = ''; + + // Associative array with empty or trimmable string keys + return [ + '' => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'A'; + + return $next($request); + }, + ' ' => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'B'; + + return $next($request); + }, + ' ' => function () use (&$sequence) { + return new Response(200, [], $sequence . 'C'); + }, + ]; + }, + 'ABC', + ]; + yield [ + function () { + $sequence = ''; + + // Mixed array keys + return [ + '' => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'A'; + + return $next($request); + }, + 0 => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'B'; + + return $next($request); + }, + 'foo' => function (ServerRequestInterface $request, $next) use (&$sequence) { + $sequence .= 'C'; + + return $next($request); + }, + 2 => function () use (&$sequence) { + return new Response(200, [], $sequence . 'D'); + }, + ]; + }, + 'ABCD', + ]; } /** @@ -420,7 +416,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); @@ -430,9 +426,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/'); @@ -445,7 +441,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(); @@ -453,9 +449,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/'); @@ -465,14 +461,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..ebc5972f 100644 --- a/tests/Io/MultipartParserTest.php +++ b/tests/Io/MultipartParserTest.php @@ -2,6 +2,7 @@ namespace React\Tests\Http\Io\Middleware; +use Psr\Http\Message\UploadedFileInterface; use React\Http\Io\MultipartParser; use React\Http\Message\ServerRequest; use React\Tests\Http\TestCase; @@ -22,9 +23,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 +48,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 +81,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 +114,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 +147,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 +177,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 +209,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 +241,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 +274,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 +300,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 +326,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 +356,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 +437,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 +492,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 +518,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 +538,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 +556,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 +577,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 +598,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 +619,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 +639,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 +663,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); @@ -673,7 +674,7 @@ public function testInvalidUploadFileWithoutContentTypeUsesNullValue() $this->assertCount(1, $files); $this->assertTrue(isset($files['file'])); - $this->assertInstanceOf('Psr\Http\Message\UploadedFileInterface', $files['file']); + $this->assertInstanceOf(UploadedFileInterface::class, $files['file']); /* @var $file \Psr\Http\Message\UploadedFileInterface */ $file = $files['file']; @@ -697,9 +698,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); @@ -708,7 +709,7 @@ public function testInvalidUploadFileWithoutMultipleContentTypeUsesLastValue() $this->assertCount(1, $files); $this->assertTrue(isset($files['file'])); - $this->assertInstanceOf('Psr\Http\Message\UploadedFileInterface', $files['file']); + $this->assertInstanceOf(UploadedFileInterface::class, $files['file']); /* @var $file \Psr\Http\Message\UploadedFileInterface */ $file = $files['file']; @@ -731,9 +732,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); @@ -742,7 +743,7 @@ public function testUploadEmptyFile() $this->assertCount(1, $files); $this->assertTrue(isset($files['file'])); - $this->assertInstanceOf('Psr\Http\Message\UploadedFileInterface', $files['file']); + $this->assertInstanceOf(UploadedFileInterface::class, $files['file']); /* @var $file \Psr\Http\Message\UploadedFileInterface */ $file = $files['file']; @@ -765,9 +766,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); @@ -776,7 +777,7 @@ public function testUploadTooLargeFile() $this->assertCount(1, $files); $this->assertTrue(isset($files['file'])); - $this->assertInstanceOf('Psr\Http\Message\UploadedFileInterface', $files['file']); + $this->assertInstanceOf(UploadedFileInterface::class, $files['file']); /* @var $file \Psr\Http\Message\UploadedFileInterface */ $file = $files['file']; @@ -798,9 +799,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); @@ -809,7 +810,7 @@ public function testUploadTooLargeFileWithIniLikeSize() $this->assertCount(1, $files); $this->assertTrue(isset($files['file'])); - $this->assertInstanceOf('Psr\Http\Message\UploadedFileInterface', $files['file']); + $this->assertInstanceOf(UploadedFileInterface::class, $files['file']); /* @var $file \Psr\Http\Message\UploadedFileInterface */ $file = $files['file']; @@ -831,9 +832,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); @@ -842,7 +843,7 @@ public function testUploadNoFile() $this->assertCount(1, $files); $this->assertTrue(isset($files['file'])); - $this->assertInstanceOf('Psr\Http\Message\UploadedFileInterface', $files['file']); + $this->assertInstanceOf(UploadedFileInterface::class, $files['file']); /* @var $file \Psr\Http\Message\UploadedFileInterface */ $file = $files['file']; @@ -869,9 +870,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 +911,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 +954,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 +1009,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,13 +1041,13 @@ 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(); - $reflectecClass = new \ReflectionClass('\React\Http\Io\MultipartParser'); + $reflectecClass = new \ReflectionClass(MultipartParser::class); $requestProperty = $reflectecClass->getProperty('request'); $requestProperty->setAccessible(true); $cursorProperty = $reflectecClass->getProperty('cursor'); diff --git a/tests/Io/PauseBufferStreamTest.php b/tests/Io/PauseBufferStreamTest.php index a9678a78..139db8fd 100644 --- a/tests/Io/PauseBufferStreamTest.php +++ b/tests/Io/PauseBufferStreamTest.php @@ -2,15 +2,16 @@ namespace React\Tests\Io; -use React\Tests\Http\TestCase; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use React\Tests\Http\TestCase; use React\Http\Io\PauseBufferStream; class PauseBufferStreamTest extends TestCase { public function testPauseMethodWillBePassedThroughToInput() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('pause'); $stream = new PauseBufferStream($input); @@ -19,7 +20,7 @@ public function testPauseMethodWillBePassedThroughToInput() public function testCloseMethodWillBePassedThroughToInput() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->once())->method('close'); $stream = new PauseBufferStream($input); @@ -28,7 +29,7 @@ public function testCloseMethodWillBePassedThroughToInput() public function testPauseMethodWillNotBePassedThroughToInputAfterClose() { - $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input = $this->createMock(ReadableStreamInterface::class); $input->expects($this->never())->method('pause'); $stream = new PauseBufferStream($input); @@ -156,7 +157,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 +168,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 +177,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 +192,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..2409a6be 100644 --- a/tests/Io/ReadableBodyStreamTest.php +++ b/tests/Io/ReadableBodyStreamTest.php @@ -3,8 +3,9 @@ namespace React\Tests\Http\Io; use React\Http\Io\ReadableBodyStream; -use React\Tests\Http\TestCase; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; +use React\Tests\Http\TestCase; class ReadableBodyStreamTest extends TestCase { @@ -16,7 +17,7 @@ class ReadableBodyStreamTest extends TestCase */ public function setUpStream() { - $this->input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $this->input = $this->createMock(ReadableStreamInterface::class); $this->stream = new ReadableBodyStream($this->input); } @@ -102,7 +103,7 @@ public function testEndInputWillEmitErrorEventWhenDataDoesNotReachExpectedLength $this->input->write('hi'); $this->input->end(); - $this->assertInstanceOf('UnderflowException', $called); + $this->assertInstanceOf(\UnderflowException::class, $called); $this->assertSame('Unexpected end of response body after 2/5 bytes', $called->getMessage()); } @@ -188,7 +189,7 @@ public function testPointlessTostringReturnsEmptyString() public function testPointlessDetachThrows() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->stream->detach(); } @@ -199,7 +200,7 @@ public function testPointlessGetSizeReturnsNull() public function testPointlessTellThrows() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->stream->tell(); } @@ -210,13 +211,13 @@ public function testPointlessIsSeekableReturnsFalse() public function testPointlessSeekThrows() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->stream->seek(0); } public function testPointlessRewindThrows() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->stream->rewind(); } @@ -227,19 +228,19 @@ public function testPointlessIsWritableReturnsFalse() public function testPointlessWriteThrows() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->stream->write(''); } public function testPointlessReadThrows() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->stream->read(8192); } public function testPointlessGetContentsThrows() { - $this->setExpectedException('BadMethodCallException'); + $this->expectException(\BadMethodCallException::class); $this->stream->getContents(); } @@ -250,6 +251,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 87d6bf1b..568fc375 100644 --- a/tests/Io/RequestHeaderParserTest.php +++ b/tests/Io/RequestHeaderParserTest.php @@ -2,50 +2,54 @@ namespace React\Tests\Http\Io; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ServerRequestInterface; +use React\Http\Io\Clock; use React\Http\Io\RequestHeaderParser; +use React\Socket\Connection; +use React\Stream\ReadableStreamInterface; use React\Tests\Http\TestCase; class RequestHeaderParserTest extends TestCase { public function testSplitShouldHappenOnDoubleCrlf() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $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() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableOnce()); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $data = $this->createGetRequest(); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); } public function testFeedTwoRequestsOnSeparateConnections() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); @@ -54,14 +58,14 @@ public function testFeedTwoRequestsOnSeparateConnections() ++$called; }); - $connection1 = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); - $connection2 = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection1 = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection2 = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection1); $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); } @@ -71,7 +75,7 @@ public function testHeadersEventShouldEmitRequestAndConnection() $request = null; $conn = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', function ($parsedRequest, $connection) use (&$request, &$conn) { @@ -79,58 +83,56 @@ public function testHeadersEventShouldEmitRequestAndConnection() $conn = $connection; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $data = $this->createGetRequest(); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); - $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $request); + $this->assertInstanceOf(RequestInterface::class, $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); } public function testHeadersEventShouldEmitRequestWhichShouldEmitEndForStreamingBodyWithoutContentLengthFromInitialRequestBody() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $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(ReadableStreamInterface::class, $body); $body->on('end', function () use (&$ended) { $ended = true; }); }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $data = "GET / HTTP/1.0\r\n\r\n"; - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertTrue($ended); } public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyDataFromInitialRequestBody() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $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(ReadableStreamInterface::class, $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; @@ -140,94 +142,91 @@ public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyDat }); }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $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); } public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyWithPlentyOfDataFromInitialRequestBody() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $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(ReadableStreamInterface::class, $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; }); }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $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)); } public function testHeadersEventShouldEmitRequestWhichShouldNotEmitStreamingBodyDataWithoutContentLengthFromInitialRequestBody() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $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(ReadableStreamInterface::class, $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; }); }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $data = "POST / HTTP/1.0\r\n\r\n"; $data .= 'RANDOM DATA'; - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); $this->assertSame('', $buffer); } public function testHeadersEventShouldEmitRequestWhichShouldEmitStreamingBodyDataUntilContentLengthBoundaryFromInitialRequestBody() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $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(ReadableStreamInterface::class, $body); $body->on('data', function ($chunk) use (&$buffer) { $buffer .= $chunk; }); }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $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); } @@ -236,28 +235,28 @@ public function testHeadersEventShouldParsePathAndQueryString() { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', function ($parsedRequest) use (&$request) { $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $data = $this->createAdvancedPostRequest(); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); - $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $request); + $this->assertInstanceOf(RequestInterface::class, $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()); } @@ -265,18 +264,18 @@ public function testHeaderEventWithShouldApplyDefaultAddressFromLocalConnectionA { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', function ($parsedRequest) use (&$request) { $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress'))->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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')); @@ -286,18 +285,18 @@ public function testHeaderEventViaHttpsShouldApplyHttpsSchemeFromLocalTlsConnect { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', function ($parsedRequest) use (&$request) { $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress'))->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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')); @@ -308,7 +307,7 @@ public function testHeaderOverflowShouldEmitError() $error = null; $passedConnection = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -317,13 +316,13 @@ public function testHeaderOverflowShouldEmitError() $passedConnection = $connection; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->setMethods(null)->getMock(); $parser->handle($connection); $data = str_repeat('A', 8193); - $connection->emit('data', array($data)); + $connection->emit('data', [$data]); - $this->assertInstanceOf('OverflowException', $error); + $this->assertInstanceOf(\OverflowException::class, $error); $this->assertSame('Maximum header size of 8192 exceeded.', $error->getMessage()); $this->assertSame($connection, $passedConnection); } @@ -332,7 +331,7 @@ public function testInvalidEmptyRequestHeadersParseException() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -340,12 +339,12 @@ public function testInvalidEmptyRequestHeadersParseException() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Unable to parse invalid request-line', $error->getMessage()); } @@ -353,7 +352,7 @@ public function testInvalidMalformedRequestLineParseException() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -361,12 +360,12 @@ public function testInvalidMalformedRequestLineParseException() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Unable to parse invalid request-line', $error->getMessage()); } @@ -374,7 +373,7 @@ public function testInvalidMalformedRequestHeadersThrowsParseException() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -382,12 +381,12 @@ public function testInvalidMalformedRequestHeadersThrowsParseException() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Unable to parse invalid request header fields', $error->getMessage()); } @@ -395,7 +394,7 @@ public function testInvalidMalformedRequestHeadersWhitespaceThrowsParseException { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -403,12 +402,12 @@ public function testInvalidMalformedRequestHeadersWhitespaceThrowsParseException $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Unable to parse invalid request header fields', $error->getMessage()); } @@ -416,7 +415,7 @@ public function testInvalidAbsoluteFormSchemeEmitsError() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -424,12 +423,12 @@ public function testInvalidAbsoluteFormSchemeEmitsError() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Invalid absolute-form request-target', $error->getMessage()); } @@ -437,7 +436,7 @@ public function testOriginFormWithSchemeSeparatorInParam() { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('error', $this->expectCallableNever()); @@ -445,18 +444,18 @@ public function testOriginFormWithSchemeSeparatorInParam() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(RequestInterface::class, $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()); } @@ -464,7 +463,7 @@ public function testUriStartingWithColonSlashSlashFails() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -472,12 +471,12 @@ public function testUriStartingWithColonSlashSlashFails() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Invalid absolute-form request-target', $error->getMessage()); } @@ -485,7 +484,7 @@ public function testInvalidAbsoluteFormWithFragmentEmitsError() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -493,12 +492,12 @@ public function testInvalidAbsoluteFormWithFragmentEmitsError() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Invalid absolute-form request-target', $error->getMessage()); } @@ -506,7 +505,7 @@ public function testInvalidHeaderContainsFullUri() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -514,12 +513,12 @@ public function testInvalidHeaderContainsFullUri() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Invalid Host header value', $error->getMessage()); } @@ -527,7 +526,7 @@ public function testInvalidAbsoluteFormWithHostHeaderEmpty() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -535,12 +534,12 @@ public function testInvalidAbsoluteFormWithHostHeaderEmpty() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('Invalid Host header value', $error->getMessage()); } @@ -548,7 +547,7 @@ public function testInvalidConnectRequestWithNonAuthorityForm() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -556,12 +555,12 @@ public function testInvalidConnectRequestWithNonAuthorityForm() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame('CONNECT method MUST use authority-form request target', $error->getMessage()); } @@ -569,7 +568,7 @@ public function testInvalidHttpVersion() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -577,12 +576,12 @@ public function testInvalidHttpVersion() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame(505, $error->getCode()); $this->assertSame('Received request with invalid protocol version', $error->getMessage()); } @@ -591,7 +590,7 @@ public function testInvalidContentLengthRequestHeaderWillEmitError() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -599,12 +598,12 @@ public function testInvalidContentLengthRequestHeaderWillEmitError() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame(400, $error->getCode()); $this->assertSame('The value of `Content-Length` is not valid', $error->getMessage()); } @@ -613,7 +612,7 @@ public function testInvalidRequestWithMultipleContentLengthRequestHeadersWillEmi { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -621,12 +620,12 @@ public function testInvalidRequestWithMultipleContentLengthRequestHeadersWillEmi $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame(400, $error->getCode()); $this->assertSame('The value of `Content-Length` is not valid', $error->getMessage()); } @@ -635,7 +634,7 @@ public function testInvalidTransferEncodingRequestHeaderWillEmitError() { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -643,12 +642,12 @@ public function testInvalidTransferEncodingRequestHeaderWillEmitError() $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame(501, $error->getCode()); $this->assertSame('Only chunked-encoding is allowed for Transfer-Encoding', $error->getMessage()); } @@ -657,7 +656,7 @@ public function testInvalidRequestWithBothTransferEncodingAndContentLengthWillEm { $error = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); $parser->on('headers', $this->expectCallableNever()); @@ -665,12 +664,12 @@ public function testInvalidRequestWithBothTransferEncodingAndContentLengthWillEm $error = $message; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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->assertInstanceOf(\InvalidArgumentException::class, $error); $this->assertSame(400, $error->getCode()); $this->assertSame('Using both `Transfer-Encoding: chunked` and `Content-Length` is not allowed', $error->getMessage()); } @@ -679,7 +678,7 @@ public function testServerParamsWillBeSetOnHttpsRequest() { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $clock->expects($this->once())->method('now')->willReturn(1652972091.3958); $parser = new RequestHeaderParser($clock); @@ -688,12 +687,12 @@ public function testServerParamsWillBeSetOnHttpsRequest() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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(); @@ -712,7 +711,7 @@ public function testServerParamsWillBeSetOnHttpRequest() { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $clock->expects($this->once())->method('now')->willReturn(1652972091.3958); $parser = new RequestHeaderParser($clock); @@ -721,12 +720,12 @@ public function testServerParamsWillBeSetOnHttpRequest() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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(); @@ -745,7 +744,7 @@ public function testServerParamsWillNotSetRemoteAddressForUnixDomainSockets() { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $clock->expects($this->once())->method('now')->willReturn(1652972091.3958); $parser = new RequestHeaderParser($clock); @@ -754,12 +753,12 @@ public function testServerParamsWillNotSetRemoteAddressForUnixDomainSockets() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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(); @@ -776,13 +775,9 @@ public function testServerParamsWillNotSetRemoteAddressForUnixDomainSockets() public function testServerParamsWontBeSetOnMissingUrls() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM'); - } - $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $clock->expects($this->once())->method('now')->willReturn(1652972091.3958); $parser = new RequestHeaderParser($clock); @@ -791,10 +786,10 @@ public function testServerParamsWontBeSetOnMissingUrls() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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(); @@ -810,17 +805,17 @@ public function testServerParamsWontBeSetOnMissingUrls() public function testServerParamsWillBeReusedForMultipleRequestsFromSameConnection() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $clock->expects($this->exactly(2))->method('now')->willReturn(1652972091.3958); $parser = new RequestHeaderParser($clock); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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) { @@ -828,7 +823,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,14 +841,14 @@ public function testServerParamsWillBeReusedForMultipleRequestsFromSameConnectio public function testServerParamsWillBeRememberedUntilConnectionIsClosed() { - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(array('getLocalAddress', 'getRemoteAddress'))->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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); @@ -861,14 +856,14 @@ 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() { $request = null; - $clock = $this->getMockBuilder('React\Http\Io\Clock')->disableOriginalConstructor()->getMock(); + $clock = $this->createMock(Clock::class); $parser = new RequestHeaderParser($clock); @@ -876,10 +871,10 @@ public function testQueryParmetersWillBeSet() $request = $parsedRequest; }); - $connection = $this->getMockBuilder('React\Socket\Connection')->disableOriginalConstructor()->setMethods(null)->getMock(); + $connection = $this->getMockBuilder(Connection::class)->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..df4c5359 100644 --- a/tests/Io/SenderTest.php +++ b/tests/Io/SenderTest.php @@ -3,19 +3,25 @@ namespace React\Tests\Http\Io; use Psr\Http\Message\RequestInterface; +use React\EventLoop\LoopInterface; use React\Http\Client\Client as HttpClient; use React\Http\Io\ClientConnectionManager; +use React\Http\Io\ClientRequestStream; use React\Http\Io\EmptyBodyStream; use React\Http\Io\ReadableBodyStream; use React\Http\Io\Sender; use React\Http\Message\Request; -use React\Promise; +use React\Promise\Promise; +use React\Socket\ConnectionInterface; +use React\Socket\ConnectorInterface; 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; /** @@ -23,19 +29,19 @@ class SenderTest extends TestCase */ public function setUpLoop() { - $this->loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $this->loop = $this->createMock(LoopInterface::class); } public function testCreateFromLoop() { $sender = Sender::createFromLoop($this->loop, null); - $this->assertInstanceOf('React\Http\Io\Sender', $sender); + $this->assertInstanceOf(Sender::class, $sender); } public function testSenderRejectsInvalidUri() { - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->never())->method('connect'); $sender = new Sender(new HttpClient(new ClientConnectionManager($connector, $this->loop))); @@ -49,13 +55,13 @@ public function testSenderRejectsInvalidUri() $exception = $e; }); - $this->assertInstanceOf('InvalidArgumentException', $exception); + $this->assertInstanceOf(\InvalidArgumentException::class, $exception); } public function testSenderConnectorRejection() { - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->willReturn(Promise\reject(new \RuntimeException('Rejected'))); + $connector = $this->createMock(ConnectorInterface::class); + $connector->expects($this->once())->method('connect')->willReturn(reject(new \RuntimeException('Rejected'))); $sender = new Sender(new HttpClient(new ClientConnectionManager($connector, $this->loop))); @@ -68,41 +74,41 @@ public function testSenderConnectorRejection() $exception = $e; }); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); } public function testSendPostWillAutomaticallySendContentLengthHeader() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return $request->getHeaderLine('Content-Length') === '5'; - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $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); } public function testSendPostWillAutomaticallySendContentLengthZeroHeaderForEmptyRequestBody() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return $request->getHeaderLine('Content-Length') === '0'; - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $sender = new Sender($client); - $request = new Request('POST', 'http://www.google.com/', array(), ''); + $request = new Request('POST', 'http://www.google.com/', [], ''); $sender->send($request); } public function testSendPostStreamWillAutomaticallySendTransferEncodingChunked() { - $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); + $outgoing = $this->createMock(ClientRequestStream::class); $outgoing->expects($this->once())->method('write')->with(""); - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return $request->getHeaderLine('Transfer-Encoding') === 'chunked'; }))->willReturn($outgoing); @@ -110,23 +116,23 @@ 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); } public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForWriteAndRespectRequestThrottling() { - $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); + $outgoing = $this->createMock(ClientRequestStream::class); $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 = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->willReturn($outgoing); $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'); @@ -135,18 +141,18 @@ public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForWriteAn public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForEnd() { - $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); + $outgoing = $this->createMock(ClientRequestStream::class); $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(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->willReturn($outgoing); $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(); @@ -154,49 +160,49 @@ public function testSendPostStreamWillAutomaticallyPipeChunkEncodeBodyForEnd() public function testSendPostStreamWillRejectWhenRequestBodyEmitsErrorEvent() { - $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); + $outgoing = $this->createMock(ClientRequestStream::class); $outgoing->expects($this->once())->method('isWritable')->willReturn(true); $outgoing->expects($this->once())->method('write')->with("")->willReturn(false); $outgoing->expects($this->never())->method('end'); $outgoing->expects($this->once())->method('close'); - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->willReturn($outgoing); $sender = new Sender($client); $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) { $exception = $e; }); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Request failed because request body reported an error', $exception->getMessage()); $this->assertSame($expected, $exception->getPrevious()); } public function testSendPostStreamWillRejectWhenRequestBodyClosesWithoutEnd() { - $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); + $outgoing = $this->createMock(ClientRequestStream::class); $outgoing->expects($this->once())->method('isWritable')->willReturn(true); $outgoing->expects($this->once())->method('write')->with("")->willReturn(false); $outgoing->expects($this->never())->method('end'); $outgoing->expects($this->once())->method('close'); - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->willReturn($outgoing); $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(); @@ -206,25 +212,25 @@ public function testSendPostStreamWillRejectWhenRequestBodyClosesWithoutEnd() $exception = $e; }); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Request failed because request body closed unexpectedly', $exception->getMessage()); } public function testSendPostStreamWillNotRejectWhenRequestBodyClosesAfterEnd() { - $outgoing = $this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock(); + $outgoing = $this->createMock(ClientRequestStream::class); $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'); - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->willReturn($outgoing); $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(); @@ -240,24 +246,24 @@ public function testSendPostStreamWillNotRejectWhenRequestBodyClosesAfterEnd() public function testSendPostStreamWithExplicitContentLengthWillSendHeaderAsIs() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return $request->getHeaderLine('Content-Length') === '100'; - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $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); } public function testSendGetWillNotPassContentLengthHeaderForEmptyRequestBody() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return !$request->hasHeader('Content-Length'); - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $sender = new Sender($client); @@ -267,25 +273,25 @@ public function testSendGetWillNotPassContentLengthHeaderForEmptyRequestBody() public function testSendGetWithEmptyBodyStreamWillNotPassContentLengthOrTransferEncodingHeader() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return !$request->hasHeader('Content-Length') && !$request->hasHeader('Transfer-Encoding'); - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $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); } public function testSendCustomMethodWillNotPassContentLengthHeaderForEmptyRequestBody() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return !$request->hasHeader('Content-Length'); - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $sender = new Sender($client); @@ -295,24 +301,24 @@ public function testSendCustomMethodWillNotPassContentLengthHeaderForEmptyReques public function testSendCustomMethodWithExplicitContentLengthZeroWillBePassedAsIs() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return $request->getHeaderLine('Content-Length') === '0'; - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $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); } /** @test */ public function getRequestWithUserAndPassShouldSendAGetRequestWithBasicAuthorizationHeader() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return $request->getHeaderLine('Authorization') === 'Basic am9objpkdW1teQ=='; - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $sender = new Sender($client); @@ -323,24 +329,24 @@ public function getRequestWithUserAndPassShouldSendAGetRequestWithBasicAuthoriza /** @test */ public function getRequestWithUserAndPassShouldSendAGetRequestWithGivenAuthorizationHeaderBasicAuthorizationHeader() { - $client = $this->getMockBuilder('React\Http\Client\Client')->disableOriginalConstructor()->getMock(); + $client = $this->createMock(HttpClient::class); $client->expects($this->once())->method('request')->with($this->callback(function (RequestInterface $request) { return $request->getHeaderLine('Authorization') === 'bearer abc123'; - }))->willReturn($this->getMockBuilder('React\Http\Io\ClientRequestStream')->disableOriginalConstructor()->getMock()); + }))->willReturn($this->createMock(ClientRequestStream::class)); $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(); }); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); + $connector = $this->createMock(ConnectorInterface::class); $connector->expects($this->once())->method('connect')->willReturn($promise); $sender = new Sender(new HttpClient(new ClientConnectionManager($connector, $this->loop))); @@ -355,16 +361,16 @@ public function testCancelRequestWillCancelConnector() $exception = $e; }); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); } public function testCancelRequestWillCloseConnection() { - $connection = $this->getMockBuilder('React\Socket\ConnectionInterface')->getMock(); + $connection = $this->createMock(ConnectionInterface::class); $connection->expects($this->once())->method('close'); - $connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock(); - $connector->expects($this->once())->method('connect')->willReturn(Promise\resolve($connection)); + $connector = $this->createMock(ConnectorInterface::class); + $connector->expects($this->once())->method('connect')->willReturn(resolve($connection)); $sender = new Sender(new HttpClient(new ClientConnectionManager($connector, $this->loop))); @@ -378,6 +384,6 @@ public function testCancelRequestWillCloseConnection() $exception = $e; }); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); } } diff --git a/tests/Io/StreamingServerTest.php b/tests/Io/StreamingServerTest.php index b4e3f2f8..a61d1425 100644 --- a/tests/Io/StreamingServerTest.php +++ b/tests/Io/StreamingServerTest.php @@ -4,14 +4,18 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\StreamInterface; use React\EventLoop\Loop; +use React\Http\Io\RequestHeaderParser; use React\Http\Io\StreamingServer; use React\Http\Message\Response; use React\Http\Message\ServerRequest; use React\Promise\Promise; +use React\Socket\Connection; use React\Stream\ThroughStream; use React\Tests\Http\SocketServerStub; use React\Tests\Http\TestCase; +use function React\Promise\resolve; class StreamingServerTest extends TestCase { @@ -34,10 +38,10 @@ public function setUpConnectionMockAndSocket() private function mockConnection(array $additionalMethods = null) { - $connection = $this->getMockBuilder('React\Socket\Connection') + $connection = $this->getMockBuilder(Connection::class) ->disableOriginalConstructor() ->setMethods(array_merge( - array( + [ 'write', 'end', 'close', @@ -48,8 +52,8 @@ private function mockConnection(array $additionalMethods = null) 'getRemoteAddress', 'getLocalAddress', 'pipe' - ), - (is_array($additionalMethods) ? $additionalMethods : array()) + ], + (is_array($additionalMethods) ? $additionalMethods : []) )) ->getMock(); @@ -64,11 +68,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,25 +80,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]); } - /** - * @requires PHP 5.4 - */ 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); } @@ -119,19 +120,19 @@ 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(); $this->assertSame(1, $i); - $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); + $this->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $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']); @@ -152,19 +153,19 @@ 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(); $this->assertSame(1, $i); - $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $requestAssertion); + $this->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $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']); @@ -178,12 +179,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('/', $requestAssertion->getRequestTarget()); $this->assertSame('/', $requestAssertion->getUri()->getPath()); @@ -200,12 +201,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('/', $requestAssertion->getRequestTarget()); $this->assertSame('/', $requestAssertion->getUri()->getPath()); @@ -222,12 +223,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('/', $requestAssertion->getRequestTarget()); $this->assertSame('/', $requestAssertion->getUri()->getPath()); @@ -244,12 +245,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('/', $requestAssertion->getRequestTarget()); $this->assertSame('/', $requestAssertion->getUri()->getPath()); @@ -265,10 +266,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() @@ -279,12 +280,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('OPTIONS', $requestAssertion->getMethod()); $this->assertSame('*', $requestAssertion->getRequestTarget()); $this->assertSame('', $requestAssertion->getUri()->getPath()); @@ -298,10 +299,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() @@ -312,12 +313,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); $this->assertSame('example.com:443', $requestAssertion->getRequestTarget()); $this->assertSame('', $requestAssertion->getUri()->getPath()); @@ -334,12 +335,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); $this->assertSame('example.com:443', $requestAssertion->getRequestTarget()); $this->assertSame('', $requestAssertion->getUri()->getPath()); @@ -356,12 +357,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); $this->assertSame('example.com:80', $requestAssertion->getRequestTarget()); $this->assertSame('', $requestAssertion->getUri()->getPath()); @@ -378,12 +379,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('CONNECT', $requestAssertion->getMethod()); $this->assertSame('example.com:80', $requestAssertion->getRequestTarget()); $this->assertSame('', $requestAssertion->getUri()->getPath()); @@ -398,10 +399,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() @@ -410,10 +411,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() @@ -430,12 +431,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('/test', $requestAssertion->getRequestTarget()); $this->assertEquals('http://127.0.0.1/test', $requestAssertion->getUri()); @@ -451,12 +452,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('http://example.com/test', $requestAssertion->getRequestTarget()); $this->assertEquals('http://example.com/test', $requestAssertion->getUri()); @@ -473,12 +474,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('GET', $requestAssertion->getMethod()); $this->assertSame('http://example.com/test', $requestAssertion->getRequestTarget()); $this->assertEquals('http://example.com/test', $requestAssertion->getUri()); @@ -492,10 +493,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() @@ -507,12 +508,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('OPTIONS', $requestAssertion->getMethod()); $this->assertSame('*', $requestAssertion->getRequestTarget()); $this->assertEquals('http://example.com', $requestAssertion->getUri()); @@ -529,12 +530,12 @@ 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->assertInstanceOf(ServerRequestInterface::class, $requestAssertion); $this->assertSame('OPTIONS', $requestAssertion->getMethod()); $this->assertSame('http://example.com', $requestAssertion->getRequestTarget()); $this->assertEquals('http://example.com', $requestAssertion->getUri()); @@ -551,7 +552,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"; @@ -559,7 +560,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() @@ -571,7 +572,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"; @@ -579,7 +580,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() @@ -591,10 +592,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() @@ -608,10 +609,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() @@ -625,10 +626,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() @@ -640,10 +641,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() @@ -655,7 +656,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"; @@ -663,7 +664,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() @@ -675,18 +676,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() @@ -700,21 +701,19 @@ public function testResponseContainsServerHeader() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("\r\nServer: ReactPHP/1\r\n", $buffer); } public function testResponsePendingPromiseWillNotSendAnything() @@ -730,19 +729,17 @@ public function testResponsePendingPromiseWillNotSendAnything() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); } @@ -760,19 +757,17 @@ public function testResponsePendingPromiseWillBeCancelledIfConnectionCloses() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); @@ -786,7 +781,7 @@ public function testResponseBodyStreamAlreadyClosedWillSendEmptyBodyChunkedEncod $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -796,19 +791,17 @@ public function testResponseBodyStreamAlreadyClosedWillSendEmptyBodyChunkedEncod $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); @@ -821,7 +814,7 @@ public function testResponseBodyStreamEndingWillSendEmptyBodyChunkedEncoded() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -831,19 +824,17 @@ public function testResponseBodyStreamEndingWillSendEmptyBodyChunkedEncoded() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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(); @@ -859,7 +850,7 @@ public function testResponseBodyStreamAlreadyClosedWillSendEmptyBodyPlainHttp10( $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -869,19 +860,17 @@ public function testResponseBodyStreamAlreadyClosedWillSendEmptyBodyPlainHttp10( $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); @@ -895,7 +884,7 @@ public function testResponseStreamWillBeClosedIfConnectionIsAlreadyClosed() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -905,18 +894,16 @@ public function testResponseStreamWillBeClosedIfConnectionIsAlreadyClosed() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); - $this->connection = $this->getMockBuilder('React\Socket\Connection') + $this->connection = $this->getMockBuilder(Connection::class) ->disableOriginalConstructor() ->setMethods( - array( + [ 'write', 'end', 'close', @@ -927,7 +914,7 @@ function ($data) use (&$buffer) { 'getRemoteAddress', 'getLocalAddress', 'pipe' - ) + ] ) ->getMock(); @@ -936,10 +923,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() @@ -950,16 +937,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'); } @@ -968,11 +955,11 @@ public function testResponseUpgradeInResponseCanBeUsedToAdvertisePossibleUpgrade $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array( + [ 'date' => '', 'server' => '', 'Upgrade' => 'demo' - ), + ], 'foo' ); }); @@ -982,19 +969,17 @@ public function testResponseUpgradeInResponseCanBeUsedToAdvertisePossibleUpgrade $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); } @@ -1004,10 +989,10 @@ public function testResponseUpgradeWishInRequestCanBeIgnoredByReturningNormalRes $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array( + [ 'date' => '', 'server' => '' - ), + ], 'foo' ); }); @@ -1017,19 +1002,17 @@ public function testResponseUpgradeWishInRequestCanBeIgnoredByReturningNormalRes $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); } @@ -1039,11 +1022,11 @@ public function testResponseUpgradeSwitchingProtocolIncludesConnectionUpgradeHea $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 101, - array( + [ 'date' => '', 'server' => '', 'Upgrade' => 'demo' - ), + ], 'foo' ); }); @@ -1055,19 +1038,17 @@ public function testResponseUpgradeSwitchingProtocolIncludesConnectionUpgradeHea $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); } @@ -1079,11 +1060,11 @@ public function testResponseUpgradeSwitchingProtocolWithStreamWillPipeDataToConn $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 101, - array( + [ 'date' => '', 'server' => '', 'Upgrade' => 'demo' - ), + ], $stream ); }); @@ -1093,19 +1074,17 @@ public function testResponseUpgradeSwitchingProtocolWithStreamWillPipeDataToConn $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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'); @@ -1120,7 +1099,7 @@ public function testResponseConnectMethodStreamWillPipeDataToConnection() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -1130,19 +1109,17 @@ public function testResponseConnectMethodStreamWillPipeDataToConnection() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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'); @@ -1158,18 +1135,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() @@ -1177,7 +1154,7 @@ public function testResponseContainsSameRequestProtocolVersionAndChunkedBodyForH $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], 'bye' ); }); @@ -1187,22 +1164,20 @@ public function testResponseContainsSameRequestProtocolVersionAndChunkedBodyForH $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("bye", $buffer); } public function testResponseContainsSameRequestProtocolVersionAndRawBodyForHttp10() @@ -1210,7 +1185,7 @@ public function testResponseContainsSameRequestProtocolVersionAndRawBodyForHttp1 $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], 'bye' ); }); @@ -1220,23 +1195,21 @@ public function testResponseContainsSameRequestProtocolVersionAndRawBodyForHttp1 $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("bye", $buffer); + $this->assertStringContainsString("HTTP/1.0 200 OK\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); + $this->assertStringContainsString("bye", $buffer); } public function testResponseContainsNoResponseBodyForHeadRequest() @@ -1244,7 +1217,7 @@ public function testResponseContainsNoResponseBodyForHeadRequest() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array(), + [], 'bye' ); }); @@ -1253,23 +1226,21 @@ public function testResponseContainsNoResponseBodyForHeadRequest() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertNotContainsString("bye", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("\r\nContent-Length: 3\r\n", $buffer); + $this->assertStringNotContainsString("bye", $buffer); } public function testResponseContainsNoResponseBodyForHeadRequestWithStreamingResponse() @@ -1280,7 +1251,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 ); }); @@ -1289,22 +1260,20 @@ public function testResponseContainsNoResponseBodyForHeadRequestWithStreamingRes $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("\r\nContent-Length: 3\r\n", $buffer); } public function testResponseContainsNoResponseBodyAndNoContentLengthForNoContentStatus() @@ -1312,7 +1281,7 @@ public function testResponseContainsNoResponseBodyAndNoContentLengthForNoContent $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 204, - array(), + [], 'bye' ); }); @@ -1321,23 +1290,21 @@ public function testResponseContainsNoResponseBodyAndNoContentLengthForNoContent $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertNotContainsString("bye", $buffer); + $this->assertStringContainsString("HTTP/1.1 204 No Content\r\n", $buffer); + $this->assertStringNotContainsString("\r\nContent-Length: 3\r\n", $buffer); + $this->assertStringNotContainsString("bye", $buffer); } public function testResponseContainsNoResponseBodyAndNoContentLengthForNoContentStatusResponseWithStreamingBody() @@ -1348,7 +1315,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 ); }); @@ -1357,22 +1324,20 @@ public function testResponseContainsNoResponseBodyAndNoContentLengthForNoContent $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 204 No Content\r\n", $buffer); + $this->assertStringNotContainsString("\r\nContent-Length: 3\r\n", $buffer); } public function testResponseContainsNoContentLengthHeaderForNotModifiedStatus() @@ -1380,7 +1345,7 @@ public function testResponseContainsNoContentLengthHeaderForNotModifiedStatus() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 304, - array(), + [], '' ); }); @@ -1389,22 +1354,20 @@ public function testResponseContainsNoContentLengthHeaderForNotModifiedStatus() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); + $this->assertStringNotContainsString("\r\nContent-Length: 0\r\n", $buffer); } public function testResponseContainsExplicitContentLengthHeaderForNotModifiedStatus() @@ -1412,7 +1375,7 @@ public function testResponseContainsExplicitContentLengthHeaderForNotModifiedSta $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 304, - array('Content-Length' => 3), + ['Content-Length' => 3], '' ); }); @@ -1421,22 +1384,20 @@ public function testResponseContainsExplicitContentLengthHeaderForNotModifiedSta $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); + $this->assertStringContainsString("\r\nContent-Length: 3\r\n", $buffer); } public function testResponseContainsExplicitContentLengthHeaderForHeadRequests() @@ -1444,7 +1405,7 @@ public function testResponseContainsExplicitContentLengthHeaderForHeadRequests() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array('Content-Length' => 3), + ['Content-Length' => 3], '' ); }); @@ -1453,22 +1414,20 @@ public function testResponseContainsExplicitContentLengthHeaderForHeadRequests() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("\r\nContent-Length: 3\r\n", $buffer); } public function testResponseContainsNoResponseBodyForNotModifiedStatus() @@ -1476,7 +1435,7 @@ public function testResponseContainsNoResponseBodyForNotModifiedStatus() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 304, - array(), + [], 'bye' ); }); @@ -1485,23 +1444,21 @@ public function testResponseContainsNoResponseBodyForNotModifiedStatus() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertNotContainsString("bye", $buffer); + $this->assertStringContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); + $this->assertStringContainsString("\r\nContent-Length: 3\r\n", $buffer); + $this->assertStringNotContainsString("bye", $buffer); } public function testResponseContainsNoResponseBodyForNotModifiedStatusWithStreamingBody() @@ -1512,7 +1469,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 ); }); @@ -1521,22 +1478,20 @@ public function testResponseContainsNoResponseBodyForNotModifiedStatusWithStream $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 304 Not Modified\r\n", $buffer); + $this->assertStringContainsString("\r\nContent-Length: 3\r\n", $buffer); } public function testRequestInvalidHttpProtocolVersionWillEmitErrorAndSendErrorResponse() @@ -1552,25 +1507,23 @@ public function testRequestInvalidHttpProtocolVersionWillEmitErrorAndSendErrorRe $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertInstanceOf(\InvalidArgumentException::class, $error); - $this->assertContainsString("HTTP/1.1 505 HTTP Version Not Supported\r\n", $buffer); - $this->assertContainsString("\r\n\r\n", $buffer); - $this->assertContainsString("Error 505: HTTP Version Not Supported", $buffer); + $this->assertStringContainsString("HTTP/1.1 505 HTTP Version Not Supported\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); + $this->assertStringContainsString("Error 505: HTTP Version Not Supported", $buffer); } public function testRequestOverflowWillEmitErrorAndSendErrorResponse() @@ -1586,25 +1539,23 @@ public function testRequestOverflowWillEmitErrorAndSendErrorResponse() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertInstanceOf(\OverflowException::class, $error); - $this->assertContainsString("HTTP/1.1 431 Request Header Fields Too Large\r\n", $buffer); - $this->assertContainsString("\r\n\r\nError 431: Request Header Fields Too Large", $buffer); + $this->assertStringContainsString("HTTP/1.1 431 Request Header Fields Too Large\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\nError 431: Request Header Fields Too Large", $buffer); } public function testRequestInvalidWillEmitErrorAndSendErrorResponse() @@ -1620,24 +1571,22 @@ public function testRequestInvalidWillEmitErrorAndSendErrorResponse() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertInstanceOf(\InvalidArgumentException::class, $error); - $this->assertContainsString("HTTP/1.1 400 Bad Request\r\n", $buffer); - $this->assertContainsString("\r\n\r\nError 400: Bad Request", $buffer); + $this->assertStringContainsString("HTTP/1.1 400 Bad Request\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\nError 400: Bad Request", $buffer); } public function testRequestContentLengthBodyDataWillEmitDataEventOnRequestStream() @@ -1655,7 +1604,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"; @@ -1664,7 +1613,7 @@ public function testRequestContentLengthBodyDataWillEmitDataEventOnRequestStream $data .= "\r\n"; $data .= "hello"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestChunkedTransferEncodingRequestWillEmitDecodedDataEventOnRequestStream() @@ -1684,7 +1633,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"; @@ -1694,7 +1643,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')); } @@ -1714,7 +1663,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"; @@ -1725,7 +1674,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() @@ -1743,7 +1692,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"; @@ -1752,7 +1701,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() @@ -1772,7 +1721,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"; @@ -1782,7 +1731,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')); } @@ -1801,7 +1750,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"; @@ -1810,7 +1759,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() @@ -1826,11 +1775,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"; @@ -1840,7 +1789,7 @@ public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditiona $data .= "hello"; $data .= "world"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestContentLengthWillEmitDataEventAndEndEventAndAdditionalDataWillBeIgnoredSplitted() @@ -1859,7 +1808,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"; @@ -1868,11 +1817,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() @@ -1891,7 +1840,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"; @@ -1899,7 +1848,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() @@ -1917,7 +1866,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"; @@ -1926,7 +1875,7 @@ public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIg $data .= "\r\n"; $data .= "hello"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestZeroContentLengthWillEmitEndAndAdditionalDataWillBeIgnoredSplitted() @@ -1944,7 +1893,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"; @@ -1952,25 +1901,25 @@ 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() { - $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf('Exception')); + $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf(\Exception::class)); $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"; @@ -1981,12 +1930,12 @@ public function testRequestInvalidChunkHeaderTooLongWillEmitErrorOnRequestStream $data .= 'a'; } - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); } public function testRequestInvalidChunkBodyTooLongWillEmitErrorOnRequestStream() { - $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf('Exception')); + $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf(\Exception::class)); $server = new StreamingServer(Loop::get(), function ($request) use ($errorEvent){ $request->getBody()->on('error', $errorEvent); }); @@ -1994,7 +1943,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"; @@ -2003,12 +1952,12 @@ 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() { - $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf('Exception')); + $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf(\Exception::class)); $server = new StreamingServer(Loop::get(), function ($request) use ($errorEvent){ $request->getBody()->on('error', $errorEvent); }); @@ -2016,7 +1965,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"; @@ -2025,13 +1974,13 @@ 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'); } public function testRequestInvalidChunkHeaderWillEmitErrorOnRequestStream() { - $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf('Exception')); + $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf(\Exception::class)); $server = new StreamingServer(Loop::get(), function ($request) use ($errorEvent){ $request->getBody()->on('error', $errorEvent); }); @@ -2039,7 +1988,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"; @@ -2048,12 +1997,12 @@ 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() { - $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf('Exception')); + $errorEvent = $this->expectCallableOnceWith($this->isInstanceOf(\Exception::class)); $server = new StreamingServer(Loop::get(), function ($request) use ($errorEvent){ $request->getBody()->on('error', $errorEvent); }); @@ -2061,7 +2010,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"; @@ -2070,7 +2019,7 @@ public function testRequestUnexpectedEndOfRequestWithContentLengthWillEmitErrorO $data .= "\r\n"; $data .= "incomplete"; - $this->connection->emit('data', array($data)); + $this->connection->emit('data', [$data]); $this->connection->emit('end'); } @@ -2091,11 +2040,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() @@ -2113,12 +2062,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() @@ -2127,7 +2076,7 @@ public function testResponseWithBodyStreamWillUseChunkedTransferEncodingByDefaul $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array(), + [], $stream ); }); @@ -2136,24 +2085,22 @@ public function testResponseWithBodyStreamWillUseChunkedTransferEncodingByDefaul $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("Transfer-Encoding: chunked", $buffer); + $this->assertStringContainsString("hello", $buffer); } public function testResponseWithBodyStringWillOverwriteExplicitContentLengthAndTransferEncoding() @@ -2161,10 +2108,10 @@ public function testResponseWithBodyStringWillOverwriteExplicitContentLengthAndT $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array( + [ 'Content-Length' => 1000, 'Transfer-Encoding' => 'chunked' - ), + ], 'hello' ); }); @@ -2173,36 +2120,34 @@ public function testResponseWithBodyStringWillOverwriteExplicitContentLengthAndT $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("hello", $buffer); + $this->assertStringNotContainsString("Transfer-Encoding: chunked", $buffer); + $this->assertStringContainsString("Content-Length: 5", $buffer); + $this->assertStringContainsString("hello", $buffer); } public function testResponseContainsResponseBodyWithTransferEncodingChunkedForBodyWithUnknownSize() { - $body = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(); + $body = $this->createMock(StreamInterface::class); $body->expects($this->once())->method('getSize')->willReturn(null); $body->expects($this->once())->method('__toString')->willReturn('body'); $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($body) { return new Response( 200, - array(), + [], $body ); }); @@ -2211,35 +2156,33 @@ public function testResponseContainsResponseBodyWithTransferEncodingChunkedForBo $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("body", $buffer); + $this->assertStringContainsString("Transfer-Encoding: chunked", $buffer); + $this->assertStringNotContainsString("Content-Length:", $buffer); + $this->assertStringContainsString("body", $buffer); } public function testResponseContainsResponseBodyWithPlainBodyWithUnknownSizeForLegacyHttp10() { - $body = $this->getMockBuilder('Psr\Http\Message\StreamInterface')->getMock(); + $body = $this->createMock(StreamInterface::class); $body->expects($this->once())->method('getSize')->willReturn(null); $body->expects($this->once())->method('__toString')->willReturn('body'); $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($body) { return new Response( 200, - array(), + [], $body ); }); @@ -2248,23 +2191,21 @@ public function testResponseContainsResponseBodyWithPlainBodyWithUnknownSizeForL $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("body", $buffer); + $this->assertStringNotContainsString("Transfer-Encoding: chunked", $buffer); + $this->assertStringNotContainsString("Content-Length:", $buffer); + $this->assertStringContainsString("body", $buffer); } public function testResponseWithCustomTransferEncodingWillBeIgnoredAndUseChunkedTransferEncodingInstead() @@ -2273,9 +2214,9 @@ public function testResponseWithCustomTransferEncodingWillBeIgnoredAndUseChunked $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($stream) { return new Response( 200, - array( + [ 'Transfer-Encoding' => 'custom' - ), + ], $stream ); }); @@ -2284,25 +2225,23 @@ public function testResponseWithCustomTransferEncodingWillBeIgnoredAndUseChunked $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("5\r\nhello\r\n", $buffer); + $this->assertStringContainsString('Transfer-Encoding: chunked', $buffer); + $this->assertStringNotContainsString('Transfer-Encoding: custom', $buffer); + $this->assertStringContainsString("5\r\nhello\r\n", $buffer); } public function testResponseWithoutExplicitDateHeaderWillAddCurrentDateFromClock() @@ -2323,24 +2262,22 @@ public function testResponseWithoutExplicitDateHeaderWillAddCurrentDateFromClock $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("\r\n\r\n", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("Date: Thu, 19 May 2022 14:54:51 GMT\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); } public function testResponseWithCustomDateHeaderOverwritesDefault() @@ -2348,7 +2285,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"] ); }); @@ -2356,24 +2293,22 @@ public function testResponseWithCustomDateHeaderOverwritesDefault() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("\r\n\r\n", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("Date: Tue, 15 Nov 1994 08:12:31 GMT\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); } public function testResponseWithEmptyDateHeaderRemovesDateHeader() @@ -2381,7 +2316,7 @@ public function testResponseWithEmptyDateHeaderRemovesDateHeader() $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array('Date' => '') + ['Date' => ''] ); }); @@ -2389,24 +2324,22 @@ public function testResponseWithEmptyDateHeaderRemovesDateHeader() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("\r\n\r\n", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringNotContainsString("Date:", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); } public function testResponseCanContainMultipleCookieHeaders() @@ -2414,14 +2347,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' => '' - ) + ] ); }); @@ -2429,20 +2362,18 @@ public function testResponseCanContainMultipleCookieHeaders() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); } @@ -2457,16 +2388,14 @@ public function testReponseWithExpectContinueRequestContainsContinueWithLaterRes $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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"; @@ -2474,9 +2403,9 @@ function ($data) use (&$buffer) { $data .= "Expect: 100-continue\r\n"; $data .= "\r\n"; - $this->connection->emit('data', array($data)); - $this->assertContainsString("HTTP/1.1 100 Continue\r\n", $buffer); - $this->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->connection->emit('data', [$data]); + $this->assertStringContainsString("HTTP/1.1 100 Continue\r\n", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); } public function testResponseWithExpectContinueRequestWontSendContinueForHttp10() @@ -2489,29 +2418,27 @@ public function testResponseWithExpectContinueRequestWontSendContinueForHttp10() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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->assertContainsString("HTTP/1.0 200 OK\r\n", $buffer); - $this->assertNotContainsString("HTTP/1.1 100 Continue\r\n\r\n", $buffer); + $this->connection->emit('data', [$data]); + $this->assertStringContainsString("HTTP/1.0 200 OK\r\n", $buffer); + $this->assertStringNotContainsString("HTTP/1.1 100 Continue\r\n\r\n", $buffer); } public function testInvalidCallbackFunctionLeadsToException() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new StreamingServer(Loop::get(), 'invalid'); } @@ -2522,7 +2449,7 @@ public function testResponseBodyStreamWillStreamDataWithChunkedTransferEncoding( $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) use ($input) { return new Response( 200, - array(), + [], $input ); }); @@ -2531,27 +2458,25 @@ public function testResponseBodyStreamWillStreamDataWithChunkedTransferEncoding( $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("1\r\n1\r\n", $buffer); - $this->assertContainsString("2\r\n23\r\n", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); + $this->assertStringContainsString("1\r\n1\r\n", $buffer); + $this->assertStringContainsString("2\r\n23\r\n", $buffer); } public function testResponseBodyStreamWithContentLengthWillStreamTillLengthWithoutTransferEncoding() @@ -2561,7 +2486,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 ); }); @@ -2570,56 +2495,52 @@ public function testResponseBodyStreamWithContentLengthWillStreamTillLengthWitho $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertNotContainsString("Transfer-Encoding", $buffer); - $this->assertContainsString("\r\n\r\n", $buffer); - $this->assertContainsString("hello", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("Content-Length: 5\r\n", $buffer); + $this->assertStringNotContainsString("Transfer-Encoding", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); + $this->assertStringContainsString("hello", $buffer); } public function testResponseWithResponsePromise() { $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { - return \React\Promise\resolve(new Response()); + return resolve(new Response()); }); $buffer = ''; $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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->assertContainsString("HTTP/1.1 200 OK\r\n", $buffer); - $this->assertContainsString("\r\n\r\n", $buffer); + $this->connection->emit('data', [$data]); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("\r\n\r\n", $buffer); } public function testResponseReturnInvalidTypeWillResultInError() @@ -2637,51 +2558,47 @@ public function testResponseReturnInvalidTypeWillResultInError() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); + $this->assertInstanceOf(\RuntimeException::class, $exception); } public function testResponseResolveWrongTypeInPromiseWillResultInError() { $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { - return \React\Promise\resolve("invalid"); + return resolve("invalid"); }); $buffer = ''; $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); } public function testResponseRejectedPromiseWillResultInErrorMessage() @@ -2697,22 +2614,20 @@ public function testResponseRejectedPromiseWillResultInErrorMessage() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); } public function testResponseExceptionInCallbackWillResultInErrorMessage() @@ -2728,22 +2643,20 @@ public function testResponseExceptionInCallbackWillResultInErrorMessage() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); } public function testResponseWithContentLengthHeaderForStringBodyOverwritesTransferEncoding() @@ -2751,7 +2664,7 @@ public function testResponseWithContentLengthHeaderForStringBodyOverwritesTransf $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { return new Response( 200, - array('Transfer-Encoding' => 'chunked'), + ['Transfer-Encoding' => 'chunked'], 'hello' ); }); @@ -2760,26 +2673,24 @@ public function testResponseWithContentLengthHeaderForStringBodyOverwritesTransf $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); - $this->assertContainsString("hello", $buffer); + $this->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); + $this->assertStringContainsString("Content-Length: 5\r\n", $buffer); + $this->assertStringContainsString("hello", $buffer); - $this->assertNotContainsString("Transfer-Encoding", $buffer); + $this->assertStringNotContainsString("Transfer-Encoding", $buffer); } public function testResponseWillBeHandled() @@ -2792,22 +2703,20 @@ public function testResponseWillBeHandled() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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->assertStringContainsString("HTTP/1.1 200 OK\r\n", $buffer); } public function testResponseExceptionThrowInCallBackFunctionWillResultInErrorMessage() @@ -2825,29 +2734,24 @@ public function testResponseExceptionThrowInCallBackFunctionWillResultInErrorMes $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertInstanceOf(\RuntimeException::class, $exception); + $this->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); $this->assertEquals('hello', $exception->getPrevious()->getMessage()); } - /** - * @requires PHP 7 - */ public function testResponseThrowableThrowInCallBackFunctionWillResultInErrorMessage() { $server = new StreamingServer(Loop::get(), function (ServerRequestInterface $request) { @@ -2863,21 +2767,19 @@ public function testResponseThrowableThrowInCallBackFunctionWillResultInErrorMes $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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. ' . @@ -2886,8 +2788,8 @@ function ($data) use (&$buffer) { ); } - $this->assertInstanceOf('RuntimeException', $exception); - $this->assertContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); + $this->assertInstanceOf(\RuntimeException::class, $exception); + $this->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); $this->assertEquals('hello', $exception->getPrevious()->getMessage()); } @@ -2908,70 +2810,66 @@ public function testResponseRejectOfNonExceptionWillResultInErrorMessage() $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); + $this->assertInstanceOf(\RuntimeException::class, $exception); } public static function provideInvalidResponse() { - $response = new Response(200, array(), '', '1.1', 'OK'); - - return array( - array( - $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') - ) - ); + $response = new Response(200, [], '', '1.1', 'OK'); + + yield [ + $response->withStatus(99, 'OK') + ]; + yield [ + $response->withStatus(1000, 'OK') + ]; + yield [ + $response->withStatus(200, "Invald\r\nReason: Yes") + ]; + yield [ + $response->withHeader('Invalid', "Yes\r\n") + ]; + yield [ + $response->withHeader('Invalid', "Yes\n") + ]; + yield [ + $response->withHeader('Invalid', "Yes\r") + ]; + yield [ + $response->withHeader("Inva\r\nlid", 'Yes') + ]; + yield [ + $response->withHeader("Inva\nlid", 'Yes') + ]; + yield [ + $response->withHeader("Inva\rlid", 'Yes') + ]; + yield [ + $response->withHeader('Inva Lid', 'Yes') + ]; + yield [ + $response->withHeader('Inva:Lid', 'Yes') + ]; + yield [ + $response->withHeader('Invalid', "Val\0ue") + ]; + yield [ + $response->withHeader("Inva\0lid", 'Yes') + ]; } /** @@ -2993,23 +2891,21 @@ public function testInvalidResponseObjectWillResultInErrorMessage(ResponseInterf $this->connection ->expects($this->any()) ->method('write') - ->will( - $this->returnCallback( - function ($data) use (&$buffer) { - $buffer .= $data; - } - ) + ->willReturnCallback( + function ($data) use (&$buffer) { + $buffer .= $data; + } ); $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); + $this->assertStringContainsString("HTTP/1.1 500 Internal Server Error\r\n", $buffer); + $this->assertInstanceOf(\InvalidArgumentException::class, $exception); } public function testRequestServerRequestParams() @@ -3030,11 +2926,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(); @@ -3054,11 +2950,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(); @@ -3074,7 +2970,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"; @@ -3082,9 +2978,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() @@ -3095,7 +2991,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"; @@ -3104,8 +3000,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() @@ -3116,7 +3012,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"; @@ -3124,8 +3020,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() @@ -3136,7 +3032,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"; @@ -3144,15 +3040,15 @@ 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() { $server = new StreamingServer(Loop::get(), $this->expectCallableNever()); - $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->once())->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3160,16 +3056,16 @@ 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)); - $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->once())->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3177,7 +3073,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'); @@ -3188,11 +3084,11 @@ 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)); - $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->once())->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3200,7 +3096,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'); @@ -3214,10 +3110,10 @@ 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(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->once())->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3225,7 +3121,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'); @@ -3242,7 +3138,7 @@ public function testNewConnectionWillInvokeParserTwiceAfterInvokingRequestHandle return new Response(); }); - $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->exactly(2))->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3250,7 +3146,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'); @@ -3261,13 +3157,13 @@ 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(); }); - $parser = $this->getMockBuilder('React\Http\Io\RequestHeaderParser')->disableOriginalConstructor()->getMock(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->exactly(2))->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3275,7 +3171,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'); @@ -3290,10 +3186,10 @@ 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(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->once())->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3301,7 +3197,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'); @@ -3316,10 +3212,10 @@ 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(); + $parser = $this->createMock(RequestHeaderParser::class); $parser->expects($this->exactly(2))->method('handle'); $ref = new \ReflectionProperty($server, 'parser'); @@ -3327,7 +3223,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'); @@ -3342,16 +3238,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..3833cfd3 100644 --- a/tests/Io/TransactionTest.php +++ b/tests/Io/TransactionTest.php @@ -5,28 +5,36 @@ use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +use React\EventLoop\LoopInterface; +use React\EventLoop\TimerInterface; use React\Http\Io\ReadableBodyStream; +use React\Http\Io\Sender; use React\Http\Io\Transaction; use React\Http\Message\Request; 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\Promise\PromiseInterface; +use React\Stream\ReadableStreamInterface; 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 { public function testWithOptionsReturnsNewInstanceWithChangedOption() { $sender = $this->makeSenderMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $transaction = new Transaction($sender, $loop); - $new = $transaction->withOptions(array('followRedirects' => false)); + $new = $transaction->withOptions(['followRedirects' => false]); - $this->assertInstanceOf('React\Http\Io\Transaction', $new); + $this->assertInstanceOf(Transaction::class, $new); $this->assertNotSame($transaction, $new); $ref = new \ReflectionProperty($new, 'followRedirects'); @@ -38,10 +46,10 @@ public function testWithOptionsReturnsNewInstanceWithChangedOption() public function testWithOptionsDoesNotChangeOriginalInstance() { $sender = $this->makeSenderMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $transaction = new Transaction($sender, $loop); - $transaction->withOptions(array('followRedirects' => false)); + $transaction->withOptions(['followRedirects' => false]); $ref = new \ReflectionProperty($transaction, 'followRedirects'); $ref->setAccessible(true); @@ -52,11 +60,11 @@ public function testWithOptionsDoesNotChangeOriginalInstance() public function testWithOptionsNullValueReturnsNewInstanceWithDefaultOption() { $sender = $this->makeSenderMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $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); @@ -66,34 +74,34 @@ public function testWithOptionsNullValueReturnsNewInstanceWithDefaultOption() public function testTimeoutExplicitOptionWillStartTimeoutTimer() { - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with(2, $this->anything())->willReturn($timer); $loop->expects($this->never())->method('cancelTimer'); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); - $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); + $this->assertInstanceOf(PromiseInterface::class, $promise); } public function testTimeoutImplicitFromIniWillStartTimeoutTimer() { - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with(2, $this->anything())->willReturn($timer); $loop->expects($this->never())->method('cancelTimer'); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); - $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($request)->willReturn(new Promise(function () { })); $transaction = new Transaction($sender, $loop); @@ -102,27 +110,27 @@ public function testTimeoutImplicitFromIniWillStartTimeoutTimer() $promise = $transaction->send($request); ini_set('default_socket_timeout', $old); - $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + $this->assertInstanceOf(PromiseInterface::class, $promise); } public function testTimeoutExplicitOptionWillRejectWhenTimerFires() { $timeout = null; - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with(2, $this->callback(function ($cb) use (&$timeout) { $timeout = $cb; return true; }))->willReturn($timer); $loop->expects($this->never())->method('cancelTimer'); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); - $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); @@ -133,194 +141,194 @@ public function testTimeoutExplicitOptionWillRejectWhenTimerFires() $exception = $e; }); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Request timed out after 2 seconds', $exception->getMessage()); } public function testTimeoutExplicitOptionWillNotStartTimeoutWhenSenderResolvesImmediately() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->never())->method('addTimer'); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), ''); + $request = $this->createMock(RequestInterface::class); + $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); + $this->assertInstanceOf(PromiseInterface::class, $promise); $promise->then($this->expectCallableOnceWith($response)); } public function testTimeoutExplicitOptionWillCancelTimeoutTimerWhenSenderResolvesLaterOn() { - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->willReturn($timer); $loop->expects($this->once())->method('cancelTimer')->with($timer); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), ''); + $request = $this->createMock(RequestInterface::class); + $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()); + $sender = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); - $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + $this->assertInstanceOf(PromiseInterface::class, $promise); $promise->then($this->expectCallableOnceWith($response)); } public function testTimeoutExplicitOptionWillNotStartTimeoutWhenSenderRejectsImmediately() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->never())->method('addTimer'); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); + $this->assertInstanceOf(PromiseInterface::class, $promise); $promise->then(null, $this->expectCallableOnceWith($exception)); } public function testTimeoutExplicitOptionWillCancelTimeoutTimerWhenSenderRejectsLaterOn() { - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->willReturn($timer); $loop->expects($this->once())->method('cancelTimer')->with($timer); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); $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()); + $sender = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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(); $deferred->reject($exception); - $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + $this->assertInstanceOf(PromiseInterface::class, $promise); $promise->then(null, $this->expectCallableOnceWith($exception)); } public function testTimeoutExplicitNegativeWillNotStartTimeoutTimer() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->never())->method('addTimer'); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); - $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); + $this->assertInstanceOf(PromiseInterface::class, $promise); } public function testTimeoutExplicitOptionWillNotStartTimeoutTimerWhenRequestBodyIsStreaming() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); + $this->assertInstanceOf(PromiseInterface::class, $promise); } public function testTimeoutExplicitOptionWillStartTimeoutTimerWhenStreamingRequestBodyIsAlreadyClosed() { - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with(2, $this->anything())->willReturn($timer); $loop->expects($this->never())->method('cancelTimer'); $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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); + $this->assertInstanceOf(PromiseInterface::class, $promise); } public function testTimeoutExplicitOptionWillStartTimeoutTimerWhenStreamingRequestBodyClosesWhileSenderIsStillPending() { - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with(2, $this->anything())->willReturn($timer); $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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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(); - $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + $this->assertInstanceOf(PromiseInterface::class, $promise); } public function testTimeoutExplicitOptionWillNotStartTimeoutTimerWhenStreamingRequestBodyClosesAfterSenderRejects() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $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()); + $sender = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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')); $stream->close(); - $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + $this->assertInstanceOf(PromiseInterface::class, $promise); $promise->then(null, $this->expectCallableOnce()); // avoid reporting unhandled rejection } @@ -328,8 +336,8 @@ public function testTimeoutExplicitOptionWillNotStartTimeoutTimerWhenStreamingRe public function testTimeoutExplicitOptionWillRejectWhenTimerFiresAfterStreamingRequestBodyCloses() { $timeout = null; - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->with(2, $this->callback(function ($cb) use (&$timeout) { $timeout = $cb; return true; @@ -337,13 +345,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 = $this->createMock(Sender::class); + $sender->expects($this->once())->method('send')->with($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(); @@ -356,22 +364,22 @@ public function testTimeoutExplicitOptionWillRejectWhenTimerFiresAfterStreamingR $exception = $e; }); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Request timed out after 2 seconds', $exception->getMessage()); } public function testReceivingErrorResponseWillRejectWithResponseException() { - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); $response = new Response(404); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); // 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($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 +396,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)); + $request = $this->createMock(RequestInterface::class); + $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($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()); @@ -413,13 +421,13 @@ public function testReceivingStreamingBodyWithContentLengthExceedingMaximumRespo $stream = new ThroughStream(); $stream->on('close', $this->expectCallableOnce()); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); - $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($request)->willReturn(resolve($response)); $transaction = new Transaction($sender, Loop::get()); @@ -433,7 +441,7 @@ public function testReceivingStreamingBodyWithContentLengthExceedingMaximumRespo $this->assertFalse($stream->isWritable()); assert($exception instanceof \OverflowException); - $this->assertInstanceOf('OverflowException', $exception); + $this->assertInstanceOf(\OverflowException::class, $exception); $this->assertEquals('Response body size of 100000000 bytes exceeds maximum of 16777216 bytes', $exception->getMessage()); $this->assertEquals(defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90, $exception->getCode()); $this->assertNull($exception->getPrevious()); @@ -444,16 +452,16 @@ public function testReceivingStreamingBodyWithContentsExceedingMaximumResponseBu $stream = new ThroughStream(); $stream->on('close', $this->expectCallableOnce()); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); + $request = $this->createMock(RequestInterface::class); - $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($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; @@ -466,7 +474,7 @@ public function testReceivingStreamingBodyWithContentsExceedingMaximumResponseBu $this->assertFalse($stream->isWritable()); assert($exception instanceof \OverflowException); - $this->assertInstanceOf('OverflowException', $exception); + $this->assertInstanceOf(\OverflowException::class, $exception); $this->assertEquals('Response body size exceeds maximum of 10 bytes', $exception->getMessage()); $this->assertEquals(defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90, $exception->getCode()); $this->assertNull($exception->getPrevious()); @@ -478,12 +486,12 @@ public function testReceivingStreamingBodyWillRejectWhenStreamEmitsError() throw new \UnexpectedValueException('Unexpected ' . $data, 42); }); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($stream)); + $request = $this->createMock(RequestInterface::class); + $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($request)->willReturn(resolve($response)); $transaction = new Transaction($sender, Loop::get()); $promise = $transaction->send($request); @@ -498,25 +506,25 @@ public function testReceivingStreamingBodyWillRejectWhenStreamEmitsError() $this->assertFalse($stream->isWritable()); assert($exception instanceof \RuntimeException); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Error while buffering response body: Unexpected Foo', $exception->getMessage()); $this->assertEquals(42, $exception->getCode()); - $this->assertInstanceOf('UnexpectedValueException', $exception->getPrevious()); + $this->assertInstanceOf(\UnexpectedValueException::class, $exception->getPrevious()); } public function testCancelBufferingResponseWillCloseStreamAndReject() { - $stream = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $stream = $this->createMock(ReadableStreamInterface::class); $stream->expects($this->any())->method('isReadable')->willReturn(true); $stream->expects($this->once())->method('close'); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($stream)); + $request = $this->createMock(RequestInterface::class); + $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(); $sender = $this->makeSenderMock(); - $sender->expects($this->once())->method('send')->with($this->equalTo($request))->willReturn($deferred->promise()); + $sender->expects($this->once())->method('send')->with($request)->willReturn($deferred->promise()); $transaction = new Transaction($sender, Loop::get()); $promise = $transaction->send($request); @@ -530,7 +538,7 @@ public function testCancelBufferingResponseWillCloseStreamAndReject() }); assert($exception instanceof \RuntimeException); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Cancelled buffering response body', $exception->getMessage()); $this->assertEquals(0, $exception->getCode()); $this->assertNull($exception->getPrevious()); @@ -538,17 +546,17 @@ public function testCancelBufferingResponseWillCloseStreamAndReject() public function testReceivingStreamingBodyWillResolveWithStreamingResponseIfStreamingIsEnabled() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $request = $this->getMockBuilder('Psr\Http\Message\RequestInterface')->getMock(); - $response = new Response(200, array(), new ReadableBodyStream($this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock())); + $request = $this->createMock(RequestInterface::class); + $response = new Response(200, [], new ReadableBodyStream($this->createMock(ReadableStreamInterface::class))); // 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($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; @@ -563,16 +571,16 @@ public function testReceivingStreamingBodyWillResolveWithStreamingResponseIfStre public function testResponseCode304WithoutLocationWillResolveWithResponseAsIs() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); // 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)); @@ -580,20 +588,20 @@ public function testResponseCode304WithoutLocationWillResolveWithResponseAsIs() public function testCustomRedirectResponseCode333WillFollowLocationHeaderAndSendRedirectedRequest() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); // 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); @@ -602,29 +610,28 @@ public function testCustomRedirectResponseCode333WillFollowLocationHeaderAndSend public function testFollowingRedirectWithSpecifiedHeaders() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $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); @@ -633,29 +640,28 @@ public function testFollowingRedirectWithSpecifiedHeaders() public function testRemovingAuthorizationHeaderWhenChangingHostnamesDuringRedirect() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $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); @@ -664,29 +670,28 @@ public function testRemovingAuthorizationHeaderWhenChangingHostnamesDuringRedire public function testAuthorizationHeaderIsForwardedWhenRedirectingToSameDomain() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $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); @@ -695,29 +700,28 @@ public function testAuthorizationHeaderIsForwardedWhenRedirectingToSameDomain() public function testAuthorizationHeaderIsForwardedWhenLocationContainsAuthentication() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $request = new Request('GET', 'http://example.com'); $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://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); @@ -726,34 +730,33 @@ public function testAuthorizationHeaderIsForwardedWhenLocationContainsAuthentica public function testSomeRequestHeadersShouldBeRemovedWhenRedirecting() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $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); @@ -762,35 +765,34 @@ public function testSomeRequestHeadersShouldBeRemovedWhenRedirecting() public function testRequestMethodShouldBeChangedWhenRedirectingWithSeeOther() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $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); @@ -799,42 +801,41 @@ public function testRequestMethodShouldBeChangedWhenRedirectingWithSeeOther() public function testRequestMethodAndBodyShouldNotBeChangedWhenRedirectingWith307Or308() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $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); @@ -843,12 +844,12 @@ public function testRequestMethodAndBodyShouldNotBeChangedWhenRedirectingWith307 public function testRedirectingStreamingBodyWith307Or308ShouldThrowCantRedirectStreamException() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); - $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 +857,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); @@ -878,12 +879,12 @@ public function testRedirectingStreamingBodyWith307Or308ShouldThrowCantRedirectS public function testCancelTransactionWillCancelRequest() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $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); @@ -896,21 +897,21 @@ public function testCancelTransactionWillCancelRequest() public function testCancelTransactionWillCancelTimeoutTimer() { - $timer = $this->getMockBuilder('React\EventLoop\TimerInterface')->getMock(); - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $timer = $this->createMock(TimerInterface::class); + $loop = $this->createMock(LoopInterface::class); $loop->expects($this->once())->method('addTimer')->willReturn($timer); $loop->expects($this->once())->method('cancelTimer')->with($timer); $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(); @@ -918,22 +919,22 @@ public function testCancelTransactionWillCancelTimeoutTimer() public function testCancelTransactionWillCancelRedirectedRequest() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $request = new Request('GET', 'http://example.com'); $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 ); @@ -945,7 +946,7 @@ public function testCancelTransactionWillCancelRedirectedRequest() public function testCancelTransactionWillCancelRedirectedRequestAgain() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $request = new Request('GET', 'http://example.com'); $sender = $this->makeSenderMock(); @@ -953,12 +954,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,14 +969,14 @@ 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(); } public function testCancelTransactionWillCloseBufferingStream() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $request = new Request('GET', 'http://example.com'); $sender = $this->makeSenderMock(); @@ -990,7 +991,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(); @@ -998,7 +999,7 @@ public function testCancelTransactionWillCloseBufferingStream() public function testCancelTransactionWillCloseBufferingStreamAgain() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $request = new Request('GET', 'http://example.com'); $sender = $this->makeSenderMock(); @@ -1013,28 +1014,28 @@ 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(); } public function testCancelTransactionShouldCancelSendingPromise() { - $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock(); + $loop = $this->createMock(LoopInterface::class); $request = new Request('GET', 'http://example.com'); $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 ); @@ -1049,6 +1050,6 @@ public function testCancelTransactionShouldCancelSendingPromise() */ private function makeSenderMock() { - return $this->getMockBuilder('React\Http\Io\Sender')->disableOriginalConstructor()->getMock(); + return $this->createMock(Sender::class); } } diff --git a/tests/Io/UploadedFileTest.php b/tests/Io/UploadedFileTest.php index 4e9c0dd5..529b75af 100644 --- a/tests/Io/UploadedFileTest.php +++ b/tests/Io/UploadedFileTest.php @@ -8,14 +8,12 @@ class UploadedFileTest extends TestCase { - public function failtyErrorProvider() + public static function failtyErrorProvider() { - return array( - array('a'), - array(null), - array(-1), - array(9), - ); + yield ['a']; + yield [null]; + yield [-1]; + yield [9]; } /** @@ -25,7 +23,8 @@ public function testFailtyError($error) { $stream = new BufferedBody(''); - $this->setExpectedException('InvalidArgumentException', 'Invalid error code, must be an UPLOAD_ERR_* constant'); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid error code, must be an UPLOAD_ERR_* constant'); new UploadedFile($stream, 0, $error, 'foo.bar', 'foo/bar'); } @@ -34,7 +33,8 @@ public function testNoMoveFile() $stream = new BufferedBody(''); $uploadedFile = new UploadedFile($stream, 0, UPLOAD_ERR_OK, 'foo.bar', 'foo/bar'); - $this->setExpectedException('RuntimeException', 'Not implemented'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Not implemented'); $uploadedFile->moveTo('bar.foo'); } @@ -54,7 +54,8 @@ public function testGetStreamOnFailedUpload() $stream = new BufferedBody(''); $uploadedFile = new UploadedFile($stream, 0, UPLOAD_ERR_NO_FILE, 'foo.bar', 'foo/bar'); - $this->setExpectedException('RuntimeException', 'Cannot retrieve stream due to upload error'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Cannot retrieve stream due to upload error'); $uploadedFile->getStream(); } } diff --git a/tests/Message/RequestTest.php b/tests/Message/RequestTest.php index 29baf8a7..148536a0 100644 --- a/tests/Message/RequestTest.php +++ b/tests/Message/RequestTest.php @@ -2,8 +2,10 @@ namespace React\Tests\Http\Message; +use Psr\Http\Message\StreamInterface; use React\Http\Io\HttpBodyStream; use React\Http\Message\Request; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; use React\Tests\Http\TestCase; @@ -14,7 +16,7 @@ public function testConstructWithStringRequestBodyReturnsStringBodyWithAutomatic $request = new Request( 'GET', 'http://localhost', - array(), + [], 'foo' ); @@ -28,13 +30,13 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWhichImplementsR $request = new Request( 'GET', 'http://localhost', - array(), + [], new ThroughStream() ); $body = $request->getBody(); - $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body); - $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf(StreamInterface::class, $body); + $this->assertInstanceOf(ReadableStreamInterface::class, $body); $this->assertNull($body->getSize()); } @@ -43,7 +45,7 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() $request = new Request( 'GET', 'http://localhost', - array(), + [], $body = new HttpBodyStream(new ThroughStream(), 100) ); @@ -52,11 +54,12 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() public function testConstructWithNullBodyThrows() { - $this->setExpectedException('InvalidArgumentException', 'Invalid request body given'); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid request body given'); new Request( 'GET', 'http://localhost', - array(), + [], null ); } diff --git a/tests/Message/ResponseTest.php b/tests/Message/ResponseTest.php index a9a244c2..6d4acb73 100644 --- a/tests/Message/ResponseTest.php +++ b/tests/Message/ResponseTest.php @@ -2,8 +2,10 @@ namespace React\Tests\Http\Message; +use Psr\Http\Message\StreamInterface; use React\Http\Io\HttpBodyStream; use React\Http\Message\Response; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; use React\Tests\Http\TestCase; @@ -11,23 +13,23 @@ 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 */ - $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body); + $this->assertInstanceOf(StreamInterface::class, $body); $this->assertEquals('hello', (string) $body); } 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 */ - $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body); - $this->assertInstanceof('React\Stream\ReadableStreamInterface', $body); - $this->assertInstanceOf('React\Http\Io\HttpBodyStream', $body); + $this->assertInstanceOf(StreamInterface::class, $body); + $this->assertInstanceof(ReadableStreamInterface::class, $body); + $this->assertInstanceOf(HttpBodyStream::class, $body); $this->assertNull($body->getSize()); } @@ -35,7 +37,7 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() { $response = new Response( 200, - array(), + [], $body = new HttpBodyStream(new ThroughStream(), 100) ); @@ -44,14 +46,14 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() public function testFloatBodyWillThrow() { - $this->setExpectedException('InvalidArgumentException'); - new Response(200, array(), 1.0); + $this->expectException(\InvalidArgumentException::class); + new Response(200, [], 1.0); } public function testResourceBodyWillThrow() { - $this->setExpectedException('InvalidArgumentException'); - new Response(200, array(), tmpfile()); + $this->expectException(\InvalidArgumentException::class); + new Response(200, [], tmpfile()); } public function testWithStatusReturnsNewInstanceWhenStatusIsChanged() @@ -97,21 +99,15 @@ public function testHtmlMethodReturnsHtmlResponse() $this->assertEquals('Hello wörld!', (string) $response->getBody()); } - /** - * @requires PHP 5.4 - */ 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')); $this->assertEquals("{\n \"text\": \"Hello wörld!\"\n}\n", (string) $response->getBody()); } - /** - * @requires PHP 5.6.6 - */ public function testJsonMethodReturnsZeroFractionsInJsonResponse() { $response = Response::json(1.0); @@ -132,11 +128,8 @@ public function testJsonMethodReturnsJsonTextForSimpleString() public function testJsonMethodThrowsForInvalidString() { - if (PHP_VERSION_ID < 50500) { - $this->setExpectedException('InvalidArgumentException', 'Unable to encode given data as JSON'); - } else { - $this->setExpectedException('InvalidArgumentException', 'Unable to encode given data as JSON: Malformed UTF-8 characters, possibly incorrectly encoded'); - } + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to encode given data as JSON: Malformed UTF-8 characters, possibly incorrectly encoded'); Response::json("Hello w\xF6rld!"); } @@ -165,7 +158,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() @@ -175,7 +168,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() @@ -185,7 +178,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() @@ -195,7 +188,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() @@ -205,7 +198,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() @@ -215,7 +208,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() @@ -225,30 +218,30 @@ 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() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); Response::parseMessage("HTTP/1.2 200 OK\r\n"); } public function testParseMessageWithInvalidHttpProtocolVersion2Throws() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); Response::parseMessage("HTTP/2 200 OK\r\n"); } public function testParseMessageWithInvalidStatusCodeUnderflowThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); Response::parseMessage("HTTP/1.1 99 OK\r\n"); } public function testParseMessageWithInvalidResponseHeaderFieldThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); Response::parseMessage("HTTP/1.1 200 OK\r\nServer\r\n"); } } diff --git a/tests/Message/ServerRequestTest.php b/tests/Message/ServerRequestTest.php index f82d60f8..596ebf47 100644 --- a/tests/Message/ServerRequestTest.php +++ b/tests/Message/ServerRequestTest.php @@ -2,8 +2,10 @@ namespace React\Tests\Http\Message; +use Psr\Http\Message\StreamInterface; use React\Http\Io\HttpBodyStream; use React\Http\Message\ServerRequest; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; use React\Tests\Http\TestCase; @@ -21,7 +23,7 @@ public function setUpRequest() public function testGetNoAttributes() { - $this->assertEquals(array(), $this->request->getAttributes()); + $this->assertEquals([], $this->request->getAttributes()); } public function testWithAttribute() @@ -29,7 +31,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 +58,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 +121,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 +141,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 +153,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 +165,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 +177,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 +189,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 +201,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 +213,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 +225,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 +237,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 +249,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 +261,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 +273,7 @@ public function testConstructWithStringRequestBodyReturnsStringBodyWithAutomatic $request = new ServerRequest( 'GET', 'http://localhost', - array(), + [], 'foo' ); @@ -285,7 +287,7 @@ public function testConstructWithHttpBodyStreamReturnsBodyAsIs() $request = new ServerRequest( 'GET', 'http://localhost', - array(), + [], $body = new HttpBodyStream(new ThroughStream(), 100) ); @@ -297,13 +299,13 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWhichImplementsR $request = new ServerRequest( 'GET', 'http://localhost', - array(), + [], new ThroughStream() ); $body = $request->getBody(); - $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body); - $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf(StreamInterface::class, $body); + $this->assertInstanceOf(ReadableStreamInterface::class, $body); $this->assertSame(0, $body->getSize()); } @@ -312,15 +314,15 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWithSizeFromCont $request = new ServerRequest( 'GET', 'http://localhost', - array( + [ 'Content-Length' => 100 - ), + ], new ThroughStream() ); $body = $request->getBody(); - $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body); - $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf(StreamInterface::class, $body); + $this->assertInstanceOf(ReadableStreamInterface::class, $body); $this->assertSame(100, $body->getSize()); } @@ -329,43 +331,43 @@ public function testConstructWithStreamingRequestBodyReturnsBodyWithSizeUnknownF $request = new ServerRequest( 'GET', 'http://localhost', - array( + [ 'Transfer-Encoding' => 'Chunked' - ), + ], new ThroughStream() ); $body = $request->getBody(); - $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $body); - $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); + $this->assertInstanceOf(StreamInterface::class, $body); + $this->assertInstanceOf(ReadableStreamInterface::class, $body); $this->assertNull($body->getSize()); } public function testConstructWithFloatRequestBodyThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new ServerRequest( 'GET', 'http://localhost', - array(), + [], 1.0 ); } public function testConstructWithResourceRequestBodyThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); 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 +376,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 +385,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 +395,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()); @@ -403,85 +405,85 @@ public function testParseMessageWithConnectMethodWithAuthorityFormRequestTarget( public function testParseMessageWithInvalidHttp11RequestWithoutHostThrows() { - $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.1\r\n", array()); + $this->expectException(\InvalidArgumentException::class); + ServerRequest::parseMessage("GET / HTTP/1.1\r\n", []); } public function testParseMessageWithInvalidHttpProtocolVersionThrows() { - $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / HTTP/1.2\r\n", array()); + $this->expectException(\InvalidArgumentException::class); + ServerRequest::parseMessage("GET / HTTP/1.2\r\n", []); } public function testParseMessageWithInvalidProtocolThrows() { - $this->setExpectedException('InvalidArgumentException'); - ServerRequest::parseMessage("GET / CUSTOM/1.1\r\n", array()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + 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()); + $this->expectException(\InvalidArgumentException::class); + ServerRequest::parseMessage("GET * HTTP/1.1\r\nHost: localhost\r\n", []); } } diff --git a/tests/Message/UriTest.php b/tests/Message/UriTest.php index 05eec723..adaee94b 100644 --- a/tests/Message/UriTest.php +++ b/tests/Message/UriTest.php @@ -9,119 +9,117 @@ class UriTest extends TestCase { public function testCtorWithInvalidSyntaxThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new Uri('///'); } public function testCtorWithInvalidSchemeThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new Uri('not+a+scheme://localhost'); } public function testCtorWithInvalidHostThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new Uri('http://not a host/'); } public function testCtorWithInvalidPortThrows() { - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); new Uri('http://localhost:80000/'); } public static function provideValidUris() { - return array( - array( - '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' - ) - ); + yield [ + 'http://localhost' + ]; + yield [ + 'http://localhost/' + ]; + yield [ + 'http://localhost:8080/' + ]; + yield [ + 'http://127.0.0.1/' + ]; + yield [ + 'http://[::1]:8080/' + ]; + yield [ + 'http://localhost/path' + ]; + yield [ + 'http://localhost/sub/path' + ]; + yield [ + 'http://localhost/with%20space' + ]; + yield [ + 'http://localhost/with%2fslash' + ]; + yield [ + 'http://localhost/?name=Alice' + ]; + yield [ + 'http://localhost/?name=John+Doe' + ]; + yield [ + 'http://localhost/?name=John%20Doe' + ]; + yield [ + 'http://localhost/?name=Alice&age=42' + ]; + yield [ + 'http://localhost/?name=Alice&' + ]; + yield [ + 'http://localhost/?choice=A%26B' + ]; + yield [ + 'http://localhost/?safe=Yes!?' + ]; + yield [ + 'http://localhost/?alias=@home' + ]; + yield [ + 'http://localhost/?assign:=true' + ]; + yield [ + 'http://localhost/?name=' + ]; + yield [ + 'http://localhost/?name' + ]; + yield [ + '' + ]; + yield [ + '/' + ]; + yield [ + '/path' + ]; + yield [ + 'path' + ]; + yield [ + 'http://user@localhost/' + ]; + yield [ + 'http://user:@localhost/' + ]; + yield [ + 'http://:pass@localhost/' + ]; + yield [ + 'http://user:pass@localhost/path?query#fragment' + ]; + yield [ + 'http://user%20name:pass%20word@localhost/path%20name?query%20name#frag%20ment' + ]; } /** @@ -130,11 +128,6 @@ public static function provideValidUris() */ public function testToStringReturnsOriginalUriGivenToCtor($string) { - if (PHP_VERSION_ID < 50519 || (PHP_VERSION_ID < 50603 && PHP_VERSION_ID >= 50606)) { - // @link https://3v4l.org/HdoPG - $this->markTestSkipped('Empty password not supported on legacy PHP'); - } - $uri = new Uri($string); $this->assertEquals($string, (string) $uri); @@ -142,36 +135,34 @@ public function testToStringReturnsOriginalUriGivenToCtor($string) public static function provideValidUrisThatWillBeTransformed() { - return array( - 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/', - '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' - ) - ); + yield [ + 'http://localhost:8080/?', + 'http://localhost:8080/' + ]; + yield [ + 'http://localhost:8080/#', + 'http://localhost:8080/' + ]; + yield [ + 'http://localhost:8080/?#', + 'http://localhost:8080/' + ]; + yield [ + 'http://@localhost:8080/', + 'http://localhost:8080/' + ]; + yield [ + 'http://localhost:8080/?percent=50%', + 'http://localhost:8080/?percent=50%25' + ]; + yield [ + 'http://user name:pass word@localhost/path name?query name#frag ment', + 'http://user%20name:pass%20word@localhost/path%20name?query%20name#frag%20ment' + ]; + yield [ + 'HTTP://USER:PASS@LOCALHOST:8080/PATH?QUERY#FRAGMENT', + 'http://USER:PASS@localhost:8080/PATH?QUERY#FRAGMENT' + ]; } /** @@ -256,7 +247,7 @@ public function testWithSchemeThrowsWhenSchemeIsInvalid() { $uri = new Uri('http://localhost'); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $uri->withScheme('invalid+scheme'); } @@ -380,7 +371,7 @@ public function testWithHostThrowsWhenHostIsInvalidWithPlus() { $uri = new Uri('http://localhost'); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $uri->withHost('invalid+host'); } @@ -388,7 +379,7 @@ public function testWithHostThrowsWhenHostIsInvalidWithSpace() { $uri = new Uri('http://localhost'); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $uri->withHost('invalid host'); } @@ -453,7 +444,7 @@ public function testWithPortThrowsWhenPortIsInvalidUnderflow() { $uri = new Uri('http://localhost'); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $uri->withPort(0); } @@ -461,7 +452,7 @@ public function testWithPortThrowsWhenPortIsInvalidOverflow() { $uri = new Uri('http://localhost'); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException(\InvalidArgumentException::class); $uri->withPort(65536); } @@ -581,113 +572,111 @@ public function testWithFragmentReturnsSameInstanceWhenFragmentIsUnchangedEncode public static function provideResolveUris() { - return array( - array( - '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' - ) - ); + yield [ + 'http://localhost/', + '', + 'http://localhost/' + ]; + yield [ + 'http://localhost/', + 'http://example.com/', + 'http://example.com/' + ]; + yield [ + 'http://localhost/', + 'path', + 'http://localhost/path' + ]; + yield [ + 'http://localhost/', + 'path/', + 'http://localhost/path/' + ]; + yield [ + 'http://localhost/', + 'path//', + 'http://localhost/path/' + ]; + yield [ + 'http://localhost', + 'path', + 'http://localhost/path' + ]; + yield [ + 'http://localhost/a/b', + '/path', + 'http://localhost/path' + ]; + yield [ + 'http://localhost/', + '/a/b/c', + 'http://localhost/a/b/c' + ]; + yield [ + 'http://localhost/a/path', + 'b/c', + 'http://localhost/a/b/c' + ]; + yield [ + 'http://localhost/a/path', + '/b/c', + 'http://localhost/b/c' + ]; + yield [ + 'http://localhost/a/path/', + 'b/c', + 'http://localhost/a/path/b/c' + ]; + yield [ + 'http://localhost/a/path/', + '../b/c', + 'http://localhost/a/b/c' + ]; + yield [ + 'http://localhost', + '../../../a/b', + 'http://localhost/a/b' + ]; + yield [ + 'http://localhost/path', + '?query', + 'http://localhost/path?query' + ]; + yield [ + 'http://localhost/path', + '#fragment', + 'http://localhost/path#fragment' + ]; + yield [ + 'http://localhost/path', + 'http://localhost', + 'http://localhost' + ]; + yield [ + 'http://localhost/path', + 'http://localhost/?query#fragment', + 'http://localhost/?query#fragment' + ]; + yield [ + 'http://localhost/path/?a#fragment', + '?b', + 'http://localhost/path/?b' + ]; + yield [ + 'http://localhost/path', + '//localhost', + 'http://localhost' + ]; + yield [ + 'http://localhost/path', + '//localhost/a?query', + 'http://localhost/a?query' + ]; + yield [ + 'http://localhost/path', + '//LOCALHOST', + 'http://localhost' + ]; } /** diff --git a/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php b/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php index faf27cb6..67656d4c 100644 --- a/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php +++ b/tests/Middleware/LimitConcurrentRequestsMiddlewareTest.php @@ -10,6 +10,7 @@ use React\Promise\Deferred; use React\Promise\Promise; use React\Promise\PromiseInterface; +use React\Stream\ReadableStreamInterface; use React\Stream\ThroughStream; use React\Tests\Http\TestCase; @@ -114,20 +115,19 @@ public function testThrowsExceptionDirectlyFromMiddlewareWhenBelowLimit() { $middleware = new LimitConcurrentRequestsMiddleware(1); - $this->setExpectedException('RuntimeException', 'demo'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('demo'); $middleware(new ServerRequest('GET', 'https://example.com/'), function () { throw new \RuntimeException('demo'); }); } - /** - * @requires PHP 7 - */ public function testThrowsErrorDirectlyFromMiddlewareWhenBelowLimit() { $middleware = new LimitConcurrentRequestsMiddleware(1); - $this->setExpectedException('Error', 'demo'); + $this->expectException(\Error::class); + $this->expectExceptionMessage('demo'); $middleware(new ServerRequest('GET', 'https://example.com/'), function () { throw new \Error('demo'); }); @@ -162,16 +162,16 @@ public function testReturnsPendingPromiseFromMiddlewareWhenAboveLimit() public function testStreamDoesNotPauseOrResumeWhenBelowLimit() { - $body = $this->getMockBuilder('React\Http\Io\HttpBodyStream')->disableOriginalConstructor()->getMock(); + $body = $this->createMock(HttpBodyStream::class); $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() { - $body = $this->getMockBuilder('React\Http\Io\HttpBodyStream')->disableOriginalConstructor()->getMock(); + $body = $this->createMock(HttpBodyStream::class); $body->expects($this->once())->method('pause'); $body->expects($this->never())->method('resume'); $limitHandlers = new LimitConcurrentRequestsMiddleware(1); @@ -180,12 +180,12 @@ 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() { - $body = $this->getMockBuilder('React\Http\Io\HttpBodyStream')->disableOriginalConstructor()->getMock(); + $body = $this->createMock(HttpBodyStream::class); $body->expects($this->once())->method('pause'); $body->expects($this->once())->method('resume'); $limitHandlers = new LimitConcurrentRequestsMiddleware(1); @@ -198,7 +198,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()); } @@ -208,7 +208,7 @@ public function testReceivesBufferedRequestSameInstance() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -227,7 +227,7 @@ public function testReceivesStreamingBodyRequestSameInstanceWhenBelowLimit() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 5) ); @@ -249,7 +249,7 @@ public function testReceivesRequestsSequentially() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -264,7 +264,7 @@ public function testDoesNotReceiveNextRequestIfHandlerIsPending() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -283,7 +283,7 @@ public function testReceivesNextRequestAfterPreviousHandlerIsSettled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -306,7 +306,7 @@ public function testReceivesNextRequestWhichThrowsAfterPreviousHandlerIsSettled( $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -334,7 +334,7 @@ public function testPendingRequestCanBeCancelledAndForwardsCancellationToInnerPr $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -357,7 +357,7 @@ public function testQueuedRequestCanBeCancelledBeforeItStartsProcessing() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -379,7 +379,7 @@ public function testReceivesNextRequestAfterPreviousHandlerIsCancelled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -403,7 +403,7 @@ public function testRejectsWhenQueuedPromiseIsCancelled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -425,7 +425,7 @@ public function testDoesNotInvokeNextHandlersWhenQueuedPromiseIsCancelled() $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], 'hello' ); @@ -448,7 +448,7 @@ public function testReceivesStreamingBodyChangesInstanceWithCustomBodyButSameDat $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 5) ); @@ -470,11 +470,11 @@ public function testReceivesStreamingBodyChangesInstanceWithCustomBodyButSameDat $deferred->reject(new \RuntimeException()); $this->assertNotSame($request, $req); - $this->assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $req); + $this->assertInstanceOf(ServerRequestInterface::class, $req); $body = $req->getBody(); - $this->assertInstanceOf('React\Stream\ReadableStreamInterface', $body); - /* @var $body \React\Stream\ReadableStreamInterface */ + $this->assertInstanceOf(ReadableStreamInterface::class, $body); + /* @var $body ReadableStreamInterface */ $this->assertEquals(5, $body->getSize()); @@ -497,7 +497,7 @@ public function testReceivesNextStreamingBodyWithBufferedDataAfterPreviousHandle $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 10) ); @@ -527,7 +527,7 @@ public function testReceivesNextStreamingBodyAndDoesNotEmitDataIfExplicitlyClose $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 10) ); @@ -558,7 +558,7 @@ public function testReceivesNextStreamingBodyAndDoesNotEmitDataIfExplicitlyPause $request = new ServerRequest( 'POST', 'http://example.com/', - array(), + [], new HttpBodyStream($stream, 10) ); @@ -589,7 +589,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 40c23378..28866c96 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) ); @@ -271,15 +272,12 @@ function (ServerRequestInterface $request) { $this->assertFalse($stream->isWritable()); assert($exception instanceof \RuntimeException); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Buffered 3', $exception->getMessage()); $this->assertEquals(42, $exception->getCode()); $this->assertNull($exception->getPrevious()); } - /** - * @requires PHP 7 - */ public function testBufferingRejectsWhenNextHandlerThrowsErrorWhenStreamEnds() { $stream = new ThroughStream(); @@ -287,7 +285,7 @@ public function testBufferingRejectsWhenNextHandlerThrowsErrorWhenStreamEnds() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -309,7 +307,7 @@ function (ServerRequestInterface $request) { $this->assertFalse($stream->isWritable()); assert($exception instanceof \Error); - $this->assertInstanceOf('Error', $exception); + $this->assertInstanceOf(\Error::class, $exception); $this->assertEquals('Buffered 3', $exception->getMessage()); $this->assertEquals(42, $exception->getCode()); $this->assertNull($exception->getPrevious()); @@ -324,7 +322,7 @@ public function testBufferingRejectsWhenStreamEmitsError() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -344,10 +342,10 @@ public function testBufferingRejectsWhenStreamEmitsError() $this->assertFalse($stream->isWritable()); assert($exception instanceof \RuntimeException); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Error while buffering request body: Unexpected Foo', $exception->getMessage()); $this->assertEquals(42, $exception->getCode()); - $this->assertInstanceOf('UnexpectedValueException', $exception->getPrevious()); + $this->assertInstanceOf(\UnexpectedValueException::class, $exception->getPrevious()); } public function testFullBodyStreamedBeforeCallingNextMiddleware() @@ -358,7 +356,7 @@ public function testFullBodyStreamedBeforeCallingNextMiddleware() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, null) ); @@ -384,7 +382,7 @@ public function testCancelBufferingClosesStreamAndRejectsPromise() $serverRequest = new ServerRequest( 'GET', 'https://example.com/', - array(), + [], new HttpBodyStream($stream, 2) ); @@ -401,7 +399,7 @@ public function testCancelBufferingClosesStreamAndRejectsPromise() }); assert($exception instanceof \RuntimeException); - $this->assertInstanceOf('RuntimeException', $exception); + $this->assertInstanceOf(\RuntimeException::class, $exception); $this->assertEquals('Cancelled buffering request body', $exception->getMessage()); $this->assertEquals(0, $exception->getCode()); $this->assertNull($exception->getPrevious()); diff --git a/tests/Middleware/RequestBodyParserMiddlewareTest.php b/tests/Middleware/RequestBodyParserMiddlewareTest.php index 989abc81..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()); @@ -109,22 +109,15 @@ function (ServerRequestInterface $request) { public function testFormUrlencodedIgnoresBodyWithExcessiveNesting() { - // supported in all Zend PHP versions and HHVM - // ini setting does exist everywhere but HHVM: https://3v4l.org/hXLiK - // HHVM limits to 64 and returns an empty array structure: https://3v4l.org/j3DK2 - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Not supported on HHVM (limited to depth 64, but keeps empty array structure)'); - } - $allowed = (int)ini_get('max_input_nesting_level'); $middleware = new RequestBodyParserMiddleware(); $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' ); @@ -137,28 +130,22 @@ function (ServerRequestInterface $request) { ); $this->assertSame( - array(), + [], $parsedRequest->getParsedBody() ); } public function testFormUrlencodedTruncatesBodyWithExcessiveLength() { - // supported as of PHP 5.3.11, no HHVM support: https://3v4l.org/PiqnQ - // ini setting already exists in PHP 5.3.9: https://3v4l.org/VF6oV - if (defined('HHVM_VERSION') || PHP_VERSION_ID < 50311) { - $this->markTestSkipped('Not supported on HHVM and PHP < 5.3.11 (unlimited length)'); - } - $allowed = (int)ini_get('max_input_vars'); $middleware = new RequestBodyParserMiddleware(); $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) ); @@ -183,9 +170,9 @@ public function testDoesNotParseJsonByDefault() $request = new ServerRequest( 'POST', 'https://example.com/', - array( - 'Content-Type' => 'application/json', - ), + [ + 'Content-Type' => 'application/json' + ], '{"hello":"world"}' ); @@ -217,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( @@ -230,12 +217,12 @@ function (ServerRequestInterface $request) { ); $this->assertSame( - array( - 'users' => array( + [ + 'users' => [ 'one' => 'single', 'two' => 'second', - ), - ), + ], + ], $parsedRequest->getParsedBody() ); $this->assertSame($data, (string)$parsedRequest->getBody()); @@ -243,13 +230,7 @@ function (ServerRequestInterface $request) { public function testMultipartFormDataIgnoresFieldWithExcessiveNesting() { - // supported in all Zend PHP versions and HHVM - // ini setting does exist everywhere but HHVM: https://3v4l.org/hXLiK - // HHVM limits to 64 and otherwise returns an empty array structure - $allowed = (int)ini_get('max_input_nesting_level'); - if ($allowed === 0) { - $allowed = 64; - } + $allowed = (int) ini_get('max_input_nesting_level'); $middleware = new RequestBodyParserMiddleware(); @@ -261,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( @@ -278,12 +259,7 @@ function (ServerRequestInterface $request) { public function testMultipartFormDataTruncatesBodyWithExcessiveLength() { - // ini setting exists in PHP 5.3.9, not in HHVM: https://3v4l.org/VF6oV - // otherwise default to 1000 as implemented within - $allowed = (int)ini_get('max_input_vars'); - if ($allowed === 0) { - $allowed = 1000; - } + $allowed = (int) ini_get('max_input_vars'); $middleware = new RequestBodyParserMiddleware(); @@ -298,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( @@ -319,12 +295,7 @@ function (ServerRequestInterface $request) { public function testMultipartFormDataTruncatesExcessiveNumberOfEmptyFileUploads() { - // ini setting exists in PHP 5.3.9, not in HHVM: https://3v4l.org/VF6oV - // otherwise default to 1000 as implemented within - $allowed = (int)ini_get('max_input_vars'); - if ($allowed === 0) { - $allowed = 1000; - } + $allowed = (int) ini_get('max_input_vars'); $middleware = new RequestBodyParserMiddleware(); @@ -339,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 72b7be8d..4df6087f 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,11 +2,12 @@ namespace React\Tests\Http; +use PHPUnit\Framework\MockObject\MockBuilder; use PHPUnit\Framework\TestCase as BaseTestCase; class TestCase extends BaseTestCase { - public function expectCallableOnce() // protected (PHP 5.4+) + protected function expectCallableOnce() { $mock = $this->createCallableMock(); $mock @@ -16,7 +17,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 +28,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 @@ -39,52 +40,12 @@ public function expectCallableNever() // protected (PHP 5.4+) protected function createCallableMock() { - if (method_exists('PHPUnit\Framework\MockObject\MockBuilder', 'addMethods')) { + if (method_exists(MockBuilder::class, 'addMethods')) { // PHPUnit 9+ - return $this->getMockBuilder('stdClass')->addMethods(array('__invoke'))->getMock(); + return $this->getMockBuilder(\stdClass::class)->addMethods(['__invoke'])->getMock(); } else { - // legacy PHPUnit 4 - PHPUnit 8 - return $this->getMockBuilder('stdClass')->setMethods(array('__invoke'))->getMock(); + // legacy PHPUnit + return $this->getMockBuilder(\stdClass::class)->setMethods(['__invoke'])->getMock(); } } - - public function assertContainsString($needle, $haystack) - { - if (method_exists($this, 'assertStringContainsString')) { - // PHPUnit 7.5+ - $this->assertStringContainsString($needle, $haystack); - } else { - // legacy PHPUnit 4 - PHPUnit 7.5 - $this->assertContains($needle, $haystack); - } - } - - public function assertNotContainsString($needle, $haystack) - { - if (method_exists($this, 'assertStringNotContainsString')) { - // PHPUnit 7.5+ - $this->assertStringNotContainsString($needle, $haystack); - } else { - // legacy PHPUnit 4 - PHPUnit 7.5 - $this->assertNotContains($needle, $haystack); - } - } - - public function setExpectedException($exception, $exceptionMessage = '', $exceptionCode = null) - { - if (method_exists($this, 'expectException')) { - // PHPUnit 5+ - $this->expectException($exception); - if ($exceptionMessage !== '') { - $this->expectExceptionMessage($exceptionMessage); - } - if ($exceptionCode !== null) { - $this->expectExceptionCode($exceptionCode); - } - } else { - // legacy PHPUnit 4 - parent::setExpectedException($exception, $exceptionMessage, $exceptionCode); - } - } - } 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; }