From f9a50947266c78b306b31c2116991533bd100aca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Kr=C3=B3lak?= <754920+taavit@users.noreply.github.com> Date: Wed, 16 Oct 2019 22:51:02 +0200 Subject: [PATCH 01/10] Replace guzzle based request/response object with PSR-17 factory --- composer.json | 5 +- src/Handshake/ClientNegotiator.php | 26 ++++---- src/Handshake/ServerNegotiator.php | 59 +++++++++++-------- tests/ab/clientRunner.php | 7 ++- tests/ab/run_ab_tests.sh | 0 tests/ab/startServer.php | 6 +- tests/unit/Handshake/ServerNegotiatorTest.php | 16 ++--- 7 files changed, 70 insertions(+), 49 deletions(-) mode change 100644 => 100755 tests/ab/run_ab_tests.sh diff --git a/composer.json b/composer.json index 224066b..27935d8 100644 --- a/composer.json +++ b/composer.json @@ -22,11 +22,12 @@ }, "require": { "php": ">=5.4.2", - "guzzlehttp/psr7": "^1.0" + "psr/http-factory-implementation": "^1.0" }, "require-dev": { "react/http": "^0.4.1", "react/socket-client": "^0.4.3", - "phpunit/phpunit": "4.8.*" + "phpunit/phpunit": "4.8.*", + "guzzlehttp/psr7": "^2.0-dev" } } diff --git a/src/Handshake/ClientNegotiator.php b/src/Handshake/ClientNegotiator.php index 70856df..a12205a 100644 --- a/src/Handshake/ClientNegotiator.php +++ b/src/Handshake/ClientNegotiator.php @@ -3,7 +3,7 @@ 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 { /** @@ -16,20 +16,26 @@ class ClientNegotiator { */ private $defaultHeader; - function __construct() { - $this->verifier = new ResponseVerifier; + /** + * @var RequestFactoryInterface + */ + private $requestFactory; - $this->defaultHeader = new Request('GET', '', [ - 'Connection' => 'Upgrade' - , 'Upgrade' => 'websocket' - , 'Sec-WebSocket-Version' => $this->getVersion() - , 'User-Agent' => "Ratchet" - ]); + function __construct(RequestFactoryInterface $requestFactory) { + $this->verifier = new ResponseVerifier; + $this->requestFactory = $requestFactory; + + $this->defaultHeader = $this->requestFactory + ->createRequest('GET', '') + ->withHeader('Connection' , 'Upgrade') + ->withHeader('Upgrade' , 'websocket') + ->withHeader('Sec-WebSocket-Version', $this->getVersion()) + ->withHeader('User-Agent' , 'Ratchet'); } public function generateRequest(UriInterface $uri) { return $this->defaultHeader->withUri($uri) - ->withHeader("Sec-WebSocket-Key", $this->generateKey()); + ->withHeader('Sec-WebSocket-Key', $this->generateKey()); } public function validateResponse(RequestInterface $request, ResponseInterface $response) { diff --git a/src/Handshake/ServerNegotiator.php b/src/Handshake/ServerNegotiator.php index 618b8e2..742f10d 100644 --- a/src/Handshake/ServerNegotiator.php +++ b/src/Handshake/ServerNegotiator.php @@ -1,7 +1,7 @@ verifier = $requestVerifier; + $this->responseFactory = $responseFactory; } /** @@ -39,47 +45,49 @@ public function getVersionNumber() { * {@inheritdoc} */ public function handshake(RequestInterface $request) { + $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))); @@ -89,20 +97,19 @@ public function handshake(RequestInterface $request) { }, 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); } } - - return 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' - ])); + return $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'); } /** diff --git a/tests/ab/clientRunner.php b/tests/ab/clientRunner.php index 0c5578a..e1bfd76 100644 --- a/tests/ab/clientRunner.php +++ b/tests/ab/clientRunner.php @@ -2,6 +2,7 @@ use GuzzleHttp\Psr7\Uri; use React\Promise\Deferred; use Ratchet\RFC6455\Messaging\Frame; +use GuzzleHttp\Psr7\HttpFactory; require __DIR__ . '/../bootstrap.php'; @@ -48,7 +49,7 @@ function getTestCases() { $deferred = new Deferred(); $factory->create($testServer, 9001)->then(function (\React\Stream\Stream $stream) use ($deferred) { - $cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator(); + $cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator(new HttpFactory()); $cnRequest = $cn->generateRequest(new Uri('ws://127.0.0.1:9001/getCaseCount')); $rawResponse = ""; @@ -105,7 +106,7 @@ function runTest($case) $deferred = new Deferred(); $factory->create($testServer, 9001)->then(function (\React\Stream\Stream $stream) use ($deferred, $casePath, $case) { - $cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator(); + $cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator(new HttpFactory()); $cnRequest = $cn->generateRequest(new Uri('ws://127.0.0.1:9001' . $casePath)); $rawResponse = ""; @@ -155,7 +156,7 @@ function createReport() { $factory->create($testServer, 9001)->then(function (\React\Stream\Stream $stream) use ($deferred) { $reportPath = "/updateReports?agent=" . AGENT . "&shutdownOnComplete=true"; - $cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator(); + $cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator(new HttpFactory()); $cnRequest = $cn->generateRequest(new Uri('ws://127.0.0.1:9001' . $reportPath)); $rawResponse = ""; 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 b256ec2..a5cd78c 100644 --- a/tests/ab/startServer.php +++ b/tests/ab/startServer.php @@ -2,6 +2,7 @@ use Ratchet\RFC6455\Messaging\MessageInterface; use Ratchet\RFC6455\Messaging\FrameInterface; use Ratchet\RFC6455\Messaging\Frame; +use GuzzleHttp\Psr7\HttpFactory; require_once __DIR__ . "/../bootstrap.php"; @@ -11,7 +12,10 @@ $server = new \React\Http\Server($socket); $closeFrameChecker = new \Ratchet\RFC6455\Messaging\CloseFrameChecker; -$negotiator = new \Ratchet\RFC6455\Handshake\ServerNegotiator(new \Ratchet\RFC6455\Handshake\RequestVerifier); +$negotiator = new \Ratchet\RFC6455\Handshake\ServerNegotiator( + new \Ratchet\RFC6455\Handshake\RequestVerifier, + new HttpFactory() +); $uException = new \UnderflowException; diff --git a/tests/unit/Handshake/ServerNegotiatorTest.php b/tests/unit/Handshake/ServerNegotiatorTest.php index 6fa8e64..654830e 100644 --- a/tests/unit/Handshake/ServerNegotiatorTest.php +++ b/tests/unit/Handshake/ServerNegotiatorTest.php @@ -5,10 +5,12 @@ use Ratchet\RFC6455\Handshake\RequestVerifier; use Ratchet\RFC6455\Handshake\ServerNegotiator; +use GuzzleHttp\Psr7\HttpFactory; + class ServerNegotiatorTest extends \PHPUnit_Framework_TestCase { public function testNoUpgradeRequested() { - $negotiator = new ServerNegotiator(new RequestVerifier()); + $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory()); $requestText = 'GET / HTTP/1.1 Host: 127.0.0.1:6789 @@ -36,7 +38,7 @@ public function testNoUpgradeRequested() { } public function testNoConnectionUpgradeRequested() { - $negotiator = new ServerNegotiator(new RequestVerifier()); + $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory()); $requestText = 'GET / HTTP/1.1 Host: 127.0.0.1:6789 @@ -62,7 +64,7 @@ public function testNoConnectionUpgradeRequested() { } public function testInvalidSecWebsocketKey() { - $negotiator = new ServerNegotiator(new RequestVerifier()); + $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory()); $requestText = 'GET / HTTP/1.1 Host: 127.0.0.1:6789 @@ -89,7 +91,7 @@ public function testInvalidSecWebsocketKey() { } public function testInvalidSecWebsocketVersion() { - $negotiator = new ServerNegotiator(new RequestVerifier()); + $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory()); $requestText = 'GET / HTTP/1.1 Host: 127.0.0.1:6789 @@ -119,7 +121,7 @@ public function testInvalidSecWebsocketVersion() { } public function testBadSubprotocolResponse() { - $negotiator = new ServerNegotiator(new RequestVerifier()); + $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory()); $negotiator->setStrictSubProtocolCheck(true); $negotiator->setSupportedSubProtocols([]); @@ -153,7 +155,7 @@ public function testBadSubprotocolResponse() { } public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn() { - $negotiator = new ServerNegotiator(new RequestVerifier()); + $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory()); $negotiator->setStrictSubProtocolCheck(false); $negotiator->setSupportedSubProtocols(['someproto']); @@ -187,7 +189,7 @@ public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn() { public function testSuggestsAppropriateSubprotocol() { - $negotiator = new ServerNegotiator(new RequestVerifier()); + $negotiator = new ServerNegotiator(new RequestVerifier(), new HttpFactory()); $negotiator->setStrictSubProtocolCheck(true); $negotiator->setSupportedSubProtocols(['someproto']); From f40306ad5e6061613bd1a4b0f97404599608c97b Mon Sep 17 00:00:00 2001 From: Michael Babker Date: Mon, 6 Dec 2021 16:34:38 -0600 Subject: [PATCH 02/10] Bump minimum PHP to 7.4 --- .github/workflows/ci.yml | 12 ------------ composer.json | 2 +- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb3698d..1feeac2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,11 +15,6 @@ jobs: - server php: - 7.4 - - 7.3 - - 7.2 - - 7.1 - - 7.0 - - 5.6 steps: - uses: actions/checkout@v2 - name: Setup PHP @@ -33,11 +28,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/composer.json b/composer.json index 054a8fb..0cb918f 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,7 @@ } }, "require": { - "php": ">=5.4.2", + "php": ">=7.4", "guzzlehttp/psr7": "^2 || ^1.7" }, "require-dev": { From fd5a6a86a8f0fd7abce8d9273e46503c7eaceb90 Mon Sep 17 00:00:00 2001 From: Michael Babker Date: Fri, 10 Dec 2021 21:22:21 -0600 Subject: [PATCH 03/10] Use latest PHPUnit and modernize test code --- .github/workflows/ci.yml | 2 + .gitignore | 1 + composer.json | 2 +- phpunit.xml.dist | 19 +- tests/AbResultsTest.php | 11 +- tests/ab/clientRunner.php | 50 +++--- tests/ab/startServer.php | 21 +-- .../PermessageDeflateOptionsTest.php | 9 +- tests/unit/Handshake/RequestVerifierTest.php | 36 ++-- tests/unit/Handshake/ResponseVerifierTest.php | 6 +- tests/unit/Handshake/ServerNegotiatorTest.php | 17 +- tests/unit/Messaging/FrameTest.php | 165 +++++------------- tests/unit/Messaging/MessageBufferTest.php | 87 +++++---- tests/unit/Messaging/MessageTest.php | 20 +-- 14 files changed, 190 insertions(+), 256 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1feeac2..dbf84e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,6 +15,8 @@ jobs: - server php: - 7.4 + - 8.0 + - 8.1 steps: - uses: actions/checkout@v2 - name: Setup PHP 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 0cb918f..6c65474 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,7 @@ "guzzlehttp/psr7": "^2 || ^1.7" }, "require-dev": { - "phpunit/phpunit": "^5.7", + "phpunit/phpunit": "^9.5", "react/socket": "^1.3" }, "scripts": { 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/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..2ecd975 100644 --- a/tests/ab/clientRunner.php +++ b/tests/ab/clientRunner.php @@ -4,12 +4,14 @@ 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 React\Socket\ConnectionInterface; use React\Socket\Connector; @@ -23,23 +25,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,13 +51,13 @@ 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) { + $connector->connect($testServer . ':9002')->then(static function (ConnectionInterface $connection) use ($deferred, $testServer): void { $cn = new ClientNegotiator(); $cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002/getCaseCount')); @@ -67,7 +67,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 +82,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 +91,7 @@ function (MessageInterface $msg) use ($deferred, $connection) { null, null, null, - function () {} + static function (): void {} ); } } @@ -109,10 +109,10 @@ function () {} return $deferred->promise(); } -$cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator( +$cn = new ClientNegotiator( PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null); -function runTest($case) +function runTest(int $case) { global $connector; global $testServer; @@ -122,7 +122,7 @@ 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( PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null); $cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002' . $casePath)); @@ -132,7 +132,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,7 +165,7 @@ function runTest($case) } }); - $connection->on('close', function () use ($deferred) { + $connection->on('close', static function () use ($deferred): void { $deferred->resolve(); }); @@ -175,13 +175,13 @@ 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; @@ -194,7 +194,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 +209,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 +218,7 @@ function (MessageInterface $msg) use ($deferred, $connection) { null, null, null, - function () {} + static function (): void {} ); } } @@ -242,7 +242,7 @@ 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(); @@ -251,7 +251,7 @@ function () {} 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 +260,7 @@ function () {} $i = 0; $runNextCase(); - $allDeferred->promise()->then(function () { + $allDeferred->promise()->then(static function (): void { createReport(); }); }); diff --git a/tests/ab/startServer.php b/tests/ab/startServer.php index 7c169c6..dde3365 100644 --- a/tests/ab/startServer.php +++ b/tests/ab/startServer.php @@ -3,6 +3,9 @@ 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; @@ -14,17 +17,17 @@ $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, 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 +61,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 +73,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..b82784e 100644 --- a/tests/unit/Handshake/ServerNegotiatorTest.php +++ b/tests/unit/Handshake/ServerNegotiatorTest.php @@ -7,9 +7,12 @@ use Ratchet\RFC6455\Handshake\ServerNegotiator; use PHPUnit\Framework\TestCase; +/** + * @covers Ratchet\RFC6455\Handshake\ServerNegotiator + */ class ServerNegotiatorTest extends TestCase { - public function testNoUpgradeRequested() { + public function testNoUpgradeRequested(): void { $negotiator = new ServerNegotiator(new RequestVerifier()); $requestText = 'GET / HTTP/1.1 @@ -37,7 +40,7 @@ public function testNoUpgradeRequested() { $this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version')); } - public function testNoConnectionUpgradeRequested() { + public function testNoConnectionUpgradeRequested(): void { $negotiator = new ServerNegotiator(new RequestVerifier()); $requestText = 'GET / HTTP/1.1 @@ -63,7 +66,7 @@ public function testNoConnectionUpgradeRequested() { $this->assertEquals('Connection Upgrade MUST be requested', $response->getReasonPhrase()); } - public function testInvalidSecWebsocketKey() { + public function testInvalidSecWebsocketKey(): void { $negotiator = new ServerNegotiator(new RequestVerifier()); $requestText = 'GET / HTTP/1.1 @@ -90,7 +93,7 @@ public function testInvalidSecWebsocketKey() { $this->assertEquals('Invalid Sec-WebSocket-Key', $response->getReasonPhrase()); } - public function testInvalidSecWebsocketVersion() { + public function testInvalidSecWebsocketVersion(): void { $negotiator = new ServerNegotiator(new RequestVerifier()); $requestText = 'GET / HTTP/1.1 @@ -120,7 +123,7 @@ public function testInvalidSecWebsocketVersion() { $this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version')); } - public function testBadSubprotocolResponse() { + public function testBadSubprotocolResponse(): void { $negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator->setStrictSubProtocolCheck(true); $negotiator->setSupportedSubProtocols([]); @@ -154,7 +157,7 @@ public function testBadSubprotocolResponse() { $this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version')); } - public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn() { + public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn(): void { $negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator->setStrictSubProtocolCheck(false); $negotiator->setSupportedSubProtocols(['someproto']); @@ -187,7 +190,7 @@ public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn() { $this->assertFalse($response->hasHeader('Sec-WebSocket-Protocol')); } - public function testSuggestsAppropriateSubprotocol() + public function testSuggestsAppropriateSubprotocol(): void { $negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator->setStrictSubProtocolCheck(true); 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..47d203a 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,14 +284,13 @@ 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, @@ -296,14 +298,13 @@ function (Frame $frame) {}, ); } - /** - * @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, @@ -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 +} From 42a6fd89e072c4adf090eeaf7be850cf41951c48 Mon Sep 17 00:00:00 2001 From: Michael Babker Date: Sun, 12 Dec 2021 10:51:46 -0600 Subject: [PATCH 04/10] Code modernization --- composer.json | 3 +- src/Handshake/ClientNegotiator.php | 29 ++-- src/Handshake/NegotiatorInterface.php | 15 ++- src/Handshake/PermessageDeflateOptions.php | 75 ++++++----- src/Handshake/RequestVerifier.php | 56 ++++---- src/Handshake/ResponseVerifier.php | 26 ++-- src/Handshake/ServerNegotiator.php | 34 +++-- src/Messaging/CloseFrameChecker.php | 28 ++-- src/Messaging/DataInterface.php | 16 +-- src/Messaging/Frame.php | 70 +++++----- src/Messaging/FrameInterface.php | 12 +- src/Messaging/Message.php | 38 ++---- src/Messaging/MessageBuffer.php | 147 ++++++++------------- src/Messaging/MessageInterface.php | 6 +- tests/unit/Messaging/MessageBufferTest.php | 4 +- 15 files changed, 243 insertions(+), 316 deletions(-) diff --git a/composer.json b/composer.json index 6c65474..b350a9a 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,8 @@ }, "require": { "php": ">=7.4", - "guzzlehttp/psr7": "^2 || ^1.7" + "guzzlehttp/psr7": "^2 || ^1.7", + "symfony/polyfill-php80": "^1.15" }, "require-dev": { "phpunit/phpunit": "^9.5", diff --git a/src/Handshake/ClientNegotiator.php b/src/Handshake/ClientNegotiator.php index c32a1cf..a7a9125 100644 --- a/src/Handshake/ClientNegotiator.php +++ b/src/Handshake/ClientNegotiator.php @@ -6,17 +6,11 @@ use GuzzleHttp\Psr7\Request; class ClientNegotiator { - /** - * @var ResponseVerifier - */ - private $verifier; + private ResponseVerifier $verifier; - /** - * @var \Psr\Http\Message\RequestInterface - */ - private $defaultHeader; + private RequestInterface $defaultHeader; - function __construct(PermessageDeflateOptions $perMessageDeflateOptions = null) { + public function __construct(PermessageDeflateOptions $perMessageDeflateOptions = null) { $this->verifier = new ResponseVerifier; $this->defaultHeader = new Request('GET', '', [ @@ -26,15 +20,12 @@ function __construct(PermessageDeflateOptions $perMessageDeflateOptions = null) , '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 +36,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()); } - 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 +56,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..ab13e81 100644 --- a/src/Handshake/ServerNegotiator.php +++ b/src/Handshake/ServerNegotiator.php @@ -2,22 +2,20 @@ namespace Ratchet\RFC6455\Handshake; use Psr\Http\Message\RequestInterface; use GuzzleHttp\Psr7\Response; +use Psr\Http\Message\ResponseInterface; /** * The latest version of the WebSocket protocol * @todo Unicode: return mb_convert_encoding(pack("N",$u), mb_internal_encoding(), 'UCS-4BE'); */ class ServerNegotiator implements NegotiatorInterface { - /** - * @var \Ratchet\RFC6455\Handshake\RequestVerifier - */ - private $verifier; + private RequestVerifier $verifier; - private $_supportedSubProtocols = []; + private array $_supportedSubProtocols = []; - private $_strictSubProtocols = false; + private bool $_strictSubProtocols = false; - private $enablePerMessageDeflate = false; + private bool $enablePerMessageDeflate = false; public function __construct(RequestVerifier $requestVerifier, $enablePerMessageDeflate = false) { $this->verifier = $requestVerifier; @@ -38,21 +36,21 @@ 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 { if (true !== $this->verifier->verifyMethod($request->getMethod())) { return new Response(405, ['Allow' => 'GET']); } @@ -98,9 +96,7 @@ public function handshake(RequestInterface $request) { 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'); @@ -137,14 +133,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 +149,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 e5d197b..eac9459 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); @@ -200,9 +171,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(); @@ -221,7 +192,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()) { @@ -259,10 +230,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() @@ -309,13 +280,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; @@ -334,7 +303,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) { @@ -347,7 +316,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'); } @@ -356,27 +325,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.'); } @@ -394,7 +363,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; @@ -417,29 +386,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, @@ -466,16 +433,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; } @@ -535,7 +500,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/unit/Messaging/MessageBufferTest.php b/tests/unit/Messaging/MessageBufferTest.php index 47d203a..b3a9eef 100644 --- a/tests/unit/Messaging/MessageBufferTest.php +++ b/tests/unit/Messaging/MessageBufferTest.php @@ -294,7 +294,7 @@ static function (Frame $frame): void {}, false, null, 0, - 0x8000000000000000 + -1 ); } @@ -307,7 +307,7 @@ static function (Message $message): void {}, static function (Frame $frame): void {}, false, null, - 0x8000000000000000, + -1, 0 ); } From 345fab10e6455bc9c3acb1aae084ba448d0a2847 Mon Sep 17 00:00:00 2001 From: Matt Bonneau Date: Tue, 3 Dec 2024 09:54:20 -0500 Subject: [PATCH 05/10] Update github ci with new PHP versions --- .github/workflows/ci.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dbf84e1..474b1c8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,10 +6,12 @@ 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 @@ -17,8 +19,11 @@ jobs: - 7.4 - 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: From 58b29fb4a3f0334c7e71a4d26b95132dbb73d8ec Mon Sep 17 00:00:00 2001 From: Matt Bonneau Date: Tue, 3 Dec 2024 13:12:56 -0500 Subject: [PATCH 06/10] Correct resolve on deferred in test runner --- tests/ab/clientRunner.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ab/clientRunner.php b/tests/ab/clientRunner.php index 2ecd975..13a5622 100644 --- a/tests/ab/clientRunner.php +++ b/tests/ab/clientRunner.php @@ -166,7 +166,7 @@ function runTest(int $case) }); $connection->on('close', static function () use ($deferred): void { - $deferred->resolve(); + $deferred->resolve(null); }); $connection->write(Message::toString($cnRequest)); From 43043372a9ca50b2efab07cb470c54b0085f17be Mon Sep 17 00:00:00 2001 From: Matt Bonneau Date: Tue, 3 Dec 2024 16:23:05 -0500 Subject: [PATCH 07/10] Fix test running calling resolve without parameter --- tests/ab/clientRunner.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ab/clientRunner.php b/tests/ab/clientRunner.php index 13a5622..c186167 100644 --- a/tests/ab/clientRunner.php +++ b/tests/ab/clientRunner.php @@ -245,7 +245,7 @@ static function (): void {} $runNextCase = static function () use (&$i, &$runNextCase, $count, $allDeferred): void { $i++; if ($i > $count) { - $allDeferred->resolve(); + $allDeferred->resolve(null); return; } echo "Running test $i/$count..."; From 2c2ace13979e9be45b90487806f53a82089f28e2 Mon Sep 17 00:00:00 2001 From: Matt Bonneau Date: Wed, 4 Dec 2024 08:12:18 -0500 Subject: [PATCH 08/10] Update version numbers --- tests/ab/clientRunner.php | 2 +- tests/ab/fuzzingclient.json | 2 +- tests/ab/fuzzingclient_skip_deflate.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/ab/clientRunner.php b/tests/ab/clientRunner.php index 32841e1..3bd8113 100644 --- a/tests/ab/clientRunner.php +++ b/tests/ab/clientRunner.php @@ -18,7 +18,7 @@ require __DIR__ . '/../bootstrap.php'; -define('AGENT', 'RatchetRFC/0.3'); +define('AGENT', 'RatchetRFC/0.4'); $testServer = $argc > 1 ? $argv[1] : "127.0.0.1"; 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} }] From 9e2c1c9bea635a40f66cdee3f9620be0c5ab400f Mon Sep 17 00:00:00 2001 From: Matt Bonneau Date: Thu, 5 Dec 2024 11:53:03 -0500 Subject: [PATCH 09/10] Added guzzlehttp/psr7 to dev deps --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 73ee8bf..07586f0 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,8 @@ }, "require-dev": { "phpunit/phpunit": "^9.5", - "react/socket": "^1.3" + "react/socket": "^1.3", + "guzzlehttp/psr7": "^2.7" }, "scripts": { "abtest-client": "ABTEST=client && sh tests/ab/run_ab_tests.sh", From 3a6e8571706750b7b31e81e9879b7bc340488f35 Mon Sep 17 00:00:00 2001 From: Matt Bonneau Date: Thu, 5 Dec 2024 17:00:38 -0500 Subject: [PATCH 10/10] Implicitly nullable parameters deprecated --- src/Handshake/ClientNegotiator.php | 2 +- src/Messaging/Frame.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Handshake/ClientNegotiator.php b/src/Handshake/ClientNegotiator.php index cfa6575..547b5ea 100644 --- a/src/Handshake/ClientNegotiator.php +++ b/src/Handshake/ClientNegotiator.php @@ -14,7 +14,7 @@ class ClientNegotiator { public function __construct( RequestFactoryInterface $requestFactory, - PermessageDeflateOptions $perMessageDeflateOptions = null + ?PermessageDeflateOptions $perMessageDeflateOptions = null ) { $this->verifier = new ResponseVerifier; $this->requestFactory = $requestFactory; diff --git a/src/Messaging/Frame.php b/src/Messaging/Frame.php index 8bc9265..7833423 100644 --- a/src/Messaging/Frame.php +++ b/src/Messaging/Frame.php @@ -67,7 +67,7 @@ class Frame implements FrameInterface { * @param int $opcode * @param callable<\UnderflowException> $ufExceptionFactory */ - public function __construct(?string $payload = null, bool $final = true, int $opcode = 1, callable $ufExceptionFactory = null) { + 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) {