diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fb3698d..474b1c8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,22 +6,24 @@ on:
jobs:
PHPUnit:
- name: PHPUnit (PHP ${{ matrix.php }})(${{ matrix.env }})
- runs-on: ubuntu-20.04
+ name: PHPUnit (PHP ${{ matrix.php }})(${{ matrix.env }}) on ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
strategy:
matrix:
+ os:
+ - ubuntu-22.04
env:
- client
- server
php:
- 7.4
- - 7.3
- - 7.2
- - 7.1
- - 7.0
- - 5.6
+ - 8.0
+ - 8.1
+ - 8.2
+ - 8.3
+ - 8.4
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
@@ -33,11 +35,4 @@ jobs:
- run: sh tests/ab/run_ab_tests.sh
env:
ABTEST: ${{ matrix.env }}
- SKIP_DEFLATE: _skip_deflate
- if: ${{ matrix.php <= 5.6 }}
-
- - run: sh tests/ab/run_ab_tests.sh
- env:
- ABTEST: ${{ matrix.env }}
- if: ${{ matrix.php >= 7.0 }}
- run: vendor/bin/phpunit --verbose
diff --git a/.gitignore b/.gitignore
index 42ab5d5..94b67da 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
+.phpunit.result.cache
composer.lock
vendor
tests/ab/reports
diff --git a/composer.json b/composer.json
index 054a8fb..07586f0 100644
--- a/composer.json
+++ b/composer.json
@@ -26,12 +26,14 @@
}
},
"require": {
- "php": ">=5.4.2",
- "guzzlehttp/psr7": "^2 || ^1.7"
+ "php": ">=7.4",
+ "psr/http-factory-implementation": "^1.0",
+ "symfony/polyfill-php80": "^1.15"
},
"require-dev": {
- "phpunit/phpunit": "^5.7",
- "react/socket": "^1.3"
+ "phpunit/phpunit": "^9.5",
+ "react/socket": "^1.3",
+ "guzzlehttp/psr7": "^2.7"
},
"scripts": {
"abtest-client": "ABTEST=client && sh tests/ab/run_ab_tests.sh",
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 8f2e7d1..155ce6a 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,27 +1,22 @@
- tests
-
- test/ab
-
+ ./tests
-
-
- ./src/
-
-
-
\ No newline at end of file
+
+
+ ./src
+
+
+
diff --git a/src/Handshake/ClientNegotiator.php b/src/Handshake/ClientNegotiator.php
index c32a1cf..547b5ea 100644
--- a/src/Handshake/ClientNegotiator.php
+++ b/src/Handshake/ClientNegotiator.php
@@ -3,38 +3,35 @@
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
-use GuzzleHttp\Psr7\Request;
+use Psr\Http\Message\RequestFactoryInterface;
class ClientNegotiator {
- /**
- * @var ResponseVerifier
- */
- private $verifier;
+ private ResponseVerifier $verifier;
- /**
- * @var \Psr\Http\Message\RequestInterface
- */
- private $defaultHeader;
+ private RequestInterface $defaultHeader;
- function __construct(PermessageDeflateOptions $perMessageDeflateOptions = null) {
+ private RequestFactoryInterface $requestFactory;
+
+ public function __construct(
+ RequestFactoryInterface $requestFactory,
+ ?PermessageDeflateOptions $perMessageDeflateOptions = null
+ ) {
$this->verifier = new ResponseVerifier;
+ $this->requestFactory = $requestFactory;
- $this->defaultHeader = new Request('GET', '', [
- 'Connection' => 'Upgrade'
- , 'Upgrade' => 'websocket'
- , 'Sec-WebSocket-Version' => $this->getVersion()
- , 'User-Agent' => "Ratchet"
- ]);
+ $this->defaultHeader = $this->requestFactory
+ ->createRequest('GET', '')
+ ->withHeader('Connection' , 'Upgrade')
+ ->withHeader('Upgrade' , 'websocket')
+ ->withHeader('Sec-WebSocket-Version', $this->getVersion())
+ ->withHeader('User-Agent' , 'Ratchet');
- if ($perMessageDeflateOptions === null) {
- $perMessageDeflateOptions = PermessageDeflateOptions::createDisabled();
- }
+ $perMessageDeflateOptions ??= PermessageDeflateOptions::createDisabled();
// https://bugs.php.net/bug.php?id=73373
// https://bugs.php.net/bug.php?id=74240 - need >=7.1.4 or >=7.0.18
- if ($perMessageDeflateOptions->isEnabled() &&
- !PermessageDeflateOptions::permessageDeflateSupported()) {
- trigger_error('permessage-deflate is being disabled because it is not support by your PHP version.', E_USER_NOTICE);
+ if ($perMessageDeflateOptions->isEnabled() && !PermessageDeflateOptions::permessageDeflateSupported()) {
+ trigger_error('permessage-deflate is being disabled because it is not supported by your PHP version.', E_USER_NOTICE);
$perMessageDeflateOptions = PermessageDeflateOptions::createDisabled();
}
if ($perMessageDeflateOptions->isEnabled() && !function_exists('deflate_add')) {
@@ -45,16 +42,16 @@ function __construct(PermessageDeflateOptions $perMessageDeflateOptions = null)
$this->defaultHeader = $perMessageDeflateOptions->addHeaderToRequest($this->defaultHeader);
}
- public function generateRequest(UriInterface $uri) {
+ public function generateRequest(UriInterface $uri): RequestInterface {
return $this->defaultHeader->withUri($uri)
- ->withHeader("Sec-WebSocket-Key", $this->generateKey());
+ ->withHeader('Sec-WebSocket-Key', $this->generateKey());
}
- public function validateResponse(RequestInterface $request, ResponseInterface $response) {
+ public function validateResponse(RequestInterface $request, ResponseInterface $response): bool {
return $this->verifier->verifyAll($request, $response);
}
- public function generateKey() {
+ public function generateKey(): string {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzyz1234567890+/=';
$charRange = strlen($chars) - 1;
$key = '';
@@ -65,7 +62,7 @@ public function generateKey() {
return base64_encode($key);
}
- public function getVersion() {
+ public function getVersion(): int {
return 13;
}
}
diff --git a/src/Handshake/NegotiatorInterface.php b/src/Handshake/NegotiatorInterface.php
index c152eca..8903a4a 100644
--- a/src/Handshake/NegotiatorInterface.php
+++ b/src/Handshake/NegotiatorInterface.php
@@ -1,6 +1,7 @@
deflateEnabled = true;
$new->client_max_window_bits = self::MAX_WINDOW_BITS;
$new->client_no_context_takeover = false;
@@ -33,35 +33,35 @@ public static function createEnabled() {
}
public static function createDisabled() {
- return new static();
+ return new self();
}
- public function withClientNoContextTakeover() {
+ public function withClientNoContextTakeover(): self {
$new = clone $this;
$new->client_no_context_takeover = true;
return $new;
}
- public function withoutClientNoContextTakeover() {
+ public function withoutClientNoContextTakeover(): self {
$new = clone $this;
$new->client_no_context_takeover = false;
return $new;
}
- public function withServerNoContextTakeover() {
+ public function withServerNoContextTakeover(): self {
$new = clone $this;
$new->server_no_context_takeover = true;
return $new;
}
- public function withoutServerNoContextTakeover() {
+ public function withoutServerNoContextTakeover(): self {
$new = clone $this;
$new->server_no_context_takeover = false;
return $new;
}
- public function withServerMaxWindowBits($bits = self::MAX_WINDOW_BITS) {
- if (!in_array($bits, self::$VALID_BITS)) {
+ public function withServerMaxWindowBits(int $bits = self::MAX_WINDOW_BITS): self {
+ if (!in_array($bits, self::VALID_BITS)) {
throw new \Exception('server_max_window_bits must have a value between 8 and 15.');
}
$new = clone $this;
@@ -69,8 +69,8 @@ public function withServerMaxWindowBits($bits = self::MAX_WINDOW_BITS) {
return $new;
}
- public function withClientMaxWindowBits($bits = self::MAX_WINDOW_BITS) {
- if (!in_array($bits, self::$VALID_BITS)) {
+ public function withClientMaxWindowBits(int $bits = self::MAX_WINDOW_BITS): self {
+ if (!in_array($bits, self::VALID_BITS)) {
throw new \Exception('client_max_window_bits must have a value between 8 and 15.');
}
$new = clone $this;
@@ -86,7 +86,7 @@ public function withClientMaxWindowBits($bits = self::MAX_WINDOW_BITS) {
* @return PermessageDeflateOptions[]
* @throws \Exception
*/
- public static function fromRequestOrResponse(MessageInterface $requestOrResponse) {
+ public static function fromRequestOrResponse(MessageInterface $requestOrResponse): array {
$optionSets = [];
$extHeader = preg_replace('/\s+/', '', join(', ', $requestOrResponse->getHeader('Sec-Websocket-Extensions')));
@@ -103,7 +103,7 @@ public static function fromRequestOrResponse(MessageInterface $requestOrResponse
}
array_shift($parts);
- $options = new static();
+ $options = new self();
$options->deflateEnabled = true;
foreach ($parts as $part) {
$kv = explode('=', $part);
@@ -119,15 +119,18 @@ public static function fromRequestOrResponse(MessageInterface $requestOrResponse
$value = true;
break;
case "server_max_window_bits":
- if (!in_array($value, self::$VALID_BITS)) {
+ $value = (int) $value;
+ if (!in_array($value, self::VALID_BITS)) {
throw new InvalidPermessageDeflateOptionsException($key . ' must have a value between 8 and 15.');
}
break;
case "client_max_window_bits":
if ($value === null) {
- $value = '15';
+ $value = 15;
+ } else {
+ $value = (int) $value;
}
- if (!in_array($value, self::$VALID_BITS)) {
+ if (!in_array($value, self::VALID_BITS)) {
throw new InvalidPermessageDeflateOptionsException($key . ' must have no value or a value between 8 and 15.');
}
break;
@@ -154,39 +157,39 @@ public static function fromRequestOrResponse(MessageInterface $requestOrResponse
}
// always put a disabled on the end
- $optionSets[] = new static();
+ $optionSets[] = new self();
return $optionSets;
}
/**
- * @return mixed
+ * @return bool|null
*/
- public function getServerNoContextTakeover()
+ public function getServerNoContextTakeover(): ?bool
{
return $this->server_no_context_takeover;
}
/**
- * @return mixed
+ * @return bool|null
*/
- public function getClientNoContextTakeover()
+ public function getClientNoContextTakeover(): ?bool
{
return $this->client_no_context_takeover;
}
/**
- * @return mixed
+ * @return int|null
*/
- public function getServerMaxWindowBits()
+ public function getServerMaxWindowBits(): ?int
{
return $this->server_max_window_bits;
}
/**
- * @return mixed
+ * @return int|null
*/
- public function getClientMaxWindowBits()
+ public function getClientMaxWindowBits(): ?int
{
return $this->client_max_window_bits;
}
@@ -194,7 +197,7 @@ public function getClientMaxWindowBits()
/**
* @return bool
*/
- public function isEnabled()
+ public function isEnabled(): bool
{
return $this->deflateEnabled;
}
@@ -203,7 +206,7 @@ public function isEnabled()
* @param ResponseInterface $response
* @return ResponseInterface
*/
- public function addHeaderToResponse(ResponseInterface $response)
+ public function addHeaderToResponse(ResponseInterface $response): ResponseInterface
{
if (!$this->deflateEnabled) {
return $response;
@@ -226,7 +229,7 @@ public function addHeaderToResponse(ResponseInterface $response)
return $response->withAddedHeader('Sec-Websocket-Extensions', $header);
}
- public function addHeaderToRequest(RequestInterface $request) {
+ public function addHeaderToRequest(RequestInterface $request): RequestInterface {
if (!$this->deflateEnabled) {
return $request;
}
@@ -249,7 +252,7 @@ public function addHeaderToRequest(RequestInterface $request) {
return $request->withAddedHeader('Sec-Websocket-Extensions', $header);
}
- public static function permessageDeflateSupported($version = PHP_VERSION) {
+ public static function permessageDeflateSupported(string $version = PHP_VERSION): bool {
if (!function_exists('deflate_init')) {
return false;
}
diff --git a/src/Handshake/RequestVerifier.php b/src/Handshake/RequestVerifier.php
index 9e192c5..c2f26a1 100644
--- a/src/Handshake/RequestVerifier.php
+++ b/src/Handshake/RequestVerifier.php
@@ -8,14 +8,14 @@
* @todo Currently just returning invalid - should consider returning appropriate HTTP status code error #s
*/
class RequestVerifier {
- const VERSION = 13;
+ public const VERSION = 13;
/**
* Given an array of the headers this method will run through all verification methods
* @param RequestInterface $request
* @return bool TRUE if all headers are valid, FALSE if 1 or more were invalid
*/
- public function verifyAll(RequestInterface $request) {
+ public function verifyAll(RequestInterface $request): bool {
$passes = 0;
$passes += (int)$this->verifyMethod($request->getMethod());
@@ -27,7 +27,7 @@ public function verifyAll(RequestInterface $request) {
$passes += (int)$this->verifyKey($request->getHeader('Sec-WebSocket-Key'));
$passes += (int)$this->verifyVersion($request->getHeader('Sec-WebSocket-Version'));
- return (8 === $passes);
+ return 8 === $passes;
}
/**
@@ -35,8 +35,8 @@ public function verifyAll(RequestInterface $request) {
* @param string
* @return bool
*/
- public function verifyMethod($val) {
- return ('get' === strtolower($val));
+ public function verifyMethod(string $val): bool {
+ return 'get' === strtolower($val);
}
/**
@@ -44,15 +44,15 @@ public function verifyMethod($val) {
* @param string|int
* @return bool
*/
- public function verifyHTTPVersion($val) {
- return (1.1 <= (double)$val);
+ public function verifyHTTPVersion($val): bool {
+ return 1.1 <= (double)$val;
}
/**
* @param string
* @return bool
*/
- public function verifyRequestURI($val) {
+ public function verifyRequestURI(string $val): bool {
if ($val[0] !== '/') {
return false;
}
@@ -73,8 +73,8 @@ public function verifyRequestURI($val) {
* @return bool
* @todo Once I fix HTTP::getHeaders just verify this isn't NULL or empty...or maybe need to verify it's a valid domain??? Or should it equal $_SERVER['HOST'] ?
*/
- public function verifyHost(array $hostHeader) {
- return (1 === count($hostHeader));
+ public function verifyHost(array $hostHeader): bool {
+ return 1 === count($hostHeader);
}
/**
@@ -82,8 +82,8 @@ public function verifyHost(array $hostHeader) {
* @param array $upgradeHeader MUST equal "websocket"
* @return bool
*/
- public function verifyUpgradeRequest(array $upgradeHeader) {
- return (1 === count($upgradeHeader) && 'websocket' === strtolower($upgradeHeader[0]));
+ public function verifyUpgradeRequest(array $upgradeHeader): bool {
+ return 1 === count($upgradeHeader) && 'websocket' === strtolower($upgradeHeader[0]);
}
/**
@@ -91,13 +91,11 @@ public function verifyUpgradeRequest(array $upgradeHeader) {
* @param array $connectionHeader MUST include "Upgrade"
* @return bool
*/
- public function verifyConnection(array $connectionHeader) {
+ public function verifyConnection(array $connectionHeader): bool {
foreach ($connectionHeader as $l) {
$upgrades = array_filter(
array_map('trim', array_map('strtolower', explode(',', $l))),
- function ($x) {
- return 'upgrade' === $x;
- }
+ static fn (string $x) => 'upgrade' === $x
);
if (count($upgrades) > 0) {
return true;
@@ -113,8 +111,8 @@ function ($x) {
* @todo The spec says we don't need to base64_decode - can I just check if the length is 24 and not decode?
* @todo Check the spec to see what the encoding of the key could be
*/
- public function verifyKey(array $keyHeader) {
- return (1 === count($keyHeader) && 16 === strlen(base64_decode($keyHeader[0])));
+ public function verifyKey(array $keyHeader): bool {
+ return 1 === count($keyHeader) && 16 === strlen(base64_decode($keyHeader[0]));
}
/**
@@ -122,33 +120,33 @@ public function verifyKey(array $keyHeader) {
* @param string[] $versionHeader MUST equal ["13"]
* @return bool
*/
- public function verifyVersion(array $versionHeader) {
- return (1 === count($versionHeader) && static::VERSION === (int)$versionHeader[0]);
+ public function verifyVersion(array $versionHeader): bool {
+ return 1 === count($versionHeader) && static::VERSION === (int)$versionHeader[0];
}
/**
* @todo Write logic for this method. See section 4.2.1.8
*/
- public function verifyProtocol($val) {
+ public function verifyProtocol($val): bool {
+ return true;
}
/**
* @todo Write logic for this method. See section 4.2.1.9
*/
- public function verifyExtensions($val) {
+ public function verifyExtensions($val): bool {
+ return true;
}
- public function getPermessageDeflateOptions(array $requestHeader, array $responseHeader) {
+ public function getPermessageDeflateOptions(array $requestHeader, array $responseHeader): array {
+ $headerChecker = static fn (string $val) => 'permessage-deflate' === substr($val, 0, strlen('permessage-deflate'));
+
$deflate = true;
- if (!isset($requestHeader['Sec-WebSocket-Extensions']) || count(array_filter($requestHeader['Sec-WebSocket-Extensions'], function ($val) {
- return 'permessage-deflate' === substr($val, 0, strlen('permessage-deflate'));
- })) === 0) {
+ if (!isset($requestHeader['Sec-WebSocket-Extensions']) || count(array_filter($requestHeader['Sec-WebSocket-Extensions'], $headerChecker)) === 0) {
$deflate = false;
}
- if (!isset($responseHeader['Sec-WebSocket-Extensions']) || count(array_filter($responseHeader['Sec-WebSocket-Extensions'], function ($val) {
- return 'permessage-deflate' === substr($val, 0, strlen('permessage-deflate'));
- })) === 0) {
+ if (!isset($responseHeader['Sec-WebSocket-Extensions']) || count(array_filter($responseHeader['Sec-WebSocket-Extensions'], $headerChecker)) === 0) {
$deflate = false;
}
diff --git a/src/Handshake/ResponseVerifier.php b/src/Handshake/ResponseVerifier.php
index 453f9d6..56c62c2 100644
--- a/src/Handshake/ResponseVerifier.php
+++ b/src/Handshake/ResponseVerifier.php
@@ -4,7 +4,7 @@
use Psr\Http\Message\ResponseInterface;
class ResponseVerifier {
- public function verifyAll(RequestInterface $request, ResponseInterface $response) {
+ public function verifyAll(RequestInterface $request, ResponseInterface $response): bool {
$passes = 0;
$passes += (int)$this->verifyStatus($response->getStatusCode());
@@ -26,31 +26,31 @@ public function verifyAll(RequestInterface $request, ResponseInterface $response
return (6 === $passes);
}
- public function verifyStatus($status) {
- return ((int)$status === 101);
+ public function verifyStatus(int $status): bool {
+ return $status === 101;
}
- public function verifyUpgrade(array $upgrade) {
- return (in_array('websocket', array_map('strtolower', $upgrade)));
+ public function verifyUpgrade(array $upgrade): bool {
+ return in_array('websocket', array_map('strtolower', $upgrade));
}
- public function verifyConnection(array $connection) {
- return (in_array('upgrade', array_map('strtolower', $connection)));
+ public function verifyConnection(array $connection): bool {
+ return in_array('upgrade', array_map('strtolower', $connection));
}
- public function verifySecWebSocketAccept($swa, $key) {
- return (
+ public function verifySecWebSocketAccept(array $swa, array $key): bool {
+ return
1 === count($swa) &&
1 === count($key) &&
$swa[0] === $this->sign($key[0])
- );
+ ;
}
- public function sign($key) {
+ public function sign(string $key): string {
return base64_encode(sha1($key . NegotiatorInterface::GUID, true));
}
- public function verifySubProtocol(array $requestHeader, array $responseHeader) {
+ public function verifySubProtocol(array $requestHeader, array $responseHeader): bool {
if (0 === count($responseHeader)) {
return true;
}
@@ -60,7 +60,7 @@ public function verifySubProtocol(array $requestHeader, array $responseHeader) {
return count($responseHeader) === 1 && count(array_intersect($responseHeader, $requestedProtocols)) === 1;
}
- public function verifyExtensions(array $requestHeader, array $responseHeader) {
+ public function verifyExtensions(array $requestHeader, array $responseHeader): int {
if (in_array('permessage-deflate', $responseHeader)) {
return strpos(implode(',', $requestHeader), 'permessage-deflate') !== false ? 1 : 0;
}
diff --git a/src/Handshake/ServerNegotiator.php b/src/Handshake/ServerNegotiator.php
index e4ce79b..94f0549 100644
--- a/src/Handshake/ServerNegotiator.php
+++ b/src/Handshake/ServerNegotiator.php
@@ -1,26 +1,32 @@
verifier = $requestVerifier;
+ $this->responseFactory = $responseFactory;
// https://bugs.php.net/bug.php?id=73373
// https://bugs.php.net/bug.php?id=74240 - need >=7.1.4 or >=7.0.18
@@ -38,85 +44,85 @@ public function __construct(RequestVerifier $requestVerifier, $enablePerMessageD
/**
* {@inheritdoc}
*/
- public function isProtocol(RequestInterface $request) {
+ public function isProtocol(RequestInterface $request): bool {
return $this->verifier->verifyVersion($request->getHeader('Sec-WebSocket-Version'));
}
/**
* {@inheritdoc}
*/
- public function getVersionNumber() {
+ public function getVersionNumber(): int {
return RequestVerifier::VERSION;
}
/**
* {@inheritdoc}
*/
- public function handshake(RequestInterface $request) {
+ public function handshake(RequestInterface $request): ResponseInterface {
+ $response = $this->responseFactory->createResponse();
if (true !== $this->verifier->verifyMethod($request->getMethod())) {
- return new Response(405, ['Allow' => 'GET']);
+ return $response->withHeader('Allow', 'GET')->withStatus(405);
}
if (true !== $this->verifier->verifyHTTPVersion($request->getProtocolVersion())) {
- return new Response(505);
+ return $response->withStatus(505);
}
if (true !== $this->verifier->verifyRequestURI($request->getUri()->getPath())) {
- return new Response(400);
+ return $response->withStatus(400);
}
if (true !== $this->verifier->verifyHost($request->getHeader('Host'))) {
- return new Response(400);
+ return $response->withStatus(400);
}
- $upgradeSuggestion = [
- 'Connection' => 'Upgrade',
- 'Upgrade' => 'websocket',
- 'Sec-WebSocket-Version' => $this->getVersionNumber()
- ];
+ $upgradeResponse = $response
+ ->withHeader('Connection' , 'Upgrade')
+ ->withHeader('Upgrade' , 'websocket')
+ ->withHeader('Sec-WebSocket-Version', $this->getVersionNumber());
+
if (count($this->_supportedSubProtocols) > 0) {
- $upgradeSuggestion['Sec-WebSocket-Protocol'] = implode(', ', array_keys($this->_supportedSubProtocols));
+ $upgradeResponse = $upgradeResponse->withHeader(
+ 'Sec-WebSocket-Protocol', implode(', ', array_keys($this->_supportedSubProtocols))
+ );
}
if (true !== $this->verifier->verifyUpgradeRequest($request->getHeader('Upgrade'))) {
- return new Response(426, $upgradeSuggestion, null, '1.1', 'Upgrade header MUST be provided');
+ return $upgradeResponse->withStatus(426, 'Upgrade header MUST be provided');
}
if (true !== $this->verifier->verifyConnection($request->getHeader('Connection'))) {
- return new Response(400, [], null, '1.1', 'Connection Upgrade MUST be requested');
+ return $response->withStatus(400, 'Connection Upgrade MUST be requested');
}
if (true !== $this->verifier->verifyKey($request->getHeader('Sec-WebSocket-Key'))) {
- return new Response(400, [], null, '1.1', 'Invalid Sec-WebSocket-Key');
+ return $response->withStatus(400, 'Invalid Sec-WebSocket-Key');
}
if (true !== $this->verifier->verifyVersion($request->getHeader('Sec-WebSocket-Version'))) {
- return new Response(426, $upgradeSuggestion);
+ return $upgradeResponse->withStatus(426);
}
- $headers = [];
$subProtocols = $request->getHeader('Sec-WebSocket-Protocol');
if (count($subProtocols) > 0 || (count($this->_supportedSubProtocols) > 0 && $this->_strictSubProtocols)) {
$subProtocols = array_map('trim', explode(',', implode(',', $subProtocols)));
- $match = array_reduce($subProtocols, function($accumulator, $protocol) {
- return $accumulator ?: (isset($this->_supportedSubProtocols[$protocol]) ? $protocol : null);
- }, null);
+ $match = array_reduce($subProtocols, fn ($accumulator, $protocol) => $accumulator ?: (isset($this->_supportedSubProtocols[$protocol]) ? $protocol : null), null);
if ($this->_strictSubProtocols && null === $match) {
- return new Response(426, $upgradeSuggestion, null, '1.1', 'No Sec-WebSocket-Protocols requested supported');
+ return $upgradeResponse->withStatus(426, 'No Sec-WebSocket-Protocols requested supported');
}
if (null !== $match) {
- $headers['Sec-WebSocket-Protocol'] = $match;
+ $response = $response->withHeader('Sec-WebSocket-Protocol', $match);
}
}
- $response = new Response(101, array_merge($headers, [
- 'Upgrade' => 'websocket'
- , 'Connection' => 'Upgrade'
- , 'Sec-WebSocket-Accept' => $this->sign((string)$request->getHeader('Sec-WebSocket-Key')[0])
- , 'X-Powered-By' => 'Ratchet'
- ]));
+ $response = $response
+ ->withStatus(101)
+ ->withHeader('Upgrade' , 'websocket')
+ ->withHeader('Connection' , 'Upgrade')
+ ->withHeader('Sec-WebSocket-Accept', $this->sign((string)$request->getHeader('Sec-WebSocket-Key')[0]))
+ ->withHeader('X-Powered-By' , 'Ratchet');
try {
$perMessageDeflateRequest = PermessageDeflateOptions::fromRequestOrResponse($request)[0];
@@ -137,14 +143,14 @@ public function handshake(RequestInterface $request) {
* @return string
* @internal
*/
- public function sign($key) {
+ public function sign(string $key): string {
return base64_encode(sha1($key . static::GUID, true));
}
/**
* @param array $protocols
*/
- function setSupportedSubProtocols(array $protocols) {
+ public function setSupportedSubProtocols(array $protocols): void {
$this->_supportedSubProtocols = array_flip($protocols);
}
@@ -153,10 +159,10 @@ function setSupportedSubProtocols(array $protocols) {
* will not upgrade if a match between request and supported subprotocols
* @param boolean $enable
* @todo Consider extending this interface and moving this there.
- * The spec does says the server can fail for this reason, but
- * it is not a requirement. This is an implementation detail.
+ * The spec does say the server can fail for this reason, but
+ * it is not a requirement. This is an implementation detail.
*/
- function setStrictSubProtocolCheck($enable) {
- $this->_strictSubProtocols = (boolean)$enable;
+ public function setStrictSubProtocolCheck(bool $enable): void {
+ $this->_strictSubProtocols = $enable;
}
}
diff --git a/src/Messaging/CloseFrameChecker.php b/src/Messaging/CloseFrameChecker.php
index 3d800e5..78435c9 100644
--- a/src/Messaging/CloseFrameChecker.php
+++ b/src/Messaging/CloseFrameChecker.php
@@ -2,23 +2,19 @@
namespace Ratchet\RFC6455\Messaging;
class CloseFrameChecker {
- private $validCloseCodes = [];
+ private array $validCloseCodes = [
+ Frame::CLOSE_NORMAL,
+ Frame::CLOSE_GOING_AWAY,
+ Frame::CLOSE_PROTOCOL,
+ Frame::CLOSE_BAD_DATA,
+ Frame::CLOSE_BAD_PAYLOAD,
+ Frame::CLOSE_POLICY,
+ Frame::CLOSE_TOO_BIG,
+ Frame::CLOSE_MAND_EXT,
+ Frame::CLOSE_SRV_ERR,
+ ];
- public function __construct() {
- $this->validCloseCodes = [
- Frame::CLOSE_NORMAL,
- Frame::CLOSE_GOING_AWAY,
- Frame::CLOSE_PROTOCOL,
- Frame::CLOSE_BAD_DATA,
- Frame::CLOSE_BAD_PAYLOAD,
- Frame::CLOSE_POLICY,
- Frame::CLOSE_TOO_BIG,
- Frame::CLOSE_MAND_EXT,
- Frame::CLOSE_SRV_ERR,
- ];
- }
-
- public function __invoke($val) {
+ public function __invoke(int $val): bool {
return ($val >= 3000 && $val <= 4999) || in_array($val, $this->validCloseCodes);
}
}
diff --git a/src/Messaging/DataInterface.php b/src/Messaging/DataInterface.php
index 18aa2e3..1bdef36 100644
--- a/src/Messaging/DataInterface.php
+++ b/src/Messaging/DataInterface.php
@@ -1,34 +1,28 @@
$ufExceptionFactory
*/
- public function __construct($payload = null, $final = true, $opcode = 1, callable $ufExceptionFactory = null) {
- $this->ufeg = $ufExceptionFactory ?: static function($msg = '') {
- return new \UnderflowException($msg);
- };
+ public function __construct(?string $payload = null, bool $final = true, int $opcode = 1, ?callable $ufExceptionFactory = null) {
+ $this->ufeg = $ufExceptionFactory ?: static fn (string $msg = '') => new \UnderflowException($msg);
if (null === $payload) {
return;
@@ -103,7 +95,7 @@ public function __construct($payload = null, $final = true, $opcode = 1, callabl
/**
* {@inheritdoc}
*/
- public function isCoalesced() {
+ public function isCoalesced(): bool {
if (true === $this->isCoalesced) {
return true;
}
@@ -123,7 +115,7 @@ public function isCoalesced() {
/**
* {@inheritdoc}
*/
- public function addBuffer($buf) {
+ public function addBuffer(string $buf): void {
$len = strlen($buf);
$this->data .= $buf;
@@ -141,7 +133,7 @@ public function addBuffer($buf) {
/**
* {@inheritdoc}
*/
- public function isFinal() {
+ public function isFinal(): bool {
if (-1 === $this->firstByte) {
throw call_user_func($this->ufeg, 'Not enough bytes received to determine if this is the final frame in message');
}
@@ -149,7 +141,7 @@ public function isFinal() {
return 128 === ($this->firstByte & 128);
}
- public function setRsv1($value = true) {
+ public function setRsv1(bool $value = true): self {
if (strlen($this->data) == 0) {
throw new \UnderflowException("Cannot set Rsv1 because there is no data.");
}
@@ -170,7 +162,7 @@ public function setRsv1($value = true) {
* @return boolean
* @throws \UnderflowException
*/
- public function getRsv1() {
+ public function getRsv1(): bool {
if (-1 === $this->firstByte) {
throw call_user_func($this->ufeg, 'Not enough bytes received to determine reserved bit');
}
@@ -182,7 +174,7 @@ public function getRsv1() {
* @return boolean
* @throws \UnderflowException
*/
- public function getRsv2() {
+ public function getRsv2(): bool {
if (-1 === $this->firstByte) {
throw call_user_func($this->ufeg, 'Not enough bytes received to determine reserved bit');
}
@@ -194,7 +186,7 @@ public function getRsv2() {
* @return boolean
* @throws \UnderflowException
*/
- public function getRsv3() {
+ public function getRsv3(): bool {
if (-1 === $this->firstByte) {
throw call_user_func($this->ufeg, 'Not enough bytes received to determine reserved bit');
}
@@ -205,7 +197,7 @@ public function getRsv3() {
/**
* {@inheritdoc}
*/
- public function isMasked() {
+ public function isMasked(): bool {
if (-1 === $this->secondByte) {
throw call_user_func($this->ufeg, "Not enough bytes received ({$this->bytesRecvd}) to determine if mask is set");
}
@@ -216,7 +208,7 @@ public function isMasked() {
/**
* {@inheritdoc}
*/
- public function getMaskingKey() {
+ public function getMaskingKey(): string {
if (!$this->isMasked()) {
return '';
}
@@ -234,7 +226,7 @@ public function getMaskingKey() {
* Create a 4 byte masking key
* @return string
*/
- public function generateMaskingKey() {
+ public function generateMaskingKey(): string {
$mask = '';
for ($i = 1; $i <= static::MASK_LENGTH; $i++) {
@@ -251,7 +243,7 @@ public function generateMaskingKey() {
* @throws \InvalidArgumentException If there is an issue with the given masking key
* @return Frame
*/
- public function maskPayload($maskingKey = null) {
+ public function maskPayload(?string $maskingKey = null): self {
if (null === $maskingKey) {
$maskingKey = $this->generateMaskingKey();
}
@@ -282,7 +274,7 @@ public function maskPayload($maskingKey = null) {
* @throws \UnderFlowException If the frame is not coalesced
* @return Frame
*/
- public function unMaskPayload() {
+ public function unMaskPayload(): self {
if (!$this->isCoalesced()) {
throw call_user_func($this->ufeg, 'Frame must be coalesced before applying mask');
}
@@ -311,7 +303,7 @@ public function unMaskPayload() {
* @throws \UnderflowException If using the payload but enough hasn't been buffered
* @return string The masked string
*/
- public function applyMask($maskingKey, $payload = null) {
+ public function applyMask(string $maskingKey, ?string $payload = null): string {
if (null === $payload) {
if (!$this->isCoalesced()) {
throw call_user_func($this->ufeg, 'Frame must be coalesced to apply a mask');
@@ -332,7 +324,7 @@ public function applyMask($maskingKey, $payload = null) {
/**
* {@inheritdoc}
*/
- public function getOpcode() {
+ public function getOpcode(): int {
if (-1 === $this->firstByte) {
throw call_user_func($this->ufeg, 'Not enough bytes received to determine opcode');
}
@@ -345,7 +337,7 @@ public function getOpcode() {
* @return int
* @throws \UnderflowException If the buffer doesn't have enough data to determine this
*/
- protected function getFirstPayloadVal() {
+ protected function getFirstPayloadVal(): int {
if (-1 === $this->secondByte) {
throw call_user_func($this->ufeg, 'Not enough bytes received');
}
@@ -357,7 +349,7 @@ protected function getFirstPayloadVal() {
* @return int (7|23|71) Number of bits defined for the payload length in the fame
* @throws \UnderflowException
*/
- protected function getNumPayloadBits() {
+ protected function getNumPayloadBits(): int {
if (-1 === $this->secondByte) {
throw call_user_func($this->ufeg, 'Not enough bytes received');
}
@@ -387,14 +379,14 @@ protected function getNumPayloadBits() {
* This just returns the number of bytes used in the frame to describe the payload length (as opposed to # of bits)
* @see getNumPayloadBits
*/
- protected function getNumPayloadBytes() {
+ protected function getNumPayloadBytes(): int {
return (1 + $this->getNumPayloadBits()) / 8;
}
/**
* {@inheritdoc}
*/
- public function getPayloadLength() {
+ public function getPayloadLength(): int {
if ($this->defPayLen !== -1) {
return $this->defPayLen;
}
@@ -424,7 +416,7 @@ public function getPayloadLength() {
/**
* {@inheritdoc}
*/
- public function getPayloadStartingByte() {
+ public function getPayloadStartingByte(): int {
return 1 + $this->getNumPayloadBytes() + ($this->isMasked() ? static::MASK_LENGTH : 0);
}
@@ -432,7 +424,7 @@ public function getPayloadStartingByte() {
* {@inheritdoc}
* @todo Consider not checking mask, always returning the payload, masked or not
*/
- public function getPayload() {
+ public function getPayload(): string {
if (!$this->isCoalesced()) {
throw call_user_func($this->ufeg, 'Can not return partial message');
}
@@ -444,11 +436,11 @@ public function getPayload() {
* Get the raw contents of the frame
* @todo This is untested, make sure the substr is right - trying to return the frame w/o the overflow
*/
- public function getContents() {
+ public function getContents(): string {
return substr($this->data, 0, $this->getPayloadStartingByte() + $this->getPayloadLength());
}
- public function __toString() {
+ public function __toString(): string {
$payload = (string)substr($this->data, $this->getPayloadStartingByte(), $this->getPayloadLength());
if ($this->isMasked()) {
@@ -463,7 +455,7 @@ public function __toString() {
* This method will take the extra bytes off the end and return them
* @return string
*/
- public function extractOverflow() {
+ public function extractOverflow(): string {
if ($this->isCoalesced()) {
$endPoint = $this->getPayloadLength();
$endPoint += $this->getPayloadStartingByte();
diff --git a/src/Messaging/FrameInterface.php b/src/Messaging/FrameInterface.php
index dc24091..4d8fe68 100644
--- a/src/Messaging/FrameInterface.php
+++ b/src/Messaging/FrameInterface.php
@@ -6,33 +6,33 @@ interface FrameInterface extends DataInterface {
* Add incoming data to the frame from peer
* @param string
*/
- function addBuffer($buf);
+ public function addBuffer(string $buf): void;
/**
* Is this the final frame in a fragmented message?
* @return bool
*/
- function isFinal();
+ public function isFinal(): bool;
/**
* Is the payload masked?
* @return bool
*/
- function isMasked();
+ public function isMasked(): bool;
/**
* @return int
*/
- function getOpcode();
+ public function getOpcode(): int;
/**
* @return int
*/
- //function getReceivedPayloadLength();
+ //public function getReceivedPayloadLength(): int;
/**
* 32-big string
* @return string
*/
- function getMaskingKey();
+ public function getMaskingKey(): string;
}
diff --git a/src/Messaging/Message.php b/src/Messaging/Message.php
index aea2050..287b1fa 100644
--- a/src/Messaging/Message.php
+++ b/src/Messaging/Message.php
@@ -2,53 +2,43 @@
namespace Ratchet\RFC6455\Messaging;
class Message implements \IteratorAggregate, MessageInterface {
- /**
- * @var \SplDoublyLinkedList
- */
- private $_frames;
+ private \SplDoublyLinkedList $_frames;
- /**
- * @var int
- */
- private $len;
+ private int $len;
- #[\ReturnTypeWillChange]
public function __construct() {
$this->_frames = new \SplDoublyLinkedList;
$this->len = 0;
}
- #[\ReturnTypeWillChange]
- public function getIterator() {
+ public function getIterator(): \Traversable {
return $this->_frames;
}
/**
* {@inheritdoc}
*/
- #[\ReturnTypeWillChange]
- public function count() {
+ public function count(): int {
return count($this->_frames);
}
/**
* {@inheritdoc}
*/
- #[\ReturnTypeWillChange]
- public function isCoalesced() {
+ public function isCoalesced(): bool {
if (count($this->_frames) == 0) {
return false;
}
$last = $this->_frames->top();
- return ($last->isCoalesced() && $last->isFinal());
+ return $last->isCoalesced() && $last->isFinal();
}
/**
* {@inheritdoc}
*/
- public function addFrame(FrameInterface $fragment) {
+ public function addFrame(FrameInterface $fragment): MessageInterface {
$this->len += $fragment->getPayloadLength();
$this->_frames->push($fragment);
@@ -58,7 +48,7 @@ public function addFrame(FrameInterface $fragment) {
/**
* {@inheritdoc}
*/
- public function getOpcode() {
+ public function getOpcode(): int {
if (count($this->_frames) == 0) {
throw new \UnderflowException('No frames have been added to this message');
}
@@ -69,14 +59,14 @@ public function getOpcode() {
/**
* {@inheritdoc}
*/
- public function getPayloadLength() {
+ public function getPayloadLength(): int {
return $this->len;
}
/**
* {@inheritdoc}
*/
- public function getPayload() {
+ public function getPayload(): string {
if (!$this->isCoalesced()) {
throw new \UnderflowException('Message has not been put back together yet');
}
@@ -87,7 +77,7 @@ public function getPayload() {
/**
* {@inheritdoc}
*/
- public function getContents() {
+ public function getContents(): string {
if (!$this->isCoalesced()) {
throw new \UnderflowException("Message has not been put back together yet");
}
@@ -101,7 +91,7 @@ public function getContents() {
return $buffer;
}
- public function __toString() {
+ public function __toString(): string {
$buffer = '';
foreach ($this->_frames as $frame) {
@@ -114,7 +104,7 @@ public function __toString() {
/**
* @return boolean
*/
- public function isBinary() {
+ public function isBinary(): bool {
if ($this->_frames->isEmpty()) {
throw new \UnderflowException('Not enough data has been received to determine if message is binary');
}
@@ -125,7 +115,7 @@ public function isBinary() {
/**
* @return boolean
*/
- public function getRsv1() {
+ public function getRsv1(): bool {
if ($this->_frames->isEmpty()) {
return false;
//throw new \UnderflowException('Not enough data has been received to determine if message is binary');
diff --git a/src/Messaging/MessageBuffer.php b/src/Messaging/MessageBuffer.php
index 317a26a..1007c6a 100644
--- a/src/Messaging/MessageBuffer.php
+++ b/src/Messaging/MessageBuffer.php
@@ -4,25 +4,16 @@
use Ratchet\RFC6455\Handshake\PermessageDeflateOptions;
class MessageBuffer {
- /**
- * @var \Ratchet\RFC6455\Messaging\CloseFrameChecker
- */
- private $closeFrameChecker;
+ private CloseFrameChecker $closeFrameChecker;
/**
* @var callable
*/
private $exceptionFactory;
- /**
- * @var \Ratchet\RFC6455\Messaging\Message
- */
- private $messageBuffer;
+ private ?MessageInterface $messageBuffer = null;
- /**
- * @var \Ratchet\RFC6455\Messaging\Frame
- */
- private $frameBuffer;
+ private ?FrameInterface $frameBuffer = null;
/**
* @var callable
@@ -34,71 +25,55 @@ class MessageBuffer {
*/
private $onControl;
- /**
- * @var bool
- */
- private $checkForMask;
+ private bool $checkForMask;
/**
* @var callable
*/
private $sender;
- /**
- * @var string
- */
- private $leftovers;
+ private string $leftovers = '';
- /**
- * @var int
- */
- private $streamingMessageOpCode = -1;
+ private int $streamingMessageOpCode = -1;
- /**
- * @var PermessageDeflateOptions
- */
- private $permessageDeflateOptions;
+ private PermessageDeflateOptions $permessageDeflateOptions;
- /**
- * @var bool
- */
- private $deflateEnabled = false;
+ private bool $deflateEnabled;
- /**
- * @var int
- */
- private $maxMessagePayloadSize;
+ private int $maxMessagePayloadSize;
+
+ private int $maxFramePayloadSize;
+
+ private bool $compressedMessage = false;
/**
- * @var int
+ * @var resource|bool|null
*/
- private $maxFramePayloadSize;
+ private $inflator = null;
/**
- * @var bool
+ * @var resource|bool|null
*/
- private $compressedMessage;
+ private $deflator = null;
- function __construct(
+ public function __construct(
CloseFrameChecker $frameChecker,
callable $onMessage,
- callable $onControl = null,
- $expectMask = true,
- $exceptionFactory = null,
- $maxMessagePayloadSize = null, // null for default - zero for no limit
- $maxFramePayloadSize = null, // null for default - zero for no limit
- callable $sender = null,
- PermessageDeflateOptions $permessageDeflateOptions = null
+ ?callable $onControl = null,
+ bool $expectMask = true,
+ ?callable $exceptionFactory = null,
+ ?int $maxMessagePayloadSize = null, // null for default - zero for no limit
+ ?int $maxFramePayloadSize = null, // null for default - zero for no limit
+ ?callable $sender = null,
+ ?PermessageDeflateOptions $permessageDeflateOptions = null
) {
$this->closeFrameChecker = $frameChecker;
- $this->checkForMask = (bool)$expectMask;
+ $this->checkForMask = $expectMask;
- $this->exceptionFactory ?: $exceptionFactory = function($msg) {
- return new \UnderflowException($msg);
- };
+ $this->exceptionFactory = $exceptionFactory ?: static fn (string $msg) => new \UnderflowException($msg);
$this->onMessage = $onMessage;
- $this->onControl = $onControl ?: function() {};
+ $this->onControl = $onControl ?: static function (): void {};
$this->sender = $sender;
@@ -110,10 +85,6 @@ function __construct(
throw new \InvalidArgumentException('sender must be set when deflate is enabled');
}
- $this->compressedMessage = false;
-
- $this->leftovers = '';
-
$memory_limit_bytes = static::getMemoryLimit();
if ($maxMessagePayloadSize === null) {
@@ -123,18 +94,18 @@ function __construct(
$maxFramePayloadSize = (int)($memory_limit_bytes / 4);
}
- if (!is_int($maxFramePayloadSize) || $maxFramePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxFramePayloadSize < 0) { // this should be interesting on non-64 bit systems
+ if ($maxFramePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxFramePayloadSize < 0) { // this should be interesting on non-64 bit systems
throw new \InvalidArgumentException($maxFramePayloadSize . ' is not a valid maxFramePayloadSize');
}
$this->maxFramePayloadSize = $maxFramePayloadSize;
- if (!is_int($maxMessagePayloadSize) || $maxMessagePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxMessagePayloadSize < 0) {
+ if ($maxMessagePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxMessagePayloadSize < 0) {
throw new \InvalidArgumentException($maxMessagePayloadSize . 'is not a valid maxMessagePayloadSize');
}
$this->maxMessagePayloadSize = $maxMessagePayloadSize;
}
- public function onData($data) {
+ public function onData(string $data): void {
$data = $this->leftovers . $data;
$dataLen = strlen($data);
@@ -214,9 +185,9 @@ public function onData($data) {
/**
* @param string $data
- * @return null
+ * @return void
*/
- private function processData($data) {
+ private function processData(string $data): void {
$this->messageBuffer ?: $this->messageBuffer = $this->newMessage();
$this->frameBuffer ?: $this->frameBuffer = $this->newFrame();
@@ -235,7 +206,7 @@ private function processData($data) {
$onControl($this->frameBuffer, $this);
if (Frame::OP_CLOSE === $opcode) {
- return '';
+ return;
}
} else {
if ($this->messageBuffer->count() === 0 && $this->frameBuffer->getRsv1()) {
@@ -273,10 +244,10 @@ private function processData($data) {
/**
* Check a frame to be added to the current message buffer
- * @param \Ratchet\RFC6455\Messaging\FrameInterface|FrameInterface $frame
- * @return \Ratchet\RFC6455\Messaging\FrameInterface|FrameInterface
+ * @param FrameInterface $frame
+ * @return FrameInterface
*/
- public function frameCheck(FrameInterface $frame) {
+ public function frameCheck(FrameInterface $frame): FrameInterface {
if ((false !== $frame->getRsv1() && !$this->deflateEnabled) ||
false !== $frame->getRsv2() ||
false !== $frame->getRsv3()
@@ -323,13 +294,11 @@ public function frameCheck(FrameInterface $frame) {
}
return $frame;
- break;
case Frame::OP_PING:
case Frame::OP_PONG:
break;
default:
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid OP code');
- break;
}
return $frame;
@@ -348,7 +317,7 @@ public function frameCheck(FrameInterface $frame) {
/**
* Determine if a message is valid
- * @param \Ratchet\RFC6455\Messaging\MessageInterface
+ * @param MessageInterface
* @return bool|int true if valid - false if incomplete - int of recommended close code
*/
public function checkMessage(MessageInterface $message) {
@@ -361,7 +330,7 @@ public function checkMessage(MessageInterface $message) {
return true;
}
- private function checkUtf8($string) {
+ private function checkUtf8(string $string): bool {
if (extension_loaded('mbstring')) {
return mb_check_encoding($string, 'UTF-8');
}
@@ -370,27 +339,27 @@ private function checkUtf8($string) {
}
/**
- * @return \Ratchet\RFC6455\Messaging\MessageInterface
+ * @return MessageInterface
*/
- public function newMessage() {
+ public function newMessage(): MessageInterface {
return new Message;
}
/**
* @param string|null $payload
- * @param bool|null $final
- * @param int|null $opcode
- * @return \Ratchet\RFC6455\Messaging\FrameInterface
+ * @param bool $final
+ * @param int $opcode
+ * @return FrameInterface
*/
- public function newFrame($payload = null, $final = null, $opcode = null) {
+ public function newFrame(?string $payload = null, bool $final = true, int $opcode = Frame::OP_TEXT): FrameInterface {
return new Frame($payload, $final, $opcode, $this->exceptionFactory);
}
- public function newCloseFrame($code, $reason = '') {
+ public function newCloseFrame(int $code, string $reason = ''): FrameInterface {
return $this->newFrame(pack('n', $code) . $reason, true, Frame::OP_CLOSE);
}
- public function sendFrame(Frame $frame) {
+ public function sendFrame(FrameInterface $frame): void {
if ($this->sender === null) {
throw new \Exception('To send frames using the MessageBuffer, sender must be set.');
}
@@ -408,7 +377,7 @@ public function sendFrame(Frame $frame) {
$sender($frame->getContents());
}
- public function sendMessage($messagePayload, $final = true, $isBinary = false) {
+ public function sendMessage(string $messagePayload, bool $final = true, bool $isBinary = false): void {
$opCode = $isBinary ? Frame::OP_BINARY : Frame::OP_TEXT;
if ($this->streamingMessageOpCode === -1) {
$this->streamingMessageOpCode = $opCode;
@@ -431,29 +400,27 @@ public function sendMessage($messagePayload, $final = true, $isBinary = false) {
}
}
- private $inflator;
-
- private function getDeflateNoContextTakeover() {
+ private function getDeflateNoContextTakeover(): ?bool {
return $this->checkForMask ?
$this->permessageDeflateOptions->getServerNoContextTakeover() :
$this->permessageDeflateOptions->getClientNoContextTakeover();
}
- private function getDeflateWindowBits() {
+ private function getDeflateWindowBits(): int {
return $this->checkForMask ? $this->permessageDeflateOptions->getServerMaxWindowBits() : $this->permessageDeflateOptions->getClientMaxWindowBits();
}
- private function getInflateNoContextTakeover() {
+ private function getInflateNoContextTakeover(): ?bool {
return $this->checkForMask ?
$this->permessageDeflateOptions->getClientNoContextTakeover() :
$this->permessageDeflateOptions->getServerNoContextTakeover();
}
- private function getInflateWindowBits() {
+ private function getInflateWindowBits(): int {
return $this->checkForMask ? $this->permessageDeflateOptions->getClientMaxWindowBits() : $this->permessageDeflateOptions->getServerMaxWindowBits();
}
- private function inflateFrame(Frame $frame) {
+ private function inflateFrame(FrameInterface $frame): Frame {
if ($this->inflator === null) {
$this->inflator = inflate_init(
ZLIB_ENCODING_RAW,
@@ -480,16 +447,14 @@ private function inflateFrame(Frame $frame) {
);
}
- private $deflator;
-
- private function deflateFrame(Frame $frame)
+ private function deflateFrame(FrameInterface $frame): FrameInterface
{
if ($frame->getRsv1()) {
return $frame; // frame is already deflated
}
if ($this->deflator === null) {
- $bits = (int)$this->getDeflateWindowBits();
+ $bits = $this->getDeflateWindowBits();
if ($bits === 8) {
$bits = 9;
}
@@ -549,7 +514,7 @@ private function deflateFrame(Frame $frame)
* @param null|string $memory_limit
* @return int
*/
- private static function getMemoryLimit($memory_limit = null) {
+ private static function getMemoryLimit(?string $memory_limit = null): int {
$memory_limit = $memory_limit === null ? \trim(\ini_get('memory_limit')) : $memory_limit;
$memory_limit_bytes = 0;
if ($memory_limit !== '') {
diff --git a/src/Messaging/MessageInterface.php b/src/Messaging/MessageInterface.php
index fd7212e..5244b81 100644
--- a/src/Messaging/MessageInterface.php
+++ b/src/Messaging/MessageInterface.php
@@ -6,15 +6,15 @@ interface MessageInterface extends DataInterface, \Traversable, \Countable {
* @param FrameInterface $fragment
* @return MessageInterface
*/
- function addFrame(FrameInterface $fragment);
+ public function addFrame(FrameInterface $fragment): self;
/**
* @return int
*/
- function getOpcode();
+ public function getOpcode(): int;
/**
* @return bool
*/
- function isBinary();
+ public function isBinary(): bool;
}
diff --git a/tests/AbResultsTest.php b/tests/AbResultsTest.php
index 9bd799e..6ab6aac 100644
--- a/tests/AbResultsTest.php
+++ b/tests/AbResultsTest.php
@@ -3,10 +3,13 @@
namespace Ratchet\RFC6455\Test;
use PHPUnit\Framework\TestCase;
+/**
+ * @coversNothing
+ */
class AbResultsTest extends TestCase {
- private function verifyAutobahnResults($fileName) {
+ private function verifyAutobahnResults(string $fileName): void {
if (!file_exists($fileName)) {
- return $this->markTestSkipped('Autobahn TestSuite results not found');
+ $this->markTestSkipped('Autobahn TestSuite results not found');
}
$resultsJson = file_get_contents($fileName);
@@ -22,11 +25,11 @@ private function verifyAutobahnResults($fileName) {
}
}
- public function testAutobahnClientResults() {
+ public function testAutobahnClientResults(): void {
$this->verifyAutobahnResults(__DIR__ . '/ab/reports/clients/index.json');
}
- public function testAutobahnServerResults() {
+ public function testAutobahnServerResults(): void {
$this->verifyAutobahnResults(__DIR__ . '/ab/reports/servers/index.json');
}
}
diff --git a/tests/ab/clientRunner.php b/tests/ab/clientRunner.php
index c6becbc..3bd8113 100644
--- a/tests/ab/clientRunner.php
+++ b/tests/ab/clientRunner.php
@@ -4,18 +4,21 @@
use GuzzleHttp\Psr7\Uri;
use Ratchet\RFC6455\Handshake\InvalidPermessageDeflateOptionsException;
use Ratchet\RFC6455\Handshake\PermessageDeflateOptions;
+use Ratchet\RFC6455\Messaging\FrameInterface;
use Ratchet\RFC6455\Messaging\MessageBuffer;
use Ratchet\RFC6455\Handshake\ClientNegotiator;
use Ratchet\RFC6455\Messaging\CloseFrameChecker;
use Ratchet\RFC6455\Messaging\MessageInterface;
use React\Promise\Deferred;
use Ratchet\RFC6455\Messaging\Frame;
+use React\Promise\PromiseInterface;
+use GuzzleHttp\Psr7\HttpFactory;
use React\Socket\ConnectionInterface;
use React\Socket\Connector;
require __DIR__ . '/../bootstrap.php';
-define('AGENT', 'RatchetRFC/0.3');
+define('AGENT', 'RatchetRFC/0.4');
$testServer = $argc > 1 ? $argv[1] : "127.0.0.1";
@@ -23,23 +26,21 @@
$connector = new Connector($loop);
-function echoStreamerFactory($conn, $permessageDeflateOptions = null)
+function echoStreamerFactory(ConnectionInterface $conn, ?PermessageDeflateOptions $permessageDeflateOptions = null): MessageBuffer
{
$permessageDeflateOptions = $permessageDeflateOptions ?: PermessageDeflateOptions::createDisabled();
- return new \Ratchet\RFC6455\Messaging\MessageBuffer(
- new \Ratchet\RFC6455\Messaging\CloseFrameChecker,
- function (\Ratchet\RFC6455\Messaging\MessageInterface $msg, MessageBuffer $messageBuffer) use ($conn) {
+ return new MessageBuffer(
+ new CloseFrameChecker,
+ static function (MessageInterface $msg, MessageBuffer $messageBuffer) use ($conn): void {
$messageBuffer->sendMessage($msg->getPayload(), true, $msg->isBinary());
},
- function (\Ratchet\RFC6455\Messaging\FrameInterface $frame, MessageBuffer $messageBuffer) use ($conn) {
+ static function (FrameInterface $frame, MessageBuffer $messageBuffer) use ($conn) {
switch ($frame->getOpcode()) {
case Frame::OP_PING:
return $conn->write((new Frame($frame->getPayload(), true, Frame::OP_PONG))->maskPayload()->getContents());
- break;
case Frame::OP_CLOSE:
return $conn->end((new Frame($frame->getPayload(), true, Frame::OP_CLOSE))->maskPayload()->getContents());
- break;
}
},
false,
@@ -51,14 +52,14 @@ function (\Ratchet\RFC6455\Messaging\FrameInterface $frame, MessageBuffer $messa
);
}
-function getTestCases() {
+function getTestCases(): PromiseInterface {
global $testServer;
global $connector;
$deferred = new Deferred();
- $connector->connect($testServer . ':9002')->then(function (ConnectionInterface $connection) use ($deferred, $testServer) {
- $cn = new ClientNegotiator();
+ $connector->connect($testServer . ':9002')->then(static function (ConnectionInterface $connection) use ($deferred, $testServer): void {
+ $cn = new ClientNegotiator(new HttpFactory());
$cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002/getCaseCount'));
$rawResponse = "";
@@ -67,7 +68,7 @@ function getTestCases() {
/** @var MessageBuffer $ms */
$ms = null;
- $connection->on('data', function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest) {
+ $connection->on('data', static function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest): void {
if ($response === null) {
$rawResponse .= $data;
$pos = strpos($rawResponse, "\r\n\r\n");
@@ -82,7 +83,7 @@ function getTestCases() {
} else {
$ms = new MessageBuffer(
new CloseFrameChecker,
- function (MessageInterface $msg) use ($deferred, $connection) {
+ static function (MessageInterface $msg) use ($deferred, $connection): void {
$deferred->resolve($msg->getPayload());
$connection->close();
},
@@ -91,7 +92,7 @@ function (MessageInterface $msg) use ($deferred, $connection) {
null,
null,
null,
- function () {}
+ static function (): void {}
);
}
}
@@ -109,10 +110,11 @@ function () {}
return $deferred->promise();
}
-$cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator(
+$cn = new ClientNegotiator(
+ new HttpFactory(),
PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null);
-function runTest($case)
+function runTest(int $case)
{
global $connector;
global $testServer;
@@ -122,8 +124,9 @@ function runTest($case)
$deferred = new Deferred();
- $connector->connect($testServer . ':9002')->then(function (ConnectionInterface $connection) use ($deferred, $casePath, $case, $testServer) {
+ $connector->connect($testServer . ':9002')->then(static function (ConnectionInterface $connection) use ($deferred, $casePath, $case, $testServer): void {
$cn = new ClientNegotiator(
+ new HttpFactory(),
PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null);
$cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002' . $casePath));
@@ -132,7 +135,7 @@ function runTest($case)
$ms = null;
- $connection->on('data', function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest) {
+ $connection->on('data', static function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest): void {
if ($response === null) {
$rawResponse .= $data;
$pos = strpos($rawResponse, "\r\n\r\n");
@@ -165,8 +168,8 @@ function runTest($case)
}
});
- $connection->on('close', function () use ($deferred) {
- $deferred->resolve();
+ $connection->on('close', static function () use ($deferred): void {
+ $deferred->resolve(null);
});
$connection->write(Message::toString($cnRequest));
@@ -175,17 +178,17 @@ function runTest($case)
return $deferred->promise();
}
-function createReport() {
+function createReport(): PromiseInterface {
global $connector;
global $testServer;
$deferred = new Deferred();
- $connector->connect($testServer . ':9002')->then(function (ConnectionInterface $connection) use ($deferred, $testServer) {
+ $connector->connect($testServer . ':9002')->then(static function (ConnectionInterface $connection) use ($deferred, $testServer): void {
// $reportPath = "/updateReports?agent=" . AGENT . "&shutdownOnComplete=true";
// we will stop it using docker now instead of just shutting down
$reportPath = "/updateReports?agent=" . AGENT;
- $cn = new ClientNegotiator();
+ $cn = new ClientNegotiator(new HttpFactory());
$cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002' . $reportPath));
$rawResponse = "";
@@ -194,7 +197,7 @@ function createReport() {
/** @var MessageBuffer $ms */
$ms = null;
- $connection->on('data', function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest) {
+ $connection->on('data', static function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest): void {
if ($response === null) {
$rawResponse .= $data;
$pos = strpos($rawResponse, "\r\n\r\n");
@@ -209,7 +212,7 @@ function createReport() {
} else {
$ms = new MessageBuffer(
new CloseFrameChecker,
- function (MessageInterface $msg) use ($deferred, $connection) {
+ static function (MessageInterface $msg) use ($deferred, $connection): void {
$deferred->resolve($msg->getPayload());
$connection->close();
},
@@ -218,7 +221,7 @@ function (MessageInterface $msg) use ($deferred, $connection) {
null,
null,
null,
- function () {}
+ static function (): void {}
);
}
}
@@ -242,16 +245,16 @@ function () {}
getTestCases()->then(function ($count) use ($loop) {
$allDeferred = new Deferred();
- $runNextCase = function () use (&$i, &$runNextCase, $count, $allDeferred) {
+ $runNextCase = static function () use (&$i, &$runNextCase, $count, $allDeferred): void {
$i++;
if ($i > $count) {
- $allDeferred->resolve();
+ $allDeferred->resolve(null);
return;
}
echo "Running test $i/$count...";
$startTime = microtime(true);
runTest($i)
- ->then(function () use ($startTime) {
+ ->then(static function () use ($startTime): void {
echo " completed " . round((microtime(true) - $startTime) * 1000) . " ms\n";
})
->then($runNextCase);
@@ -260,7 +263,7 @@ function () {}
$i = 0;
$runNextCase();
- $allDeferred->promise()->then(function () {
+ $allDeferred->promise()->then(static function (): void {
createReport();
});
});
diff --git a/tests/ab/fuzzingclient.json b/tests/ab/fuzzingclient.json
index d410be3..50171ba 100644
--- a/tests/ab/fuzzingclient.json
+++ b/tests/ab/fuzzingclient.json
@@ -4,7 +4,7 @@
}
, "outdir": "/reports/servers"
, "servers": [{
- "agent": "RatchetRFC/0.3"
+ "agent": "RatchetRFC/0.4"
, "url": "ws://host.ratchet.internal:9001"
, "options": {"version": 18}
}]
diff --git a/tests/ab/fuzzingclient_skip_deflate.json b/tests/ab/fuzzingclient_skip_deflate.json
index b1fddbe..b7314ec 100644
--- a/tests/ab/fuzzingclient_skip_deflate.json
+++ b/tests/ab/fuzzingclient_skip_deflate.json
@@ -4,7 +4,7 @@
}
, "outdir": "/reports/servers"
, "servers": [{
- "agent": "RatchetRFC/0.3"
+ "agent": "RatchetRFC/0.4"
, "url": "ws://host.ratchet.internal:9001"
, "options": {"version": 18}
}]
diff --git a/tests/ab/run_ab_tests.sh b/tests/ab/run_ab_tests.sh
old mode 100644
new mode 100755
diff --git a/tests/ab/startServer.php b/tests/ab/startServer.php
index 7c169c6..0f6fc44 100644
--- a/tests/ab/startServer.php
+++ b/tests/ab/startServer.php
@@ -3,10 +3,14 @@
use GuzzleHttp\Psr7\Message;
use GuzzleHttp\Psr7\Response;
use Ratchet\RFC6455\Handshake\PermessageDeflateOptions;
+use Ratchet\RFC6455\Handshake\RequestVerifier;
+use Ratchet\RFC6455\Handshake\ServerNegotiator;
+use Ratchet\RFC6455\Messaging\CloseFrameChecker;
use Ratchet\RFC6455\Messaging\MessageBuffer;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\RFC6455\Messaging\FrameInterface;
use Ratchet\RFC6455\Messaging\Frame;
+use GuzzleHttp\Psr7\HttpFactory;
require_once __DIR__ . "/../bootstrap.php";
@@ -14,17 +18,22 @@
$socket = new \React\Socket\Server('0.0.0.0:9001', $loop);
-$closeFrameChecker = new \Ratchet\RFC6455\Messaging\CloseFrameChecker;
-$negotiator = new \Ratchet\RFC6455\Handshake\ServerNegotiator(new \Ratchet\RFC6455\Handshake\RequestVerifier, PermessageDeflateOptions::permessageDeflateSupported());
+$closeFrameChecker = new CloseFrameChecker;
+
+$negotiator = new ServerNegotiator(
+ new RequestVerifier,
+ new HttpFactory(),
+ PermessageDeflateOptions::permessageDeflateSupported()
+);
$uException = new \UnderflowException;
-$socket->on('connection', function (React\Socket\ConnectionInterface $connection) use ($negotiator, $closeFrameChecker, $uException, $socket) {
+$socket->on('connection', static function (React\Socket\ConnectionInterface $connection) use ($negotiator, $closeFrameChecker, $uException, $socket): void {
$headerComplete = false;
$buffer = '';
$parser = null;
- $connection->on('data', function ($data) use ($connection, &$parser, &$headerComplete, &$buffer, $negotiator, $closeFrameChecker, $uException, $socket) {
+ $connection->on('data', static function ($data) use ($connection, &$parser, &$headerComplete, &$buffer, $negotiator, $closeFrameChecker, $uException, $socket): void {
if ($headerComplete) {
$parser->onData($data);
return;
@@ -58,10 +67,10 @@
// we support any valid permessage deflate
$deflateOptions = PermessageDeflateOptions::fromRequestOrResponse($psrRequest)[0];
- $parser = new \Ratchet\RFC6455\Messaging\MessageBuffer($closeFrameChecker,
- function (MessageInterface $message, MessageBuffer $messageBuffer) {
+ $parser = new MessageBuffer($closeFrameChecker,
+ static function (MessageInterface $message, MessageBuffer $messageBuffer): void {
$messageBuffer->sendMessage($message->getPayload(), true, $message->isBinary());
- }, function (FrameInterface $frame) use ($connection, &$parser) {
+ }, static function (FrameInterface $frame) use ($connection, &$parser): void {
switch ($frame->getOpCode()) {
case Frame::OP_CLOSE:
$connection->end($frame->getContents());
@@ -70,9 +79,7 @@ function (MessageInterface $message, MessageBuffer $messageBuffer) {
$connection->write($parser->newFrame($frame->getPayload(), true, Frame::OP_PONG)->getContents());
break;
}
- }, true, function () use ($uException) {
- return $uException;
- },
+ }, true, static fn (): \Exception => $uException,
null,
null,
[$connection, 'write'],
diff --git a/tests/unit/Handshake/PermessageDeflateOptionsTest.php b/tests/unit/Handshake/PermessageDeflateOptionsTest.php
index 11d3739..267ca88 100644
--- a/tests/unit/Handshake/PermessageDeflateOptionsTest.php
+++ b/tests/unit/Handshake/PermessageDeflateOptionsTest.php
@@ -5,9 +5,12 @@
use Ratchet\RFC6455\Handshake\PermessageDeflateOptions;
use PHPUnit\Framework\TestCase;
+/**
+ * @covers Ratchet\RFC6455\Handshake\PermessageDeflateOptions
+ */
class PermessageDeflateOptionsTest extends TestCase
{
- public static function versionSupportProvider() {
+ public static function versionSupportProvider(): array {
return [
['7.0.17', false],
['7.0.18', true],
@@ -24,7 +27,7 @@ public static function versionSupportProvider() {
* @requires function deflate_init
* @dataProvider versionSupportProvider
*/
- public function testVersionSupport($version, $supported) {
+ public function testVersionSupport(string $version, bool $supported): void {
$this->assertEquals($supported, PermessageDeflateOptions::permessageDeflateSupported($version));
}
-}
\ No newline at end of file
+}
diff --git a/tests/unit/Handshake/RequestVerifierTest.php b/tests/unit/Handshake/RequestVerifierTest.php
index 5ba26b6..6573582 100644
--- a/tests/unit/Handshake/RequestVerifierTest.php
+++ b/tests/unit/Handshake/RequestVerifierTest.php
@@ -14,11 +14,11 @@ class RequestVerifierTest extends TestCase {
*/
protected $_v;
- public function setUp() {
+ protected function setUp(): void {
$this->_v = new RequestVerifier();
}
- public static function methodProvider() {
+ public static function methodProvider(): array {
return array(
array(true, 'GET'),
array(true, 'get'),
@@ -32,11 +32,11 @@ public static function methodProvider() {
/**
* @dataProvider methodProvider
*/
- public function testMethodMustBeGet($result, $in) {
+ public function testMethodMustBeGet(bool $result, string $in): void {
$this->assertEquals($result, $this->_v->verifyMethod($in));
}
- public static function httpVersionProvider() {
+ public static function httpVersionProvider(): array {
return array(
array(true, 1.1),
array(true, '1.1'),
@@ -56,11 +56,11 @@ public static function httpVersionProvider() {
/**
* @dataProvider httpVersionProvider
*/
- public function testHttpVersionIsAtLeast1Point1($expected, $in) {
+ public function testHttpVersionIsAtLeast1Point1(bool $expected, $in): void {
$this->assertEquals($expected, $this->_v->verifyHTTPVersion($in));
}
- public static function uRIProvider() {
+ public static function uRIProvider(): array {
return array(
array(true, '/chat'),
array(true, '/hello/world?key=val'),
@@ -74,11 +74,11 @@ public static function uRIProvider() {
/**
* @dataProvider URIProvider
*/
- public function testRequestUri($expected, $in) {
+ public function testRequestUri(bool $expected, string $in): void {
$this->assertEquals($expected, $this->_v->verifyRequestURI($in));
}
- public static function hostProvider() {
+ public static function hostProvider(): array {
return array(
array(true, ['server.example.com']),
array(false, [])
@@ -88,11 +88,11 @@ public static function hostProvider() {
/**
* @dataProvider HostProvider
*/
- public function testVerifyHostIsSet($expected, $in) {
+ public function testVerifyHostIsSet(bool $expected, array $in): void {
$this->assertEquals($expected, $this->_v->verifyHost($in));
}
- public static function upgradeProvider() {
+ public static function upgradeProvider(): array {
return array(
array(true, ['websocket']),
array(true, ['Websocket']),
@@ -105,11 +105,11 @@ public static function upgradeProvider() {
/**
* @dataProvider upgradeProvider
*/
- public function testVerifyUpgradeIsWebSocket($expected, $val) {
+ public function testVerifyUpgradeIsWebSocket(bool $expected, array $val): void {
$this->assertEquals($expected, $this->_v->verifyUpgradeRequest($val));
}
- public static function connectionProvider() {
+ public static function connectionProvider(): array {
return array(
array(true, ['Upgrade']),
array(true, ['upgrade']),
@@ -129,11 +129,11 @@ public static function connectionProvider() {
/**
* @dataProvider connectionProvider
*/
- public function testConnectionHeaderVerification($expected, $val) {
+ public function testConnectionHeaderVerification(bool $expected, array $val): void {
$this->assertEquals($expected, $this->_v->verifyConnection($val));
}
- public static function keyProvider() {
+ public static function keyProvider(): array {
return array(
array(true, ['hkfa1L7uwN6DCo4IS3iWAw==']),
array(true, ['765vVoQpKSGJwPzJIMM2GA==']),
@@ -154,11 +154,11 @@ public static function keyProvider() {
/**
* @dataProvider keyProvider
*/
- public function testKeyIsBase64Encoded16BitNonce($expected, $val) {
+ public function testKeyIsBase64Encoded16BitNonce(bool $expected, array $val): void {
$this->assertEquals($expected, $this->_v->verifyKey($val));
}
- public static function versionProvider() {
+ public static function versionProvider(): array {
return array(
array(true, [13]),
array(true, ['13']),
@@ -174,7 +174,7 @@ public static function versionProvider() {
/**
* @dataProvider versionProvider
*/
- public function testVersionEquals13($expected, $in) {
+ public function testVersionEquals13(bool $expected, array $in): void {
$this->assertEquals($expected, $this->_v->verifyVersion($in));
}
-}
\ No newline at end of file
+}
diff --git a/tests/unit/Handshake/ResponseVerifierTest.php b/tests/unit/Handshake/ResponseVerifierTest.php
index 9a1459b..1a50b53 100644
--- a/tests/unit/Handshake/ResponseVerifierTest.php
+++ b/tests/unit/Handshake/ResponseVerifierTest.php
@@ -14,11 +14,11 @@ class ResponseVerifierTest extends TestCase {
*/
protected $_v;
- public function setUp() {
+ protected function setUp(): void {
$this->_v = new ResponseVerifier;
}
- public static function subProtocolsProvider() {
+ public static function subProtocolsProvider(): array {
return [
[true, ['a'], ['a']]
, [true, ['c', 'd', 'a'], ['a']]
@@ -33,7 +33,7 @@ public static function subProtocolsProvider() {
/**
* @dataProvider subProtocolsProvider
*/
- public function testVerifySubProtocol($expected, $request, $response) {
+ public function testVerifySubProtocol(bool $expected, array $request, array $response): void {
$this->assertEquals($expected, $this->_v->verifySubProtocol($request, $response));
}
}
diff --git a/tests/unit/Handshake/ServerNegotiatorTest.php b/tests/unit/Handshake/ServerNegotiatorTest.php
index 720bdf9..382d96a 100644
--- a/tests/unit/Handshake/ServerNegotiatorTest.php
+++ b/tests/unit/Handshake/ServerNegotiatorTest.php
@@ -3,14 +3,18 @@
namespace Ratchet\RFC6455\Test\Unit\Handshake;
use GuzzleHttp\Psr7\Message;
+use GuzzleHttp\Psr7\HttpFactory;
use Ratchet\RFC6455\Handshake\RequestVerifier;
use Ratchet\RFC6455\Handshake\ServerNegotiator;
use PHPUnit\Framework\TestCase;
+/**
+ * @covers Ratchet\RFC6455\Handshake\ServerNegotiator
+ */
class ServerNegotiatorTest extends TestCase
{
- public function testNoUpgradeRequested() {
- $negotiator = new ServerNegotiator(new RequestVerifier());
+ public function testNoUpgradeRequested(): void {
+ $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory());
$requestText = 'GET / HTTP/1.1
Host: 127.0.0.1:6789
@@ -37,8 +41,8 @@ public function testNoUpgradeRequested() {
$this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version'));
}
- public function testNoConnectionUpgradeRequested() {
- $negotiator = new ServerNegotiator(new RequestVerifier());
+ public function testNoConnectionUpgradeRequested(): void {
+ $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory());
$requestText = 'GET / HTTP/1.1
Host: 127.0.0.1:6789
@@ -63,8 +67,8 @@ public function testNoConnectionUpgradeRequested() {
$this->assertEquals('Connection Upgrade MUST be requested', $response->getReasonPhrase());
}
- public function testInvalidSecWebsocketKey() {
- $negotiator = new ServerNegotiator(new RequestVerifier());
+ public function testInvalidSecWebsocketKey(): void {
+ $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory());
$requestText = 'GET / HTTP/1.1
Host: 127.0.0.1:6789
@@ -90,8 +94,8 @@ public function testInvalidSecWebsocketKey() {
$this->assertEquals('Invalid Sec-WebSocket-Key', $response->getReasonPhrase());
}
- public function testInvalidSecWebsocketVersion() {
- $negotiator = new ServerNegotiator(new RequestVerifier());
+ public function testInvalidSecWebsocketVersion(): void {
+ $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory());
$requestText = 'GET / HTTP/1.1
Host: 127.0.0.1:6789
@@ -120,8 +124,8 @@ public function testInvalidSecWebsocketVersion() {
$this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version'));
}
- public function testBadSubprotocolResponse() {
- $negotiator = new ServerNegotiator(new RequestVerifier());
+ public function testBadSubprotocolResponse(): void {
+ $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory());
$negotiator->setStrictSubProtocolCheck(true);
$negotiator->setSupportedSubProtocols([]);
@@ -154,8 +158,8 @@ public function testBadSubprotocolResponse() {
$this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version'));
}
- public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn() {
- $negotiator = new ServerNegotiator(new RequestVerifier());
+ public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn(): void {
+ $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory());
$negotiator->setStrictSubProtocolCheck(false);
$negotiator->setSupportedSubProtocols(['someproto']);
@@ -187,9 +191,9 @@ public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn() {
$this->assertFalse($response->hasHeader('Sec-WebSocket-Protocol'));
}
- public function testSuggestsAppropriateSubprotocol()
+ public function testSuggestsAppropriateSubprotocol(): void
{
- $negotiator = new ServerNegotiator(new RequestVerifier());
+ $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory());
$negotiator->setStrictSubProtocolCheck(true);
$negotiator->setSupportedSubProtocols(['someproto']);
diff --git a/tests/unit/Messaging/FrameTest.php b/tests/unit/Messaging/FrameTest.php
index 54a4599..ced09b8 100644
--- a/tests/unit/Messaging/FrameTest.php
+++ b/tests/unit/Messaging/FrameTest.php
@@ -20,7 +20,7 @@ class FrameTest extends TestCase {
protected $_packer;
- public function setUp() {
+ protected function setUp(): void {
$this->_frame = new Frame;
}
@@ -29,7 +29,7 @@ public function setUp() {
* @param string of 1's and 0's
* @return string
*/
- public static function encode($in) {
+ public static function encode(string $in): string {
if (strlen($in) > 8) {
$out = '';
while (strlen($in) >= 8) {
@@ -46,7 +46,7 @@ public static function encode($in) {
* param string The UTF8 message
* param string The WebSocket framed message, then base64_encoded
*/
- public static function UnframeMessageProvider() {
+ public static function UnframeMessageProvider(): array {
return array(
array('Hello World!', 'gYydAIfa1WXrtvIg0LXvbOP7'),
array('!@#$%^&*()-=_+[]{}\|/.,<>`~', 'gZv+h96r38f9j9vZ+IHWrvOWoayF9oX6gtfRqfKXwOeg'),
@@ -58,7 +58,7 @@ public static function UnframeMessageProvider() {
);
}
- public static function underflowProvider() {
+ public static function underflowProvider(): array {
return array(
array('isFinal', ''),
array('getRsv1', ''),
@@ -75,19 +75,9 @@ public static function underflowProvider() {
/**
* @dataProvider underflowProvider
- *
- * @covers Ratchet\RFC6455\Messaging\Frame::isFinal
- * @covers Ratchet\RFC6455\Messaging\Frame::getRsv1
- * @covers Ratchet\RFC6455\Messaging\Frame::getRsv2
- * @covers Ratchet\RFC6455\Messaging\Frame::getRsv3
- * @covers Ratchet\RFC6455\Messaging\Frame::getOpcode
- * @covers Ratchet\RFC6455\Messaging\Frame::isMasked
- * @covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
- * @covers Ratchet\RFC6455\Messaging\Frame::getMaskingKey
- * @covers Ratchet\RFC6455\Messaging\Frame::getPayload
*/
- public function testUnderflowExceptionFromAllTheMethodsMimickingBuffering($method, $bin) {
- $this->setExpectedException('\UnderflowException');
+ public function testUnderflowExceptionFromAllTheMethodsMimickingBuffering(string $method, string $bin): void {
+ $this->expectException(\UnderflowException::class);
if (!empty($bin)) {
$this->_frame->addBuffer(static::encode($bin));
}
@@ -100,7 +90,7 @@ public function testUnderflowExceptionFromAllTheMethodsMimickingBuffering($metho
* param int Given, what is the expected opcode
* param string of 0|1 Each character represents a bit in the byte
*/
- public static function firstByteProvider() {
+ public static function firstByteProvider(): array {
return array(
array(false, false, false, true, 8, '00011000'),
array(true, false, true, false, 10, '10101010'),
@@ -113,20 +103,16 @@ public static function firstByteProvider() {
/**
* @dataProvider firstByteProvider
- * covers Ratchet\RFC6455\Messaging\Frame::isFinal
*/
- public function testFinCodeFromBits($fin, $rsv1, $rsv2, $rsv3, $opcode, $bin) {
+ public function testFinCodeFromBits(bool $fin, bool $rsv1, bool $rsv2, bool $rsv3, int $opcode, string $bin): void {
$this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($fin, $this->_frame->isFinal());
}
/**
* @dataProvider firstByteProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getRsv1
- * covers Ratchet\RFC6455\Messaging\Frame::getRsv2
- * covers Ratchet\RFC6455\Messaging\Frame::getRsv3
*/
- public function testGetRsvFromBits($fin, $rsv1, $rsv2, $rsv3, $opcode, $bin) {
+ public function testGetRsvFromBits(bool $fin, bool $rsv1, bool $rsv2, bool $rsv3, int $opcode, string $bin): void {
$this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($rsv1, $this->_frame->getRsv1());
$this->assertEquals($rsv2, $this->_frame->getRsv2());
@@ -135,32 +121,29 @@ public function testGetRsvFromBits($fin, $rsv1, $rsv2, $rsv3, $opcode, $bin) {
/**
* @dataProvider firstByteProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getOpcode
*/
- public function testOpcodeFromBits($fin, $rsv1, $rsv2, $rsv3, $opcode, $bin) {
+ public function testOpcodeFromBits(bool $fin, bool $rsv1, bool $rsv2, bool $rsv3, int $opcode, string $bin): void {
$this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($opcode, $this->_frame->getOpcode());
}
/**
* @dataProvider UnframeMessageProvider
- * covers Ratchet\RFC6455\Messaging\Frame::isFinal
*/
- public function testFinCodeFromFullMessage($msg, $encoded) {
+ public function testFinCodeFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded));
$this->assertTrue($this->_frame->isFinal());
}
/**
* @dataProvider UnframeMessageProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getOpcode
*/
- public function testOpcodeFromFullMessage($msg, $encoded) {
+ public function testOpcodeFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded));
$this->assertEquals(1, $this->_frame->getOpcode());
}
- public static function payloadLengthDescriptionProvider() {
+ public static function payloadLengthDescriptionProvider(): array {
return array(
array(7, '01110101'),
array(7, '01111101'),
@@ -173,10 +156,8 @@ public static function payloadLengthDescriptionProvider() {
/**
* @dataProvider payloadLengthDescriptionProvider
- * covers Ratchet\RFC6455\Messaging\Frame::addBuffer
- * covers Ratchet\RFC6455\Messaging\Frame::getFirstPayloadVal
*/
- public function testFirstPayloadDesignationValue($bits, $bin) {
+ public function testFirstPayloadDesignationValue(int $bits, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin));
$ref = new \ReflectionClass($this->_frame);
@@ -185,22 +166,18 @@ public function testFirstPayloadDesignationValue($bits, $bin) {
$this->assertEquals(bindec($bin), $cb->invoke($this->_frame));
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::getFirstPayloadVal
- */
- public function testFirstPayloadValUnderflow() {
+ public function testFirstPayloadValUnderflow(): void {
$ref = new \ReflectionClass($this->_frame);
$cb = $ref->getMethod('getFirstPayloadVal');
$cb->setAccessible(true);
- $this->setExpectedException('UnderflowException');
+ $this->expectException(\UnderflowException::class);
$cb->invoke($this->_frame);
}
/**
* @dataProvider payloadLengthDescriptionProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getNumPayloadBits
*/
- public function testDetermineHowManyBitsAreUsedToDescribePayload($expected_bits, $bin) {
+ public function testDetermineHowManyBitsAreUsedToDescribePayload(int $expected_bits, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin));
$ref = new \ReflectionClass($this->_frame);
@@ -209,18 +186,15 @@ public function testDetermineHowManyBitsAreUsedToDescribePayload($expected_bits,
$this->assertEquals($expected_bits, $cb->invoke($this->_frame));
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::getNumPayloadBits
- */
- public function testgetNumPayloadBitsUnderflow() {
+ public function testgetNumPayloadBitsUnderflow(): void {
$ref = new \ReflectionClass($this->_frame);
$cb = $ref->getMethod('getNumPayloadBits');
$cb->setAccessible(true);
- $this->setExpectedException('UnderflowException');
+ $this->expectException(\UnderflowException::class);
$cb->invoke($this->_frame);
}
- public function secondByteProvider() {
+ public function secondByteProvider(): array {
return array(
array(true, 1, '10000001'),
array(false, 1, '00000001'),
@@ -229,9 +203,8 @@ public function secondByteProvider() {
}
/**
* @dataProvider secondByteProvider
- * covers Ratchet\RFC6455\Messaging\Frame::isMasked
*/
- public function testIsMaskedReturnsExpectedValue($masked, $payload_length, $bin) {
+ public function testIsMaskedReturnsExpectedValue(bool $masked, int $payload_length, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($masked, $this->_frame->isMasked());
@@ -239,18 +212,16 @@ public function testIsMaskedReturnsExpectedValue($masked, $payload_length, $bin)
/**
* @dataProvider UnframeMessageProvider
- * covers Ratchet\RFC6455\Messaging\Frame::isMasked
*/
- public function testIsMaskedFromFullMessage($msg, $encoded) {
+ public function testIsMaskedFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded));
$this->assertTrue($this->_frame->isMasked());
}
/**
* @dataProvider secondByteProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
*/
- public function testGetPayloadLengthWhenOnlyFirstFrameIsUsed($masked, $payload_length, $bin) {
+ public function testGetPayloadLengthWhenOnlyFirstFrameIsUsed(bool $masked, int $payload_length, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($payload_length, $this->_frame->getPayloadLength());
@@ -258,15 +229,14 @@ public function testGetPayloadLengthWhenOnlyFirstFrameIsUsed($masked, $payload_l
/**
* @dataProvider UnframeMessageProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
* @todo Not yet testing when second additional payload length descriptor
*/
- public function testGetPayloadLengthFromFullMessage($msg, $encoded) {
+ public function testGetPayloadLengthFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded));
$this->assertEquals(strlen($msg), $this->_frame->getPayloadLength());
}
- public function maskingKeyProvider() {
+ public function maskingKeyProvider(): array {
$frame = new Frame;
return array(
array($frame->generateMaskingKey()),
@@ -277,35 +247,30 @@ public function maskingKeyProvider() {
/**
* @dataProvider maskingKeyProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getMaskingKey
* @todo I I wrote the dataProvider incorrectly, skipping for now
*/
- public function testGetMaskingKey($mask) {
+ public function testGetMaskingKey(string $mask): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($this->_secondByteMaskedSPL));
$this->_frame->addBuffer($mask);
$this->assertEquals($mask, $this->_frame->getMaskingKey());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::getMaskingKey
- */
- public function testGetMaskingKeyOnUnmaskedPayload() {
+ public function testGetMaskingKeyOnUnmaskedPayload(): void {
$frame = new Frame('Hello World!');
$this->assertEquals('', $frame->getMaskingKey());
}
/**
* @dataProvider UnframeMessageProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getPayload
* @todo Move this test to bottom as it requires all methods of the class
*/
- public function testUnframeFullMessage($unframed, $base_framed) {
+ public function testUnframeFullMessage(string $unframed, string $base_framed): void {
$this->_frame->addBuffer(base64_decode($base_framed));
$this->assertEquals($unframed, $this->_frame->getPayload());
}
- public static function messageFragmentProvider() {
+ public static function messageFragmentProvider(): array {
return array(
array(false, '', '', '', '', '')
);
@@ -313,9 +278,8 @@ public static function messageFragmentProvider() {
/**
* @dataProvider UnframeMessageProvider
- * covers Ratchet\RFC6455\Messaging\Frame::getPayload
*/
- public function testCheckPiecingTogetherMessage($msg, $encoded) {
+ public function testCheckPiecingTogetherMessage(string $msg, string $encoded): void {
$framed = base64_decode($encoded);
for ($i = 0, $len = strlen($framed);$i < $len; $i++) {
$this->_frame->addBuffer(substr($framed, $i, 1));
@@ -323,12 +287,7 @@ public function testCheckPiecingTogetherMessage($msg, $encoded) {
$this->assertEquals($msg, $this->_frame->getPayload());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::__construct
- * covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
- * covers Ratchet\RFC6455\Messaging\Frame::getPayload
- */
- public function testLongCreate() {
+ public function testLongCreate(): void {
$len = 65525;
$pl = $this->generateRandomString($len);
$frame = new Frame($pl, true, Frame::OP_PING);
@@ -339,20 +298,13 @@ public function testLongCreate() {
$this->assertEquals($pl, $frame->getPayload());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::__construct
- * covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
- */
- public function testReallyLongCreate() {
+ public function testReallyLongCreate(): void {
$len = 65575;
$frame = new Frame($this->generateRandomString($len));
$this->assertEquals($len, $frame->getPayloadLength());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::__construct
- * covers Ratchet\RFC6455\Messaging\Frame::extractOverflow
- */
- public function testExtractOverflow() {
+
+ public function testExtractOverflow(): void {
$string1 = $this->generateRandomString();
$frame1 = new Frame($string1);
$string2 = $this->generateRandomString();
@@ -367,10 +319,7 @@ public function testExtractOverflow() {
$this->assertEquals($string2, $uncat->getPayload());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::extractOverflow
- */
- public function testEmptyExtractOverflow() {
+ public function testEmptyExtractOverflow(): void {
$string = $this->generateRandomString();
$frame = new Frame($string);
$this->assertEquals($string, $frame->getPayload());
@@ -378,10 +327,7 @@ public function testEmptyExtractOverflow() {
$this->assertEquals($string, $frame->getPayload());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::getContents
- */
- public function testGetContents() {
+ public function testGetContents(): void {
$msg = 'The quick brown fox jumps over the lazy dog.';
$frame1 = new Frame($msg);
$frame2 = new Frame($msg);
@@ -390,10 +336,7 @@ public function testGetContents() {
$this->assertEquals(strlen($frame1->getContents()) + 4, strlen($frame2->getContents()));
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::maskPayload
- */
- public function testMasking() {
+ public function testMasking(): void {
$msg = 'The quick brown fox jumps over the lazy dog.';
$frame = new Frame($msg);
$frame->maskPayload();
@@ -401,10 +344,7 @@ public function testMasking() {
$this->assertEquals($msg, $frame->getPayload());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::unMaskPayload
- */
- public function testUnMaskPayload() {
+ public function testUnMaskPayload(): void {
$string = $this->generateRandomString();
$frame = new Frame($string);
$frame->maskPayload()->unMaskPayload();
@@ -412,10 +352,7 @@ public function testUnMaskPayload() {
$this->assertEquals($string, $frame->getPayload());
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::generateMaskingKey
- */
- public function testGenerateMaskingKey() {
+ public function testGenerateMaskingKey(): void {
$dupe = false;
$done = array();
for ($i = 0; $i < 10; $i++) {
@@ -429,27 +366,20 @@ public function testGenerateMaskingKey() {
$this->assertFalse($dupe);
}
- /**
- * covers Ratchet\RFC6455\Messaging\Frame::maskPayload
- */
- public function testGivenMaskIsValid() {
- $this->setExpectedException('InvalidArgumentException');
+ public function testGivenMaskIsValid(): void {
+ $this->expectException(\InvalidArgumentException::class);
$this->_frame->maskPayload('hello world');
}
/**
- * covers Ratchet\RFC6455\Messaging\Frame::maskPayload
+ * @requires extension mbstring
*/
- public function testGivenMaskIsValidAscii() {
- if (!extension_loaded('mbstring')) {
- $this->markTestSkipped("mbstring required for this test");
- return;
- }
- $this->setExpectedException('OutOfBoundsException');
+ public function testGivenMaskIsValidAscii(): void {
+ $this->expectException(\OutOfBoundsException::class);
$this->_frame->maskPayload('x✖');
}
- protected function generateRandomString($length = 10, $addSpaces = true, $addNumbers = true) {
+ protected function generateRandomString(int $length = 10, bool $addSpaces = true, bool $addNumbers = true): string {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"$%&/()=[]{}'; // ยง
$useChars = array();
for($i = 0; $i < $length; $i++) {
@@ -473,11 +403,8 @@ protected function generateRandomString($length = 10, $addSpaces = true, $addNum
* to set the payload length to 126 and then not recalculate it once the full length information was available.
*
* This is fixed by setting the defPayLen back to -1 before the underflow exception is thrown.
- *
- * covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
- * covers Ratchet\RFC6455\Messaging\Frame::extractOverflow
*/
- public function testFrameDeliveredOneByteAtATime() {
+ public function testFrameDeliveredOneByteAtATime(): void {
$startHeader = "\x01\x7e\x01\x00"; // header for a text frame of 256 - non-final
$framePayload = str_repeat("*", 256);
$rawOverflow = "xyz";
diff --git a/tests/unit/Messaging/MessageBufferTest.php b/tests/unit/Messaging/MessageBufferTest.php
index 89dcca0..b3a9eef 100644
--- a/tests/unit/Messaging/MessageBufferTest.php
+++ b/tests/unit/Messaging/MessageBufferTest.php
@@ -9,13 +9,16 @@
use React\EventLoop\Factory;
use PHPUnit\Framework\TestCase;
+/**
+ * @covers Ratchet\RFC6455\Messaging\MessageBuffer
+ */
class MessageBufferTest extends TestCase
{
/**
* This is to test that MessageBuffer can handle a large receive
* buffer with many many frames without blowing the stack (pre-v0.4 issue)
*/
- public function testProcessingLotsOfFramesInASingleChunk() {
+ public function testProcessingLotsOfFramesInASingleChunk(): void {
$frame = new Frame('a', true, Frame::OP_TEXT);
$frameRaw = $frame->getContents();
@@ -26,7 +29,7 @@ public function testProcessingLotsOfFramesInASingleChunk() {
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) use (&$messageCount) {
+ function (Message $message) use (&$messageCount): void {
$messageCount++;
$this->assertEquals('a', $message->getPayload());
},
@@ -39,7 +42,7 @@ function (Message $message) use (&$messageCount) {
$this->assertEquals(1000, $messageCount);
}
- public function testProcessingMessagesAsynchronouslyWhileBlockingInMessageHandler() {
+ public function testProcessingMessagesAsynchronouslyWhileBlockingInMessageHandler(): void {
$loop = Factory::create();
$frameA = new Frame('a', true, Frame::OP_TEXT);
@@ -49,7 +52,7 @@ public function testProcessingMessagesAsynchronouslyWhileBlockingInMessageHandle
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) use (&$messageCount, &$bReceived, $loop) {
+ static function (Message $message) use (&$messageCount, &$bReceived, $loop): void {
$payload = $message->getPayload();
$bReceived = $payload === 'b';
@@ -61,7 +64,7 @@ function (Message $message) use (&$messageCount, &$bReceived, $loop) {
false
);
- $loop->addPeriodicTimer(0.1, function () use ($messageBuffer, $frameB, $loop) {
+ $loop->addPeriodicTimer(0.1, static function () use ($messageBuffer, $frameB, $loop): void {
$loop->stop();
$messageBuffer->onData($frameB->getContents());
});
@@ -71,7 +74,7 @@ function (Message $message) use (&$messageCount, &$bReceived, $loop) {
$this->assertTrue($bReceived);
}
- public function testInvalidFrameLength() {
+ public function testInvalidFrameLength(): void {
$frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT);
$frameRaw = $frame->getContents();
@@ -93,7 +96,7 @@ public function testInvalidFrameLength() {
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) use (&$messageCount) {
+ static function (Message $message) use (&$messageCount): void {
$messageCount++;
},
function (Frame $frame) use (&$controlFrame) {
@@ -109,13 +112,13 @@ function (Frame $frame) use (&$controlFrame) {
$messageBuffer->onData($frameRaw);
$this->assertEquals(0, $messageCount);
- $this->assertTrue($controlFrame instanceof Frame);
+ $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_PROTOCOL], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
}
- public function testFrameLengthTooBig() {
+ public function testFrameLengthTooBig(): void {
$frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT);
$frameRaw = $frame->getContents();
@@ -137,10 +140,10 @@ public function testFrameLengthTooBig() {
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) use (&$messageCount) {
+ static function (Message $message) use (&$messageCount): void {
$messageCount++;
},
- function (Frame $frame) use (&$controlFrame) {
+ function (Frame $frame) use (&$controlFrame): void {
$this->assertNull($controlFrame);
$controlFrame = $frame;
},
@@ -153,12 +156,12 @@ function (Frame $frame) use (&$controlFrame) {
$messageBuffer->onData($frameRaw);
$this->assertEquals(0, $messageCount);
- $this->assertTrue($controlFrame instanceof Frame);
+ $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
}
- public function testFrameLengthBiggerThanMaxMessagePayload() {
+ public function testFrameLengthBiggerThanMaxMessagePayload(): void {
$frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT);
$frameRaw = $frame->getContents();
@@ -169,10 +172,10 @@ public function testFrameLengthBiggerThanMaxMessagePayload() {
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) use (&$messageCount) {
+ static function (Message $message) use (&$messageCount): void {
$messageCount++;
},
- function (Frame $frame) use (&$controlFrame) {
+ function (Frame $frame) use (&$controlFrame): void {
$this->assertNull($controlFrame);
$controlFrame = $frame;
},
@@ -185,12 +188,12 @@ function (Frame $frame) use (&$controlFrame) {
$messageBuffer->onData($frameRaw);
$this->assertEquals(0, $messageCount);
- $this->assertTrue($controlFrame instanceof Frame);
+ $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
}
- public function testSecondFrameLengthPushesPastMaxMessagePayload() {
+ public function testSecondFrameLengthPushesPastMaxMessagePayload(): void {
$frame = new Frame(str_repeat('a', 200), false, Frame::OP_TEXT);
$firstFrameRaw = $frame->getContents();
$frame = new Frame(str_repeat('b', 200), true, Frame::OP_TEXT);
@@ -202,10 +205,10 @@ public function testSecondFrameLengthPushesPastMaxMessagePayload() {
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) use (&$messageCount) {
+ static function (Message $message) use (&$messageCount): void {
$messageCount++;
},
- function (Frame $frame) use (&$controlFrame) {
+ function (Frame $frame) use (&$controlFrame): void {
$this->assertNull($controlFrame);
$controlFrame = $frame;
},
@@ -220,7 +223,7 @@ function (Frame $frame) use (&$controlFrame) {
$messageBuffer->onData(substr($secondFrameRaw, 0, 150));
$this->assertEquals(0, $messageCount);
- $this->assertTrue($controlFrame instanceof Frame);
+ $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
}
@@ -258,15 +261,15 @@ function (Frame $frame) use (&$controlFrame) {
* @param string $phpConfigurationValue
* @param int $expectedLimit
*/
- public function testMemoryLimits($phpConfigurationValue, $expectedLimit) {
- $method = new \ReflectionMethod('Ratchet\RFC6455\Messaging\MessageBuffer', 'getMemoryLimit');
+ public function testMemoryLimits(string $phpConfigurationValue, int $expectedLimit): void {
+ $method = new \ReflectionMethod(MessageBuffer::class, 'getMemoryLimit');
$method->setAccessible(true);
$actualLimit = $method->invoke(null, $phpConfigurationValue);
$this->assertSame($expectedLimit, $actualLimit);
}
- public function phpConfigurationProvider() {
+ public function phpConfigurationProvider(): array {
return [
'without unit type, just bytes' => ['500', 500],
'1 GB with big "G"' => ['1G', 1 * 1024 * 1024 * 1024],
@@ -281,32 +284,30 @@ public function phpConfigurationProvider() {
];
}
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testInvalidMaxFramePayloadSizes() {
- $messageBuffer = new MessageBuffer(
+ public function testInvalidMaxFramePayloadSizes(): void {
+ $this->expectException(\InvalidArgumentException::class);
+
+ new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) {},
- function (Frame $frame) {},
+ static function (Message $message): void {},
+ static function (Frame $frame): void {},
false,
null,
0,
- 0x8000000000000000
+ -1
);
}
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testInvalidMaxMessagePayloadSizes() {
- $messageBuffer = new MessageBuffer(
+ public function testInvalidMaxMessagePayloadSizes(): void {
+ $this->expectException(\InvalidArgumentException::class);
+
+ new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) {},
- function (Frame $frame) {},
+ static function (Message $message): void {},
+ static function (Frame $frame): void {},
false,
null,
- 0x8000000000000000,
+ -1,
0
);
}
@@ -318,9 +319,8 @@ function (Frame $frame) {},
* @param int $expectedLimit
*
* @runInSeparateProcess
- * @requires PHP 7.0
*/
- public function testIniSizes($phpConfigurationValue, $expectedLimit) {
+ public function testIniSizes(string $phpConfigurationValue, int $expectedLimit): void {
$value = @ini_set('memory_limit', $phpConfigurationValue);
if ($value === false) {
$this->markTestSkipped("Does not support setting the memory_limit lower than current memory_usage");
@@ -328,8 +328,8 @@ public function testIniSizes($phpConfigurationValue, $expectedLimit) {
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(),
- function (Message $message) {},
- function (Frame $frame) {},
+ static function (Message $message): void {},
+ static function (Frame $frame): void {},
false,
null
);
@@ -349,9 +349,8 @@ function (Frame $frame) {},
/**
* @runInSeparateProcess
- * @requires PHP 7.0
*/
- public function testInvalidIniSize() {
+ public function testInvalidIniSize(): void {
$value = @ini_set('memory_limit', 'lots of memory');
if ($value === false) {
$this->markTestSkipped("Does not support setting the memory_limit lower than current memory_usage");
@@ -373,4 +372,4 @@ function (Frame $frame) {},
$prop->setAccessible(true);
$this->assertEquals(0, $prop->getValue($messageBuffer));
}
-}
\ No newline at end of file
+}
diff --git a/tests/unit/Messaging/MessageTest.php b/tests/unit/Messaging/MessageTest.php
index c307da8..9042bcd 100644
--- a/tests/unit/Messaging/MessageTest.php
+++ b/tests/unit/Messaging/MessageTest.php
@@ -13,20 +13,20 @@ class MessageTest extends TestCase {
/** @var Message */
protected $message;
- public function setUp() {
+ protected function setUp(): void {
$this->message = new Message;
}
- public function testNoFrames() {
+ public function testNoFrames(): void {
$this->assertFalse($this->message->isCoalesced());
}
- public function testNoFramesOpCode() {
- $this->setExpectedException('UnderflowException');
+ public function testNoFramesOpCode(): void {
+ $this->expectException(\UnderflowException::class);
$this->message->getOpCode();
}
- public function testFragmentationPayload() {
+ public function testFragmentationPayload(): void {
$a = 'Hello ';
$b = 'World!';
$f1 = new Frame($a, false);
@@ -36,13 +36,13 @@ public function testFragmentationPayload() {
$this->assertEquals($a . $b, $this->message->getPayload());
}
- public function testUnbufferedFragment() {
+ public function testUnbufferedFragment(): void {
$this->message->addFrame(new Frame('The quick brow', false));
- $this->setExpectedException('UnderflowException');
+ $this->expectException(\UnderflowException::class);
$this->message->getPayload();
}
- public function testGetOpCode() {
+ public function testGetOpCode(): void {
$this->message
->addFrame(new Frame('The quick brow', false, Frame::OP_TEXT))
->addFrame(new Frame('n fox jumps ov', false, Frame::OP_CONTINUE))
@@ -51,11 +51,11 @@ public function testGetOpCode() {
$this->assertEquals(Frame::OP_TEXT, $this->message->getOpCode());
}
- public function testGetUnBufferedPayloadLength() {
+ public function testGetUnBufferedPayloadLength(): void {
$this->message
->addFrame(new Frame('The quick brow', false, Frame::OP_TEXT))
->addFrame(new Frame('n fox jumps ov', false, Frame::OP_CONTINUE))
;
$this->assertEquals(28, $this->message->getPayloadLength());
}
-}
\ No newline at end of file
+}