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 Psr\Http\Message\UriInterface; 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 @@ class ClientNegotiator { , '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 @@ class ClientNegotiator { $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 @@ class ClientNegotiator { 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 @@ final class PermessageDeflateOptions } 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 @@ final class PermessageDeflateOptions 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 @@ final class PermessageDeflateOptions * @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 @@ final class PermessageDeflateOptions } array_shift($parts); - $options = new static(); + $options = new self(); $options->deflateEnabled = true; foreach ($parts as $part) { $kv = explode('=', $part); @@ -119,15 +119,18 @@ final class PermessageDeflateOptions $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 @@ final class PermessageDeflateOptions } // 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 @@ final class PermessageDeflateOptions /** * @return bool */ - public function isEnabled() + public function isEnabled(): bool { return $this->deflateEnabled; } @@ -203,7 +206,7 @@ final class PermessageDeflateOptions * @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 @@ final class PermessageDeflateOptions 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 @@ final class PermessageDeflateOptions 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 @@ use Psr\Http\Message\RequestInterface; * @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 @@ class RequestVerifier { $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 @@ class RequestVerifier { * @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 @@ class RequestVerifier { * @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 @@ class RequestVerifier { * @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 @@ class RequestVerifier { * @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 @@ class RequestVerifier { * @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 @@ class RequestVerifier { * @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 @@ class RequestVerifier { * @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\RequestInterface; 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 @@ class ResponseVerifier { 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 @@ class ResponseVerifier { 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 @@ class ServerNegotiator implements NegotiatorInterface { /** * {@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 @@ class ServerNegotiator implements NegotiatorInterface { 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 @@ class ServerNegotiator implements NegotiatorInterface { * @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 @@ class ServerNegotiator implements NegotiatorInterface { * 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 @@ class Frame implements FrameInterface { /** * {@inheritdoc} */ - public function isCoalesced() { + public function isCoalesced(): bool { if (true === $this->isCoalesced) { return true; } @@ -123,7 +115,7 @@ class Frame implements FrameInterface { /** * {@inheritdoc} */ - public function addBuffer($buf) { + public function addBuffer(string $buf): void { $len = strlen($buf); $this->data .= $buf; @@ -141,7 +133,7 @@ class Frame implements FrameInterface { /** * {@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 @@ class Frame implements FrameInterface { 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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { /** * {@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 @@ class Frame implements FrameInterface { /** * {@inheritdoc} */ - public function getMaskingKey() { + public function getMaskingKey(): string { if (!$this->isMasked()) { return ''; } @@ -234,7 +226,7 @@ class Frame implements FrameInterface { * 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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { /** * {@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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { * @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 @@ class Frame implements FrameInterface { * 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 @@ class Frame implements FrameInterface { /** * {@inheritdoc} */ - public function getPayloadStartingByte() { + public function getPayloadStartingByte(): int { return 1 + $this->getNumPayloadBytes() + ($this->isMasked() ? static::MASK_LENGTH : 0); } @@ -432,7 +424,7 @@ class Frame implements FrameInterface { * {@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 @@ class Frame implements FrameInterface { * 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 @@ class Frame implements FrameInterface { * 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 @@ class Message implements \IteratorAggregate, MessageInterface { /** * {@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 @@ class Message implements \IteratorAggregate, MessageInterface { /** * {@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 @@ class Message implements \IteratorAggregate, MessageInterface { /** * {@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 @@ class Message implements \IteratorAggregate, MessageInterface { return $buffer; } - public function __toString() { + public function __toString(): string { $buffer = ''; foreach ($this->_frames as $frame) { @@ -114,7 +104,7 @@ class Message implements \IteratorAggregate, MessageInterface { /** * @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 @@ class Message implements \IteratorAggregate, MessageInterface { /** * @return boolean */ - public function getRsv1() { + public function getRsv1(): bool { if ($this->_frames->isEmpty()) { return false; //throw new \UnderflowException('Not enough data has been received to determine if message is binary'); diff --git a/src/Messaging/MessageBuffer.php b/src/Messaging/MessageBuffer.php index 317a26a..1007c6a 100644 --- a/src/Messaging/MessageBuffer.php +++ b/src/Messaging/MessageBuffer.php @@ -4,25 +4,16 @@ namespace Ratchet\RFC6455\Messaging; 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 = ''; + + private int $streamingMessageOpCode = -1; + + private PermessageDeflateOptions $permessageDeflateOptions; + + private bool $deflateEnabled; + + private int $maxMessagePayloadSize; + + private int $maxFramePayloadSize; + + private bool $compressedMessage = false; /** - * @var int + * @var resource|bool|null */ - private $streamingMessageOpCode = -1; + private $inflator = null; /** - * @var PermessageDeflateOptions + * @var resource|bool|null */ - private $permessageDeflateOptions; + private $deflator = null; - /** - * @var bool - */ - private $deflateEnabled = false; - - /** - * @var int - */ - private $maxMessagePayloadSize; - - /** - * @var int - */ - private $maxFramePayloadSize; - - /** - * @var bool - */ - private $compressedMessage; - - 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 @@ class MessageBuffer { 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 @@ class MessageBuffer { $maxFramePayloadSize = (int)($memory_limit_bytes / 4); } - if (!is_int($maxFramePayloadSize) || $maxFramePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxFramePayloadSize < 0) { // this should be interesting on non-64 bit systems + if ($maxFramePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxFramePayloadSize < 0) { // this should be interesting on non-64 bit systems throw new \InvalidArgumentException($maxFramePayloadSize . ' is not a valid maxFramePayloadSize'); } $this->maxFramePayloadSize = $maxFramePayloadSize; - if (!is_int($maxMessagePayloadSize) || $maxMessagePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxMessagePayloadSize < 0) { + if ($maxMessagePayloadSize > 0x7FFFFFFFFFFFFFFF || $maxMessagePayloadSize < 0) { throw new \InvalidArgumentException($maxMessagePayloadSize . 'is not a valid maxMessagePayloadSize'); } $this->maxMessagePayloadSize = $maxMessagePayloadSize; } - public function onData($data) { + public function onData(string $data): void { $data = $this->leftovers . $data; $dataLen = strlen($data); @@ -214,9 +185,9 @@ class MessageBuffer { /** * @param string $data - * @return null + * @return void */ - private function processData($data) { + private function processData(string $data): void { $this->messageBuffer ?: $this->messageBuffer = $this->newMessage(); $this->frameBuffer ?: $this->frameBuffer = $this->newFrame(); @@ -235,7 +206,7 @@ class MessageBuffer { $onControl($this->frameBuffer, $this); if (Frame::OP_CLOSE === $opcode) { - return ''; + return; } } else { if ($this->messageBuffer->count() === 0 && $this->frameBuffer->getRsv1()) { @@ -273,10 +244,10 @@ class MessageBuffer { /** * Check a frame to be added to the current message buffer - * @param \Ratchet\RFC6455\Messaging\FrameInterface|FrameInterface $frame - * @return \Ratchet\RFC6455\Messaging\FrameInterface|FrameInterface + * @param FrameInterface $frame + * @return FrameInterface */ - public function frameCheck(FrameInterface $frame) { + public function frameCheck(FrameInterface $frame): FrameInterface { if ((false !== $frame->getRsv1() && !$this->deflateEnabled) || false !== $frame->getRsv2() || false !== $frame->getRsv3() @@ -323,13 +294,11 @@ class MessageBuffer { } return $frame; - break; case Frame::OP_PING: case Frame::OP_PONG: break; default: return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid OP code'); - break; } return $frame; @@ -348,7 +317,7 @@ class MessageBuffer { /** * Determine if a message is valid - * @param \Ratchet\RFC6455\Messaging\MessageInterface + * @param MessageInterface * @return bool|int true if valid - false if incomplete - int of recommended close code */ public function checkMessage(MessageInterface $message) { @@ -361,7 +330,7 @@ class MessageBuffer { return true; } - private function checkUtf8($string) { + private function checkUtf8(string $string): bool { if (extension_loaded('mbstring')) { return mb_check_encoding($string, 'UTF-8'); } @@ -370,27 +339,27 @@ class MessageBuffer { } /** - * @return \Ratchet\RFC6455\Messaging\MessageInterface + * @return MessageInterface */ - public function newMessage() { + public function newMessage(): MessageInterface { return new Message; } /** * @param string|null $payload - * @param bool|null $final - * @param int|null $opcode - * @return \Ratchet\RFC6455\Messaging\FrameInterface + * @param bool $final + * @param int $opcode + * @return FrameInterface */ - public function newFrame($payload = null, $final = null, $opcode = null) { + public function newFrame(?string $payload = null, bool $final = true, int $opcode = Frame::OP_TEXT): FrameInterface { return new Frame($payload, $final, $opcode, $this->exceptionFactory); } - public function newCloseFrame($code, $reason = '') { + public function newCloseFrame(int $code, string $reason = ''): FrameInterface { return $this->newFrame(pack('n', $code) . $reason, true, Frame::OP_CLOSE); } - public function sendFrame(Frame $frame) { + public function sendFrame(FrameInterface $frame): void { if ($this->sender === null) { throw new \Exception('To send frames using the MessageBuffer, sender must be set.'); } @@ -408,7 +377,7 @@ class MessageBuffer { $sender($frame->getContents()); } - public function sendMessage($messagePayload, $final = true, $isBinary = false) { + public function sendMessage(string $messagePayload, bool $final = true, bool $isBinary = false): void { $opCode = $isBinary ? Frame::OP_BINARY : Frame::OP_TEXT; if ($this->streamingMessageOpCode === -1) { $this->streamingMessageOpCode = $opCode; @@ -431,29 +400,27 @@ class MessageBuffer { } } - private $inflator; - - private function getDeflateNoContextTakeover() { + private function getDeflateNoContextTakeover(): ?bool { return $this->checkForMask ? $this->permessageDeflateOptions->getServerNoContextTakeover() : $this->permessageDeflateOptions->getClientNoContextTakeover(); } - private function getDeflateWindowBits() { + private function getDeflateWindowBits(): int { return $this->checkForMask ? $this->permessageDeflateOptions->getServerMaxWindowBits() : $this->permessageDeflateOptions->getClientMaxWindowBits(); } - private function getInflateNoContextTakeover() { + private function getInflateNoContextTakeover(): ?bool { return $this->checkForMask ? $this->permessageDeflateOptions->getClientNoContextTakeover() : $this->permessageDeflateOptions->getServerNoContextTakeover(); } - private function getInflateWindowBits() { + private function getInflateWindowBits(): int { return $this->checkForMask ? $this->permessageDeflateOptions->getClientMaxWindowBits() : $this->permessageDeflateOptions->getServerMaxWindowBits(); } - private function inflateFrame(Frame $frame) { + private function inflateFrame(FrameInterface $frame): Frame { if ($this->inflator === null) { $this->inflator = inflate_init( ZLIB_ENCODING_RAW, @@ -480,16 +447,14 @@ class MessageBuffer { ); } - private $deflator; - - private function deflateFrame(Frame $frame) + private function deflateFrame(FrameInterface $frame): FrameInterface { if ($frame->getRsv1()) { return $frame; // frame is already deflated } if ($this->deflator === null) { - $bits = (int)$this->getDeflateWindowBits(); + $bits = $this->getDeflateWindowBits(); if ($bits === 8) { $bits = 9; } @@ -549,7 +514,7 @@ class MessageBuffer { * @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 @@ class MessageBufferTest extends TestCase false, null, 0, - 0x8000000000000000 + -1 ); } @@ -307,7 +307,7 @@ class MessageBufferTest extends TestCase static function (Frame $frame): void {}, false, null, - 0x8000000000000000, + -1, 0 ); }