From 2485c421fccef5a89372b5b8f82add1de6600c51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Ha=C5=82as?= Date: Sat, 2 May 2026 10:06:24 +0200 Subject: [PATCH] M1I10: ProtocolHandlerInterface + TcpHandler --- .../Protocol/ProtocolHandlerInterface.php | 12 ++++ src/Server/Protocol/TcpHandler.php | 23 +++++++ tests/Server/Protocol/TcpHandlerTest.php | 67 +++++++++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 src/Server/Protocol/ProtocolHandlerInterface.php create mode 100644 src/Server/Protocol/TcpHandler.php create mode 100644 tests/Server/Protocol/TcpHandlerTest.php diff --git a/src/Server/Protocol/ProtocolHandlerInterface.php b/src/Server/Protocol/ProtocolHandlerInterface.php new file mode 100644 index 0000000..92830dd --- /dev/null +++ b/src/Server/Protocol/ProtocolHandlerInterface.php @@ -0,0 +1,12 @@ +callback instanceof \Closure) { + ($this->callback)($connection); + } + } +} diff --git a/tests/Server/Protocol/TcpHandlerTest.php b/tests/Server/Protocol/TcpHandlerTest.php new file mode 100644 index 0000000..19620d8 --- /dev/null +++ b/tests/Server/Protocol/TcpHandlerTest.php @@ -0,0 +1,67 @@ +assertNotFalse($socket); + + $connection = new Connection($socket); + $handler = new TcpHandler(); + + $handler->handle($connection); + + $this->assertFalse($connection->isClosed()); + + $connection->close(); + } + + public function testCallbackIsCalledWithConnection(): void + { + $socket = \socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + $this->assertNotFalse($socket); + + $connection = new Connection($socket); + + $called = false; + $passedConnection = null; + + $handler = new TcpHandler(function (Connection $conn) use (&$called, &$passedConnection): void { + $called = true; + $passedConnection = $conn; + }); + + $handler->handle($connection); + + $this->assertTrue($called); + $this->assertSame($connection, $passedConnection); + + $connection->close(); + } + + public function testHandlerDoesNotCloseConnection(): void + { + $socket = \socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + $this->assertNotFalse($socket); + + $connection = new Connection($socket); + + $handler = new TcpHandler(function (Connection $conn): void { + }); + + $handler->handle($connection); + + $this->assertFalse($connection->isClosed()); + + $connection->close(); + } +}