diff --git a/src/Gelf/Transport/AbstractTransport.php b/src/Gelf/Transport/AbstractTransport.php index 640f936..05128d1 100644 --- a/src/Gelf/Transport/AbstractTransport.php +++ b/src/Gelf/Transport/AbstractTransport.php @@ -1,4 +1,5 @@ */ -abstract class AbstractTransport implements TransportInterface, PublisherInterface +abstract class AbstractTransport implements TransportInterface { + protected EncoderInterface $messageEncoder; - /** - * @var EncoderInterface - */ - protected $messageEncoder; + public function __construct(?EncoderInterface $messageEncoder = null) + { + $this->messageEncoder = $messageEncoder ?? new JsonEncoder(); + } /** * Sets a message encoder - * - * @param EncoderInterface $encoder - * - * @return $this */ - public function setMessageEncoder(EncoderInterface $encoder) + public function setMessageEncoder(EncoderInterface $encoder): self { $this->messageEncoder = $encoder; @@ -45,27 +44,9 @@ public function setMessageEncoder(EncoderInterface $encoder) /** * Returns the current message encoder - * - * @return EncoderInterface */ - public function getMessageEncoder() + public function getMessageEncoder(): EncoderInterface { return $this->messageEncoder; } - - /** - * Alias to send() without return value - * Required to fulfill the PublisherInterface - * - * @deprecated deprecated since 1.1 - * @codeCoverageIgnore - * - * @param MessageInterface $message - * - * @return int the number of bytes sent - */ - public function publish(MessageInterface $message) - { - return $this->send($message); - } } diff --git a/src/Gelf/Transport/AmqpTransport.php b/src/Gelf/Transport/AmqpTransport.php index e156831..6ff28a5 100644 --- a/src/Gelf/Transport/AmqpTransport.php +++ b/src/Gelf/Transport/AmqpTransport.php @@ -1,4 +1,5 @@ queue = $queue; - $this->exchange = $exchange; - $this->messageEncoder = new DefaultEncoder(); + public function __construct( + private AMQPExchange $exchange, + private AMQPQueue $queue + ) { + parent::__construct(); } /** * @inheritdoc */ - public function send(Message $message) + public function send(Message $message): int { $rawMessage = $this->getMessageEncoder()->encode($message); - $attributes = array( + $attributes = [ 'Content-type' => 'application/json' - ); + ]; // if queue is durable then mark message as 'persistent' if (($this->queue->getFlags() & AMQP_DURABLE) > 0) { diff --git a/src/Gelf/Transport/HttpTransport.php b/src/Gelf/Transport/HttpTransport.php index 217a7e7..ae7e0b3 100644 --- a/src/Gelf/Transport/HttpTransport.php +++ b/src/Gelf/Transport/HttpTransport.php @@ -27,76 +27,29 @@ */ class HttpTransport extends AbstractTransport { - const DEFAULT_HOST = "127.0.0.1"; - const DEFAULT_PORT = 12202; - const DEFAULT_PATH = "/gelf"; - - const AUTO_SSL_PORT = 443; - - /** - * @var string - */ - protected $host; - - /** - * @var int - */ - protected $port; - - /** - * @var string - */ - protected $path; - - /** - * @var StreamSocketClient - */ - protected $socketClient; - - /** - * @var SslOptions|null - */ - protected $sslOptions = null; - - /** - * @var string|null - */ - protected $authentication = null; + private const DEFAULT_HOST = "127.0.0.1"; + private const DEFAULT_PORT = 12202; + private const DEFAULT_PATH = "/gelf"; + private const AUTO_SSL_PORT = 443; - /** - * @var string|null - */ - protected $proxyUri = null; + private StreamSocketClient $socketClient; - /** - * @var bool - */ - protected $requestFullUri = false; + private ?string $authentication = null; + private ?string $proxyUri = null; + private ?bool $requestFullUri = false; - /** - * Class constructor - * - * @param string|null $host when NULL or empty default-host is used - * @param int|null $port when NULL or empty default-port is used - * @param string|null $path when NULL or empty default-path is used - * @param SslOptions|null $sslOptions when null not SSL is used - */ public function __construct( - $host = self::DEFAULT_HOST, - $port = self::DEFAULT_PORT, - $path = self::DEFAULT_PATH, - SslOptions $sslOptions = null + private string $host = self::DEFAULT_HOST, + private int $port = self::DEFAULT_PORT, + private string $path = self::DEFAULT_PATH, + private ?SslOptions $sslOptions = null ) { - $this->host = $host; - $this->port = $port; - $this->path = $path; + parent::__construct(); - if ($port == self::AUTO_SSL_PORT && $sslOptions == null) { - $sslOptions = new SslOptions(); + if ($port == self::AUTO_SSL_PORT && $sslOptions === null) { + $this->sslOptions = new SslOptions(); } - $this->sslOptions = $sslOptions; - $this->messageEncoder = new DefaultEncoder(); $this->socketClient = new StreamSocketClient( $this->getScheme(), $this->host, @@ -113,13 +66,8 @@ public function __construct( * If a username but no password is given, and empty password is used. * If a https URI is given, the provided SslOptions (with a fallback to * the default SslOptions) are used. - * - * @param string $url - * @param SslOptions|null $sslOptions - * - * @return HttpTransport */ - public static function fromUrl($url, SslOptions $sslOptions = null) + public static function fromUrl(string $url, ?SslOptions $sslOptions = null): static { $parsed = parse_url($url); @@ -130,12 +78,12 @@ public static function fromUrl($url, SslOptions $sslOptions = null) // check it's http or https $scheme = strtolower($parsed['scheme']); - if (!in_array($scheme, array('http', 'https'))) { + if (!in_array($scheme, ['http', 'https'])) { throw new \InvalidArgumentException("$url is not a valid http/https URL"); } // setup defaults - $defaults = array('port' => 80, 'path' => '', 'user' => null, 'pass' => ''); + $defaults = ['port' => 80, 'path' => '', 'user' => null, 'pass' => '']; // change some defaults for https if ($scheme == 'https') { @@ -157,22 +105,16 @@ public static function fromUrl($url, SslOptions $sslOptions = null) /** * Sets HTTP basic authentication - * - * @param string $username - * @param string $password */ - public function setAuthentication($username, $password) + public function setAuthentication(string $username, string $password): void { $this->authentication = $username . ":" . $password; } /** * Enables HTTP proxy - * - * @param $proxyUri - * @param bool $requestFullUri */ - public function setProxy($proxyUri, $requestFullUri = false) + public function setProxy(string $proxyUri, bool $requestFullUri = false): void { $this->proxyUri = $proxyUri; $this->requestFullUri = $requestFullUri; @@ -181,25 +123,21 @@ public function setProxy($proxyUri, $requestFullUri = false) } /** - * Sends a Message over this transport - * - * @param MessageInterface $message - * - * @return int the number of bytes sent + * @inheritDoc */ - public function send(MessageInterface $message) + public function send(MessageInterface $message): int { $messageEncoder = $this->getMessageEncoder(); $rawMessage = $messageEncoder->encode($message); - $request = array( + $request = [ sprintf("POST %s HTTP/1.1", $this->path), sprintf("Host: %s:%d", $this->host, $this->port), sprintf("Content-Length: %d", strlen($rawMessage)), "Content-Type: application/json", "Connection: Keep-Alive", "Accept: */*" - ); + ]; if (null !== $this->authentication) { $request[] = "Authorization: Basic " . base64_encode($this->authentication); @@ -219,7 +157,7 @@ public function send(MessageInterface $message) // if we don't have a HTTP/1.1 connection, or the server decided to close the connection // we should do so as well. next read/write-attempt will open a new socket in this case. - if (strpos($headers, "HTTP/1.1") !== 0 || preg_match("!Connection:\s*Close!i", $headers)) { + if (!str_starts_with($headers, "HTTP/1.1") || preg_match("!Connection:\s*Close!i", $headers)) { $this->socketClient->close(); } @@ -235,10 +173,7 @@ public function send(MessageInterface $message) return $byteCount; } - /** - * @return string - */ - private function readResponseHeaders() + private function readResponseHeaders(): string { $chunkSize = 1024; // number of bytes to read at once $delimiter = "\r\n\r\n"; // delimiter between headers and response @@ -247,37 +182,31 @@ private function readResponseHeaders() do { $chunk = $this->socketClient->read($chunkSize); $response .= $chunk; - } while (false === strpos($chunk, $delimiter) && strlen($chunk) > 0); + } while (!str_contains($chunk, $delimiter) && strlen($chunk) > 0); $elements = explode($delimiter, $response, 2); return $elements[0]; } - /** - * @return string - */ - private function getScheme() + private function getScheme(): string { return null === $this->sslOptions ? 'tcp' : 'ssl'; } - /** - * @return array - */ - private function getContext() + private function getContext(): array { - $options = array(); + $options = []; if (null !== $this->sslOptions) { $options = array_merge($options, $this->sslOptions->toStreamContext($this->host)); } if (null !== $this->proxyUri) { - $options['http'] = array( + $options['http'] = [ 'proxy' => $this->proxyUri, 'request_fulluri' => $this->requestFullUri - ); + ]; } return $options; @@ -285,20 +214,16 @@ private function getContext() /** * Sets the connect-timeout - * - * @param int $timeout */ - public function setConnectTimeout($timeout) + public function setConnectTimeout(int $timeout): void { $this->socketClient->setConnectTimeout($timeout); } /** * Returns the connect-timeout - * - * @return int */ - public function getConnectTimeout() + public function getConnectTimeout(): int { return $this->socketClient->getConnectTimeout(); } diff --git a/src/Gelf/Transport/IgnoreErrorTransportWrapper.php b/src/Gelf/Transport/IgnoreErrorTransportWrapper.php index fb1a350..bd1e1e9 100644 --- a/src/Gelf/Transport/IgnoreErrorTransportWrapper.php +++ b/src/Gelf/Transport/IgnoreErrorTransportWrapper.php @@ -1,48 +1,32 @@ transport = $transport; + public function __construct( + private TransportInterface $transport + ) { } /** - * Sends a Message over this transport. - * - * @param Message $message - * - * @return int the number of bytes sent + * @inheritDoc */ - public function send(Message $message) + public function send(Message $message): int { try { return $this->transport->send($message); - } catch (\Exception $e) { + } catch (Throwable $e) { $this->lastError = $e; return 0; } @@ -50,9 +34,8 @@ public function send(Message $message) /** * Returns the last error - * @return \Exception|null */ - public function getLastError() + public function getLastError(): ?Throwable { return $this->lastError; } diff --git a/src/Gelf/Transport/KeepAliveRetryTransportWrapper.php b/src/Gelf/Transport/KeepAliveRetryTransportWrapper.php index 6588255..7207b3e 100644 --- a/src/Gelf/Transport/KeepAliveRetryTransportWrapper.php +++ b/src/Gelf/Transport/KeepAliveRetryTransportWrapper.php @@ -1,4 +1,5 @@ transport = $transport; - $this->maxRetries = $maxRetries; - $this->exceptionMatcher = $exceptionMatcher; + public function __construct( + private TransportInterface $transport, + private int $maxRetries, + ?callable $exceptionMatcher = null + ) { + $this->exceptionMatcher = Closure::fromCallable($exceptionMatcher ?? fn (Throwable $_) => true); } - /** - * @return TransportInterface - */ - public function getTransport() + public function getTransport(): TransportInterface { return $this->transport; } /** - * Sends a Message over this transport. - * - * @param Message $message - * - * @return int calls function to send message + * @inheritDoc */ - public function send(Message $message) + public function send(Message $message): int { $tries = 0; @@ -64,12 +40,12 @@ public function send(Message $message) try { $tries++; return $this->transport->send($message); - } catch (\Exception $e) { + } catch (Throwable $e) { if ($this->maxRetries !== 0 && $tries > $this->maxRetries) { throw $e; } - if ($this->exceptionMatcher && !call_user_func($this->exceptionMatcher, $e)) { + if (!call_user_func($this->exceptionMatcher, $e)) { throw $e; } } diff --git a/src/Gelf/Transport/SslOptions.php b/src/Gelf/Transport/SslOptions.php index 4fda266..ccb98cd 100644 --- a/src/Gelf/Transport/SslOptions.php +++ b/src/Gelf/Transport/SslOptions.php @@ -1,4 +1,5 @@ */ @@ -20,80 +21,62 @@ class SslOptions { /** * Enable certificate validation of remote party - * - * @param boolean */ - protected $verifyPeer = true; + private bool $verifyPeer = true; /** * Allow self-signed certificates - * - * @param boolean */ - protected $allowSelfSigned = false; + private bool $allowSelfSigned = false; /** * Path to custom CA - * - * @param string|null */ - protected $caFile = null; + private ?string $caFile = null; /** * List of ciphers the SSL layer may use * * Formatted as specified in `ciphers(1)` - * - * @param string|null */ - protected $ciphers = null; + private ?string $ciphers = null; /** * Whether self-signed certificates are allowed - * - * @return boolean */ - public function getAllowSelfSigned() + public function getAllowSelfSigned(): bool { return $this->allowSelfSigned; } /** * Enables or disables the error on self-signed certificates - * - * @param boolean $allowSelfSigned */ - public function setAllowSelfSigned($allowSelfSigned) + public function setAllowSelfSigned(bool $allowSelfSigned): void { $this->allowSelfSigned = $allowSelfSigned; } /** * Returns the path to a custom CA - * - * @return string|null */ - public function getCaFile() + public function getCaFile(): ?string { return $this->caFile; } /** * Sets the path toa custom CA - * - * @param string|null $caFile */ - public function setCaFile($caFile) + public function setCaFile(?string $caFile): void { $this->caFile = $caFile; } /** * Returns des description of allowed ciphers - * - * @return string|null */ - public function getCiphers() + public function getCiphers(): ?string { return $this->ciphers; } @@ -102,46 +85,37 @@ public function getCiphers() * Set the allowed SSL/TLS ciphers * * Format must follow `ciphers(1)` - * - * @param string|null $ciphers */ - public function setCiphers($ciphers) + public function setCiphers(?string $ciphers): void { $this->ciphers = $ciphers; } /** * Whether to check the peer certificate - * - * @return boolean */ - public function getVerifyPeer() + public function getVerifyPeer(): bool { return $this->verifyPeer; } /** * Enable or disable the peer certificate check - * - * @param boolean $verifyPeer */ - public function setVerifyPeer($verifyPeer) + public function setVerifyPeer(bool $verifyPeer): void { $this->verifyPeer = $verifyPeer; } /** * Returns a stream-context representation of this config - * - * @param string|null $serverName - * @return array */ - public function toStreamContext($serverName = null) + public function toStreamContext(?string $serverName = null): array { - $sslContext = array( - 'verify_peer' => (bool) $this->verifyPeer, - 'allow_self_signed' => (bool) $this->allowSelfSigned - ); + $sslContext = [ + 'verify_peer' => $this->verifyPeer, + 'allow_self_signed' => $this->allowSelfSigned + ]; if (null !== $this->caFile) { $sslContext['cafile'] = $this->caFile; @@ -160,6 +134,6 @@ public function toStreamContext($serverName = null) } } - return array('ssl' => $sslContext); + return ['ssl' => $sslContext]; } } diff --git a/src/Gelf/Transport/StreamSocketClient.php b/src/Gelf/Transport/StreamSocketClient.php index 2b6add1..1cd7b8a 100644 --- a/src/Gelf/Transport/StreamSocketClient.php +++ b/src/Gelf/Transport/StreamSocketClient.php @@ -1,4 +1,5 @@ scheme = $scheme; - $this->host = $host; - $this->port = $port; - $this->context = $context; + public function __construct( + private string $scheme, + private string $host, + private int $port, + private array $context = [] + ) { } /** @@ -80,51 +45,6 @@ public function __destruct() $this->close(); } - /** - * Initializes socket-client - * - * @deprecated deprecated since v1.4.0 - * - * @param string $scheme like "udp" or "tcp" - * @param string $host - * @param integer $port - * @param array $context - * - * @return resource - * - * @throws RuntimeException on connection-failure - */ - protected static function initSocket($scheme, $host, $port, array $context) - { - $socketDescriptor = sprintf("%s://%s:%d", $scheme, $host, $port); - $socket = @stream_socket_client( - $socketDescriptor, - $errNo, - $errStr, - static::SOCKET_TIMEOUT, - \STREAM_CLIENT_CONNECT, - stream_context_create($context) - ); - - if ($socket === false) { - throw new RuntimeException( - sprintf( - "Failed to create socket-client for %s: %s (%s)", - $socketDescriptor, - $errStr, - $errNo - ) - ); - } - - // set non-blocking for UDP - if (strcasecmp("udp", $scheme) == 0) { - stream_set_blocking($socket, 0); - } - - return $socket; - } - /** * Internal function mimicking the behaviour of static::initSocket @@ -135,7 +55,7 @@ protected static function initSocket($scheme, $host, $port, array $context) * * @throws RuntimeException on connection-failure */ - private function buildSocket() + private function buildSocket(): mixed { $socketDescriptor = sprintf( "%s://%s:%d", @@ -166,7 +86,7 @@ private function buildSocket() // set non-blocking for UDP if (strcasecmp("udp", $this->scheme) == 0) { - stream_set_blocking($socket, 0); + stream_set_blocking($socket, true); } return $socket; @@ -177,7 +97,7 @@ private function buildSocket() * * @return resource */ - public function getSocket() + public function getSocket(): mixed { // lazy initializing of socket-descriptor if (!$this->socket) { @@ -190,25 +110,18 @@ public function getSocket() /** * Writes a given string to the socket and returns the * number of written bytes - * - * @param string $buffer - * - * @return int - * - * @throws RuntimeException on write-failure */ - public function write($buffer) + public function write(string $buffer): int { - $buffer = (string) $buffer; $bufLen = Binary::safeStrlen($buffer); $socket = $this->getSocket(); $written = 0; while ($written < $bufLen) { - // PHP's fwrite does not behave nice in regards to errors, so we wrap + // PHP's fwrite does not behave nice in regard to errors, so we wrap // it with a temporary error handler and treat every warning/notice as - // a error + // an error $failed = false; $errorMessage = "Failed to write to socket"; set_error_handler(function ($errno, $errstr) use (&$failed, &$errorMessage) { @@ -223,7 +136,7 @@ public function write($buffer) } if ($failed || $byteCount === false) { - throw new \RuntimeException($errorMessage); + throw new RuntimeException($errorMessage); } $written += $byteCount; @@ -235,12 +148,8 @@ public function write($buffer) /** * Reads a given number of bytes from the socket - * - * @param integer $byteCount - * - * @return string */ - public function read($byteCount) + public function read(int $byteCount): string { return fread($this->getSocket(), $byteCount); } @@ -248,7 +157,7 @@ public function read($byteCount) /** * Closes underlying socket explicitly */ - public function close() + public function close(): void { if (!is_resource($this->socket)) { return; @@ -260,30 +169,24 @@ public function close() /** * Checks if the socket is closed - * - * @return bool */ - public function isClosed() + public function isClosed(): bool { return $this->socket === null; } /** * Returns the current connect-timeout - * - * @return int */ - public function getConnectTimeout() + public function getConnectTimeout(): int { return $this->connectTimeout; } /** * Sets the connect-timeout - * - * @param int $timeout */ - public function setConnectTimeout($timeout) + public function setConnectTimeout(int $timeout): void { if (!$this->isClosed()) { throw new \LogicException("Cannot change socket properties with an open connection"); @@ -294,20 +197,16 @@ public function setConnectTimeout($timeout) /** * Returns the stream context - * - * @return array */ - public function getContext() + public function getContext(): array { return $this->context; } /** * Sets the stream context - * - * @param array $context */ - public function setContext(array $context) + public function setContext(array $context): void { if (!$this->isClosed()) { throw new \LogicException("Cannot change socket properties with an open connection"); diff --git a/src/Gelf/Transport/TcpTransport.php b/src/Gelf/Transport/TcpTransport.php index 5eb6c2c..8a47a2f 100644 --- a/src/Gelf/Transport/TcpTransport.php +++ b/src/Gelf/Transport/TcpTransport.php @@ -1,4 +1,5 @@ host = $host; - $this->port = $port; + parent::__construct(); - if ($port == self::AUTO_SSL_PORT && $sslOptions == null) { - $sslOptions = new SslOptions(); + if ($port == self::AUTO_SSL_PORT && $this->sslOptions == null) { + $this->sslOptions = new SslOptions(); } - $this->sslOptions = $sslOptions; - - $this->setMessageEncoder(new DefaultEncoder()); $this->socketClient = new StreamSocketClient( $this->getScheme(), $this->host, @@ -85,37 +56,25 @@ public function __construct( } /** - * Sends a Message over this transport - * - * @param Message $message - * - * @return int the number of TCP packets sent + * @inheritDoc */ - public function send(Message $message) + public function send(Message $message): int { $rawMessage = $this->getMessageEncoder()->encode($message) . "\0"; // send message in one packet - $this->socketClient->write($rawMessage); - - return 1; + return $this->socketClient->write($rawMessage); } - /** - * @return string - */ - private function getScheme() + private function getScheme(): string { return null === $this->sslOptions ? 'tcp' : 'ssl'; } - /** - * @return array - */ - private function getContext() + private function getContext(): array { if (null === $this->sslOptions) { - return array(); + return []; } return $this->sslOptions->toStreamContext($this->host); @@ -123,25 +82,21 @@ private function getContext() /** * Sets the connect-timeout - * - * @param int $timeout */ - public function setConnectTimeout($timeout) + public function setConnectTimeout(int $timeout): void { $this->socketClient->setConnectTimeout($timeout); } /** * Returns the connect-timeout - * - * @return int */ - public function getConnectTimeout() + public function getConnectTimeout(): int { return $this->socketClient->getConnectTimeout(); } - public function setMessageEncoder(EncoderInterface $encoder) + public function setMessageEncoder(EncoderInterface $encoder): self { if (!$encoder instanceof NoNullByteEncoderInterface) { throw new InvalidArgumentException( diff --git a/src/Gelf/Transport/TransportInterface.php b/src/Gelf/Transport/TransportInterface.php index afd2ec3..93ce196 100644 --- a/src/Gelf/Transport/TransportInterface.php +++ b/src/Gelf/Transport/TransportInterface.php @@ -1,4 +1,5 @@ socketClient = new StreamSocketClient('udp', $host, $port); - $this->chunkSize = $chunkSize; - - $this->messageEncoder = new DefaultEncoder(); if ($chunkSize > 0 && $chunkSize <= self::CHUNK_HEADER_LENGTH) { throw new InvalidArgumentException('Chunk-size has to exceed ' . self::CHUNK_HEADER_LENGTH @@ -75,13 +68,9 @@ public function __construct( } /** - * Sends a Message over this transport - * - * @param Message $message - * - * @return int the number of UDP packets sent + * @inheritDoc */ - public function send(Message $message) + public function send(Message $message): int { $rawMessage = $this->getMessageEncoder()->encode($message); @@ -100,14 +89,8 @@ public function send(Message $message) /** * Sends given string in multiple chunks - * - * @param string $rawMessage - * @return int - * - * @throws RuntimeException on too large messages which would exceed the - * maximum number of possible chunks */ - protected function sendMessageInChunks($rawMessage) + private function sendMessageInChunks(string $rawMessage): int { // split to chunks $chunks = str_split($rawMessage, $this->chunkSize - self::CHUNK_HEADER_LENGTH); diff --git a/tests/Gelf/Test/Transport/AmqpTransportTest.php b/tests/Gelf/Test/Transport/AmqpTransportTest.php deleted file mode 100644 index 5fb7ef5..0000000 --- a/tests/Gelf/Test/Transport/AmqpTransportTest.php +++ /dev/null @@ -1,150 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Gelf\Test\Transport; - -use Gelf\Transport\AmqpTransport; -use PHPUnit\Framework\TestCase; - -class AmqpTransportTest extends TestCase -{ - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $message; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | \Gelf\Encoder\EncoderInterface - */ - protected $encoder; - /** - * @var string - */ - protected $testMessage; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | AmqpTransport - */ - protected $transport; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | \AMQPExchange - */ - protected $exchange; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject | \AMQPQueue - */ - protected $queue; - - public function setUp() - { - if (!extension_loaded('amqp')) { - $this->markTestSkipped('Requires ext-amqp'); - return; - } - - if (!defined('AMQP_NOPARAM')) { - define('AMQP_NOPARAM', 0); - } - - if (!defined('AMQP_DURABLE')) { - define('AMQP_DURABLE', 2); - } - - $this->testMessage = str_repeat("0123456789", 30); // 300 char string - - $this->exchange = $this->createMock( - "\\AMQPExchange", - $methods = array('publish'), - $args = array(), - $mockClassName = '', - $callConstructor = false - ); - $this->queue = $this->createMock( - "\\AMQPQueue", - $methods = array('getName', 'getFlags'), - $args = array(), - $mockClassName = '', - $callConstructor = false - ); - - $this->message = $this->createMock("\\Gelf\\Message"); - - // create an encoder always return $testMessage - $this->encoder = $this->createMock("\\Gelf\\Encoder\\EncoderInterface"); - $this->encoder->expects($this->any())->method('encode')->will( - $this->returnValue($this->testMessage) - ); - $this->transport = $this->getTransport(0); - } - - protected function getTransport() - { - $transport = new AmqpTransport($this->exchange, $this->queue); - $transport->setMessageEncoder($this->encoder); - - $reflectedTransport = new \ReflectionObject($transport); - - $reflectedExchange = $reflectedTransport->getProperty('exchange'); - $reflectedExchange->setAccessible(true); - $reflectedExchange->setValue($transport, $this->exchange); - - $reflectedQueue = $reflectedTransport->getProperty('queue'); - $reflectedQueue->setAccessible(true); - $reflectedQueue->setValue($transport, $this->queue); - - return $transport; - } - - public function testSetEncoder() - { - $encoder = $this->createMock('\\Gelf\\Encoder\\EncoderInterface'); - $this->transport->setMessageEncoder($encoder); - - $this->assertEquals($encoder, $this->transport->getMessageEncoder()); - } - - public function testGetEncoder() - { - $transport = new AmqpTransport($this->exchange, $this->queue); - $this->assertInstanceOf( - "\\Gelf\\Encoder\\EncoderInterface", - $transport->getMessageEncoder() - ); - } - - public function testPublish() - { - $transport = $this->getMockBuilder("\\Gelf\\Transport\\HttpTransport") - ->setMethods(array("send")) - ->disableOriginalConstructor() - ->getMock(); - - $transport - ->expects($this->once()) - ->method("send") - ->with($this->message) - ->willReturn(42); - - $response = $transport->publish($this->message); - - $this->assertSame(42, $response); - } - - public function testSend() - { - $this->exchange->expects($this->once())->method('publish'); - - $transport = $this->getTransport(); - $transport->send($this->message); - } -} diff --git a/tests/Gelf/Test/Transport/HttpTransportTest.php b/tests/Gelf/Test/Transport/HttpTransportTest.php index 9c4d561..f9cb760 100644 --- a/tests/Gelf/Test/Transport/HttpTransportTest.php +++ b/tests/Gelf/Test/Transport/HttpTransportTest.php @@ -1,4 +1,5 @@ testMessage = str_repeat("0123456789", 30); // 300 char string - $this->socketClient = $this->createMock( - "\\Gelf\\Transport\\StreamSocketClient", - $methods = array(), - $args = array(), - $mockClassName = '', - $callConstructor = false - ); - $this->message = $this->createMock("\\Gelf\\Message"); + $this->socketClient = $this->createMock(StreamSocketClient::class); + $this->message = $this->createMock(MessageInterface::class); // create an encoder always return $testMessage - $this->encoder = $this->createMock("\\Gelf\\Encoder\\EncoderInterface"); + $this->encoder = $this->createMock(EncoderInterface::class); $this->encoder->expects($this->any())->method('encode')->will( $this->returnValue($this->testMessage) ); @@ -70,7 +49,7 @@ public function setUp() $this->transport = $this->getTransport(); } - protected function getTransport() + private function getTransport(): HttpTransport { // initialize transport with an unlimited packet-size // and the mocked message encoder @@ -78,17 +57,16 @@ protected function getTransport() $transport->setMessageEncoder($this->encoder); // replace internal stream socket client with our mock - $reflectedTransport = new \ReflectionObject($transport); + $reflectedTransport = new ReflectionObject($transport); $reflectedClient = $reflectedTransport->getProperty('socketClient'); $reflectedClient->setAccessible(true); - $this->originalSocketClient = $reflectedClient->getValue($transport); $reflectedClient->setValue($transport, $this->socketClient); return $transport; } - public function testConstructor() + public function testConstructor(): void { $transport = new HttpTransport(); $this->validateTransport($transport, '127.0.0.1', 12202, '/gelf'); @@ -103,19 +81,15 @@ public function testConstructor() $this->validateTransport($transport, 'localhost', 443, '/gelf', new SslOptions()); } - /** - * @expectedException \InvalidArgumentException - */ - public function testFromUrlConstructorInvalidUri() + public function testFromUrlConstructorInvalidUri(): void { + self::expectException(InvalidArgumentException::class); HttpTransport::fromUrl('-://:-'); } - /** - * @expectedException \InvalidArgumentException - */ - public function testFromUrlConstructorInvalidScheme() + public function testFromUrlConstructorInvalidScheme(): void { + self::expectException(InvalidArgumentException::class); HttpTransport::fromUrl('ftp://foobar'); } @@ -155,8 +129,8 @@ public function validateTransport( $path, $sslOptions = null, $authentication = null - ) { - $r = new \ReflectionObject($transport); + ): void { + $r = new ReflectionObject($transport); $testProperties = array( 'host' => $host, @@ -169,54 +143,46 @@ public function validateTransport( foreach ($testProperties as $property => $value) { $p = $r->getProperty($property); $p->setAccessible(true); - $this->assertEquals($value, $p->getValue($transport)); + self::assertEquals($value, $p->getValue($transport)); } } - public function testSslOptionsAreUsed() + public function testSslOptionsAreUsed(): void { - $sslOptions = $this->createMock('\\Gelf\\Transport\\SslOptions'); + $sslOptions = $this->createMock(SslOptions::class); $sslOptions->expects($this->exactly(2)) ->method('toStreamContext') ->will($this->returnValue(array('ssl' => null))); - $transport = new HttpTransport("localhost", "12345", "/gelf", $sslOptions); + $transport = new HttpTransport("localhost", 12345, "/gelf", $sslOptions); - $reflectedTransport = new \ReflectionObject($transport); + $reflectedTransport = new ReflectionObject($transport); $reflectedGetContext = $reflectedTransport->getMethod('getContext'); $reflectedGetContext->setAccessible(true); $context = $reflectedGetContext->invoke($transport); - $this->assertEquals(array('ssl' => null), $context); + self::assertEquals(array('ssl' => null), $context); } - public function testSetEncoder() + public function testSetEncoder(): void { - $encoder = $this->createMock('\\Gelf\\Encoder\\EncoderInterface'); + $encoder = $this->createMock(EncoderInterface::class); $this->transport->setMessageEncoder($encoder); - $this->assertEquals($encoder, $this->transport->getMessageEncoder()); + self::assertEquals($encoder, $this->transport->getMessageEncoder()); } - public function testGetEncoder() + public function testEmptyResponseException(): void { - $transport = new HttpTransport(); - $this->assertInstanceOf( - "\\Gelf\\Encoder\\EncoderInterface", - $transport->getMessageEncoder() + self::expectException(RuntimeException::class); + self::expectExceptionMessage( + "Graylog-Server didn't answer properly, expected 'HTTP/1.x 202 Accepted', response is ''" ); - } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Graylog-Server didn't answer properly, expected 'HTTP/1.x 202 Accepted', response is '' - */ - public function testEmptyResponseException() - { $this->transport->send($this->message); } - public function testSendUncompressed() + public function testSendUncompressed(): void { $request = "POST /gelf HTTP/1.1"."\r\n" . "Host: 127.0.0.1:12202"."\r\n" @@ -224,7 +190,7 @@ public function testSendUncompressed() . "Content-Type: application/json"."\r\n" . "Connection: Keep-Alive"."\r\n" . "Accept: */*"."\r\n" - . ""."\r\n" + . "\r\n" . $this->testMessage; $this->socketClient @@ -240,17 +206,19 @@ public function testSendUncompressed() $this->transport->send($this->message); } - public function testAuthentication() + public function testAuthentication(): void { $this->transport->setAuthentication("test", "test"); - $test = $this; $this->socketClient->expects($this->once()) ->method("write") - ->will($this->returnCallback(function ($data) use ($test) { - $test->assertContains("Authorization: Basic " . base64_encode("test:test"), $data); + ->will($this->returnCallback(function ($data) { + self::assertStringContainsString("Authorization: Basic " . base64_encode("test:test"), $data); + return 1; })); - + + + $this->socketClient ->expects($this->once()) ->method("read") @@ -259,14 +227,13 @@ public function testAuthentication() $this->transport->send($this->message); } - public function testProxy() + public function testProxy(): void { - $test = $this; $this->socketClient->expects($this->once()) ->method("setContext") - ->willReturnCallback(function (array $context) use ($test) { - $test->assertArrayHasKey("http", $context); - $test->assertEquals( + ->willReturnCallback(function (array $context) { + self::assertArrayHasKey("http", $context); + self::assertEquals( array( "proxy" => "tcp://proxy.example.com:5100", "request_fulluri" => true @@ -278,7 +245,7 @@ public function testProxy() $this->transport->setProxy("tcp://proxy.example.com:5100", true); } - public function testSendCompressed() + public function testSendCompressed(): void { $request = "POST /gelf HTTP/1.1"."\r\n" . "Host: 127.0.0.1:12202"."\r\n" @@ -300,7 +267,7 @@ public function testSendCompressed() ->method("read") ->will($this->returnValue("HTTP/1.1 202 Accepted\r\n\r\n")); - $compressedEncoder = $this->createMock("\\Gelf\\Encoder\\CompressedJsonEncoder"); + $compressedEncoder = $this->createMock(CompressedJsonEncoder::class); $compressedEncoder ->expects($this->any()) ->method('encode') @@ -312,25 +279,7 @@ public function testSendCompressed() $this->transport->send($this->message); } - public function testPublish() - { - $transport = $this->getMockBuilder("\\Gelf\\Transport\\HttpTransport") - ->setMethods(array("send")) - ->disableOriginalConstructor() - ->getMock(); - - $transport - ->expects($this->once()) - ->method("send") - ->with($this->message) - ->willReturn(42); - - $response = $transport->publish($this->message); - - $this->assertSame(42, $response); - } - - public function testCloseSocketOnHttpOneZero() + public function testCloseSocketOnHttpOneZero(): void { $this->socketClient ->expects($this->once()) @@ -344,7 +293,7 @@ public function testCloseSocketOnHttpOneZero() $this->transport->send($this->message); } - public function testCloseSocketOnConnectionClose() + public function testCloseSocketOnConnectionClose(): void { $this->socketClient ->expects($this->once()) @@ -358,14 +307,14 @@ public function testCloseSocketOnConnectionClose() $this->transport->send($this->message); } - public function testConnectTimeout() + public function testConnectTimeout(): void { $this->socketClient ->expects($this->once()) ->method('getConnectTimeout') ->will($this->returnValue(123)); - $this->assertEquals(123, $this->transport->getConnectTimeout()); + self::assertEquals(123, $this->transport->getConnectTimeout()); $this->socketClient ->expects($this->once()) diff --git a/tests/Gelf/Test/Transport/IgnoreErrorTransportWrapperTest.php b/tests/Gelf/Test/Transport/IgnoreErrorTransportWrapperTest.php index ff41b96..4dd5863 100644 --- a/tests/Gelf/Test/Transport/IgnoreErrorTransportWrapperTest.php +++ b/tests/Gelf/Test/Transport/IgnoreErrorTransportWrapperTest.php @@ -1,19 +1,21 @@ buildMessage(); - $expectedException = new \RuntimeException(); + $expectedException = new RuntimeException(); $transport = $this->buildTransport(); $wrapper = new IgnoreErrorTransportWrapper($transport); @@ -26,23 +28,17 @@ public function testSend() $bytes = $wrapper->send($expectedMessage); $lastError = $wrapper->getLastError(); - $this->assertEquals(0, $bytes); - $this->assertSame($expectedException, $lastError); + self::assertEquals(0, $bytes); + self::assertSame($expectedException, $lastError); } - /** - * @return MockObject|AbstractTransport - */ - private function buildTransport() + private function buildTransport(): MockObject|TransportInterface { - return $this->createMock("\\Gelf\\Transport\\AbstractTransport"); + return $this->createMock(TransportInterface::class); } - /** - * @return MockObject|Message - */ - private function buildMessage() + private function buildMessage(): MockObject|MessageInterface { - return $this->createMock("\\Gelf\\Message"); + return $this->createMock(MessageInterface::class); } } diff --git a/tests/Gelf/Test/Transport/KeepAliveRetryTransportWrapperTest.php b/tests/Gelf/Test/Transport/KeepAliveRetryTransportWrapperTest.php index 2ba8299..b4ed92b 100644 --- a/tests/Gelf/Test/Transport/KeepAliveRetryTransportWrapperTest.php +++ b/tests/Gelf/Test/Transport/KeepAliveRetryTransportWrapperTest.php @@ -1,83 +1,67 @@ message = new Message(); - $this->transport = $this->buildTransport(); + $this->transport = $this->createMock(HttpTransport::class); $this->wrapper = new KeepAliveRetryTransportWrapper($this->transport); } - public function testSendSuccess() + public function testSendSuccess(): void { $this->transport->expects($this->once()) ->method('send') ->with($this->message) - ->will($this->returnValue(self::SUCCESS_VALUE)); + ->will($this->returnValue(42)); $bytes = $this->wrapper->send($this->message); - $this->assertEquals(self::SUCCESS_VALUE, $bytes); + self::assertEquals(42, $bytes); } - public function testSendSuccessAfterRetry() + public function testSendSuccessAfterRetry(): void { - $expectedException = new RuntimeException(KeepAliveRetryTransportWrapper::NO_RESPONSE); + $expectedException = new RuntimeException(self::FAILURE_MESSAGE); $this->transport->expects($this->exactly(2)) ->method('send') ->with($this->message) ->will($this->onConsecutiveCalls( $this->throwException($expectedException), - $this->returnValue(self::SUCCESS_VALUE) + 42 )); $bytes = $this->wrapper->send($this->message); - $this->assertEquals(self::SUCCESS_VALUE, $bytes); + self::assertEquals(42, $bytes); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage response is '' - */ - public function testSendFailTwiceWithoutResponse() + public function testSendFailTwiceWithoutResponse(): void { - $expectedException1 = new RuntimeException(KeepAliveRetryTransportWrapper::NO_RESPONSE); - $expectedException2 = new RuntimeException(KeepAliveRetryTransportWrapper::NO_RESPONSE); + self::expectException(RuntimeException::class); + self::expectExceptionMessage("response is ''"); + + $expectedException1 = new RuntimeException(self::FAILURE_MESSAGE); + $expectedException2 = new RuntimeException(self::FAILURE_MESSAGE); $this->transport->expects($this->exactly(2)) ->method('send') @@ -90,12 +74,11 @@ public function testSendFailTwiceWithoutResponse() $this->wrapper->send($this->message); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage foo - */ - public function testSendFailWithUnmanagedException() + public function testSendFailWithUnmanagedException(): void { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage("foo"); + $expectedException = new RuntimeException('foo'); $this->transport->expects($this->once()) @@ -105,12 +88,4 @@ public function testSendFailWithUnmanagedException() $this->wrapper->send($this->message); } - - /** - * @return MockObject|HttpTransport - */ - private function buildTransport() - { - return $this->createMock("\\Gelf\\Transport\\HttpTransport"); - } } diff --git a/tests/Gelf/Test/Transport/RetryTransportWrapperTest.php b/tests/Gelf/Test/Transport/RetryTransportWrapperTest.php index bf37596..be95099 100644 --- a/tests/Gelf/Test/Transport/RetryTransportWrapperTest.php +++ b/tests/Gelf/Test/Transport/RetryTransportWrapperTest.php @@ -1,44 +1,37 @@ message = new Message(); - $this->transport = $this->buildTransport(); + $this->transport = $this->createMock(TransportInterface::class); } - public function testGetTransport() + public function testGetTransport(): void { $wrapper = new RetryTransportWrapper($this->transport, 1, null); - $this->assertEquals($this->transport, $wrapper->getTransport()); + self::assertEquals($this->transport, $wrapper->getTransport()); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage bar - */ - public function testWithoutMatcher() + public function testWithoutMatcher(): void { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage("bar"); + $wrapper = new RetryTransportWrapper($this->transport, 1, null); $expectedException1 = new RuntimeException('foo'); @@ -54,18 +47,15 @@ public function testWithoutMatcher() $bytes = $wrapper->send($this->message); - $this->assertEquals('', $bytes); + self::assertEquals('', $bytes); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage bar - */ - public function testWithMatcher() + public function testWithMatcher(): void { - $wrapper = new RetryTransportWrapper($this->transport, 1, function (RuntimeException $e) { - return true; - }); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage("bar"); + + $wrapper = new RetryTransportWrapper($this->transport, 1); $expectedException1 = new RuntimeException('foo'); $expectedException2 = new RuntimeException('bar'); @@ -80,18 +70,14 @@ public function testWithMatcher() $bytes = $wrapper->send($this->message); - $this->assertEquals('', $bytes); + self::assertEquals('', $bytes); } - - /** - * @expectedException RuntimeException - * @expectedExceptionMessage foo - */ - public function testWithFalseMatcher() + + public function testWithFalseMatcher(): void { - $wrapper = new RetryTransportWrapper($this->transport, 1, function (RuntimeException $e) { - return false; - }); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage("foo"); + $wrapper = new RetryTransportWrapper($this->transport, 1, fn () => false); $expectedException1 = new RuntimeException('foo'); @@ -102,14 +88,6 @@ public function testWithFalseMatcher() $bytes = $wrapper->send($this->message); - $this->assertEquals('', $bytes); - } - - /** - * @return MockObject|AbstractTransport - */ - private function buildTransport() - { - return $this->createMock("\\Gelf\\Transport\\AbstractTransport"); + self::assertEquals('', $bytes); } } diff --git a/tests/Gelf/Test/Transport/SslOptionsTest.php b/tests/Gelf/Test/Transport/SslOptionsTest.php index f5344f7..512b984 100644 --- a/tests/Gelf/Test/Transport/SslOptionsTest.php +++ b/tests/Gelf/Test/Transport/SslOptionsTest.php @@ -1,4 +1,5 @@ assertTrue($options->getVerifyPeer()); - $this->assertFalse($options->getAllowSelfSigned()); - $this->assertNull($options->getCaFile()); - $this->assertNull($options->getCiphers()); + self::assertTrue($options->getVerifyPeer()); + self::assertFalse($options->getAllowSelfSigned()); + self::assertNull($options->getCaFile()); + self::assertNull($options->getCiphers()); // test setters $options->setVerifyPeer(false); @@ -32,49 +33,49 @@ public function testState() $options->setCaFile('/path/to/ca'); $options->setCiphers('ALL:!ADH:@STRENGTH'); - $this->assertFalse($options->getVerifyPeer()); - $this->assertTrue($options->getAllowSelfSigned()); - $this->assertEquals('/path/to/ca', $options->getCaFile()); - $this->assertEquals('ALL:!ADH:@STRENGTH', $options->getCiphers()); + self::assertFalse($options->getVerifyPeer()); + self::assertTrue($options->getAllowSelfSigned()); + self::assertEquals('/path/to/ca', $options->getCaFile()); + self::assertEquals('ALL:!ADH:@STRENGTH', $options->getCiphers()); } - public function testToStreamContext() + public function testToStreamContext(): void { $options = new SslOptions(); - $this->assertEquals(array( - 'ssl' => array( + self::assertEquals([ + 'ssl' => [ 'verify_peer' => true, 'allow_self_signed' => false, - ) - ), $options->toStreamContext()); + ] + ], $options->toStreamContext()); $options->setVerifyPeer(false); $options->setAllowSelfSigned(true); $options->setCaFile('/path/to/ca'); $options->setCiphers('ALL:!ADH:@STRENGTH'); - $this->assertEquals(array( - 'ssl' => array( + self::assertEquals([ + 'ssl' => [ 'verify_peer' => false, 'allow_self_signed' => true, 'cafile' => '/path/to/ca', 'ciphers' => 'ALL:!ADH:@STRENGTH' - ) - ), $options->toStreamContext()); + ] + ], $options->toStreamContext()); $options->setCaFile(null); $options->setCiphers(null); - $this->assertEquals(array( - 'ssl' => array( + self::assertEquals([ + 'ssl' => [ 'verify_peer' => false, 'allow_self_signed' => true, - ) - ), $options->toStreamContext()); + ] + ], $options->toStreamContext()); } - public function testToStreamContextWithHostname() + public function testToStreamContextWithHostname(): void { $options = new SslOptions(); $peerNameKey = PHP_VERSION_ID < 50600 ? 'CN_match' : 'peer_name'; @@ -84,25 +85,25 @@ public function testToStreamContextWithHostname() $options->setVerifyPeer(false); $context = $options->toStreamContext($host); - $this->assertArrayHasKey('ssl', $context); - $this->assertArrayHasKey('SNI_enabled', $context['ssl']); - $this->assertArrayNotHasKey('CN_match', $context['ssl']); - $this->assertArrayHasKey($sniPeerNameKey, $context['ssl']); + self::assertArrayHasKey('ssl', $context); + self::assertArrayHasKey('SNI_enabled', $context['ssl']); + self::assertArrayNotHasKey('CN_match', $context['ssl']); + self::assertArrayHasKey($sniPeerNameKey, $context['ssl']); - $this->assertEquals(true, $context['ssl']['SNI_enabled']); - $this->assertEquals($host, $context['ssl'][$sniPeerNameKey]); + self::assertEquals(true, $context['ssl']['SNI_enabled']); + self::assertEquals($host, $context['ssl'][$sniPeerNameKey]); $options->setVerifyPeer(true); $context = $options->toStreamContext($host); - $this->assertArrayHasKey('ssl', $context); - $this->assertArrayHasKey('SNI_enabled', $context['ssl']); - $this->assertArrayHasKey($peerNameKey, $context['ssl']); - $this->assertArrayHasKey($sniPeerNameKey, $context['ssl']); + self::assertArrayHasKey('ssl', $context); + self::assertArrayHasKey('SNI_enabled', $context['ssl']); + self::assertArrayHasKey($peerNameKey, $context['ssl']); + self::assertArrayHasKey($sniPeerNameKey, $context['ssl']); - $this->assertEquals(true, $context['ssl']['SNI_enabled']); - $this->assertEquals($host, $context['ssl'][$peerNameKey]); - $this->assertEquals($host, $context['ssl'][$sniPeerNameKey]); + self::assertEquals(true, $context['ssl']['SNI_enabled']); + self::assertEquals($host, $context['ssl'][$peerNameKey]); + self::assertEquals($host, $context['ssl'][$sniPeerNameKey]); } } diff --git a/tests/Gelf/Test/Transport/StreamSocketClientTcpTest.php b/tests/Gelf/Test/Transport/StreamSocketClientTcpTest.php index 636f9e5..19d0d1a 100644 --- a/tests/Gelf/Test/Transport/StreamSocketClientTcpTest.php +++ b/tests/Gelf/Test/Transport/StreamSocketClientTcpTest.php @@ -1,4 +1,5 @@ host; - $this->serverSocket = stream_socket_server( - "tcp://$host:0", - $errNo, - $errMsg - ); + $this->serverSocket = stream_socket_server("tcp://$host:0"); if (!$this->serverSocket) { - throw new \RuntimeException("Failed to create test-server-socket"); + throw new RuntimeException("Failed to create test-server-socket"); } // get random port $socketName = stream_socket_get_name( $this->serverSocket, - $peerName = false + remote: false ); - list(, $port) = explode(":", $socketName); + [, $port] = explode(":", $socketName); - $this->socketClient = new StreamSocketClient('tcp', $host, $port); - $this->port = $port; + $this->socketClient = new StreamSocketClient('tcp', $host, (int)$port); + $this->port = (int)$port; } - public function tearDown() + public function tearDown(): void { unset($this->socketClient); if ($this->serverSocket !== null) { @@ -63,37 +54,36 @@ public function tearDown() } } - public function testGetSocket() + public function testGetSocket(): void { - $this->assertInternalType('resource', $this->socketClient->getSocket()); + self::assertIsResource($this->socketClient->getSocket()); } - public function testWrite() + public function testWrite(): void { $testData = "Hello World!"; $numBytes = $this->socketClient->write($testData); - $this->assertEquals(strlen($testData), $numBytes); + self::assertEquals(strlen($testData), $numBytes); // check that message is sent to server $connection = stream_socket_accept($this->serverSocket); $readData = fread($connection, $numBytes); - $this->assertEquals($testData, $readData); + self::assertEquals($testData, $readData); } - /** - * @expectedException \RuntimeException - */ - public function testBadWrite() + public function testBadWrite(): void { + self::expectException(RuntimeException::class); + $this->socketClient->write("Hello "); fclose($this->serverSocket); $this->serverSocket = null; $this->socketClient->write("world!"); } - public function testMultiWrite() + public function testMultiWrite(): void { // lower timeout for server-socket stream_set_timeout($this->serverSocket, 0, 100); @@ -103,33 +93,33 @@ public function testMultiWrite() $testData = "First thing in the morning should be to check,"; $numBytes = $this->socketClient->write($testData); - $this->assertEquals(strlen($testData), $numBytes); + self::assertEquals(strlen($testData), $numBytes); // open connection on server-socket $serverConnection = stream_socket_accept($this->serverSocket); $readData = fread($serverConnection, $numBytes); - $this->assertEquals($testData, $readData); + self::assertEquals($testData, $readData); // -- second write $testData = "if we can write multiple times on the same socket"; $numBytes = $this->socketClient->write($testData); - $this->assertEquals(strlen($testData), $numBytes); + self::assertEquals(strlen($testData), $numBytes); $readData = fread($serverConnection, $numBytes); - $this->assertEquals($testData, $readData); + self::assertEquals($testData, $readData); fclose($serverConnection); } - public function testRead() + public function testRead(): void { $testData = "Hello Reader :)"; $numBytes = $this->socketClient->write($testData); - $this->assertEquals(strlen($testData), $numBytes); + self::assertEquals(strlen($testData), $numBytes); // lower timeout for server-socket stream_set_timeout($this->serverSocket, 0, 100); @@ -142,15 +132,15 @@ public function testRead() fclose($connection); $readData = $this->socketClient->read($numBytes); - $this->assertEquals($testData, $readData); + self::assertEquals($testData, $readData); } - public function testReadContents() + public function testReadContents(): void { $testData = str_repeat("0123456789", mt_rand(1, 10)); $numBytes = $this->socketClient->write($testData); - $this->assertEquals(strlen($testData), $numBytes); + self::assertEquals(strlen($testData), $numBytes); // lower timeout for server-socket stream_set_timeout($this->serverSocket, 0, 100); @@ -164,64 +154,54 @@ public function testReadContents() $readData = $this->socketClient->read(1024); - $this->assertEquals($testData, $readData); + self::assertEquals($testData, $readData); } - public function testCloseWithoutConnectionWrite() + public function testCloseWithoutConnectionWrite(): void { // close unopened stream $this->socketClient->close(); - $this->assertTrue($this->socketClient->isClosed()); + self::assertTrue($this->socketClient->isClosed()); $this->socketClient->write("abcd"); - $this->assertFalse($this->socketClient->isClosed()); + self::assertFalse($this->socketClient->isClosed()); $client = stream_socket_accept($this->serverSocket); - $this->assertEquals("abcd", fread($client, 4)); + self::assertEquals("abcd", fread($client, 4)); } - public function testCloseWrite() + public function testCloseWrite(): void { $this->socketClient->write("abcd"); - $this->assertFalse($this->socketClient->isClosed()); + self::assertFalse($this->socketClient->isClosed()); $client = stream_socket_accept($this->serverSocket); - $this->assertEquals("abcd", fread($client, 4)); + self::assertEquals("abcd", fread($client, 4)); $this->socketClient->close(); - $this->assertTrue($this->socketClient->isClosed()); + self::assertTrue($this->socketClient->isClosed()); $this->socketClient->write("efgh"); $client2 = stream_socket_accept($this->serverSocket); - $this->assertEquals("efgh", fread($client2, 4)); + self::assertEquals("efgh", fread($client2, 4)); } - /** - * @group hhvm-failures - */ - public function testStreamContext() + public function testStreamContext(): void { - $this->failsOnHHVM(); - $testName = '127.0.0.1:12345'; - $context = array( - 'socket' => array( + $context = [ + 'socket' => [ 'bindto' => $testName - ) - ); + ] + ]; $client = new StreamSocketClient("tcp", $this->host, $this->port, $context); - $this->assertEquals($context, $client->getContext()); + self::assertEquals($context, $client->getContext()); - $this->assertEquals($testName, stream_socket_get_name($client->getSocket(), false)); - $this->assertNotEquals($testName, stream_socket_get_name($this->socketClient->getSocket(), false)); + self::assertEquals($testName, stream_socket_get_name($client->getSocket(), false)); + self::assertNotEquals($testName, stream_socket_get_name($this->socketClient->getSocket(), false)); } - /** - * @group hhvm-failures - */ - public function testUpdateStreamContext() + public function testUpdateStreamContext(): void { - $this->failsOnHHVM(); - $testName = '127.0.0.1:12345'; $context = array( 'socket' => array( @@ -229,32 +209,28 @@ public function testUpdateStreamContext() ) ); - $this->assertEquals(array(), $this->socketClient->getContext()); - $this->assertNotEquals($testName, stream_socket_get_name($this->socketClient->getSocket(), false)); + self::assertEquals(array(), $this->socketClient->getContext()); + self::assertNotEquals($testName, stream_socket_get_name($this->socketClient->getSocket(), false)); $this->socketClient->close(); $this->socketClient->setContext($context); - $this->assertEquals($context, $this->socketClient->getContext()); + self::assertEquals($context, $this->socketClient->getContext()); - $this->assertEquals($testName, stream_socket_get_name($this->socketClient->getSocket(), false)); + self::assertEquals($testName, stream_socket_get_name($this->socketClient->getSocket(), false)); } - /** - * @expectedException \LogicException - */ - public function testSetContextFailsAfterConnect() + public function testSetContextFailsAfterConnect(): void { + self::expectException(LogicException::class); // enforce connect $this->socketClient->getSocket(); $this->socketClient->setContext(array("foo" => "bar")); } - /** - * @expectedException \LogicException - */ - public function testSetConnectTimeoutFailsAfterConnect() + public function testSetConnectTimeoutFailsAfterConnect(): void { + self::expectException(LogicException::class); // enforce connect $this->socketClient->getSocket(); @@ -263,8 +239,7 @@ public function testSetConnectTimeoutFailsAfterConnect() public function testConnectTimeout() { - $this->assertEquals(StreamSocketClient::SOCKET_TIMEOUT, $this->socketClient->getConnectTimeout()); $this->socketClient->setConnectTimeout(1); - $this->assertEquals(1, $this->socketClient->getConnectTimeout()); + self::assertEquals(1, $this->socketClient->getConnectTimeout()); } } diff --git a/tests/Gelf/Test/Transport/StreamSocketClientUdpTest.php b/tests/Gelf/Test/Transport/StreamSocketClientUdpTest.php index 0824085..ac56fda 100644 --- a/tests/Gelf/Test/Transport/StreamSocketClientUdpTest.php +++ b/tests/Gelf/Test/Transport/StreamSocketClientUdpTest.php @@ -1,4 +1,5 @@ serverSocket = stream_socket_server( "udp://$host:0", $errNo, $errMsg, - $flags = STREAM_SERVER_BIND + flags: STREAM_SERVER_BIND ); if (!$this->serverSocket) { @@ -44,43 +38,42 @@ public function setUp() // get random port $socketName = stream_socket_get_name( $this->serverSocket, - $peerName = false + remote: false ); - list(, $port) = explode(":", $socketName); + [, $port] = explode(":", $socketName); - $this->socketClient = new StreamSocketClient('udp', $host, $port); + $this->socketClient = new StreamSocketClient('udp', $host, (int)$port); } - public function tearDown() + public function tearDown(): void { unset($this->socketClient); fclose($this->serverSocket); } - /** - * @expectedException RuntimeException - */ - public function testInvalidConstructorArguments() + public function testInvalidConstructorArguments(): void { + self::expectException(RuntimeException::class); + $client = new StreamSocketClient("not-a-scheme", "not-a-host", -1); $client->getSocket(); } - public function testGetSocket() + public function testGetSocket(): void { - $this->assertInternalType('resource', $this->socketClient->getSocket()); + self::assertIsResource($this->socketClient->getSocket()); } - public function testWrite() + public function testWrite(): void { $testData = "Hello World!"; $numBytes = $this->socketClient->write($testData); - $this->assertEquals(strlen($testData), $numBytes); + self::assertEquals(strlen($testData), $numBytes); // check that message is sent to server $readData = fread($this->serverSocket, $numBytes); - $this->assertEquals($testData, $readData); + self::assertEquals($testData, $readData); } } diff --git a/tests/Gelf/Test/Transport/TcpTransportTest.php b/tests/Gelf/Test/Transport/TcpTransportTest.php index 4648610..57a85e8 100644 --- a/tests/Gelf/Test/Transport/TcpTransportTest.php +++ b/tests/Gelf/Test/Transport/TcpTransportTest.php @@ -1,4 +1,5 @@ testMessage = str_repeat("0123456789", 30); // 300 char string - $this->socketClient = $this->getMockBuilder("\\Gelf\\Transport\\StreamSocketClient") + $this->socketClient = $this->getMockBuilder(StreamSocketClient::class) ->disableOriginalConstructor() ->getMock(); - $this->message = $this->createMock("\\Gelf\\Message"); + $this->message = $this->createMock(MessageInterface::class); // create an encoder always return $testMessage - $this->encoder = $this->createMock("\\Gelf\\Encoder\\NoNullByteEncoderInterface"); + $this->encoder = $this->createMock(NoNullByteEncoderInterface::class); $this->encoder->expects($this->any())->method('encode')->will( $this->returnValue($this->testMessage) ); @@ -60,15 +51,15 @@ public function setUp() $this->transport = $this->getTransport(); } - protected function getTransport() + private function getTransport(): TcpTransport { // initialize transport with an unlimited packet-size // and the mocked message encoder - $transport = new TcpTransport(null, null); + $transport = new TcpTransport("", 0); $transport->setMessageEncoder($this->encoder); // replace internal stream socket client with our mock - $reflectedTransport = new \ReflectionObject($transport); + $reflectedTransport = new ReflectionObject($transport); $reflectedClient = $reflectedTransport->getProperty('socketClient'); $reflectedClient->setAccessible(true); $reflectedClient->setValue($transport, $this->socketClient); @@ -76,7 +67,7 @@ protected function getTransport() return $transport; } - public function testConstructor() + public function testConstructor(): void { $transport = new TcpTransport(); $this->validateTransport($transport, '127.0.0.1', 12201); @@ -95,51 +86,42 @@ public function validateTransport( $host, $port, $sslOptions = null - ) { - $r = new \ReflectionObject($transport); + ): void { + $r = new ReflectionObject($transport); - foreach (array('host', 'port', 'sslOptions') as $test) { + foreach (['host' => $host, 'port' => $port, 'sslOptions' => $sslOptions] as $test => $value) { $p = $r->getProperty($test); $p->setAccessible(true); - $this->assertEquals(${$test}, $p->getValue($transport)); + self::assertEquals($value, $p->getValue($transport)); } } - public function testSslOptionsAreUsed() + public function testSslOptionsAreUsed(): void { - $sslOptions = $this->createMock('\\Gelf\\Transport\\SslOptions'); + $sslOptions = $this->createMock(SslOptions::class); $sslOptions->expects($this->exactly(2)) ->method('toStreamContext') - ->will($this->returnValue(array('ssl' => null))); + ->will($this->returnValue(['ssl' => null])); - $transport = new TcpTransport("localhost", "12202", $sslOptions); + $transport = new TcpTransport("localhost", 12202, $sslOptions); - $reflectedTransport = new \ReflectionObject($transport); + $reflectedTransport = new ReflectionObject($transport); $reflectedGetContext = $reflectedTransport->getMethod('getContext'); $reflectedGetContext->setAccessible(true); $context = $reflectedGetContext->invoke($transport); - $this->assertEquals(array('ssl' => null), $context); + self::assertEquals(['ssl' => null], $context); } - public function testSetEncoder() + public function testSetEncoder(): void { - $encoder = $this->createMock('\\Gelf\\Encoder\\NoNullByteEncoderInterface'); + $encoder = $this->createMock(NoNullByteEncoderInterface::class); $this->transport->setMessageEncoder($encoder); - $this->assertEquals($encoder, $this->transport->getMessageEncoder()); - } - - public function testGetEncoder() - { - $transport = new TcpTransport(); - $this->assertInstanceOf( - "\\Gelf\\Encoder\\EncoderInterface", - $transport->getMessageEncoder() - ); + self::assertEquals($encoder, $this->transport->getMessageEncoder()); } - public function testSend() + public function testSend(): void { $this->socketClient ->expects($this->once()) @@ -151,14 +133,14 @@ public function testSend() $this->transport->send($this->message); } - public function testConnectTimeout() + public function testConnectTimeout(): void { $this->socketClient ->expects($this->once()) ->method('getConnectTimeout') ->will($this->returnValue(123)); - $this->assertEquals(123, $this->transport->getConnectTimeout()); + self::assertEquals(123, $this->transport->getConnectTimeout()); $this->socketClient ->expects($this->once()) @@ -168,26 +150,21 @@ public function testConnectTimeout() $this->transport->setConnectTimeout(123); } - public function testNonNullSafeEncoderFails() + public function testNonNullSafeEncoderFails(): void { - $this->expectException('InvalidArgumentException'); + self::expectException(InvalidArgumentException::class); $this->transport->setMessageEncoder(new CompressedJsonEncoder()); } - public function testSafeEncoderSucceeds() + public function testSafeEncoderSucceeds(): void { - $this->assertInstanceOf( - "Gelf\Encoder\NoNullByteEncoderInterface", - $this->transport->getMessageEncoder() - ); - $encoder = new JsonEncoder(); - $this->assertInstanceOf( - "Gelf\Encoder\NoNullByteEncoderInterface", + self::assertInstanceOf( + NoNullByteEncoderInterface::class, $encoder ); $this->transport->setMessageEncoder($encoder); - $this->assertEquals($encoder, $this->transport->getMessageEncoder()); + self::assertEquals($encoder, $this->transport->getMessageEncoder()); } } diff --git a/tests/Gelf/Test/Transport/UdpTransportTest.php b/tests/Gelf/Test/Transport/UdpTransportTest.php index 97caefb..0bba39b 100644 --- a/tests/Gelf/Test/Transport/UdpTransportTest.php +++ b/tests/Gelf/Test/Transport/UdpTransportTest.php @@ -1,4 +1,5 @@ testMessage = str_repeat("0123456789", 30); // 300 char string - $this->socketClient = $this->createMock( - "\\Gelf\\Transport\\StreamSocketClient", - $methods = array(), - $args = array(), - $mockClassName = '', - $callConstructor = false - ); - $this->message = $this->createMock("\\Gelf\\Message"); + $this->socketClient = $this->createMock(StreamSocketClient::class); + $this->message = $this->createMock(MessageInterface::class); // create an encoder always return $testMessage - $this->encoder = $this->createMock("\\Gelf\\Encoder\\EncoderInterface"); + $this->encoder = $this->createMock(EncoderInterface::class); $this->encoder->expects($this->any())->method('encode')->will( $this->returnValue($this->testMessage) ); @@ -61,15 +47,15 @@ public function setUp() $this->transport = $this->getTransport(0); } - protected function getTransport($chunkSize) + private function getTransport(int $chunkSize): UdpTransport { // initialize transport with an unlimited packet-size // and the mocked message encoder - $transport = new UdpTransport(null, null, $chunkSize); + $transport = new UdpTransport("", 0, $chunkSize); $transport->setMessageEncoder($this->encoder); // replace internal stream socket client with our mock - $reflectedTransport = new \ReflectionObject($transport); + $reflectedTransport = new ReflectionObject($transport); $reflectedClient = $reflectedTransport->getProperty('socketClient'); $reflectedClient->setAccessible(true); $reflectedClient->setValue($transport, $this->socketClient); @@ -77,24 +63,15 @@ protected function getTransport($chunkSize) return $transport; } - public function testSetEncoder() + public function testSetEncoder(): void { - $encoder = $this->createMock('\\Gelf\\Encoder\\EncoderInterface'); + $encoder = $this->createMock(EncoderInterface::class); $this->transport->setMessageEncoder($encoder); - $this->assertEquals($encoder, $this->transport->getMessageEncoder()); + self::assertEquals($encoder, $this->transport->getMessageEncoder()); } - public function testGetEncoder() - { - $transport = new UdpTransport(); - $this->assertInstanceOf( - "\\Gelf\\Encoder\\EncoderInterface", - $transport->getMessageEncoder() - ); - } - - public function testSendUnchunked() + public function testSendUnchunked(): void { $this->socketClient ->expects($this->once()) @@ -104,11 +81,11 @@ public function testSendUnchunked() $this->transport->send($this->message); } - public function testSendChunked() + public function testSendChunked(): void { - $chunkSize = 20 + UdpTransport::CHUNK_HEADER_LENGTH; + $chunkSize = 20 + self::CHUNK_HEADER_LENGTH; $transport = $this->getTransport($chunkSize); - $expectedMessageCount = strlen($this->testMessage) / ($chunkSize - UdpTransport::CHUNK_HEADER_LENGTH); + $expectedMessageCount = strlen($this->testMessage) / ($chunkSize - self::CHUNK_HEADER_LENGTH); $test = $this; $this->socketClient @@ -116,17 +93,17 @@ public function testSendChunked() ->method('write') ->willReturnCallback(function ($data) use ($chunkSize, $test) { $test->assertLessThanOrEqual($chunkSize, strlen($data)); + return 1; }); $transport->send($this->message); } - /** - * @expectedException \RuntimeException - */ public function testInvalidChunkNumber() { - $transport = $this->getTransport(UdpTransport::CHUNK_HEADER_LENGTH + 1); + self::expectException(RuntimeException::class); + + $transport = $this->getTransport(self::CHUNK_HEADER_LENGTH + 1); $transport->send($this->message); } } diff --git a/tests/Gelf/TestCase.php b/tests/Gelf/TestCase.php deleted file mode 100644 index 308331f..0000000 --- a/tests/Gelf/TestCase.php +++ /dev/null @@ -1,14 +0,0 @@ -markTestSkipped("Relies on missing HHVM functionaility"); - } - } -} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 95ef3ad..c66f272 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -8,5 +8,3 @@ } require_once $autoloadFile; - -require_once __DIR__ . '/Gelf/TestCase.php';