From ed76966dfc6d788ec1dbff6640f6c67832358649 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 7 Oct 2025 15:16:50 +0200 Subject: [PATCH 01/26] First batch of new tests --- .../integrational/PublishFileMessageTest.php | 351 ++++++++++ tests/unit/BasePathManagerTest.php | 150 +++++ tests/unit/CryptoCryptorGettersTest.php | 346 ++++++++++ tests/unit/PNConfigurationExtendedTest.php | 613 ++++++++++++++++++ tests/unit/PubNubCborDecodeTest.php | 453 +++++++++++++ tests/unit/PubNubCryptoMethodsTest.php | 354 ++++++++++ tests/unit/PubNubFactoryMethodsTest.php | 266 ++++++++ tests/unit/PubNubSdkInfoTest.php | 320 +++++++++ tests/unit/PubNubUtilExtendedTest.php | 585 +++++++++++++++++ tests/unit/PubNubUtilityMethodsTest.php | 361 +++++++++++ tests/unit/StateManagerTest.php | 342 ++++++++++ tests/unit/TokenManagerTest.php | 64 ++ 12 files changed, 4205 insertions(+) create mode 100644 tests/integrational/PublishFileMessageTest.php create mode 100644 tests/unit/BasePathManagerTest.php create mode 100644 tests/unit/CryptoCryptorGettersTest.php create mode 100644 tests/unit/PNConfigurationExtendedTest.php create mode 100644 tests/unit/PubNubCborDecodeTest.php create mode 100644 tests/unit/PubNubCryptoMethodsTest.php create mode 100644 tests/unit/PubNubFactoryMethodsTest.php create mode 100644 tests/unit/PubNubSdkInfoTest.php create mode 100644 tests/unit/PubNubUtilExtendedTest.php create mode 100644 tests/unit/PubNubUtilityMethodsTest.php create mode 100644 tests/unit/StateManagerTest.php create mode 100644 tests/unit/TokenManagerTest.php diff --git a/tests/integrational/PublishFileMessageTest.php b/tests/integrational/PublishFileMessageTest.php new file mode 100644 index 0000000..fe8a2cd --- /dev/null +++ b/tests/integrational/PublishFileMessageTest.php @@ -0,0 +1,351 @@ +testFilePath = sys_get_temp_dir() . '/test_file_' . uniqid() . '.txt'; + file_put_contents($this->testFilePath, 'Test file content for publish file message'); + } + + public function tearDown(): void + { + // Clean up temporary file + if (file_exists($this->testFilePath)) { + unlink($this->testFilePath); + } + + // Clean up uploaded files + try { + $listResponse = $this->pubnub->listFiles()->channel($this->channel)->sync(); + foreach ($listResponse->getData() as $file) { + $this->pubnub->deleteFile() + ->channel($this->channel) + ->fileId($file['id']) + ->fileName($file['name']) + ->sync(); + } + } catch (\Exception $e) { + // Ignore cleanup errors + } + + parent::tearDown(); + } + + public function testPublishFileMessageWithBasicMessage() + { + // First upload a file to get file ID + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("Initial file upload") + ->sync(); + + fclose($file); + + $this->assertNotEmpty($uploadResponse->getFileId()); + + // Now publish a file message notification + $response = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("File notification message") + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageWithMetadata() + { + // Upload a file first + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("File with metadata") + ->sync(); + + fclose($file); + + // Publish file message with metadata + $metadata = [ + "author" => "test-user", + "fileType" => "text", + "importance" => "high" + ]; + + $response = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("File with metadata notification") + ->meta($metadata) + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageWithCustomMessageType() + { + // Upload a file first + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("File upload") + ->sync(); + + fclose($file); + + // Publish file message with custom message type + $response = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("Custom type notification") + ->customMessageType("file_notification") + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageWithTTL() + { + // Upload a file first + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("File upload") + ->sync(); + + fclose($file); + + // Publish file message with TTL + $response = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("Message with TTL") + ->ttl(60) // 60 minutes + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageWithShouldStore() + { + // Upload a file first + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("File upload") + ->sync(); + + fclose($file); + + // Publish file message with shouldStore flag + $response = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("Stored message") + ->shouldStore(true) + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageWithAllOptions() + { + // Upload a file first + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("File upload") + ->sync(); + + fclose($file); + + // Publish file message with all options + $metadata = [ + "category" => "documents", + "tags" => ["important", "urgent"] + ]; + + $response = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("Complete file notification") + ->meta($metadata) + ->customMessageType("complete_notification") + ->ttl(120) + ->shouldStore(true) + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageWithEncryption() + { + // Use encrypted pubnub instance + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub_enc->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("Encrypted file upload") + ->sync(); + + fclose($file); + + // Publish encrypted file message + $response = $this->pubnub_enc->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("Encrypted file notification") + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageWithComplexMessage() + { + // Upload a file first + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("File upload") + ->sync(); + + fclose($file); + + // Publish file message with complex message structure + $complexMessage = [ + "type" => "file_uploaded", + "details" => [ + "uploader" => "test-user", + "timestamp" => time(), + "description" => "Important document" + ], + "actions" => ["review", "approve", "archive"] + ]; + + $response = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message($complexMessage) + ->sync(); + + $this->assertNotEmpty($response); + $this->assertNotEmpty($response->getTimetoken()); + } + + public function testPublishFileMessageMultipleTimes() + { + // Upload a file first + $file = fopen($this->testFilePath, "r"); + $fileName = basename($this->testFilePath); + + $uploadResponse = $this->pubnub->sendFile() + ->channel($this->channel) + ->fileHandle($file) + ->fileName($fileName) + ->message("File upload") + ->sync(); + + fclose($file); + + // Publish multiple file messages for the same file + $response1 = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("First notification") + ->sync(); + + $response2 = $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId($uploadResponse->getFileId()) + ->fileName($fileName) + ->message("Second notification") + ->sync(); + + $this->assertNotEmpty($response1->getTimetoken()); + $this->assertNotEmpty($response2->getTimetoken()); + $this->assertNotEquals($response1->getTimetoken(), $response2->getTimetoken()); + } + + public function testPublishFileMessageWithInvalidFileId() + { + $this->expectException(\PubNub\Exceptions\PubNubServerException::class); + + // Try to publish with non-existent file ID + $this->pubnub->publishFileMessage() + ->channel($this->channel) + ->fileId('invalid-file-id-12345') + ->fileName('nonexistent.txt') + ->message("This should fail") + ->sync(); + } + + public function testPublishFileMessageWithEmptyChannel() + { + $this->expectException(\PubNub\Exceptions\PubNubValidationException::class); + + $this->pubnub->publishFileMessage() + ->channel('') + ->fileId('some-file-id') + ->fileName('test.txt') + ->message("Empty channel") + ->sync(); + } +} diff --git a/tests/unit/BasePathManagerTest.php b/tests/unit/BasePathManagerTest.php new file mode 100644 index 0000000..63ab2cb --- /dev/null +++ b/tests/unit/BasePathManagerTest.php @@ -0,0 +1,150 @@ +setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath(); + + $this->assertEquals('https://ps.pndsn.com', $basePath); + } + + public function testGetBasePathWithCustomOrigin() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setOrigin('custom.pubnub.com'); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath(); + + $this->assertEquals('https://custom.pubnub.com', $basePath); + } + + public function testGetBasePathWithCustomHost() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath('special.pubnub.com'); + + $this->assertEquals('https://special.pubnub.com', $basePath); + } + + public function testGetBasePathWithCustomHostOverridesOrigin() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setOrigin('config-origin.pubnub.com'); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath('param-host.pubnub.com'); + + $this->assertEquals('https://param-host.pubnub.com', $basePath); + } + + public function testGetBasePathWithInsecureConnection() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setSecure(false); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath(); + + $this->assertEquals('http://ps.pndsn.com', $basePath); + } + + public function testGetBasePathWithInsecureAndCustomOrigin() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setSecure(false); + $config->setOrigin('insecure.pubnub.com'); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath(); + + $this->assertEquals('http://insecure.pubnub.com', $basePath); + } + + public function testGetBasePathWithIPAddress() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setOrigin('192.168.1.100'); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath(); + + $this->assertEquals('https://192.168.1.100', $basePath); + } + + public function testGetBasePathWithPortNumber() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setOrigin('localhost:8080'); + + $manager = new BasePathManager($config); + + $basePath = $manager->getBasePath(); + + $this->assertEquals('https://localhost:8080', $basePath); + } + + public function testGetBasePathMultipleCalls() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $manager = new BasePathManager($config); + + $basePath1 = $manager->getBasePath(); + $basePath2 = $manager->getBasePath(); + $basePath3 = $manager->getBasePath(); + + $this->assertEquals($basePath1, $basePath2); + $this->assertEquals($basePath2, $basePath3); + } + + public function testGetBasePathWithDifferentCustomHosts() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $manager = new BasePathManager($config); + + $basePath1 = $manager->getBasePath('host1.pubnub.com'); + $basePath2 = $manager->getBasePath('host2.pubnub.com'); + + $this->assertEquals('https://host1.pubnub.com', $basePath1); + $this->assertEquals('https://host2.pubnub.com', $basePath2); + } +} diff --git a/tests/unit/CryptoCryptorGettersTest.php b/tests/unit/CryptoCryptorGettersTest.php new file mode 100644 index 0000000..76672ac --- /dev/null +++ b/tests/unit/CryptoCryptorGettersTest.php @@ -0,0 +1,346 @@ +assertInstanceOf(AesCbcCryptor::class, $cryptor); + } + + public function testAesCbcCryptorGetCipherKey() + { + $cryptor = new AesCbcCryptor('my-cipher-key'); + + $this->assertEquals('my-cipher-key', $cryptor->getCipherKey()); + } + + public function testAesCbcCryptorGetCipherKeyWithNullParameter() + { + $cryptor = new AesCbcCryptor('my-cipher-key'); + + $this->assertEquals('my-cipher-key', $cryptor->getCipherKey(null)); + } + + public function testAesCbcCryptorGetCipherKeyWithCustomParameter() + { + $cryptor = new AesCbcCryptor('default-key'); + + // If a custom key is provided, it should return that instead + $this->assertEquals('custom-key', $cryptor->getCipherKey('custom-key')); + } + + public function testAesCbcCryptorGetIV() + { + $cryptor = new AesCbcCryptor('test-key'); + $iv = $cryptor->getIV(); + + $this->assertIsString($iv); + $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes + } + + public function testAesCbcCryptorGetIVReturnsRandomValues() + { + $cryptor = new AesCbcCryptor('test-key'); + $iv1 = $cryptor->getIV(); + $iv2 = $cryptor->getIV(); + + // Each call should return a different random IV + $this->assertNotEquals($iv1, $iv2); + } + + public function testAesCbcCryptorEncryptReturnsPayload() + { + $cryptor = new AesCbcCryptor('test-key'); + $result = $cryptor->encrypt('test message'); + + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $result); + } + + public function testAesCbcCryptorEncryptPayloadHasCryptorId() + { + $cryptor = new AesCbcCryptor('test-key'); + $result = $cryptor->encrypt('test message'); + + $this->assertEquals('ACRH', $result->getCryptorId()); + } + + public function testAesCbcCryptorEncryptPayloadHasData() + { + $cryptor = new AesCbcCryptor('test-key'); + $result = $cryptor->encrypt('test message'); + + $this->assertNotEmpty($result->getData()); + } + + public function testAesCbcCryptorEncryptPayloadHasCryptorData() + { + $cryptor = new AesCbcCryptor('test-key'); + $result = $cryptor->encrypt('test message'); + + // Cryptor data should contain the IV (16 bytes) + $this->assertEquals(16, strlen($result->getCryptorData())); + } + + public function testAesCbcCryptorEncryptDecryptRoundTrip() + { + $cryptor = new AesCbcCryptor('test-key'); + $original = 'Hello, World!'; + + $encrypted = $cryptor->encrypt($original); + $decrypted = $cryptor->decrypt($encrypted); + + $this->assertEquals($original, $decrypted); + } + + public function testAesCbcCryptorWithDifferentKeys() + { + $cryptor1 = new AesCbcCryptor('key1'); + $cryptor2 = new AesCbcCryptor('key2'); + + $this->assertEquals('key1', $cryptor1->getCipherKey()); + $this->assertEquals('key2', $cryptor2->getCipherKey()); + } + + // ============================================================================ + // LegacyCryptor TESTS + // ============================================================================ + + public function testLegacyCryptorConstructor() + { + $cryptor = new LegacyCryptor('test-key', false); + + $this->assertInstanceOf(LegacyCryptor::class, $cryptor); + } + + public function testLegacyCryptorConstructorWithRandomIV() + { + $cryptor = new LegacyCryptor('test-key', true); + + $this->assertInstanceOf(LegacyCryptor::class, $cryptor); + } + + public function testLegacyCryptorGetCipherKey() + { + $cryptor = new LegacyCryptor('my-legacy-key', false); + + $this->assertEquals('my-legacy-key', $cryptor->getCipherKey()); + } + + public function testLegacyCryptorGetIVWithStaticIV() + { + $cryptor = new LegacyCryptor('test-key', false); + $iv = $cryptor->getIV(); + + $this->assertIsString($iv); + $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes + $this->assertEquals('0123456789012345', $iv); // Static IV + } + + public function testLegacyCryptorGetIVWithStaticIVIsConsistent() + { + $cryptor = new LegacyCryptor('test-key', false); + $iv1 = $cryptor->getIV(); + $iv2 = $cryptor->getIV(); + + // With static IV, should return same value every time + $this->assertEquals($iv1, $iv2); + $this->assertEquals('0123456789012345', $iv1); + } + + public function testLegacyCryptorGetIVWithRandomIV() + { + $cryptor = new LegacyCryptor('test-key', true); + $iv = $cryptor->getIV(); + + $this->assertIsString($iv); + $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes + } + + public function testLegacyCryptorGetIVWithRandomIVReturnsRandomValues() + { + $cryptor = new LegacyCryptor('test-key', true); + $iv1 = $cryptor->getIV(); + $iv2 = $cryptor->getIV(); + + // With random IV, each call should return different value + $this->assertNotEquals($iv1, $iv2); + } + + public function testLegacyCryptorEncryptReturnsPayload() + { + $cryptor = new LegacyCryptor('test-key', false); + $result = $cryptor->encrypt('test message'); + + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $result); + } + + public function testLegacyCryptorEncryptPayloadHasCryptorId() + { + $cryptor = new LegacyCryptor('test-key', false); + $result = $cryptor->encrypt('test message'); + + $this->assertEquals('0000', $result->getCryptorId()); + } + + public function testLegacyCryptorEncryptPayloadHasData() + { + $cryptor = new LegacyCryptor('test-key', false); + $result = $cryptor->encrypt('test message'); + + $this->assertNotEmpty($result->getData()); + } + + public function testLegacyCryptorEncryptPayloadCryptorDataIsEmpty() + { + $cryptor = new LegacyCryptor('test-key', false); + $result = $cryptor->encrypt('test message'); + + // Legacy cryptor uses empty string for cryptor data + $this->assertEquals('', $result->getCryptorData()); + } + + public function testLegacyCryptorEncryptDecryptRoundTripWithStaticIV() + { + $cryptor = new LegacyCryptor('test-key', false); + $original = 'Hello, Legacy!'; + + $encrypted = $cryptor->encrypt($original); + $decrypted = $cryptor->decrypt($encrypted); + + $this->assertEquals($original, $decrypted); + } + + public function testLegacyCryptorEncryptDecryptRoundTripWithRandomIV() + { + $cryptor = new LegacyCryptor('test-key', true); + $original = 'Hello, Random IV!'; + + $encrypted = $cryptor->encrypt($original); + $decrypted = $cryptor->decrypt($encrypted); + + $this->assertEquals($original, $decrypted); + } + + public function testLegacyCryptorWithDifferentKeys() + { + $cryptor1 = new LegacyCryptor('key1', false); + $cryptor2 = new LegacyCryptor('key2', true); + + $this->assertEquals('key1', $cryptor1->getCipherKey()); + $this->assertEquals('key2', $cryptor2->getCipherKey()); + } + + // ============================================================================ + // COMPARISON TESTS + // ============================================================================ + + public function testAesCbcCryptorAndLegacyCryptorHaveDifferentCryptorIds() + { + $aesCbc = new AesCbcCryptor('key'); + $legacy = new LegacyCryptor('key', false); + + $aesEncrypted = $aesCbc->encrypt('test'); + $legacyEncrypted = $legacy->encrypt('test'); + + $this->assertEquals('ACRH', $aesEncrypted->getCryptorId()); + $this->assertEquals('0000', $legacyEncrypted->getCryptorId()); + $this->assertNotEquals($aesEncrypted->getCryptorId(), $legacyEncrypted->getCryptorId()); + } + + public function testBothCryptorsReturnPayloadObjects() + { + $aesCbc = new AesCbcCryptor('key'); + $legacy = new LegacyCryptor('key', false); + + $aesResult = $aesCbc->encrypt('test'); + $legacyResult = $legacy->encrypt('test'); + + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $aesResult); + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $legacyResult); + } + + public function testBothCryptorsHandleEmptyStrings() + { + $aesCbc = new AesCbcCryptor('key'); + $legacy = new LegacyCryptor('key', false); + + $aesResult = $aesCbc->encrypt(''); + $legacyResult = $legacy->encrypt(''); + + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $aesResult); + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $legacyResult); + } + + public function testBothCryptorsHandleLongMessages() + { + $longMessage = str_repeat('A', 10000); // 10KB message + + $aesCbc = new AesCbcCryptor('key'); + $legacy = new LegacyCryptor('key', false); + + $aesEncrypted = $aesCbc->encrypt($longMessage); + $legacyEncrypted = $legacy->encrypt($longMessage); + + $this->assertEquals($longMessage, $aesCbc->decrypt($aesEncrypted)); + $this->assertEquals($longMessage, $legacy->decrypt($legacyEncrypted)); + } + + public function testBothCryptorsHandleUnicodeCharacters() + { + $unicodeMessage = '🔒 Encrypted 文字 مشفر'; + + $aesCbc = new AesCbcCryptor('key'); + $legacy = new LegacyCryptor('key', false); + + $aesEncrypted = $aesCbc->encrypt($unicodeMessage); + $legacyEncrypted = $legacy->encrypt($unicodeMessage); + + $this->assertEquals($unicodeMessage, $aesCbc->decrypt($aesEncrypted)); + $this->assertEquals($unicodeMessage, $legacy->decrypt($legacyEncrypted)); + } + + public function testBothCryptorsHaveGetCipherKeyMethod() + { + $aesCbc = new AesCbcCryptor('key1'); + $legacy = new LegacyCryptor('key2', false); + + $this->assertTrue(method_exists($aesCbc, 'getCipherKey')); + $this->assertTrue(method_exists($legacy, 'getCipherKey')); + + $this->assertEquals('key1', $aesCbc->getCipherKey()); + $this->assertEquals('key2', $legacy->getCipherKey()); + } + + public function testBothCryptorsHaveGetIVMethod() + { + $aesCbc = new AesCbcCryptor('key'); + $legacy = new LegacyCryptor('key', false); + + $this->assertTrue(method_exists($aesCbc, 'getIV')); + $this->assertTrue(method_exists($legacy, 'getIV')); + + $this->assertEquals(16, strlen($aesCbc->getIV())); + $this->assertEquals(16, strlen($legacy->getIV())); + } + + public function testBothCryptorsImplementEncryptAndDecrypt() + { + $aesCbc = new AesCbcCryptor('key'); + $legacy = new LegacyCryptor('key', false); + + $this->assertTrue(method_exists($aesCbc, 'encrypt')); + $this->assertTrue(method_exists($aesCbc, 'decrypt')); + $this->assertTrue(method_exists($legacy, 'encrypt')); + $this->assertTrue(method_exists($legacy, 'decrypt')); + } +} diff --git a/tests/unit/PNConfigurationExtendedTest.php b/tests/unit/PNConfigurationExtendedTest.php new file mode 100644 index 0000000..d79ddef --- /dev/null +++ b/tests/unit/PNConfigurationExtendedTest.php @@ -0,0 +1,613 @@ +assertEquals(10, $config->getNonSubscribeRequestTimeout()); + } + + public function testSetNonSubscribeRequestTimeout() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setNonSubscribeRequestTimeout(20); + + $this->assertEquals(20, $config->getNonSubscribeRequestTimeout()); + } + + public function testSetNonSubscribeRequestTimeoutWithZero() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setNonSubscribeRequestTimeout(0); + + $this->assertEquals(0, $config->getNonSubscribeRequestTimeout()); + } + + public function testSetNonSubscribeRequestTimeoutWithLargeValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setNonSubscribeRequestTimeout(3600); + + $this->assertEquals(3600, $config->getNonSubscribeRequestTimeout()); + } + + public function testGetSubscribeTimeoutReturnsDefault() + { + $config = new PNConfiguration(); + + $this->assertEquals(310, $config->getSubscribeTimeout()); + } + + public function testSetSubscribeTimeout() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setSubscribeTimeout(400); + + $this->assertEquals(400, $config->getSubscribeTimeout()); + } + + public function testSetSubscribeTimeoutWithMinimalValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setSubscribeTimeout(1); + + $this->assertEquals(1, $config->getSubscribeTimeout()); + } + + public function testSetSubscribeTimeoutWithLargeValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setSubscribeTimeout(10000); + + $this->assertEquals(10000, $config->getSubscribeTimeout()); + } + + public function testGetConnectTimeoutReturnsDefault() + { + $config = new PNConfiguration(); + + $this->assertEquals(10, $config->getConnectTimeout()); + } + + public function testSetConnectTimeout() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setConnectTimeout(15); + + $this->assertEquals(15, $config->getConnectTimeout()); + } + + public function testSetConnectTimeoutWithMinimalValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setConnectTimeout(1); + + $this->assertEquals(1, $config->getConnectTimeout()); + } + + public function testSetConnectTimeoutWithLargeValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setConnectTimeout(300); + + $this->assertEquals(300, $config->getConnectTimeout()); + } + + public function testAllTimeoutSettingsTogether() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setNonSubscribeRequestTimeout(25); + $config->setSubscribeTimeout(350); + $config->setConnectTimeout(20); + + $this->assertEquals(25, $config->getNonSubscribeRequestTimeout()); + $this->assertEquals(350, $config->getSubscribeTimeout()); + $this->assertEquals(20, $config->getConnectTimeout()); + } + + // ============================================================================ + // SECURITY CONFIGURATION TESTS + // ============================================================================ + + public function testIsSecureReturnsDefaultTrue() + { + $config = new PNConfiguration(); + + $this->assertTrue($config->isSecure()); + } + + public function testSetSecureFalse() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setSecure(false); + + $this->assertFalse($config->isSecure()); + } + + public function testSetSecureTrue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setSecure(false); + $this->assertFalse($config->isSecure()); + + $config->setSecure(true); + $this->assertTrue($config->isSecure()); + } + + public function testSetSecureDefaultsToTrue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setSecure(false); + $config->setSecure(); // No parameter, should default to true + + $this->assertTrue($config->isSecure()); + } + + public function testSetSecureCanBeToggled() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $this->assertTrue($config->isSecure()); + + $config->setSecure(false); + $this->assertFalse($config->isSecure()); + + $config->setSecure(true); + $this->assertTrue($config->isSecure()); + } + + // ============================================================================ + // ORIGIN CONFIGURATION TESTS + // ============================================================================ + + public function testGetOriginReturnsNullByDefault() + { + $config = new PNConfiguration(); + + $this->assertNull($config->getOrigin()); + } + + public function testSetOriginAndGetOrigin() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setOrigin('custom.pubnub.com'); + + $this->assertEquals('custom.pubnub.com', $config->getOrigin()); + } + + public function testSetOriginWithIPAddress() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setOrigin('192.168.1.100'); + + $this->assertEquals('192.168.1.100', $config->getOrigin()); + } + + public function testSetOriginWithPort() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setOrigin('localhost:8080'); + + $this->assertEquals('localhost:8080', $config->getOrigin()); + } + + public function testSetOriginOverwritesPrevious() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setOrigin('first-origin.com'); + $this->assertEquals('first-origin.com', $config->getOrigin()); + + $config->setOrigin('second-origin.com'); + $this->assertEquals('second-origin.com', $config->getOrigin()); + } + + // ============================================================================ + // AUTH KEY CONFIGURATION TESTS + // ============================================================================ + + public function testGetAuthKeyReturnsNullByDefault() + { + $config = new PNConfiguration(); + + $this->assertNull($config->getAuthKey()); + } + + public function testSetAuthKeyAndGetAuthKey() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setAuthKey('my-auth-key'); + + $this->assertEquals('my-auth-key', $config->getAuthKey()); + } + + public function testSetAuthKeyWithEmptyString() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setAuthKey(''); + + $this->assertEquals('', $config->getAuthKey()); + } + + public function testSetAuthKeyWithSpecialCharacters() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $authKey = 'auth!@#$%^&*()_+-={}[]|:;<>?,./'; + $config->setAuthKey($authKey); + + $this->assertEquals($authKey, $config->getAuthKey()); + } + + public function testSetAuthKeyOverwritesPrevious() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setAuthKey('first-key'); + $this->assertEquals('first-key', $config->getAuthKey()); + + $config->setAuthKey('second-key'); + $this->assertEquals('second-key', $config->getAuthKey()); + } + + // ============================================================================ + // FILTER EXPRESSION TESTS + // ============================================================================ + + public function testGetFilterExpressionReturnsNullByDefault() + { + $config = new PNConfiguration(); + + $this->assertNull($config->getFilterExpression()); + } + + public function testSetFilterExpressionAndGetFilterExpression() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setFilterExpression('uuid == "user123"'); + + $this->assertEquals('uuid == "user123"', $config->getFilterExpression()); + } + + public function testSetFilterExpressionWithComplexExpression() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $expression = 'uuid == "admin" && region == "us-east"'; + $config->setFilterExpression($expression); + + $this->assertEquals($expression, $config->getFilterExpression()); + } + + public function testSetFilterExpressionOverwritesPrevious() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setFilterExpression('first-expression'); + $this->assertEquals('first-expression', $config->getFilterExpression()); + + $config->setFilterExpression('second-expression'); + $this->assertEquals('second-expression', $config->getFilterExpression()); + } + + // ============================================================================ + // CRYPTO CONFIGURATION TESTS + // ============================================================================ + + public function testIsAesEnabledReturnsFalseByDefault() + { + $config = new PNConfiguration(); + + $this->assertFalse($config->isAesEnabled()); + } + + public function testIsAesEnabledReturnsTrueWhenCipherKeySet() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setCipherKey('test-key'); + + $this->assertTrue($config->isAesEnabled()); + } + + public function testIsAesEnabledReturnsTrueWhenCryptoModuleSet() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $cryptoModule = CryptoModule::legacyCryptor('key', false); + $config->setCryptoModule($cryptoModule); + + $this->assertTrue($config->isAesEnabled()); + } + + public function testGetCryptoSafeReturnsNullWhenNotConfigured() + { + $config = new PNConfiguration(); + + $this->assertNull($config->getCryptoSafe()); + } + + public function testGetCryptoSafeReturnsCryptoWhenConfigured() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setCipherKey('test-key'); + + $crypto = $config->getCryptoSafe(); + + $this->assertInstanceOf(CryptoModule::class, $crypto); + } + + public function testGetCryptoSafeDoesNotThrowException() + { + $config = new PNConfiguration(); + + // This should not throw an exception + $crypto = $config->getCryptoSafe(); + + $this->assertNull($crypto); + } + + public function testSetCryptoModuleAndGetCryptoSafe() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $cryptoModule = CryptoModule::aesCbcCryptor('my-key', true); + $config->setCryptoModule($cryptoModule); + + $crypto = $config->getCryptoSafe(); + + $this->assertSame($cryptoModule, $crypto); + } + + public function testGetUseRandomIVReturnsDefaultTrue() + { + $config = new PNConfiguration(); + + $this->assertTrue($config->getUseRandomIV()); + } + + public function testSetUseRandomIVFalse() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setUseRandomIV(false); + + $this->assertFalse($config->getUseRandomIV()); + } + + public function testSetUseRandomIVTrue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + + $config->setUseRandomIV(false); + $config->setUseRandomIV(true); + + $this->assertTrue($config->getUseRandomIV()); + } + + // ============================================================================ + // KEY GETTERS TESTS + // ============================================================================ + + public function testGetPublishKeyReturnsNull() + { + $config = new PNConfiguration(); + + $this->assertNull($config->getPublishKey()); + } + + public function testGetPublishKeyReturnsSetValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setPublishKey('pub-key-123'); + + $this->assertEquals('pub-key-123', $config->getPublishKey()); + } + + public function testGetSecretKeyReturnsNull() + { + $config = new PNConfiguration(); + + $this->assertNull($config->getSecretKey()); + } + + public function testGetSecretKeyReturnsSetValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setSecretKey('sec-key-456'); + + $this->assertEquals('sec-key-456', $config->getSecretKey()); + } + + public function testGetSubscribeKeyReturnsSetValue() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setSubscribeKey('sub-key-789'); + + $this->assertEquals('sub-key-789', $config->getSubscribeKey()); + } + + // ============================================================================ + // CLONE METHOD TESTS + // ============================================================================ + + public function testCloneCreatesNewInstance() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setSubscribeKey('demo'); + + $cloned = $config->clone(); + + $this->assertNotSame($config, $cloned); + } + + public function testClonePreservesValues() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setSubscribeKey('sub-key'); + $config->setPublishKey('pub-key'); + $config->setSecretKey('secret-key'); + $config->setOrigin('custom-origin.com'); + $config->setAuthKey('auth-key'); + $config->setSecure(false); + + $cloned = $config->clone(); + + $this->assertEquals('test-user', $cloned->getUserId()); + $this->assertEquals('sub-key', $cloned->getSubscribeKey()); + $this->assertEquals('pub-key', $cloned->getPublishKey()); + $this->assertEquals('secret-key', $cloned->getSecretKey()); + $this->assertEquals('custom-origin.com', $cloned->getOrigin()); + $this->assertEquals('auth-key', $cloned->getAuthKey()); + $this->assertFalse($cloned->isSecure()); + } + + public function testClonePreservesTimeoutSettings() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setNonSubscribeRequestTimeout(25); + $config->setSubscribeTimeout(400); + $config->setConnectTimeout(15); + + $cloned = $config->clone(); + + $this->assertEquals(25, $cloned->getNonSubscribeRequestTimeout()); + $this->assertEquals(400, $cloned->getSubscribeTimeout()); + $this->assertEquals(15, $cloned->getConnectTimeout()); + } + + public function testCloneCreatesUnlockedConfiguration() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setSubscribeKey('demo'); + $config->lock(); + + $cloned = $config->clone(); + + // Cloned config should not be locked, so this should not throw + $cloned->setPublishKey('new-pub-key'); + $this->assertEquals('new-pub-key', $cloned->getPublishKey()); + } + + public function testCloneIsIndependent() + { + $config = new PNConfiguration(); + $config->setUserId('original-user'); + $config->setSubscribeKey('original-key'); + + $cloned = $config->clone(); + $cloned->setUserId('cloned-user'); + $cloned->setSubscribeKey('cloned-key'); + + // Original should be unchanged + $this->assertEquals('original-user', $config->getUserId()); + $this->assertEquals('original-key', $config->getSubscribeKey()); + + // Cloned should have new values + $this->assertEquals('cloned-user', $cloned->getUserId()); + $this->assertEquals('cloned-key', $cloned->getSubscribeKey()); + } + + // ============================================================================ + // COMPREHENSIVE INTEGRATION TESTS + // ============================================================================ + + public function testFullConfigurationSetup() + { + $config = new PNConfiguration(); + $config->setUserId('test-user'); + $config->setSubscribeKey('sub-key'); + $config->setPublishKey('pub-key'); + $config->setSecretKey('secret-key'); + $config->setOrigin('custom.pubnub.com'); + $config->setAuthKey('my-auth-key'); + $config->setSecure(true); + $config->setNonSubscribeRequestTimeout(30); + $config->setSubscribeTimeout(320); + $config->setConnectTimeout(12); + $config->setFilterExpression('uuid != "bot"'); + $config->setUseRandomIV(true); + $config->setCipherKey('cipher-key'); + + // Verify all values + $this->assertEquals('test-user', $config->getUserId()); + $this->assertEquals('sub-key', $config->getSubscribeKey()); + $this->assertEquals('pub-key', $config->getPublishKey()); + $this->assertEquals('secret-key', $config->getSecretKey()); + $this->assertEquals('custom.pubnub.com', $config->getOrigin()); + $this->assertEquals('my-auth-key', $config->getAuthKey()); + $this->assertTrue($config->isSecure()); + $this->assertEquals(30, $config->getNonSubscribeRequestTimeout()); + $this->assertEquals(320, $config->getSubscribeTimeout()); + $this->assertEquals(12, $config->getConnectTimeout()); + $this->assertEquals('uuid != "bot"', $config->getFilterExpression()); + $this->assertTrue($config->isAesEnabled()); + $this->assertTrue($config->getUseRandomIV()); + } +} diff --git a/tests/unit/PubNubCborDecodeTest.php b/tests/unit/PubNubCborDecodeTest.php new file mode 100644 index 0000000..8fa6ae8 --- /dev/null +++ b/tests/unit/PubNubCborDecodeTest.php @@ -0,0 +1,453 @@ +assertEquals(0, PubNubCborDecode::decode('00')); + $this->assertEquals(1, PubNubCborDecode::decode('01')); + $this->assertEquals(10, PubNubCborDecode::decode('0A')); + $this->assertEquals(23, PubNubCborDecode::decode('17')); + } + + public function testDecodeUnsignedInteger1Byte() + { + // Test 1-byte integers (24-255) + $this->assertEquals(24, PubNubCborDecode::decode('1818')); + $this->assertEquals(100, PubNubCborDecode::decode('1864')); + $this->assertEquals(255, PubNubCborDecode::decode('18FF')); + } + + public function testDecodeUnsignedInteger2Bytes() + { + // Test 2-byte integers (256-65535) + $this->assertEquals(256, PubNubCborDecode::decode('190100')); + $this->assertEquals(1000, PubNubCborDecode::decode('1903E8')); + $this->assertEquals(65535, PubNubCborDecode::decode('19FFFF')); + } + + public function testDecodeUnsignedInteger4Bytes() + { + // Test 4-byte integers + $this->assertEquals(100000, PubNubCborDecode::decode('1A000186A0')); + $this->assertEquals(1000000, PubNubCborDecode::decode('1A000F4240')); + } + + public function testDecodeUnsignedInteger8Bytes() + { + // Test 8-byte integers + $this->assertEquals(1000000000, PubNubCborDecode::decode('1B000000003B9ACA00')); + } + + // ============================================================================ + // NEGATIVE INTEGER TESTS + // ============================================================================ + + public function testDecodeNegativeIntegerSmall() + { + // Negative integers: -1 to -24 encoded as 0x20-0x37 + $this->assertEquals(-1, PubNubCborDecode::decode('20')); + $this->assertEquals(-10, PubNubCborDecode::decode('29')); + $this->assertEquals(-24, PubNubCborDecode::decode('37')); + } + + public function testDecodeNegativeInteger1Byte() + { + // -25 to -256 + $this->assertEquals(-25, PubNubCborDecode::decode('3818')); + $this->assertEquals(-100, PubNubCborDecode::decode('3863')); + $this->assertEquals(-256, PubNubCborDecode::decode('38FF')); + } + + public function testDecodeNegativeInteger2Bytes() + { + // -257 to -65536 + $this->assertEquals(-1000, PubNubCborDecode::decode('3903E7')); + } + + // ============================================================================ + // BYTE STRING TESTS + // ============================================================================ + + public function testDecodeByteStringEmpty() + { + $this->assertEquals('', PubNubCborDecode::decode('40')); + } + + public function testDecodeByteStringSmall() + { + // Byte string "hello" (68656C6C6F in hex) + $this->assertEquals('hello', PubNubCborDecode::decode('4568656C6C6F')); + } + + public function testDecodeByteString1ByteLength() + { + // Byte string with 1-byte length indicator + $decoded = PubNubCborDecode::decode('5818' . bin2hex(str_repeat('a', 24))); + $this->assertEquals(str_repeat('a', 24), $decoded); + } + + // ============================================================================ + // TEXT STRING TESTS + // ============================================================================ + + public function testDecodeTextStringEmpty() + { + $this->assertEquals('', PubNubCborDecode::decode('60')); + } + + public function testDecodeTextStringSmall() + { + // Text string "IETF" + $this->assertEquals('IETF', PubNubCborDecode::decode('6449455446')); + } + + public function testDecodeTextStringUnicode() + { + // Text string with unicode + $this->assertEquals('hello', PubNubCborDecode::decode('6568656C6C6F')); + } + + public function testDecodeTextString1ByteLength() + { + // Text string with 1-byte length + $text = str_repeat('x', 24); + $decoded = PubNubCborDecode::decode('7818' . bin2hex($text)); + $this->assertEquals($text, $decoded); + } + + // ============================================================================ + // ARRAY TESTS + // ============================================================================ + + public function testDecodeArrayEmpty() + { + $this->assertEquals([], PubNubCborDecode::decode('80')); + } + + public function testDecodeArrayWithIntegers() + { + // Array [1, 2, 3] + $this->assertEquals([1, 2, 3], PubNubCborDecode::decode('83010203')); + } + + public function testDecodeArrayWithMixedTypes() + { + // Array [1, "hello"] + $result = PubNubCborDecode::decode('82016568656C6C6F'); + $this->assertEquals([1, 'hello'], $result); + } + + public function testDecodeArrayNested() + { + // Array [[1, 2], [3, 4]] + $result = PubNubCborDecode::decode('828201028203 04'); + $this->assertEquals([[1, 2], [3, 4]], $result); + } + + public function testDecodeArrayWithNegativeNumbers() + { + // Array [-1, -2, -3] + $this->assertEquals([-1, -2, -3], PubNubCborDecode::decode('83202122')); + } + + // ============================================================================ + // HASHMAP (OBJECT) TESTS + // ============================================================================ + + public function testDecodeHashmapEmpty() + { + $this->assertEquals([], PubNubCborDecode::decode('A0')); + } + + public function testDecodeHashmapWithStrings() + { + // Map {"a": "A"} + $result = PubNubCborDecode::decode('A161616141'); + $this->assertEquals(['a' => 'A'], $result); + } + + public function testDecodeHashmapWithNumbers() + { + // Map {"a": 1, "b": 2} + $result = PubNubCborDecode::decode('A26161016162 02'); + $this->assertEquals(['a' => 1, 'b' => 2], $result); + } + + public function testDecodeHashmapNested() + { + // Map {"a": {"b": "c"}} + $result = PubNubCborDecode::decode('A16161A161626163'); + $this->assertEquals(['a' => ['b' => 'c']], $result); + } + + public function testDecodeHashmapWithArray() + { + // Map {"array": [1, 2, 3]} + $result = PubNubCborDecode::decode('A16561727261798301 0203'); + $this->assertEquals(['array' => [1, 2, 3]], $result); + } + + // ============================================================================ + // SIMPLE VALUES TESTS + // ============================================================================ + + public function testDecodeSimpleValueFalse() + { + $this->assertFalse(PubNubCborDecode::decode('F4')); + } + + public function testDecodeSimpleValueTrue() + { + $this->assertTrue(PubNubCborDecode::decode('F5')); + } + + public function testDecodeSimpleValueNull() + { + $this->assertNull(PubNubCborDecode::decode('F6')); + } + + public function testDecodeSimpleValueUndefined() + { + // Undefined maps to null in PHP + $this->assertNull(PubNubCborDecode::decode('F7')); + } + + // ============================================================================ + // FLOAT TESTS + // ============================================================================ + + public function testDecodeFloat16Bit() + { + // Test 16-bit float (half-precision) + // 1.0 in half precision: 0x3C00 + $result = PubNubCborDecode::decode('F93C00'); + $this->assertEquals(1.0, $result); + } + + public function testDecodeFloat32Bit() + { + // Test 32-bit float (single precision) + // 3.14159 approximately in single precision + $result = PubNubCborDecode::decode('FA40490FDA'); + $this->assertEqualsWithDelta(3.14159, $result, 0.00001); + } + + public function testDecodeFloat64Bit() + { + // Test 64-bit float (double precision) + // 1.1 in double precision + $result = PubNubCborDecode::decode('FB3FF199999999999A'); + $this->assertEqualsWithDelta(1.1, $result, 0.0000001); + } + + public function testDecodeFloatZero() + { + // 0.0 in half precision: 0x0000 + $result = PubNubCborDecode::decode('F90000'); + $this->assertEquals(0.0, $result); + } + + public function testDecodeFloatNegative() + { + // -1.0 in half precision: 0xBC00 + $result = PubNubCborDecode::decode('F9BC00'); + $this->assertEquals(-1.0, $result); + } + + public function testDecodeFloatInfinity() + { + // Positive infinity in half precision: 0x7C00 + $result = PubNubCborDecode::decode('F97C00'); + $this->assertEquals(INF, $result); + } + + // ============================================================================ + // COMPLEX DATA STRUCTURE TESTS + // ============================================================================ + + public function testDecodeComplexNestedStructure() + { + // Complex structure: {"users": [{"name": "Alice", "age": 30}]} + $cbor = 'A1' . // Map with 1 entry + '657573657273' . // key: "users" + '81' . // Array with 1 element + 'A2' . // Map with 2 entries + '646E616D65' . // key: "name" + '65416C696365' . // value: "Alice" + '63616765' . // key: "age" + '181E'; // value: 30 + + $result = PubNubCborDecode::decode($cbor); + + $this->assertIsArray($result); + $this->assertArrayHasKey('users', $result); + $this->assertIsArray($result['users']); + $this->assertEquals('Alice', $result['users'][0]['name']); + $this->assertEquals(30, $result['users'][0]['age']); + } + + public function testDecodeArrayOfMixedPrimitives() + { + // Array with: integer, string, boolean, null + // [42, "test", true, null] + $cbor = '84' . // Array with 4 elements + '182A' . // 42 + '6474657374' . // "test" + 'F5' . // true + 'F6'; // null + + $result = PubNubCborDecode::decode($cbor); + + $this->assertEquals([42, 'test', true, null], $result); + } + + // ============================================================================ + // INPUT SANITIZATION TESTS + // ============================================================================ + + public function testDecodeWithSpaces() + { + // Should handle spaces in input + $this->assertEquals(42, PubNubCborDecode::decode('18 2A')); + $this->assertEquals([1, 2], PubNubCborDecode::decode('82 01 02')); + } + + public function testDecodeWithLowerCase() + { + // Should handle lowercase hex + $this->assertEquals(255, PubNubCborDecode::decode('18ff')); + $this->assertEquals('hello', PubNubCborDecode::decode('6568656c6c6f')); + } + + public function testDecodeWithMixedCase() + { + // Should handle mixed case hex + $this->assertEquals(1000, PubNubCborDecode::decode('1903E8')); + $this->assertEquals('Test', PubNubCborDecode::decode('6454657374')); + } + + // ============================================================================ + // ERROR HANDLING TESTS + // ============================================================================ + + public function testDecodeInvalidHexCharacters() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid Input'); + + PubNubCborDecode::decode('GG'); + } + + public function testDecodeInvalidHexWithSpecialChars() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid Input'); + + PubNubCborDecode::decode('18@A'); + } + + public function testDecodeInvalidHexWithNonHexLetters() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Invalid Input'); + + PubNubCborDecode::decode('18ZZ'); + } + + // ============================================================================ + // EDGE CASES + // ============================================================================ + + public function testDecodeEmptyArray() + { + $result = PubNubCborDecode::decode('80'); + $this->assertIsArray($result); + $this->assertEmpty($result); + } + + public function testDecodeEmptyMap() + { + $result = PubNubCborDecode::decode('A0'); + $this->assertIsArray($result); + $this->assertEmpty($result); + } + + public function testDecodeEmptyString() + { + $this->assertEquals('', PubNubCborDecode::decode('60')); + } + + public function testDecodeLargeInteger() + { + // Test maximum values for different byte sizes + $this->assertEquals(4294967295, PubNubCborDecode::decode('1AFFFFFFFF')); + } + + public function testDecodeArrayWith1ByteLength() + { + // Array with length specified in 1 byte (25+ elements) + $cbor = '9818'; // Array with length in next byte: 24 elements + for ($i = 0; $i < 24; $i++) { + $cbor .= '0' . dechex($i % 16); // Add elements 0-15 repeated + } + + $result = PubNubCborDecode::decode($cbor); + $this->assertCount(24, $result); + } + + public function testDecodeMapWith1ByteLength() + { + // Map with length specified in 1 byte + $cbor = 'B818'; // Map with length in next byte: 24 entries + for ($i = 0; $i < 24; $i++) { + $key = chr(65 + $i); // A, B, C, ... + $cbor .= '61' . bin2hex($key); // key + $cbor .= '0' . dechex($i % 16); // value + } + + $result = PubNubCborDecode::decode($cbor); + $this->assertCount(24, $result); + } + + public function testDecodeMultipleNesting() + { + // Deep nesting: [[[1]]] + $result = PubNubCborDecode::decode('818181 01'); + $this->assertEquals([[[1]]], $result); + } + + public function testDecodeBooleanArray() + { + // Array of booleans: [true, false, true] + $result = PubNubCborDecode::decode('83F5F4F5'); + $this->assertEquals([true, false, true], $result); + } + + public function testDecodeNullArray() + { + // Array with nulls: [null, null] + $result = PubNubCborDecode::decode('82F6F6'); + $this->assertEquals([null, null], $result); + } + + public function testDecodeStringWithSpecialCharacters() + { + // String with special chars like newline, tab + $specialString = "test\nwith\ttabs"; + $hex = bin2hex($specialString); + $length = strlen($specialString); + $cbor = '6' . dechex($length) . $hex; + + $result = PubNubCborDecode::decode($cbor); + $this->assertEquals($specialString, $result); + } +} diff --git a/tests/unit/PubNubCryptoMethodsTest.php b/tests/unit/PubNubCryptoMethodsTest.php new file mode 100644 index 0000000..0b22db4 --- /dev/null +++ b/tests/unit/PubNubCryptoMethodsTest.php @@ -0,0 +1,354 @@ +setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + + $this->assertFalse($pubnub->isCryptoEnabled()); + } + + public function testIsCryptoEnabledReturnsTrueWhenCipherKeySet() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setCipherKey('test-cipher-key'); + + $pubnub = new PubNub($config); + + $this->assertTrue($pubnub->isCryptoEnabled()); + } + + public function testIsCryptoEnabledReturnsTrueWhenCryptoModuleSet() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::legacyCryptor('test-key', false); + $pubnub->setCrypto($cryptoModule); + + $this->assertTrue($pubnub->isCryptoEnabled()); + } + + public function testIsCryptoEnabledAfterSettingCryptoOnPubNub() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $this->assertFalse($pubnub->isCryptoEnabled()); + + $cryptoModule = CryptoModule::aesCbcCryptor('my-key', true); + $pubnub->setCrypto($cryptoModule); + + $this->assertTrue($pubnub->isCryptoEnabled()); + } + + // ============================================================================ + // getCrypto() TESTS + // ============================================================================ + + public function testGetCryptoReturnsNullWhenNotConfigured() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + + $this->assertNull($pubnub->getCrypto()); + } + + public function testGetCryptoReturnsModuleWhenCipherKeySet() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setCipherKey('test-cipher-key'); + + $pubnub = new PubNub($config); + $crypto = $pubnub->getCrypto(); + + $this->assertInstanceOf(CryptoModule::class, $crypto); + } + + public function testGetCryptoReturnsModuleWhenCryptoModuleSet() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::legacyCryptor('test-key', false); + $pubnub->setCrypto($cryptoModule); + + $crypto = $pubnub->getCrypto(); + + $this->assertInstanceOf(CryptoModule::class, $crypto); + $this->assertSame($cryptoModule, $crypto); + } + + public function testGetCryptoReturnsConfigurationCryptoWhenNoPubNubCrypto() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setCipherKey('config-key'); + + $pubnub = new PubNub($config); + $crypto = $pubnub->getCrypto(); + + $this->assertInstanceOf(CryptoModule::class, $crypto); + } + + public function testGetCryptoPrefersInstanceCryptoOverConfiguration() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setCipherKey('config-key'); + + $pubnub = new PubNub($config); + + $instanceCrypto = CryptoModule::aesCbcCryptor('instance-key', true); + $pubnub->setCrypto($instanceCrypto); + + $crypto = $pubnub->getCrypto(); + + $this->assertSame($instanceCrypto, $crypto); + } + + // ============================================================================ + // setCrypto() TESTS + // ============================================================================ + + public function testSetCryptoStoresModule() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::legacyCryptor('my-cipher-key', false); + + $pubnub->setCrypto($cryptoModule); + + $this->assertSame($cryptoModule, $pubnub->getCrypto()); + } + + public function testSetCryptoOverwritesPreviousCrypto() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + + $crypto1 = CryptoModule::legacyCryptor('key1', false); + $pubnub->setCrypto($crypto1); + $this->assertSame($crypto1, $pubnub->getCrypto()); + + $crypto2 = CryptoModule::aesCbcCryptor('key2', true); + $pubnub->setCrypto($crypto2); + $this->assertSame($crypto2, $pubnub->getCrypto()); + } + + public function testSetCryptoEnablesCrypto() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $this->assertFalse($pubnub->isCryptoEnabled()); + + $cryptoModule = CryptoModule::legacyCryptor('my-key', false); + $pubnub->setCrypto($cryptoModule); + + $this->assertTrue($pubnub->isCryptoEnabled()); + } + + public function testSetCryptoWithLegacyCryptor() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::legacyCryptor('legacy-key', false); + + $pubnub->setCrypto($cryptoModule); + + $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); + } + + public function testSetCryptoWithAesCbcCryptor() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::aesCbcCryptor('aes-key', true); + + $pubnub->setCrypto($cryptoModule); + + $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); + } + + public function testSetCryptoWithRandomIV() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::legacyCryptor('test-key', true); + + $pubnub->setCrypto($cryptoModule); + + $crypto = $pubnub->getCrypto(); + $this->assertNotNull($crypto); + } + + public function testSetCryptoWithStaticIV() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::legacyCryptor('test-key', false); + + $pubnub->setCrypto($cryptoModule); + + $crypto = $pubnub->getCrypto(); + $this->assertNotNull($crypto); + } + + // ============================================================================ + // INTEGRATION TESTS (getCrypto + setCrypto + isCryptoEnabled) + // ============================================================================ + + public function testCryptoWorkflowConfigurationOnly() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setCipherKey('config-cipher-key'); + + $pubnub = new PubNub($config); + + $this->assertTrue($pubnub->isCryptoEnabled()); + $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); + } + + public function testCryptoWorkflowInstanceOnly() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $this->assertFalse($pubnub->isCryptoEnabled()); + + $cryptoModule = CryptoModule::aesCbcCryptor('instance-key', true); + $pubnub->setCrypto($cryptoModule); + + $this->assertTrue($pubnub->isCryptoEnabled()); + $this->assertSame($cryptoModule, $pubnub->getCrypto()); + } + + public function testCryptoWorkflowBothConfigurationAndInstance() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setCipherKey('config-key'); + + $pubnub = new PubNub($config); + $this->assertTrue($pubnub->isCryptoEnabled()); + + $instanceCrypto = CryptoModule::legacyCryptor('instance-key', false); + $pubnub->setCrypto($instanceCrypto); + + $this->assertTrue($pubnub->isCryptoEnabled()); + $this->assertSame($instanceCrypto, $pubnub->getCrypto()); + } + + public function testCryptoCanBeUsedForEncryptionDecryption() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + + $pubnub = new PubNub($config); + $cryptoModule = CryptoModule::aesCbcCryptor('encryption-key', false); + $pubnub->setCrypto($cryptoModule); + + $crypto = $pubnub->getCrypto(); + + $plaintext = 'Hello, World!'; + $encrypted = $crypto->encrypt($plaintext); + $decrypted = $crypto->decrypt($encrypted); + + $this->assertEquals($plaintext, $decrypted); + } + + public function testMultiplePubNubInstancesWithDifferentCrypto() + { + $config1 = new PNConfiguration(); + $config1->setSubscribeKey('demo'); + $config1->setUserId('user1'); + $pubnub1 = new PubNub($config1); + $crypto1 = CryptoModule::legacyCryptor('key1', false); + $pubnub1->setCrypto($crypto1); + + $config2 = new PNConfiguration(); + $config2->setSubscribeKey('demo'); + $config2->setUserId('user2'); + $pubnub2 = new PubNub($config2); + $crypto2 = CryptoModule::aesCbcCryptor('key2', true); + $pubnub2->setCrypto($crypto2); + + $this->assertNotSame($pubnub1->getCrypto(), $pubnub2->getCrypto()); + $this->assertSame($crypto1, $pubnub1->getCrypto()); + $this->assertSame($crypto2, $pubnub2->getCrypto()); + } + + public function testCryptoModuleCanBeRetrievedAndUsedDirectly() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test-user'); + $config->setCipherKey('direct-use-key'); + + $pubnub = new PubNub($config); + $crypto = $pubnub->getCrypto(); + + // Use crypto module directly + $message = 'Test message'; + $encrypted = $crypto->encrypt($message); + + $this->assertNotEquals($message, $encrypted); + $this->assertIsString($encrypted); + } +} diff --git a/tests/unit/PubNubFactoryMethodsTest.php b/tests/unit/PubNubFactoryMethodsTest.php new file mode 100644 index 0000000..aa3324f --- /dev/null +++ b/tests/unit/PubNubFactoryMethodsTest.php @@ -0,0 +1,266 @@ +assertInstanceOf(PubNub::class, $pubnub); + } + + public function testDemoHasDemoKeys() + { + $pubnub = PubNub::demo(); + $config = $pubnub->getConfiguration(); + + $this->assertEquals('demo', $config->getSubscribeKey()); + $this->assertEquals('demo', $config->getPublishKey()); + } + + public function testDemoHasDemoUserId() + { + $pubnub = PubNub::demo(); + $config = $pubnub->getConfiguration(); + + $this->assertEquals('demo', $config->getUserId()); + } + + public function testDemoIsImmediatelyUsable() + { + $pubnub = PubNub::demo(); + + // Should be able to call methods without configuration errors + $config = $pubnub->getConfiguration(); + + $this->assertNotNull($config->getSubscribeKey()); + $this->assertNotNull($config->getPublishKey()); + $this->assertNotNull($config->getUserId()); + } + + public function testDemoCreatesNewInstanceEachTime() + { + $pubnub1 = PubNub::demo(); + $pubnub2 = PubNub::demo(); + + $this->assertNotSame($pubnub1, $pubnub2); + } + + public function testDemoInstancesAreIndependent() + { + $pubnub1 = PubNub::demo(); + $pubnub2 = PubNub::demo(); + + // Modify one instance + $pubnub1->setToken('token1'); + $pubnub2->setToken('token2'); + + $this->assertEquals('token1', $pubnub1->getToken()); + $this->assertEquals('token2', $pubnub2->getToken()); + } + + public function testDemoConfigurationIsLocked() + { + $pubnub = PubNub::demo(); + $config = $pubnub->getConfiguration(); + + // Configuration should be locked after being passed to PubNub constructor + $this->expectException(\PubNub\Exceptions\PubNubConfigurationException::class); + $config->setPublishKey('new-key'); + } + + public function testDemoCanBeUsedForBasicOperations() + { + $pubnub = PubNub::demo(); + + // Should be able to create endpoint builders + $this->assertNotNull($pubnub->publish()); + $this->assertNotNull($pubnub->subscribe()); + $this->assertNotNull($pubnub->time()); + } + + // ============================================================================ + // PNConfiguration::demoKeys() TESTS + // ============================================================================ + + public function testDemoKeysReturnsValidConfiguration() + { + $config = PNConfiguration::demoKeys(); + + $this->assertInstanceOf(PNConfiguration::class, $config); + } + + public function testDemoKeysHasSubscribeKey() + { + $config = PNConfiguration::demoKeys(); + + $this->assertEquals('demo', $config->getSubscribeKey()); + } + + public function testDemoKeysHasPublishKey() + { + $config = PNConfiguration::demoKeys(); + + $this->assertEquals('demo', $config->getPublishKey()); + } + + public function testDemoKeysHasUserId() + { + $config = PNConfiguration::demoKeys(); + + $this->assertEquals('demo', $config->getUserId()); + } + + public function testDemoKeysConfigurationIsNotLocked() + { + $config = PNConfiguration::demoKeys(); + + // Should be able to modify the configuration + $config->setPublishKey('new-pub-key'); + $this->assertEquals('new-pub-key', $config->getPublishKey()); + + $config->setSubscribeKey('new-sub-key'); + $this->assertEquals('new-sub-key', $config->getSubscribeKey()); + + // Test other modifiable properties (userId has special handling due to UUID/UserId distinction) + $config->setSecure(false); + $this->assertFalse($config->isSecure()); + + $config->setOrigin('custom.origin.com'); + $this->assertEquals('custom.origin.com', $config->getOrigin()); + } + + public function testDemoKeysCreatesNewInstanceEachTime() + { + $config1 = PNConfiguration::demoKeys(); + $config2 = PNConfiguration::demoKeys(); + + $this->assertNotSame($config1, $config2); + } + + public function testDemoKeysInstancesAreIndependent() + { + $config1 = PNConfiguration::demoKeys(); + $config2 = PNConfiguration::demoKeys(); + + $config1->setPublishKey('key1'); + $config2->setPublishKey('key2'); + + $this->assertEquals('key1', $config1->getPublishKey()); + $this->assertEquals('key2', $config2->getPublishKey()); + } + + public function testDemoKeysCanBeCustomized() + { + $config = PNConfiguration::demoKeys(); + + // Customize the demo configuration + $config->setSecure(false); + $config->setOrigin('custom-origin.pubnub.com'); + $config->setAuthKey('auth-key-123'); + + $this->assertFalse($config->isSecure()); + $this->assertEquals('custom-origin.pubnub.com', $config->getOrigin()); + $this->assertEquals('auth-key-123', $config->getAuthKey()); + } + + public function testDemoKeysCanBeUsedToCreatePubNub() + { + $config = PNConfiguration::demoKeys(); + $pubnub = new PubNub($config); + + $this->assertInstanceOf(PubNub::class, $pubnub); + + $retrievedConfig = $pubnub->getConfiguration(); + $this->assertEquals('demo', $retrievedConfig->getSubscribeKey()); + $this->assertEquals('demo', $retrievedConfig->getPublishKey()); + $this->assertEquals('demo', $retrievedConfig->getUserId()); + } + + public function testDemoKeysHasDefaultSecureSettings() + { + $config = PNConfiguration::demoKeys(); + + $this->assertTrue($config->isSecure()); + } + + public function testDemoKeysHasDefaultTimeouts() + { + $config = PNConfiguration::demoKeys(); + + $this->assertEquals(10, $config->getNonSubscribeRequestTimeout()); + $this->assertEquals(310, $config->getSubscribeTimeout()); + $this->assertEquals(10, $config->getConnectTimeout()); + } + + // ============================================================================ + // INTEGRATION TESTS + // ============================================================================ + + public function testDemoMethodUsesDemoKeysInternally() + { + $demoConfig = PNConfiguration::demoKeys(); + $demoPubNub = PubNub::demo(); + + $config = $demoPubNub->getConfiguration(); + + // Should have same values as demoKeys() + $this->assertEquals($demoConfig->getSubscribeKey(), $config->getSubscribeKey()); + $this->assertEquals($demoConfig->getPublishKey(), $config->getPublishKey()); + $this->assertEquals($demoConfig->getUserId(), $config->getUserId()); + } + + public function testDemoKeysAndDemoProduceSimilarResults() + { + $configFromDemoKeys = PNConfiguration::demoKeys(); + $pubnubFromDemo = PubNub::demo(); + $configFromDemo = $pubnubFromDemo->getConfiguration(); + + $this->assertEquals( + $configFromDemoKeys->getSubscribeKey(), + $configFromDemo->getSubscribeKey() + ); + $this->assertEquals( + $configFromDemoKeys->getPublishKey(), + $configFromDemo->getPublishKey() + ); + $this->assertEquals( + $configFromDemoKeys->getUserId(), + $configFromDemo->getUserId() + ); + } + + public function testDemoKeysCanBeCloned() + { + $config = PNConfiguration::demoKeys(); + $cloned = $config->clone(); + + $this->assertNotSame($config, $cloned); + $this->assertEquals('demo', $cloned->getSubscribeKey()); + $this->assertEquals('demo', $cloned->getPublishKey()); + $this->assertEquals('demo', $cloned->getUserId()); + } + + public function testMultipleDemoInstancesCanCoexist() + { + $pubnub1 = PubNub::demo(); + $pubnub2 = PubNub::demo(); + $pubnub3 = PubNub::demo(); + + $this->assertInstanceOf(PubNub::class, $pubnub1); + $this->assertInstanceOf(PubNub::class, $pubnub2); + $this->assertInstanceOf(PubNub::class, $pubnub3); + + $this->assertNotSame($pubnub1, $pubnub2); + $this->assertNotSame($pubnub2, $pubnub3); + $this->assertNotSame($pubnub1, $pubnub3); + } +} diff --git a/tests/unit/PubNubSdkInfoTest.php b/tests/unit/PubNubSdkInfoTest.php new file mode 100644 index 0000000..28a62aa --- /dev/null +++ b/tests/unit/PubNubSdkInfoTest.php @@ -0,0 +1,320 @@ +assertIsString($version); + } + + public function testGetSdkVersionIsNotEmpty() + { + $version = PubNub::getSdkVersion(); + + $this->assertNotEmpty($version); + } + + public function testGetSdkVersionFollowsSemanticVersioning() + { + $version = PubNub::getSdkVersion(); + + // Should match semantic versioning pattern (e.g., 7.1.0, 7.1.0-beta.1, etc.) + $pattern = '/^\d+\.\d+\.\d+(-[a-zA-Z0-9\.\-]+)?$/'; + $this->assertMatchesRegularExpression($pattern, $version); + } + + public function testGetSdkVersionIsConsistent() + { + $version1 = PubNub::getSdkVersion(); + $version2 = PubNub::getSdkVersion(); + + $this->assertEquals($version1, $version2); + } + + public function testGetSdkVersionStartsWithDigit() + { + $version = PubNub::getSdkVersion(); + + $this->assertMatchesRegularExpression('/^\d/', $version); + } + + public function testGetSdkVersionContainsMajorMinorPatch() + { + $version = PubNub::getSdkVersion(); + + // Split by '.' and check we have at least 3 parts (major.minor.patch) + $parts = explode('.', $version); + $this->assertGreaterThanOrEqual(3, count($parts)); + } + + public function testGetSdkVersionMajorVersionIsNumeric() + { + $version = PubNub::getSdkVersion(); + $parts = explode('.', $version); + + $this->assertIsNumeric($parts[0]); + } + + public function testGetSdkVersionMinorVersionIsNumeric() + { + $version = PubNub::getSdkVersion(); + $parts = explode('.', $version); + + $this->assertIsNumeric($parts[1]); + } + + public function testGetSdkVersionPatchVersionIsNumeric() + { + $version = PubNub::getSdkVersion(); + $parts = explode('.', $version); + + // Patch might have a pre-release suffix (e.g., 0-beta) + // So we extract just the numeric part + preg_match('/^(\d+)/', $parts[2], $matches); + $this->assertIsNumeric($matches[1]); + } + + // ============================================================================ + // getSdkName() TESTS + // ============================================================================ + + public function testGetSdkNameReturnsString() + { + $name = PubNub::getSdkName(); + + $this->assertIsString($name); + } + + public function testGetSdkNameIsNotEmpty() + { + $name = PubNub::getSdkName(); + + $this->assertNotEmpty($name); + } + + public function testGetSdkNameIsConsistent() + { + $name1 = PubNub::getSdkName(); + $name2 = PubNub::getSdkName(); + + $this->assertEquals($name1, $name2); + } + + public function testGetSdkNameContainsPHP() + { + $name = PubNub::getSdkName(); + + // SDK name should indicate it's a PHP SDK + $this->assertMatchesRegularExpression('/php/i', $name); + } + + public function testGetSdkNameContainsPubNub() + { + $name = PubNub::getSdkName(); + + // SDK name should contain "PubNub" + $this->assertMatchesRegularExpression('/pubnub/i', $name); + } + + public function testGetSdkNameFormat() + { + $name = PubNub::getSdkName(); + + // Should be in format like "PubNub-PHP" or similar + $this->assertMatchesRegularExpression('/^[a-zA-Z\-]+$/', $name); + } + + public function testGetSdkNameDoesNotContainVersion() + { + $name = PubNub::getSdkName(); + + // Name should not contain version numbers + $this->assertDoesNotMatchRegularExpression('/\d+\.\d+/', $name); + } + + // ============================================================================ + // getSdkFullName() TESTS + // ============================================================================ + + public function testGetSdkFullNameReturnsString() + { + $fullName = PubNub::getSdkFullName(); + + $this->assertIsString($fullName); + } + + public function testGetSdkFullNameIsNotEmpty() + { + $fullName = PubNub::getSdkFullName(); + + $this->assertNotEmpty($fullName); + } + + public function testGetSdkFullNameIsConsistent() + { + $fullName1 = PubNub::getSdkFullName(); + $fullName2 = PubNub::getSdkFullName(); + + $this->assertEquals($fullName1, $fullName2); + } + + public function testGetSdkFullNameContainsSdkName() + { + $name = PubNub::getSdkName(); + $fullName = PubNub::getSdkFullName(); + + $this->assertStringContainsString($name, $fullName); + } + + public function testGetSdkFullNameContainsSdkVersion() + { + $version = PubNub::getSdkVersion(); + $fullName = PubNub::getSdkFullName(); + + $this->assertStringContainsString($version, $fullName); + } + + public function testGetSdkFullNameFormat() + { + $fullName = PubNub::getSdkFullName(); + + // Should be in format like "PubNub-PHP/7.1.0" or "PubNub-PHP-7.1.0" + $pattern = '/^[a-zA-Z\-]+[\/\-]\d+\.\d+\.\d+/'; + $this->assertMatchesRegularExpression($pattern, $fullName); + } + + public function testGetSdkFullNameIsConcatenationOfNameAndVersion() + { + $name = PubNub::getSdkName(); + $version = PubNub::getSdkVersion(); + $fullName = PubNub::getSdkFullName(); + + // Full name should be name + separator + version + $expectedPattern = '/' . preg_quote($name, '/') . '[\/\-]' . preg_quote($version, '/') . '/'; + $this->assertMatchesRegularExpression($expectedPattern, $fullName); + } + + public function testGetSdkFullNameLongerThanName() + { + $name = PubNub::getSdkName(); + $fullName = PubNub::getSdkFullName(); + + $this->assertGreaterThan(strlen($name), strlen($fullName)); + } + + public function testGetSdkFullNameLongerThanVersion() + { + $version = PubNub::getSdkVersion(); + $fullName = PubNub::getSdkFullName(); + + $this->assertGreaterThan(strlen($version), strlen($fullName)); + } + + // ============================================================================ + // INTEGRATION TESTS + // ============================================================================ + + public function testSdkInfoMethodsAreAllConsistent() + { + $name = PubNub::getSdkName(); + $version = PubNub::getSdkVersion(); + $fullName = PubNub::getSdkFullName(); + + $this->assertStringContainsString($name, $fullName); + $this->assertStringContainsString($version, $fullName); + } + + public function testSdkInfoMethodsCanBeCalledMultipleTimes() + { + // Call each method multiple times + for ($i = 0; $i < 5; $i++) { + $this->assertIsString(PubNub::getSdkName()); + $this->assertIsString(PubNub::getSdkVersion()); + $this->assertIsString(PubNub::getSdkFullName()); + } + } + + public function testSdkInfoMethodsReturnSameValuesAcrossInstances() + { + $pubnub1 = PubNub::demo(); + $pubnub2 = PubNub::demo(); + + // Static methods should return same values regardless of instance + $this->assertEquals(PubNub::getSdkName(), PubNub::getSdkName()); + $this->assertEquals(PubNub::getSdkVersion(), PubNub::getSdkVersion()); + $this->assertEquals(PubNub::getSdkFullName(), PubNub::getSdkFullName()); + } + + public function testSdkVersionCanBeParsed() + { + $version = PubNub::getSdkVersion(); + + // Should be parsable as a version string + $parts = explode('.', $version); + + $this->assertGreaterThanOrEqual(3, count($parts)); + $this->assertIsNumeric($parts[0]); // Major + $this->assertIsNumeric($parts[1]); // Minor + + // Patch might have pre-release suffix, extract numeric part + preg_match('/^(\d+)/', $parts[2], $matches); + $this->assertNotEmpty($matches); + $this->assertIsNumeric($matches[1]); // Patch + } + + public function testSdkFullNameIsUsableForUserAgent() + { + $fullName = PubNub::getSdkFullName(); + + // Should be a valid format for User-Agent headers (no spaces, special chars) + $this->assertMatchesRegularExpression('/^[a-zA-Z0-9\-\.\/]+$/', $fullName); + } + + public function testSdkNameIsUsableAsIdentifier() + { + $name = PubNub::getSdkName(); + + // Should be a valid identifier (no spaces, no version numbers) + $this->assertMatchesRegularExpression('/^[a-zA-Z\-]+$/', $name); + } + + public function testSdkVersionIsValidSemanticVersion() + { + $version = PubNub::getSdkVersion(); + + // Validate against semantic versioning 2.0.0 spec + $semverPattern = '/^' + . '(\d+)\.(\d+)\.(\d+)' // Major.Minor.Patch + . '(-[0-9A-Za-z\-\.]+)?' // Pre-release (optional) + . '(\+[0-9A-Za-z\-\.]+)?' // Build metadata (optional) + . '$/'; + + $this->assertMatchesRegularExpression($semverPattern, $version); + } + + public function testSdkInfoDoesNotChangeAtRuntime() + { + // Capture initial values + $name1 = PubNub::getSdkName(); + $version1 = PubNub::getSdkVersion(); + $fullName1 = PubNub::getSdkFullName(); + + // Create some PubNub instances + $pubnub1 = PubNub::demo(); + $pubnub2 = PubNub::demo(); + + // Values should remain the same + $this->assertEquals($name1, PubNub::getSdkName()); + $this->assertEquals($version1, PubNub::getSdkVersion()); + $this->assertEquals($fullName1, PubNub::getSdkFullName()); + } +} diff --git a/tests/unit/PubNubUtilExtendedTest.php b/tests/unit/PubNubUtilExtendedTest.php new file mode 100644 index 0000000..2fb37ba --- /dev/null +++ b/tests/unit/PubNubUtilExtendedTest.php @@ -0,0 +1,585 @@ + 'test-user', 'pnsdk' => 'PubNub-PHP/8.0.0']; + + $url = PubNubUtil::buildUrl($basePath, $path, $params); + + $this->assertStringStartsWith($basePath . $path, $url); + $this->assertStringContainsString('uuid=test-user', $url); + $this->assertStringContainsString('pnsdk=PubNub-PHP/8.0.0', $url); + } + + public function testBuildUrlWithEmptyParams() + { + $basePath = 'https://ps.pndsn.com'; + $path = '/v2/time/0'; + $params = []; + + $url = PubNubUtil::buildUrl($basePath, $path, $params); + + $this->assertEquals($basePath . $path . '?', $url); + } + + public function testBuildUrlWithSpecialCharactersInParams() + { + $basePath = 'https://ps.pndsn.com'; + $path = '/publish'; + $params = ['message' => 'hello%20world']; + + $url = PubNubUtil::buildUrl($basePath, $path, $params); + + $this->assertStringContainsString('message=hello%20world', $url); + } + + public function testBuildUrlWithMultipleParams() + { + $basePath = 'https://ps.pndsn.com'; + $path = '/v2/history'; + $params = [ + 'channel' => 'test-channel', + 'count' => '100', + 'reverse' => 'false' + ]; + + $url = PubNubUtil::buildUrl($basePath, $path, $params); + + $this->assertStringContainsString('channel=test-channel', $url); + $this->assertStringContainsString('count=100', $url); + $this->assertStringContainsString('reverse=false', $url); + } + + // ============================================================================ + // joinChannels() TESTS + // ============================================================================ + + public function testJoinChannelsWithSingleChannel() + { + $channels = ['channel1']; + + $result = PubNubUtil::joinChannels($channels); + + $this->assertEquals('channel1', $result); + } + + public function testJoinChannelsWithMultipleChannels() + { + $channels = ['channel1', 'channel2', 'channel3']; + + $result = PubNubUtil::joinChannels($channels); + + $this->assertEquals('channel1,channel2,channel3', $result); + } + + public function testJoinChannelsWithEmptyArray() + { + $channels = []; + + $result = PubNubUtil::joinChannels($channels); + + $this->assertEquals(',', $result); + } + + public function testJoinChannelsWithSpecialCharacters() + { + $channels = ['channel-1', 'channel.2', 'channel_3']; + + $result = PubNubUtil::joinChannels($channels); + + $this->assertEquals('channel-1,channel.2,channel_3', $result); + } + + public function testJoinChannelsEncodesSpecialCharacters() + { + $channels = ['channel with spaces', 'channel#special']; + + $result = PubNubUtil::joinChannels($channels); + + $this->assertStringContainsString('channel+with+spaces', $result); + $this->assertStringContainsString('channel%23special', $result); + } + + // ============================================================================ + // joinItems() TESTS + // ============================================================================ + + public function testJoinItemsWithSingleItem() + { + $items = ['item1']; + + $result = PubNubUtil::joinItems($items); + + $this->assertEquals('item1', $result); + } + + public function testJoinItemsWithMultipleItems() + { + $items = ['item1', 'item2', 'item3']; + + $result = PubNubUtil::joinItems($items); + + $this->assertEquals('item1,item2,item3', $result); + } + + public function testJoinItemsWithEmptyArray() + { + $items = []; + + $result = PubNubUtil::joinItems($items); + + $this->assertEquals('', $result); + } + + public function testJoinItemsWithNumericItems() + { + $items = ['1', '2', '3']; + + $result = PubNubUtil::joinItems($items); + + $this->assertEquals('1,2,3', $result); + } + + // ============================================================================ + // extendArray() TESTS - Already used in tests but testing edge cases + // ============================================================================ + + public function testExtendArrayWithArrays() + { + $existing = ['a', 'b']; + $new = ['c', 'd']; + + $result = PubNubUtil::extendArray($existing, $new); + + $this->assertEquals(['a', 'b', 'c', 'd'], $result); + } + + public function testExtendArrayWithString() + { + $existing = ['a', 'b']; + $new = 'c,d'; + + $result = PubNubUtil::extendArray($existing, $new); + + $this->assertEquals(['a', 'b', 'c', 'd'], $result); + } + + public function testExtendArrayWithEmptyExisting() + { + $existing = []; + $new = ['a', 'b']; + + $result = PubNubUtil::extendArray($existing, $new); + + $this->assertEquals(['a', 'b'], $result); + } + + public function testExtendArrayWithEmptyNew() + { + $existing = ['a', 'b']; + $new = []; + + $result = PubNubUtil::extendArray($existing, $new); + + $this->assertEquals(['a', 'b'], $result); + } + + public function testExtendArrayWithEmptyString() + { + $existing = ['a', 'b']; + $new = ''; + + $result = PubNubUtil::extendArray($existing, $new); + + $this->assertEquals(['a', 'b'], $result); + } + + // ============================================================================ + // splitItems() TESTS + // ============================================================================ + + public function testSplitItemsWithSingleItem() + { + $items = 'item1'; + + $result = PubNubUtil::splitItems($items); + + $this->assertEquals(['item1'], $result); + } + + public function testSplitItemsWithMultipleItems() + { + $items = 'item1,item2,item3'; + + $result = PubNubUtil::splitItems($items); + + $this->assertEquals(['item1', 'item2', 'item3'], $result); + } + + public function testSplitItemsWithEmptyString() + { + $items = ''; + + $result = PubNubUtil::splitItems($items); + + $this->assertEquals([], $result); + } + + public function testSplitItemsPreservesSpaces() + { + $items = 'item 1,item 2'; + + $result = PubNubUtil::splitItems($items); + + $this->assertEquals(['item 1', 'item 2'], $result); + } + + public function testSplitItemsWithTrailingComma() + { + $items = 'item1,item2,'; + + $result = PubNubUtil::splitItems($items); + + $this->assertEquals(['item1', 'item2', ''], $result); + } + + // ============================================================================ + // uuid() TESTS + // ============================================================================ + + public function testUuidReturnsString() + { + $uuid = PubNubUtil::uuid(); + + $this->assertIsString($uuid); + } + + public function testUuidHasCorrectFormat() + { + $uuid = PubNubUtil::uuid(); + + // UUID format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + $this->assertMatchesRegularExpression( + '/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i', + $uuid + ); + } + + public function testUuidIsUnique() + { + $uuid1 = PubNubUtil::uuid(); + $uuid2 = PubNubUtil::uuid(); + + $this->assertNotEquals($uuid1, $uuid2); + } + + public function testUuidGeneratesMultipleUniqueValues() + { + $uuids = []; + for ($i = 0; $i < 100; $i++) { + $uuids[] = PubNubUtil::uuid(); + } + + // All UUIDs should be unique + $this->assertEquals(100, count(array_unique($uuids))); + } + + public function testUuidLength() + { + $uuid = PubNubUtil::uuid(); + + // UUID with dashes is 36 characters + $this->assertEquals(36, strlen($uuid)); + } + + // ============================================================================ + // fetchPamPermissionsFrom() TESTS + // ============================================================================ + + public function testFetchPamPermissionsFromWithAllPermissions() + { + $input = [ + 'r' => 1, + 'w' => 1, + 'm' => 1, + 'd' => 1, + 'g' => 1, + 'u' => 1, + 'j' => 1, + 'ttl' => 1440 + ]; + + $result = PubNubUtil::fetchPamPermissionsFrom($input); + + $this->assertEquals([true, true, true, true, true, true, true, 1440], $result); + } + + public function testFetchPamPermissionsFromWithNoPermissions() + { + $input = [ + 'r' => 0, + 'w' => 0, + 'm' => 0, + 'd' => 0, + 'g' => 0, + 'u' => 0, + 'j' => 0, + 'ttl' => 0 + ]; + + $result = PubNubUtil::fetchPamPermissionsFrom($input); + + $this->assertEquals([false, false, false, false, false, false, false, 0], $result); + } + + public function testFetchPamPermissionsFromWithPartialPermissions() + { + $input = [ + 'r' => 1, + 'w' => 0, + 'm' => 1, + 'ttl' => 60 + ]; + + $result = PubNubUtil::fetchPamPermissionsFrom($input); + + $this->assertEquals([true, false, true, null, null, null, null, 60], $result); + } + + public function testFetchPamPermissionsFromWithEmptyInput() + { + $input = []; + + $result = PubNubUtil::fetchPamPermissionsFrom($input); + + $this->assertEquals([null, null, null, null, null, null, null, null], $result); + } + + public function testFetchPamPermissionsFromWithOnlyTTL() + { + $input = ['ttl' => 120]; + + $result = PubNubUtil::fetchPamPermissionsFrom($input); + + $this->assertEquals([null, null, null, null, null, null, null, 120], $result); + } + + // ============================================================================ + // isAssoc() TESTS + // ============================================================================ + + public function testIsAssocWithIndexedArray() + { + $array = ['a', 'b', 'c']; + + $result = PubNubUtil::isAssoc($array); + + $this->assertFalse($result); + } + + public function testIsAssocWithAssociativeArray() + { + $array = ['key1' => 'value1', 'key2' => 'value2']; + + $result = PubNubUtil::isAssoc($array); + + $this->assertTrue($result); + } + + public function testIsAssocWithNumericKeys() + { + $array = [0 => 'a', 1 => 'b', 2 => 'c']; + + $result = PubNubUtil::isAssoc($array); + + $this->assertFalse($result); + } + + public function testIsAssocWithMixedKeys() + { + $array = [0 => 'a', 'key' => 'b', 2 => 'c']; + + $result = PubNubUtil::isAssoc($array); + + $this->assertTrue($result); + } + + public function testIsAssocWithEmptyArray() + { + $array = []; + + $result = PubNubUtil::isAssoc($array); + + // Empty array returns true because array_keys([]) !== range(0, count([]) - 1) + // array_keys([]) = [], range(0, -1) = [] + // But the comparison returns true (not equal) + $this->assertTrue($result); + } + + public function testIsAssocWithNonArray() + { + $result = PubNubUtil::isAssoc('not an array'); + + $this->assertFalse($result); + } + + public function testIsAssocWithNonSequentialKeys() + { + $array = [1 => 'a', 3 => 'b', 5 => 'c']; + + $result = PubNubUtil::isAssoc($array); + + $this->assertTrue($result); + } + + // ============================================================================ + // tokenEncode() TESTS + // ============================================================================ + + public function testTokenEncodeWithBasicString() + { + $token = 'mytoken123'; + + $result = PubNubUtil::tokenEncode($token); + + $this->assertEquals('mytoken123', $result); + } + + public function testTokenEncodeConvertsSpacesToPercent20() + { + $token = 'token with spaces'; + + $result = PubNubUtil::tokenEncode($token); + + $this->assertStringContainsString('%20', $result); + $this->assertStringNotContainsString('+', $result); + } + + public function testTokenEncodeWithSpecialCharacters() + { + $token = 'token!@#$%'; + + $result = PubNubUtil::tokenEncode($token); + + $this->assertIsString($result); + } + + public function testTokenEncodeWithPlusSign() + { + $token = 'token+with+plus'; + + $result = PubNubUtil::tokenEncode($token); + + // Plus signs are first URL encoded to %2B, then the str_replace doesn't affect them + // because str_replace looks for literal '+' which is already encoded + $this->assertStringContainsString('%2B', $result); + } + + // ============================================================================ + // convertIso8859ToUtf8() TESTS + // ============================================================================ + + public function testConvertIso8859ToUtf8WithAscii() + { + $input = 'Hello World'; + + $result = PubNubUtil::convertIso8859ToUtf8($input); + + $this->assertEquals('Hello World', $result); + } + + public function testConvertIso8859ToUtf8WithExtendedCharacters() + { + // Test with some ISO-8859-1 characters + $input = chr(0xA9); // Copyright symbol in ISO-8859-1 + + $result = PubNubUtil::convertIso8859ToUtf8($input); + + $this->assertNotEmpty($result); + $this->assertIsString($result); + } + + public function testConvertIso8859ToUtf8WithEmptyString() + { + $input = ''; + + $result = PubNubUtil::convertIso8859ToUtf8($input); + + $this->assertEquals('', $result); + } + + public function testConvertIso8859ToUtf8PreservesAsciiCharacters() + { + $input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + $result = PubNubUtil::convertIso8859ToUtf8($input); + + $this->assertEquals($input, $result); + } + + public function testConvertIso8859ToUtf8WithNumbers() + { + $input = '1234567890'; + + $result = PubNubUtil::convertIso8859ToUtf8($input); + + $this->assertEquals($input, $result); + } + + // ============================================================================ + // INTEGRATION TESTS + // ============================================================================ + + public function testChannelWorkflow() + { + // Split channels from string + $channelString = 'channel1,channel2,channel3'; + $channels = PubNubUtil::splitItems($channelString); + + $this->assertCount(3, $channels); + + // Join channels back + $joined = PubNubUtil::joinChannels($channels); + + $this->assertEquals('channel1,channel2,channel3', $joined); + } + + public function testArrayExtensionWorkflow() + { + $existing = ['channel1', 'channel2']; + $newString = 'channel3,channel4'; + + $extended = PubNubUtil::extendArray($existing, $newString); + + $this->assertCount(4, $extended); + $this->assertEquals(['channel1', 'channel2', 'channel3', 'channel4'], $extended); + } + + public function testUrlBuildingWorkflow() + { + $basePath = 'https://ps.pndsn.com'; + $path = '/v2/subscribe/demo/my-channel/0'; + $params = [ + 'uuid' => 'user-123', + 'tt' => '0', + 'pnsdk' => 'PubNub-PHP/8.0.0' + ]; + + $url = PubNubUtil::buildUrl($basePath, $path, $params); + + $this->assertStringStartsWith('https://ps.pndsn.com', $url); + $this->assertStringContainsString('uuid=user-123', $url); + $this->assertStringContainsString('&', $url); + } +} diff --git a/tests/unit/PubNubUtilityMethodsTest.php b/tests/unit/PubNubUtilityMethodsTest.php new file mode 100644 index 0000000..8716755 --- /dev/null +++ b/tests/unit/PubNubUtilityMethodsTest.php @@ -0,0 +1,361 @@ +config = new PNConfiguration(); + $this->config->setSubscribeKey('demo'); + $this->config->setPublishKey('demo'); + $this->config->setUserId('test-user'); + + $this->pubnub = new PubNub($this->config); + } + + // ============================================================================ + // TOKEN METHODS TESTS + // ============================================================================ + + public function testGetTokenReturnsNullByDefault() + { + $token = $this->pubnub->getToken(); + + $this->assertNull($token); + } + + public function testSetTokenAndGetToken() + { + $testToken = 'test-token-abc123'; + + $this->pubnub->setToken($testToken); + + $this->assertEquals($testToken, $this->pubnub->getToken()); + } + + public function testSetTokenOverwritesPreviousToken() + { + $this->pubnub->setToken('first-token'); + $this->assertEquals('first-token', $this->pubnub->getToken()); + + $this->pubnub->setToken('second-token'); + $this->assertEquals('second-token', $this->pubnub->getToken()); + } + + public function testSetTokenWithEmptyString() + { + $this->pubnub->setToken(''); + + $this->assertEquals('', $this->pubnub->getToken()); + } + + public function testSetTokenWithLongToken() + { + $longToken = 'qEF2AkF0GmFtet9DdHRsGDxDcmVzpURjaGFuoWpteS1jaGFubmVsGENDZ3JwoEN1c3KgQ3NwY6BEdXVpZKBDcGF0pURjaGFuoENnc' . + 'nCgQ3VzcqBDc3BjoER1dWlkoERtZXRhoER1dWlkZ215LXV1aWRDc2lnWCAvUKKYbfc0vvvEhYqepG7-_lN5jh_yaA6eo98nAHV8Ug=='; + + $this->pubnub->setToken($longToken); + + $this->assertEquals($longToken, $this->pubnub->getToken()); + } + + public function testSetTokenPersistsAcrossMultipleCalls() + { + $token = 'persistent-token'; + $this->pubnub->setToken($token); + + // Call getToken multiple times + $this->assertEquals($token, $this->pubnub->getToken()); + $this->assertEquals($token, $this->pubnub->getToken()); + $this->assertEquals($token, $this->pubnub->getToken()); + } + + // ============================================================================ + // TIMESTAMP METHOD TESTS + // ============================================================================ + + public function testTimestampReturnsInteger() + { + $timestamp = $this->pubnub->timestamp(); + + $this->assertIsInt($timestamp); + } + + public function testTimestampReturnsCurrentTime() + { + $before = time(); + $timestamp = $this->pubnub->timestamp(); + $after = time(); + + // Timestamp should be between before and after + $this->assertGreaterThanOrEqual($before, $timestamp); + $this->assertLessThanOrEqual($after, $timestamp); + } + + public function testTimestampReturnsUnixTimestamp() + { + $timestamp = $this->pubnub->timestamp(); + + // Should be a reasonable Unix timestamp (after year 2020) + $this->assertGreaterThan(1577836800, $timestamp); // Jan 1, 2020 + + // Should be before year 2100 + $this->assertLessThan(4102444800, $timestamp); // Jan 1, 2100 + } + + public function testTimestampChangesOverTime() + { + $timestamp1 = $this->pubnub->timestamp(); + usleep(1100000); // Sleep for slightly over 1 second + $timestamp2 = $this->pubnub->timestamp(); + + $this->assertGreaterThan($timestamp1, $timestamp2); + } + + // ============================================================================ + // SEQUENCE ID TESTS + // ============================================================================ + + public function testGetSequenceIdReturnsInteger() + { + $sequenceId = $this->pubnub->getSequenceId(); + + $this->assertIsInt($sequenceId); + } + + public function testGetSequenceIdStartsAtOne() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setPublishKey('demo'); + $config->setUserId('test-user'); + $pubnub = new PubNub($config); + + $sequenceId = $pubnub->getSequenceId(); + + $this->assertEquals(1, $sequenceId); + } + + public function testGetSequenceIdIncrementsOnEachCall() + { + $id1 = $this->pubnub->getSequenceId(); + $id2 = $this->pubnub->getSequenceId(); + $id3 = $this->pubnub->getSequenceId(); + + $this->assertEquals($id1 + 1, $id2); + $this->assertEquals($id2 + 1, $id3); + } + + public function testGetSequenceIdWrapsAtMaxSequence() + { + // Get sequence to near max + for ($i = 0; $i < PubNub::$MAX_SEQUENCE; $i++) { + $this->pubnub->getSequenceId(); + } + + // Next call should wrap to 1 + $sequenceId = $this->pubnub->getSequenceId(); + + $this->assertEquals(1, $sequenceId); + } + + public function testGetSequenceIdIsUnique() + { + $ids = []; + for ($i = 0; $i < 100; $i++) { + $ids[] = $this->pubnub->getSequenceId(); + } + + // All IDs should be unique + $this->assertEquals(100, count(array_unique($ids))); + } + + // ============================================================================ + // TELEMETRY MANAGER TESTS + // ============================================================================ + + public function testGetTelemetryManagerReturnsInstance() + { + $telemetryManager = $this->pubnub->getTelemetryManager(); + + $this->assertInstanceOf(\PubNub\Managers\TelemetryManager::class, $telemetryManager); + } + + public function testGetTelemetryManagerReturnsSameInstance() + { + $telemetryManager1 = $this->pubnub->getTelemetryManager(); + $telemetryManager2 = $this->pubnub->getTelemetryManager(); + + $this->assertSame($telemetryManager1, $telemetryManager2); + } + + // ============================================================================ + // CONFIGURATION GETTER TESTS + // ============================================================================ + + public function testGetConfigurationReturnsConfiguration() + { + $config = $this->pubnub->getConfiguration(); + + $this->assertInstanceOf(PNConfiguration::class, $config); + } + + public function testGetConfigurationReturnsSameConfiguration() + { + $config1 = $this->pubnub->getConfiguration(); + $config2 = $this->pubnub->getConfiguration(); + + $this->assertSame($config1, $config2); + } + + public function testGetConfigurationReturnsCorrectValues() + { + $config = $this->pubnub->getConfiguration(); + + $this->assertEquals('demo', $config->getSubscribeKey()); + $this->assertEquals('demo', $config->getPublishKey()); + $this->assertEquals('test-user', $config->getUserId()); + } + + // ============================================================================ + // BASE PATH TESTS + // ============================================================================ + + public function testGetBasePathReturnsString() + { + $basePath = $this->pubnub->getBasePath(); + + $this->assertIsString($basePath); + } + + public function testGetBasePathReturnsValidUrl() + { + $basePath = $this->pubnub->getBasePath(); + + $this->assertStringStartsWith('http', $basePath); + } + + public function testGetBasePathWithCustomHost() + { + $basePath = $this->pubnub->getBasePath('custom.pubnub.com'); + + $this->assertEquals('https://custom.pubnub.com', $basePath); + } + + public function testGetBasePathUsesConfigurationOrigin() + { + $config = new PNConfiguration(); + $config->setSubscribeKey('demo'); + $config->setUserId('test'); + $config->setOrigin('my-origin.pubnub.com'); + + $pubnub = new PubNub($config); + $basePath = $pubnub->getBasePath(); + + $this->assertEquals('https://my-origin.pubnub.com', $basePath); + } + + // ============================================================================ + // HTTP CLIENT TESTS + // ============================================================================ + + public function testGetClientReturnsClientInterface() + { + $client = $this->pubnub->getClient(); + + $this->assertInstanceOf(\Psr\Http\Client\ClientInterface::class, $client); + } + + public function testSetClientAndGetClient() + { + $mockClient = $this->createMock(\Psr\Http\Client\ClientInterface::class); + + $this->pubnub->setClient($mockClient); + + $this->assertSame($mockClient, $this->pubnub->getClient()); + } + + public function testGetClientReturnsSameInstanceByDefault() + { + $client1 = $this->pubnub->getClient(); + $client2 = $this->pubnub->getClient(); + + $this->assertSame($client1, $client2); + } + + // ============================================================================ + // REQUEST FACTORY TESTS + // ============================================================================ + + public function testGetRequestFactoryReturnsRequestFactoryInterface() + { + $requestFactory = $this->pubnub->getRequestFactory(); + + $this->assertInstanceOf(\Psr\Http\Message\RequestFactoryInterface::class, $requestFactory); + } + + public function testSetRequestFactoryAndGetRequestFactory() + { + $mockFactory = $this->createMock(\Psr\Http\Message\RequestFactoryInterface::class); + + $this->pubnub->setRequestFactory($mockFactory); + + $this->assertSame($mockFactory, $this->pubnub->getRequestFactory()); + } + + public function testGetRequestFactoryReturnsSameInstanceByDefault() + { + $factory1 = $this->pubnub->getRequestFactory(); + $factory2 = $this->pubnub->getRequestFactory(); + + $this->assertSame($factory1, $factory2); + } + + // ============================================================================ + // LOGGER TESTS + // ============================================================================ + + public function testGetLoggerReturnsLoggerInterface() + { + $logger = $this->pubnub->getLogger(); + + $this->assertInstanceOf(LoggerInterface::class, $logger); + } + + public function testSetLoggerAndGetLogger() + { + $mockLogger = $this->createMock(LoggerInterface::class); + + $this->pubnub->setLogger($mockLogger); + + $this->assertSame($mockLogger, $this->pubnub->getLogger()); + } + + public function testGetLoggerReturnsSameInstanceByDefault() + { + $logger1 = $this->pubnub->getLogger(); + $logger2 = $this->pubnub->getLogger(); + + $this->assertSame($logger1, $logger2); + } + + public function testSetLoggerReplacesDefaultLogger() + { + $defaultLogger = $this->pubnub->getLogger(); + $this->assertInstanceOf(\Psr\Log\NullLogger::class, $defaultLogger); + + $customLogger = $this->createMock(LoggerInterface::class); + $this->pubnub->setLogger($customLogger); + + $this->assertNotSame($defaultLogger, $this->pubnub->getLogger()); + $this->assertSame($customLogger, $this->pubnub->getLogger()); + } +} diff --git a/tests/unit/StateManagerTest.php b/tests/unit/StateManagerTest.php new file mode 100644 index 0000000..94e09d2 --- /dev/null +++ b/tests/unit/StateManagerTest.php @@ -0,0 +1,342 @@ +setSubscribeKey('demo'); + $config->setPublishKey('demo'); + $config->setUserId('test-user'); + + $this->pubnub = new PubNub($config); + $this->stateManager = new StateManager($this->pubnub); + } + + public function testIsEmptyByDefault() + { + $this->assertTrue($this->stateManager->isEmpty()); + } + + public function testAdaptSubscribeBuilderWithChannels() + { + $operation = new SubscribeOperation( + ['channel1', 'channel2'], + [], + false, + null + ); + + $this->stateManager->adaptSubscribeBuilder($operation); + + $this->assertFalse($this->stateManager->isEmpty()); + } + + public function testAdaptSubscribeBuilderWithChannelGroups() + { + $operation = new SubscribeOperation( + [], + ['group1', 'group2'], + false, + null + ); + + $this->stateManager->adaptSubscribeBuilder($operation); + + $this->assertFalse($this->stateManager->isEmpty()); + } + + public function testAdaptSubscribeBuilderWithChannelsAndGroups() + { + $operation = new SubscribeOperation( + ['channel1'], + ['group1'], + false, + null + ); + + $this->stateManager->adaptSubscribeBuilder($operation); + + $this->assertFalse($this->stateManager->isEmpty()); + } + + public function testPrepareChannelListWithoutPresence() + { + $operation = new SubscribeOperation( + ['channel1', 'channel2'], + [], + false, + null + ); + + $this->stateManager->adaptSubscribeBuilder($operation); + $channelList = $this->stateManager->prepareChannelList(false); + + $this->assertCount(2, $channelList); + $this->assertContains('channel1', $channelList); + $this->assertContains('channel2', $channelList); + } + + public function testPrepareChannelListWithPresence() + { + $operation = new SubscribeOperation( + ['channel1', 'channel2'], + [], + true, + null + ); + + $this->stateManager->adaptSubscribeBuilder($operation); + $channelList = $this->stateManager->prepareChannelList(true); + + $this->assertCount(4, $channelList); + $this->assertContains('channel1', $channelList); + $this->assertContains('channel2', $channelList); + $this->assertContains('channel1-pnpres', $channelList); + $this->assertContains('channel2-pnpres', $channelList); + } + + public function testPrepareChannelGroupListWithoutPresence() + { + $operation = new SubscribeOperation( + [], + ['group1', 'group2'], + false, + null + ); + + $this->stateManager->adaptSubscribeBuilder($operation); + $groupList = $this->stateManager->prepareChannelGroupList(false); + + $this->assertCount(2, $groupList); + $this->assertContains('group1', $groupList); + $this->assertContains('group2', $groupList); + } + + public function testPrepareChannelGroupListWithPresence() + { + $operation = new SubscribeOperation( + [], + ['group1', 'group2'], + true, + null + ); + + $this->stateManager->adaptSubscribeBuilder($operation); + $groupList = $this->stateManager->prepareChannelGroupList(true); + + $this->assertCount(4, $groupList); + $this->assertContains('group1', $groupList); + $this->assertContains('group2', $groupList); + $this->assertContains('group1-pnpres', $groupList); + $this->assertContains('group2-pnpres', $groupList); + } + + public function testAdaptUnsubscribeBuilderRemovesChannels() + { + // First subscribe + $subscribeOp = new SubscribeOperation( + ['channel1', 'channel2'], + [], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($subscribeOp); + + // Then unsubscribe from one channel + $unsubscribeOp = new UnsubscribeOperation(); + $unsubscribeOp->setChannels(['channel1']); + $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); + + $channelList = $this->stateManager->prepareChannelList(false); + + $this->assertCount(1, $channelList); + $this->assertContains('channel2', $channelList); + $this->assertNotContains('channel1', $channelList); + } + + public function testAdaptUnsubscribeBuilderRemovesChannelGroups() + { + // First subscribe + $subscribeOp = new SubscribeOperation( + [], + ['group1', 'group2'], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($subscribeOp); + + // Then unsubscribe from one group + $unsubscribeOp = new UnsubscribeOperation(); + $unsubscribeOp->setChannelGroups(['group1']); + $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); + + $groupList = $this->stateManager->prepareChannelGroupList(false); + + $this->assertCount(1, $groupList); + $this->assertContains('group2', $groupList); + $this->assertNotContains('group1', $groupList); + } + + public function testAdaptUnsubscribeBuilderRemovesPresenceChannels() + { + // Subscribe with presence + $subscribeOp = new SubscribeOperation( + ['channel1', 'channel2'], + [], + true, + null + ); + $this->stateManager->adaptSubscribeBuilder($subscribeOp); + + // Unsubscribe from channel1 + $unsubscribeOp = new UnsubscribeOperation(); + $unsubscribeOp->setChannels(['channel1']); + $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); + + $channelList = $this->stateManager->prepareChannelList(true); + + // Should have channel2 and channel2-pnpres, but not channel1 or channel1-pnpres + $this->assertCount(2, $channelList); + $this->assertContains('channel2', $channelList); + $this->assertContains('channel2-pnpres', $channelList); + $this->assertNotContains('channel1', $channelList); + $this->assertNotContains('channel1-pnpres', $channelList); + } + + public function testIsEmptyAfterUnsubscribingFromAll() + { + // Subscribe + $subscribeOp = new SubscribeOperation( + ['channel1'], + ['group1'], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($subscribeOp); + $this->assertFalse($this->stateManager->isEmpty()); + + // Unsubscribe from all + $unsubscribeOp = new UnsubscribeOperation(); + $unsubscribeOp->setChannels(['channel1']); + $unsubscribeOp->setChannelGroups(['group1']); + $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); + + $this->assertTrue($this->stateManager->isEmpty()); + } + + public function testMultipleSubscribeOperations() + { + // First subscription + $operation1 = new SubscribeOperation( + ['channel1'], + [], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($operation1); + + // Second subscription + $operation2 = new SubscribeOperation( + ['channel2'], + [], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($operation2); + + $channelList = $this->stateManager->prepareChannelList(false); + + $this->assertCount(2, $channelList); + $this->assertContains('channel1', $channelList); + $this->assertContains('channel2', $channelList); + } + + public function testResubscribeToSameChannel() + { + // Subscribe to channel1 + $operation1 = new SubscribeOperation( + ['channel1'], + [], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($operation1); + + // Subscribe again to channel1 (should overwrite, not duplicate) + $operation2 = new SubscribeOperation( + ['channel1'], + [], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($operation2); + + $channelList = $this->stateManager->prepareChannelList(false); + + $this->assertCount(1, $channelList); + $this->assertContains('channel1', $channelList); + } + + public function testEmptyChannelListWhenNoChannels() + { + $operation = new SubscribeOperation( + [], + ['group1'], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($operation); + + $channelList = $this->stateManager->prepareChannelList(false); + + $this->assertEmpty($channelList); + } + + public function testEmptyGroupListWhenNoGroups() + { + $operation = new SubscribeOperation( + ['channel1'], + [], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($operation); + + $groupList = $this->stateManager->prepareChannelGroupList(false); + + $this->assertEmpty($groupList); + } + + public function testUnsubscribeFromNonExistentChannel() + { + $operation = new SubscribeOperation( + ['channel1'], + [], + false, + null + ); + $this->stateManager->adaptSubscribeBuilder($operation); + + // Unsubscribe from channel that was never subscribed + $unsubscribeOp = new UnsubscribeOperation(); + $unsubscribeOp->setChannels(['channel2']); + $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); + + $channelList = $this->stateManager->prepareChannelList(false); + + // channel1 should still be there + $this->assertCount(1, $channelList); + $this->assertContains('channel1', $channelList); + } +} diff --git a/tests/unit/TokenManagerTest.php b/tests/unit/TokenManagerTest.php new file mode 100644 index 0000000..71b3556 --- /dev/null +++ b/tests/unit/TokenManagerTest.php @@ -0,0 +1,64 @@ +setToken($token); + + $this->assertEquals($token, $manager->getToken()); + } + + public function testGetTokenReturnsNullByDefault() + { + $manager = new TokenManager(); + + $this->assertNull($manager->getToken()); + } + + public function testSetTokenOverwritesPreviousToken() + { + $manager = new TokenManager(); + + $manager->setToken('first-token'); + $this->assertEquals('first-token', $manager->getToken()); + + $manager->setToken('second-token'); + $this->assertEquals('second-token', $manager->getToken()); + } + + public function testSetTokenWithEmptyString() + { + $manager = new TokenManager(); + + $manager->setToken(''); + + $this->assertEquals('', $manager->getToken()); + } + + public function testSetTokenWithLongString() + { + $manager = new TokenManager(); + $longToken = str_repeat('a', 10000); + + $manager->setToken($longToken); + + $this->assertEquals($longToken, $manager->getToken()); + } + + public function testSetTokenWithSpecialCharacters() + { + $manager = new TokenManager(); + $specialToken = 'token-with-special!@#$%^&*()_+-={}[]|\\:";\'<>?,./'; + + $manager->setToken($specialToken); + + $this->assertEquals($specialToken, $manager->getToken()); + } +} From fe2f483c60312e9acd0535e830f69eaf4e5c45e3 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Tue, 7 Oct 2025 15:47:37 +0200 Subject: [PATCH 02/26] Fix linter errors --- .../integrational/PublishFileMessageTest.php | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/integrational/PublishFileMessageTest.php b/tests/integrational/PublishFileMessageTest.php index fe8a2cd..d8f6652 100644 --- a/tests/integrational/PublishFileMessageTest.php +++ b/tests/integrational/PublishFileMessageTest.php @@ -42,7 +42,7 @@ public function tearDown(): void parent::tearDown(); } - public function testPublishFileMessageWithBasicMessage() + public function testPublishFileMessageWithBasicMessage(): void { // First upload a file to get file ID $file = fopen($this->testFilePath, "r"); @@ -71,7 +71,7 @@ public function testPublishFileMessageWithBasicMessage() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageWithMetadata() + public function testPublishFileMessageWithMetadata(): void { // Upload a file first $file = fopen($this->testFilePath, "r"); @@ -105,7 +105,7 @@ public function testPublishFileMessageWithMetadata() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageWithCustomMessageType() + public function testPublishFileMessageWithCustomMessageType(): void { // Upload a file first $file = fopen($this->testFilePath, "r"); @@ -133,7 +133,7 @@ public function testPublishFileMessageWithCustomMessageType() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageWithTTL() + public function testPublishFileMessageWithTTL(): void { // Upload a file first $file = fopen($this->testFilePath, "r"); @@ -161,7 +161,7 @@ public function testPublishFileMessageWithTTL() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageWithShouldStore() + public function testPublishFileMessageWithShouldStore(): void { // Upload a file first $file = fopen($this->testFilePath, "r"); @@ -189,7 +189,7 @@ public function testPublishFileMessageWithShouldStore() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageWithAllOptions() + public function testPublishFileMessageWithAllOptions(): void { // Upload a file first $file = fopen($this->testFilePath, "r"); @@ -225,7 +225,7 @@ public function testPublishFileMessageWithAllOptions() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageWithEncryption() + public function testPublishFileMessageWithEncryption(): void { // Use encrypted pubnub instance $file = fopen($this->testFilePath, "r"); @@ -252,7 +252,7 @@ public function testPublishFileMessageWithEncryption() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageWithComplexMessage() + public function testPublishFileMessageWithComplexMessage(): void { // Upload a file first $file = fopen($this->testFilePath, "r"); @@ -289,7 +289,7 @@ public function testPublishFileMessageWithComplexMessage() $this->assertNotEmpty($response->getTimetoken()); } - public function testPublishFileMessageMultipleTimes() + public function testPublishFileMessageMultipleTimes(): void { // Upload a file first $file = fopen($this->testFilePath, "r"); @@ -324,7 +324,7 @@ public function testPublishFileMessageMultipleTimes() $this->assertNotEquals($response1->getTimetoken(), $response2->getTimetoken()); } - public function testPublishFileMessageWithInvalidFileId() + public function testPublishFileMessageWithInvalidFileId(): void { $this->expectException(\PubNub\Exceptions\PubNubServerException::class); @@ -337,7 +337,7 @@ public function testPublishFileMessageWithInvalidFileId() ->sync(); } - public function testPublishFileMessageWithEmptyChannel() + public function testPublishFileMessageWithEmptyChannel(): void { $this->expectException(\PubNub\Exceptions\PubNubValidationException::class); From 95db5584a1521233035f10e8c57ee885a0c6177b Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 14:10:43 +0200 Subject: [PATCH 03/26] Fix linter errors --- tests/unit/BasePathManagerTest.php | 20 ++--- tests/unit/CryptoCryptorGettersTest.php | 68 ++++++++-------- tests/unit/PubNubCryptoMethodsTest.php | 44 +++++----- tests/unit/PubNubFactoryMethodsTest.php | 44 +++++----- tests/unit/PubNubSdkInfoTest.php | 66 +++++++-------- tests/unit/PubNubUtilExtendedTest.php | 104 ++++++++++++------------ tests/unit/PubNubUtilityMethodsTest.php | 68 ++++++++-------- tests/unit/StateManagerTest.php | 34 ++++---- tests/unit/TokenManagerTest.php | 12 +-- 9 files changed, 230 insertions(+), 230 deletions(-) diff --git a/tests/unit/BasePathManagerTest.php b/tests/unit/BasePathManagerTest.php index 63ab2cb..f6e701e 100644 --- a/tests/unit/BasePathManagerTest.php +++ b/tests/unit/BasePathManagerTest.php @@ -6,7 +6,7 @@ class BasePathManagerTest extends TestCase { - public function testGetBasePathWithDefaultSettings() + public function testGetBasePathWithDefaultSettings(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -19,7 +19,7 @@ public function testGetBasePathWithDefaultSettings() $this->assertEquals('https://ps.pndsn.com', $basePath); } - public function testGetBasePathWithCustomOrigin() + public function testGetBasePathWithCustomOrigin(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -33,7 +33,7 @@ public function testGetBasePathWithCustomOrigin() $this->assertEquals('https://custom.pubnub.com', $basePath); } - public function testGetBasePathWithCustomHost() + public function testGetBasePathWithCustomHost(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -46,7 +46,7 @@ public function testGetBasePathWithCustomHost() $this->assertEquals('https://special.pubnub.com', $basePath); } - public function testGetBasePathWithCustomHostOverridesOrigin() + public function testGetBasePathWithCustomHostOverridesOrigin(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -60,7 +60,7 @@ public function testGetBasePathWithCustomHostOverridesOrigin() $this->assertEquals('https://param-host.pubnub.com', $basePath); } - public function testGetBasePathWithInsecureConnection() + public function testGetBasePathWithInsecureConnection(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -74,7 +74,7 @@ public function testGetBasePathWithInsecureConnection() $this->assertEquals('http://ps.pndsn.com', $basePath); } - public function testGetBasePathWithInsecureAndCustomOrigin() + public function testGetBasePathWithInsecureAndCustomOrigin(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -89,7 +89,7 @@ public function testGetBasePathWithInsecureAndCustomOrigin() $this->assertEquals('http://insecure.pubnub.com', $basePath); } - public function testGetBasePathWithIPAddress() + public function testGetBasePathWithIPAddress(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -103,7 +103,7 @@ public function testGetBasePathWithIPAddress() $this->assertEquals('https://192.168.1.100', $basePath); } - public function testGetBasePathWithPortNumber() + public function testGetBasePathWithPortNumber(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -117,7 +117,7 @@ public function testGetBasePathWithPortNumber() $this->assertEquals('https://localhost:8080', $basePath); } - public function testGetBasePathMultipleCalls() + public function testGetBasePathMultipleCalls(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -133,7 +133,7 @@ public function testGetBasePathMultipleCalls() $this->assertEquals($basePath2, $basePath3); } - public function testGetBasePathWithDifferentCustomHosts() + public function testGetBasePathWithDifferentCustomHosts(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); diff --git a/tests/unit/CryptoCryptorGettersTest.php b/tests/unit/CryptoCryptorGettersTest.php index 76672ac..6acbcfe 100644 --- a/tests/unit/CryptoCryptorGettersTest.php +++ b/tests/unit/CryptoCryptorGettersTest.php @@ -10,28 +10,28 @@ class CryptoCryptorGettersTest extends TestCase // AesCbcCryptor TESTS // ============================================================================ - public function testAesCbcCryptorConstructor() + public function testAesCbcCryptorConstructor(): void { $cryptor = new AesCbcCryptor('test-key'); $this->assertInstanceOf(AesCbcCryptor::class, $cryptor); } - public function testAesCbcCryptorGetCipherKey() + public function testAesCbcCryptorGetCipherKey(): void { $cryptor = new AesCbcCryptor('my-cipher-key'); $this->assertEquals('my-cipher-key', $cryptor->getCipherKey()); } - public function testAesCbcCryptorGetCipherKeyWithNullParameter() + public function testAesCbcCryptorGetCipherKeyWithNullParameter(): void { $cryptor = new AesCbcCryptor('my-cipher-key'); $this->assertEquals('my-cipher-key', $cryptor->getCipherKey(null)); } - public function testAesCbcCryptorGetCipherKeyWithCustomParameter() + public function testAesCbcCryptorGetCipherKeyWithCustomParameter(): void { $cryptor = new AesCbcCryptor('default-key'); @@ -39,7 +39,7 @@ public function testAesCbcCryptorGetCipherKeyWithCustomParameter() $this->assertEquals('custom-key', $cryptor->getCipherKey('custom-key')); } - public function testAesCbcCryptorGetIV() + public function testAesCbcCryptorGetIV(): void { $cryptor = new AesCbcCryptor('test-key'); $iv = $cryptor->getIV(); @@ -48,7 +48,7 @@ public function testAesCbcCryptorGetIV() $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes } - public function testAesCbcCryptorGetIVReturnsRandomValues() + public function testAesCbcCryptorGetIVReturnsRandomValues(): void { $cryptor = new AesCbcCryptor('test-key'); $iv1 = $cryptor->getIV(); @@ -58,7 +58,7 @@ public function testAesCbcCryptorGetIVReturnsRandomValues() $this->assertNotEquals($iv1, $iv2); } - public function testAesCbcCryptorEncryptReturnsPayload() + public function testAesCbcCryptorEncryptReturnsPayload(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); @@ -66,7 +66,7 @@ public function testAesCbcCryptorEncryptReturnsPayload() $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $result); } - public function testAesCbcCryptorEncryptPayloadHasCryptorId() + public function testAesCbcCryptorEncryptPayloadHasCryptorId(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); @@ -74,7 +74,7 @@ public function testAesCbcCryptorEncryptPayloadHasCryptorId() $this->assertEquals('ACRH', $result->getCryptorId()); } - public function testAesCbcCryptorEncryptPayloadHasData() + public function testAesCbcCryptorEncryptPayloadHasData(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); @@ -82,7 +82,7 @@ public function testAesCbcCryptorEncryptPayloadHasData() $this->assertNotEmpty($result->getData()); } - public function testAesCbcCryptorEncryptPayloadHasCryptorData() + public function testAesCbcCryptorEncryptPayloadHasCryptorData(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); @@ -91,7 +91,7 @@ public function testAesCbcCryptorEncryptPayloadHasCryptorData() $this->assertEquals(16, strlen($result->getCryptorData())); } - public function testAesCbcCryptorEncryptDecryptRoundTrip() + public function testAesCbcCryptorEncryptDecryptRoundTrip(): void { $cryptor = new AesCbcCryptor('test-key'); $original = 'Hello, World!'; @@ -102,7 +102,7 @@ public function testAesCbcCryptorEncryptDecryptRoundTrip() $this->assertEquals($original, $decrypted); } - public function testAesCbcCryptorWithDifferentKeys() + public function testAesCbcCryptorWithDifferentKeys(): void { $cryptor1 = new AesCbcCryptor('key1'); $cryptor2 = new AesCbcCryptor('key2'); @@ -115,28 +115,28 @@ public function testAesCbcCryptorWithDifferentKeys() // LegacyCryptor TESTS // ============================================================================ - public function testLegacyCryptorConstructor() + public function testLegacyCryptorConstructor(): void { $cryptor = new LegacyCryptor('test-key', false); $this->assertInstanceOf(LegacyCryptor::class, $cryptor); } - public function testLegacyCryptorConstructorWithRandomIV() + public function testLegacyCryptorConstructorWithRandomIV(): void { $cryptor = new LegacyCryptor('test-key', true); $this->assertInstanceOf(LegacyCryptor::class, $cryptor); } - public function testLegacyCryptorGetCipherKey() + public function testLegacyCryptorGetCipherKey(): void { $cryptor = new LegacyCryptor('my-legacy-key', false); $this->assertEquals('my-legacy-key', $cryptor->getCipherKey()); } - public function testLegacyCryptorGetIVWithStaticIV() + public function testLegacyCryptorGetIVWithStaticIV(): void { $cryptor = new LegacyCryptor('test-key', false); $iv = $cryptor->getIV(); @@ -146,7 +146,7 @@ public function testLegacyCryptorGetIVWithStaticIV() $this->assertEquals('0123456789012345', $iv); // Static IV } - public function testLegacyCryptorGetIVWithStaticIVIsConsistent() + public function testLegacyCryptorGetIVWithStaticIVIsConsistent(): void { $cryptor = new LegacyCryptor('test-key', false); $iv1 = $cryptor->getIV(); @@ -157,7 +157,7 @@ public function testLegacyCryptorGetIVWithStaticIVIsConsistent() $this->assertEquals('0123456789012345', $iv1); } - public function testLegacyCryptorGetIVWithRandomIV() + public function testLegacyCryptorGetIVWithRandomIV(): void { $cryptor = new LegacyCryptor('test-key', true); $iv = $cryptor->getIV(); @@ -166,7 +166,7 @@ public function testLegacyCryptorGetIVWithRandomIV() $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes } - public function testLegacyCryptorGetIVWithRandomIVReturnsRandomValues() + public function testLegacyCryptorGetIVWithRandomIVReturnsRandomValues(): void { $cryptor = new LegacyCryptor('test-key', true); $iv1 = $cryptor->getIV(); @@ -176,7 +176,7 @@ public function testLegacyCryptorGetIVWithRandomIVReturnsRandomValues() $this->assertNotEquals($iv1, $iv2); } - public function testLegacyCryptorEncryptReturnsPayload() + public function testLegacyCryptorEncryptReturnsPayload(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); @@ -184,7 +184,7 @@ public function testLegacyCryptorEncryptReturnsPayload() $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $result); } - public function testLegacyCryptorEncryptPayloadHasCryptorId() + public function testLegacyCryptorEncryptPayloadHasCryptorId(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); @@ -192,7 +192,7 @@ public function testLegacyCryptorEncryptPayloadHasCryptorId() $this->assertEquals('0000', $result->getCryptorId()); } - public function testLegacyCryptorEncryptPayloadHasData() + public function testLegacyCryptorEncryptPayloadHasData(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); @@ -200,7 +200,7 @@ public function testLegacyCryptorEncryptPayloadHasData() $this->assertNotEmpty($result->getData()); } - public function testLegacyCryptorEncryptPayloadCryptorDataIsEmpty() + public function testLegacyCryptorEncryptPayloadCryptorDataIsEmpty(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); @@ -209,7 +209,7 @@ public function testLegacyCryptorEncryptPayloadCryptorDataIsEmpty() $this->assertEquals('', $result->getCryptorData()); } - public function testLegacyCryptorEncryptDecryptRoundTripWithStaticIV() + public function testLegacyCryptorEncryptDecryptRoundTripWithStaticIV(): void { $cryptor = new LegacyCryptor('test-key', false); $original = 'Hello, Legacy!'; @@ -220,7 +220,7 @@ public function testLegacyCryptorEncryptDecryptRoundTripWithStaticIV() $this->assertEquals($original, $decrypted); } - public function testLegacyCryptorEncryptDecryptRoundTripWithRandomIV() + public function testLegacyCryptorEncryptDecryptRoundTripWithRandomIV(): void { $cryptor = new LegacyCryptor('test-key', true); $original = 'Hello, Random IV!'; @@ -231,7 +231,7 @@ public function testLegacyCryptorEncryptDecryptRoundTripWithRandomIV() $this->assertEquals($original, $decrypted); } - public function testLegacyCryptorWithDifferentKeys() + public function testLegacyCryptorWithDifferentKeys(): void { $cryptor1 = new LegacyCryptor('key1', false); $cryptor2 = new LegacyCryptor('key2', true); @@ -244,7 +244,7 @@ public function testLegacyCryptorWithDifferentKeys() // COMPARISON TESTS // ============================================================================ - public function testAesCbcCryptorAndLegacyCryptorHaveDifferentCryptorIds() + public function testAesCbcCryptorAndLegacyCryptorHaveDifferentCryptorIds(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); @@ -257,7 +257,7 @@ public function testAesCbcCryptorAndLegacyCryptorHaveDifferentCryptorIds() $this->assertNotEquals($aesEncrypted->getCryptorId(), $legacyEncrypted->getCryptorId()); } - public function testBothCryptorsReturnPayloadObjects() + public function testBothCryptorsReturnPayloadObjects(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); @@ -269,7 +269,7 @@ public function testBothCryptorsReturnPayloadObjects() $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $legacyResult); } - public function testBothCryptorsHandleEmptyStrings() + public function testBothCryptorsHandleEmptyStrings(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); @@ -281,7 +281,7 @@ public function testBothCryptorsHandleEmptyStrings() $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $legacyResult); } - public function testBothCryptorsHandleLongMessages() + public function testBothCryptorsHandleLongMessages(): void { $longMessage = str_repeat('A', 10000); // 10KB message @@ -295,7 +295,7 @@ public function testBothCryptorsHandleLongMessages() $this->assertEquals($longMessage, $legacy->decrypt($legacyEncrypted)); } - public function testBothCryptorsHandleUnicodeCharacters() + public function testBothCryptorsHandleUnicodeCharacters(): void { $unicodeMessage = '🔒 Encrypted 文字 مشفر'; @@ -309,7 +309,7 @@ public function testBothCryptorsHandleUnicodeCharacters() $this->assertEquals($unicodeMessage, $legacy->decrypt($legacyEncrypted)); } - public function testBothCryptorsHaveGetCipherKeyMethod() + public function testBothCryptorsHaveGetCipherKeyMethod(): void { $aesCbc = new AesCbcCryptor('key1'); $legacy = new LegacyCryptor('key2', false); @@ -321,7 +321,7 @@ public function testBothCryptorsHaveGetCipherKeyMethod() $this->assertEquals('key2', $legacy->getCipherKey()); } - public function testBothCryptorsHaveGetIVMethod() + public function testBothCryptorsHaveGetIVMethod(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); @@ -333,7 +333,7 @@ public function testBothCryptorsHaveGetIVMethod() $this->assertEquals(16, strlen($legacy->getIV())); } - public function testBothCryptorsImplementEncryptAndDecrypt() + public function testBothCryptorsImplementEncryptAndDecrypt(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); diff --git a/tests/unit/PubNubCryptoMethodsTest.php b/tests/unit/PubNubCryptoMethodsTest.php index 0b22db4..c833deb 100644 --- a/tests/unit/PubNubCryptoMethodsTest.php +++ b/tests/unit/PubNubCryptoMethodsTest.php @@ -11,7 +11,7 @@ class PubNubCryptoMethodsTest extends TestCase // isCryptoEnabled() TESTS // ============================================================================ - public function testIsCryptoEnabledReturnsFalseByDefault() + public function testIsCryptoEnabledReturnsFalseByDefault(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -22,7 +22,7 @@ public function testIsCryptoEnabledReturnsFalseByDefault() $this->assertFalse($pubnub->isCryptoEnabled()); } - public function testIsCryptoEnabledReturnsTrueWhenCipherKeySet() + public function testIsCryptoEnabledReturnsTrueWhenCipherKeySet(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -34,7 +34,7 @@ public function testIsCryptoEnabledReturnsTrueWhenCipherKeySet() $this->assertTrue($pubnub->isCryptoEnabled()); } - public function testIsCryptoEnabledReturnsTrueWhenCryptoModuleSet() + public function testIsCryptoEnabledReturnsTrueWhenCryptoModuleSet(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -47,7 +47,7 @@ public function testIsCryptoEnabledReturnsTrueWhenCryptoModuleSet() $this->assertTrue($pubnub->isCryptoEnabled()); } - public function testIsCryptoEnabledAfterSettingCryptoOnPubNub() + public function testIsCryptoEnabledAfterSettingCryptoOnPubNub(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -66,7 +66,7 @@ public function testIsCryptoEnabledAfterSettingCryptoOnPubNub() // getCrypto() TESTS // ============================================================================ - public function testGetCryptoReturnsNullWhenNotConfigured() + public function testGetCryptoReturnsNullWhenNotConfigured(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -77,7 +77,7 @@ public function testGetCryptoReturnsNullWhenNotConfigured() $this->assertNull($pubnub->getCrypto()); } - public function testGetCryptoReturnsModuleWhenCipherKeySet() + public function testGetCryptoReturnsModuleWhenCipherKeySet(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -90,7 +90,7 @@ public function testGetCryptoReturnsModuleWhenCipherKeySet() $this->assertInstanceOf(CryptoModule::class, $crypto); } - public function testGetCryptoReturnsModuleWhenCryptoModuleSet() + public function testGetCryptoReturnsModuleWhenCryptoModuleSet(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -106,7 +106,7 @@ public function testGetCryptoReturnsModuleWhenCryptoModuleSet() $this->assertSame($cryptoModule, $crypto); } - public function testGetCryptoReturnsConfigurationCryptoWhenNoPubNubCrypto() + public function testGetCryptoReturnsConfigurationCryptoWhenNoPubNubCrypto(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -119,7 +119,7 @@ public function testGetCryptoReturnsConfigurationCryptoWhenNoPubNubCrypto() $this->assertInstanceOf(CryptoModule::class, $crypto); } - public function testGetCryptoPrefersInstanceCryptoOverConfiguration() + public function testGetCryptoPrefersInstanceCryptoOverConfiguration(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -140,7 +140,7 @@ public function testGetCryptoPrefersInstanceCryptoOverConfiguration() // setCrypto() TESTS // ============================================================================ - public function testSetCryptoStoresModule() + public function testSetCryptoStoresModule(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -154,7 +154,7 @@ public function testSetCryptoStoresModule() $this->assertSame($cryptoModule, $pubnub->getCrypto()); } - public function testSetCryptoOverwritesPreviousCrypto() + public function testSetCryptoOverwritesPreviousCrypto(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -171,7 +171,7 @@ public function testSetCryptoOverwritesPreviousCrypto() $this->assertSame($crypto2, $pubnub->getCrypto()); } - public function testSetCryptoEnablesCrypto() + public function testSetCryptoEnablesCrypto(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -186,7 +186,7 @@ public function testSetCryptoEnablesCrypto() $this->assertTrue($pubnub->isCryptoEnabled()); } - public function testSetCryptoWithLegacyCryptor() + public function testSetCryptoWithLegacyCryptor(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -200,7 +200,7 @@ public function testSetCryptoWithLegacyCryptor() $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); } - public function testSetCryptoWithAesCbcCryptor() + public function testSetCryptoWithAesCbcCryptor(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -214,7 +214,7 @@ public function testSetCryptoWithAesCbcCryptor() $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); } - public function testSetCryptoWithRandomIV() + public function testSetCryptoWithRandomIV(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -229,7 +229,7 @@ public function testSetCryptoWithRandomIV() $this->assertNotNull($crypto); } - public function testSetCryptoWithStaticIV() + public function testSetCryptoWithStaticIV(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -248,7 +248,7 @@ public function testSetCryptoWithStaticIV() // INTEGRATION TESTS (getCrypto + setCrypto + isCryptoEnabled) // ============================================================================ - public function testCryptoWorkflowConfigurationOnly() + public function testCryptoWorkflowConfigurationOnly(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -261,7 +261,7 @@ public function testCryptoWorkflowConfigurationOnly() $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); } - public function testCryptoWorkflowInstanceOnly() + public function testCryptoWorkflowInstanceOnly(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -277,7 +277,7 @@ public function testCryptoWorkflowInstanceOnly() $this->assertSame($cryptoModule, $pubnub->getCrypto()); } - public function testCryptoWorkflowBothConfigurationAndInstance() + public function testCryptoWorkflowBothConfigurationAndInstance(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -294,7 +294,7 @@ public function testCryptoWorkflowBothConfigurationAndInstance() $this->assertSame($instanceCrypto, $pubnub->getCrypto()); } - public function testCryptoCanBeUsedForEncryptionDecryption() + public function testCryptoCanBeUsedForEncryptionDecryption(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -313,7 +313,7 @@ public function testCryptoCanBeUsedForEncryptionDecryption() $this->assertEquals($plaintext, $decrypted); } - public function testMultiplePubNubInstancesWithDifferentCrypto() + public function testMultiplePubNubInstancesWithDifferentCrypto(): void { $config1 = new PNConfiguration(); $config1->setSubscribeKey('demo'); @@ -334,7 +334,7 @@ public function testMultiplePubNubInstancesWithDifferentCrypto() $this->assertSame($crypto2, $pubnub2->getCrypto()); } - public function testCryptoModuleCanBeRetrievedAndUsedDirectly() + public function testCryptoModuleCanBeRetrievedAndUsedDirectly(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); diff --git a/tests/unit/PubNubFactoryMethodsTest.php b/tests/unit/PubNubFactoryMethodsTest.php index aa3324f..d8effce 100644 --- a/tests/unit/PubNubFactoryMethodsTest.php +++ b/tests/unit/PubNubFactoryMethodsTest.php @@ -10,7 +10,7 @@ class PubNubFactoryMethodsTest extends TestCase // PubNub::demo() TESTS // ============================================================================ - public function testDemoReturnsValidPubNubInstance() + public function testDemoReturnsValidPubNubInstance(): void { $pubnub = PubNub::demo(); @@ -26,7 +26,7 @@ public function testDemoHasDemoKeys() $this->assertEquals('demo', $config->getPublishKey()); } - public function testDemoHasDemoUserId() + public function testDemoHasDemoUserId(): void { $pubnub = PubNub::demo(); $config = $pubnub->getConfiguration(); @@ -34,7 +34,7 @@ public function testDemoHasDemoUserId() $this->assertEquals('demo', $config->getUserId()); } - public function testDemoIsImmediatelyUsable() + public function testDemoIsImmediatelyUsable(): void { $pubnub = PubNub::demo(); @@ -46,7 +46,7 @@ public function testDemoIsImmediatelyUsable() $this->assertNotNull($config->getUserId()); } - public function testDemoCreatesNewInstanceEachTime() + public function testDemoCreatesNewInstanceEachTime(): void { $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); @@ -54,7 +54,7 @@ public function testDemoCreatesNewInstanceEachTime() $this->assertNotSame($pubnub1, $pubnub2); } - public function testDemoInstancesAreIndependent() + public function testDemoInstancesAreIndependent(): void { $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); @@ -67,7 +67,7 @@ public function testDemoInstancesAreIndependent() $this->assertEquals('token2', $pubnub2->getToken()); } - public function testDemoConfigurationIsLocked() + public function testDemoConfigurationIsLocked(): void { $pubnub = PubNub::demo(); $config = $pubnub->getConfiguration(); @@ -77,7 +77,7 @@ public function testDemoConfigurationIsLocked() $config->setPublishKey('new-key'); } - public function testDemoCanBeUsedForBasicOperations() + public function testDemoCanBeUsedForBasicOperations(): void { $pubnub = PubNub::demo(); @@ -91,35 +91,35 @@ public function testDemoCanBeUsedForBasicOperations() // PNConfiguration::demoKeys() TESTS // ============================================================================ - public function testDemoKeysReturnsValidConfiguration() + public function testDemoKeysReturnsValidConfiguration(): void { $config = PNConfiguration::demoKeys(); $this->assertInstanceOf(PNConfiguration::class, $config); } - public function testDemoKeysHasSubscribeKey() + public function testDemoKeysHasSubscribeKey(): void { $config = PNConfiguration::demoKeys(); $this->assertEquals('demo', $config->getSubscribeKey()); } - public function testDemoKeysHasPublishKey() + public function testDemoKeysHasPublishKey(): void { $config = PNConfiguration::demoKeys(); $this->assertEquals('demo', $config->getPublishKey()); } - public function testDemoKeysHasUserId() + public function testDemoKeysHasUserId(): void { $config = PNConfiguration::demoKeys(); $this->assertEquals('demo', $config->getUserId()); } - public function testDemoKeysConfigurationIsNotLocked() + public function testDemoKeysConfigurationIsNotLocked(): void { $config = PNConfiguration::demoKeys(); @@ -138,7 +138,7 @@ public function testDemoKeysConfigurationIsNotLocked() $this->assertEquals('custom.origin.com', $config->getOrigin()); } - public function testDemoKeysCreatesNewInstanceEachTime() + public function testDemoKeysCreatesNewInstanceEachTime(): void { $config1 = PNConfiguration::demoKeys(); $config2 = PNConfiguration::demoKeys(); @@ -146,7 +146,7 @@ public function testDemoKeysCreatesNewInstanceEachTime() $this->assertNotSame($config1, $config2); } - public function testDemoKeysInstancesAreIndependent() + public function testDemoKeysInstancesAreIndependent(): void { $config1 = PNConfiguration::demoKeys(); $config2 = PNConfiguration::demoKeys(); @@ -158,7 +158,7 @@ public function testDemoKeysInstancesAreIndependent() $this->assertEquals('key2', $config2->getPublishKey()); } - public function testDemoKeysCanBeCustomized() + public function testDemoKeysCanBeCustomized(): void { $config = PNConfiguration::demoKeys(); @@ -172,7 +172,7 @@ public function testDemoKeysCanBeCustomized() $this->assertEquals('auth-key-123', $config->getAuthKey()); } - public function testDemoKeysCanBeUsedToCreatePubNub() + public function testDemoKeysCanBeUsedToCreatePubNub(): void { $config = PNConfiguration::demoKeys(); $pubnub = new PubNub($config); @@ -185,14 +185,14 @@ public function testDemoKeysCanBeUsedToCreatePubNub() $this->assertEquals('demo', $retrievedConfig->getUserId()); } - public function testDemoKeysHasDefaultSecureSettings() + public function testDemoKeysHasDefaultSecureSettings(): void { $config = PNConfiguration::demoKeys(); $this->assertTrue($config->isSecure()); } - public function testDemoKeysHasDefaultTimeouts() + public function testDemoKeysHasDefaultTimeouts(): void { $config = PNConfiguration::demoKeys(); @@ -205,7 +205,7 @@ public function testDemoKeysHasDefaultTimeouts() // INTEGRATION TESTS // ============================================================================ - public function testDemoMethodUsesDemoKeysInternally() + public function testDemoMethodUsesDemoKeysInternally(): void { $demoConfig = PNConfiguration::demoKeys(); $demoPubNub = PubNub::demo(); @@ -218,7 +218,7 @@ public function testDemoMethodUsesDemoKeysInternally() $this->assertEquals($demoConfig->getUserId(), $config->getUserId()); } - public function testDemoKeysAndDemoProduceSimilarResults() + public function testDemoKeysAndDemoProduceSimilarResults(): void { $configFromDemoKeys = PNConfiguration::demoKeys(); $pubnubFromDemo = PubNub::demo(); @@ -238,7 +238,7 @@ public function testDemoKeysAndDemoProduceSimilarResults() ); } - public function testDemoKeysCanBeCloned() + public function testDemoKeysCanBeCloned(): void { $config = PNConfiguration::demoKeys(); $cloned = $config->clone(); @@ -249,7 +249,7 @@ public function testDemoKeysCanBeCloned() $this->assertEquals('demo', $cloned->getUserId()); } - public function testMultipleDemoInstancesCanCoexist() + public function testMultipleDemoInstancesCanCoexist(): void { $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); diff --git a/tests/unit/PubNubSdkInfoTest.php b/tests/unit/PubNubSdkInfoTest.php index 28a62aa..0223c85 100644 --- a/tests/unit/PubNubSdkInfoTest.php +++ b/tests/unit/PubNubSdkInfoTest.php @@ -9,21 +9,21 @@ class PubNubSdkInfoTest extends TestCase // getSdkVersion() TESTS // ============================================================================ - public function testGetSdkVersionReturnsString() + public function testGetSdkVersionReturnsString(): void { $version = PubNub::getSdkVersion(); $this->assertIsString($version); } - public function testGetSdkVersionIsNotEmpty() + public function testGetSdkVersionIsNotEmpty(): void { $version = PubNub::getSdkVersion(); $this->assertNotEmpty($version); } - public function testGetSdkVersionFollowsSemanticVersioning() + public function testGetSdkVersionFollowsSemanticVersioning(): void { $version = PubNub::getSdkVersion(); @@ -32,7 +32,7 @@ public function testGetSdkVersionFollowsSemanticVersioning() $this->assertMatchesRegularExpression($pattern, $version); } - public function testGetSdkVersionIsConsistent() + public function testGetSdkVersionIsConsistent(): void { $version1 = PubNub::getSdkVersion(); $version2 = PubNub::getSdkVersion(); @@ -40,14 +40,14 @@ public function testGetSdkVersionIsConsistent() $this->assertEquals($version1, $version2); } - public function testGetSdkVersionStartsWithDigit() + public function testGetSdkVersionStartsWithDigit(): void { $version = PubNub::getSdkVersion(); $this->assertMatchesRegularExpression('/^\d/', $version); } - public function testGetSdkVersionContainsMajorMinorPatch() + public function testGetSdkVersionContainsMajorMinorPatch(): void { $version = PubNub::getSdkVersion(); @@ -56,7 +56,7 @@ public function testGetSdkVersionContainsMajorMinorPatch() $this->assertGreaterThanOrEqual(3, count($parts)); } - public function testGetSdkVersionMajorVersionIsNumeric() + public function testGetSdkVersionMajorVersionIsNumeric(): void { $version = PubNub::getSdkVersion(); $parts = explode('.', $version); @@ -64,7 +64,7 @@ public function testGetSdkVersionMajorVersionIsNumeric() $this->assertIsNumeric($parts[0]); } - public function testGetSdkVersionMinorVersionIsNumeric() + public function testGetSdkVersionMinorVersionIsNumeric(): void { $version = PubNub::getSdkVersion(); $parts = explode('.', $version); @@ -72,7 +72,7 @@ public function testGetSdkVersionMinorVersionIsNumeric() $this->assertIsNumeric($parts[1]); } - public function testGetSdkVersionPatchVersionIsNumeric() + public function testGetSdkVersionPatchVersionIsNumeric(): void { $version = PubNub::getSdkVersion(); $parts = explode('.', $version); @@ -87,21 +87,21 @@ public function testGetSdkVersionPatchVersionIsNumeric() // getSdkName() TESTS // ============================================================================ - public function testGetSdkNameReturnsString() + public function testGetSdkNameReturnsString(): void { $name = PubNub::getSdkName(); $this->assertIsString($name); } - public function testGetSdkNameIsNotEmpty() + public function testGetSdkNameIsNotEmpty(): void { $name = PubNub::getSdkName(); $this->assertNotEmpty($name); } - public function testGetSdkNameIsConsistent() + public function testGetSdkNameIsConsistent(): void { $name1 = PubNub::getSdkName(); $name2 = PubNub::getSdkName(); @@ -109,7 +109,7 @@ public function testGetSdkNameIsConsistent() $this->assertEquals($name1, $name2); } - public function testGetSdkNameContainsPHP() + public function testGetSdkNameContainsPHP(): void { $name = PubNub::getSdkName(); @@ -117,7 +117,7 @@ public function testGetSdkNameContainsPHP() $this->assertMatchesRegularExpression('/php/i', $name); } - public function testGetSdkNameContainsPubNub() + public function testGetSdkNameContainsPubNub(): void { $name = PubNub::getSdkName(); @@ -125,7 +125,7 @@ public function testGetSdkNameContainsPubNub() $this->assertMatchesRegularExpression('/pubnub/i', $name); } - public function testGetSdkNameFormat() + public function testGetSdkNameFormat(): void { $name = PubNub::getSdkName(); @@ -133,7 +133,7 @@ public function testGetSdkNameFormat() $this->assertMatchesRegularExpression('/^[a-zA-Z\-]+$/', $name); } - public function testGetSdkNameDoesNotContainVersion() + public function testGetSdkNameDoesNotContainVersion(): void { $name = PubNub::getSdkName(); @@ -145,21 +145,21 @@ public function testGetSdkNameDoesNotContainVersion() // getSdkFullName() TESTS // ============================================================================ - public function testGetSdkFullNameReturnsString() + public function testGetSdkFullNameReturnsString(): void { $fullName = PubNub::getSdkFullName(); $this->assertIsString($fullName); } - public function testGetSdkFullNameIsNotEmpty() + public function testGetSdkFullNameIsNotEmpty(): void { $fullName = PubNub::getSdkFullName(); $this->assertNotEmpty($fullName); } - public function testGetSdkFullNameIsConsistent() + public function testGetSdkFullNameIsConsistent(): void { $fullName1 = PubNub::getSdkFullName(); $fullName2 = PubNub::getSdkFullName(); @@ -167,7 +167,7 @@ public function testGetSdkFullNameIsConsistent() $this->assertEquals($fullName1, $fullName2); } - public function testGetSdkFullNameContainsSdkName() + public function testGetSdkFullNameContainsSdkName(): void { $name = PubNub::getSdkName(); $fullName = PubNub::getSdkFullName(); @@ -175,7 +175,7 @@ public function testGetSdkFullNameContainsSdkName() $this->assertStringContainsString($name, $fullName); } - public function testGetSdkFullNameContainsSdkVersion() + public function testGetSdkFullNameContainsSdkVersion(): void { $version = PubNub::getSdkVersion(); $fullName = PubNub::getSdkFullName(); @@ -183,7 +183,7 @@ public function testGetSdkFullNameContainsSdkVersion() $this->assertStringContainsString($version, $fullName); } - public function testGetSdkFullNameFormat() + public function testGetSdkFullNameFormat(): void { $fullName = PubNub::getSdkFullName(); @@ -192,7 +192,7 @@ public function testGetSdkFullNameFormat() $this->assertMatchesRegularExpression($pattern, $fullName); } - public function testGetSdkFullNameIsConcatenationOfNameAndVersion() + public function testGetSdkFullNameIsConcatenationOfNameAndVersion(): void { $name = PubNub::getSdkName(); $version = PubNub::getSdkVersion(); @@ -203,7 +203,7 @@ public function testGetSdkFullNameIsConcatenationOfNameAndVersion() $this->assertMatchesRegularExpression($expectedPattern, $fullName); } - public function testGetSdkFullNameLongerThanName() + public function testGetSdkFullNameLongerThanName(): void { $name = PubNub::getSdkName(); $fullName = PubNub::getSdkFullName(); @@ -211,7 +211,7 @@ public function testGetSdkFullNameLongerThanName() $this->assertGreaterThan(strlen($name), strlen($fullName)); } - public function testGetSdkFullNameLongerThanVersion() + public function testGetSdkFullNameLongerThanVersion(): void { $version = PubNub::getSdkVersion(); $fullName = PubNub::getSdkFullName(); @@ -223,7 +223,7 @@ public function testGetSdkFullNameLongerThanVersion() // INTEGRATION TESTS // ============================================================================ - public function testSdkInfoMethodsAreAllConsistent() + public function testSdkInfoMethodsAreAllConsistent(): void { $name = PubNub::getSdkName(); $version = PubNub::getSdkVersion(); @@ -233,7 +233,7 @@ public function testSdkInfoMethodsAreAllConsistent() $this->assertStringContainsString($version, $fullName); } - public function testSdkInfoMethodsCanBeCalledMultipleTimes() + public function testSdkInfoMethodsCanBeCalledMultipleTimes(): void { // Call each method multiple times for ($i = 0; $i < 5; $i++) { @@ -243,7 +243,7 @@ public function testSdkInfoMethodsCanBeCalledMultipleTimes() } } - public function testSdkInfoMethodsReturnSameValuesAcrossInstances() + public function testSdkInfoMethodsReturnSameValuesAcrossInstances(): void { $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); @@ -254,7 +254,7 @@ public function testSdkInfoMethodsReturnSameValuesAcrossInstances() $this->assertEquals(PubNub::getSdkFullName(), PubNub::getSdkFullName()); } - public function testSdkVersionCanBeParsed() + public function testSdkVersionCanBeParsed(): void { $version = PubNub::getSdkVersion(); @@ -271,7 +271,7 @@ public function testSdkVersionCanBeParsed() $this->assertIsNumeric($matches[1]); // Patch } - public function testSdkFullNameIsUsableForUserAgent() + public function testSdkFullNameIsUsableForUserAgent(): void { $fullName = PubNub::getSdkFullName(); @@ -279,7 +279,7 @@ public function testSdkFullNameIsUsableForUserAgent() $this->assertMatchesRegularExpression('/^[a-zA-Z0-9\-\.\/]+$/', $fullName); } - public function testSdkNameIsUsableAsIdentifier() + public function testSdkNameIsUsableAsIdentifier(): void { $name = PubNub::getSdkName(); @@ -287,7 +287,7 @@ public function testSdkNameIsUsableAsIdentifier() $this->assertMatchesRegularExpression('/^[a-zA-Z\-]+$/', $name); } - public function testSdkVersionIsValidSemanticVersion() + public function testSdkVersionIsValidSemanticVersion(): void { $version = PubNub::getSdkVersion(); @@ -301,7 +301,7 @@ public function testSdkVersionIsValidSemanticVersion() $this->assertMatchesRegularExpression($semverPattern, $version); } - public function testSdkInfoDoesNotChangeAtRuntime() + public function testSdkInfoDoesNotChangeAtRuntime(): void { // Capture initial values $name1 = PubNub::getSdkName(); diff --git a/tests/unit/PubNubUtilExtendedTest.php b/tests/unit/PubNubUtilExtendedTest.php index 2fb37ba..ea905d2 100644 --- a/tests/unit/PubNubUtilExtendedTest.php +++ b/tests/unit/PubNubUtilExtendedTest.php @@ -9,7 +9,7 @@ class PubNubUtilExtendedTest extends TestCase // buildUrl() TESTS // ============================================================================ - public function testBuildUrlWithBasicParams() + public function testBuildUrlWithBasicParams(): void { $basePath = 'https://ps.pndsn.com'; $path = '/v2/subscribe/demo/ch1/0'; @@ -22,7 +22,7 @@ public function testBuildUrlWithBasicParams() $this->assertStringContainsString('pnsdk=PubNub-PHP/8.0.0', $url); } - public function testBuildUrlWithEmptyParams() + public function testBuildUrlWithEmptyParams(): void { $basePath = 'https://ps.pndsn.com'; $path = '/v2/time/0'; @@ -33,7 +33,7 @@ public function testBuildUrlWithEmptyParams() $this->assertEquals($basePath . $path . '?', $url); } - public function testBuildUrlWithSpecialCharactersInParams() + public function testBuildUrlWithSpecialCharactersInParams(): void { $basePath = 'https://ps.pndsn.com'; $path = '/publish'; @@ -44,7 +44,7 @@ public function testBuildUrlWithSpecialCharactersInParams() $this->assertStringContainsString('message=hello%20world', $url); } - public function testBuildUrlWithMultipleParams() + public function testBuildUrlWithMultipleParams(): void { $basePath = 'https://ps.pndsn.com'; $path = '/v2/history'; @@ -65,7 +65,7 @@ public function testBuildUrlWithMultipleParams() // joinChannels() TESTS // ============================================================================ - public function testJoinChannelsWithSingleChannel() + public function testJoinChannelsWithSingleChannel(): void { $channels = ['channel1']; @@ -74,7 +74,7 @@ public function testJoinChannelsWithSingleChannel() $this->assertEquals('channel1', $result); } - public function testJoinChannelsWithMultipleChannels() + public function testJoinChannelsWithMultipleChannels(): void { $channels = ['channel1', 'channel2', 'channel3']; @@ -83,7 +83,7 @@ public function testJoinChannelsWithMultipleChannels() $this->assertEquals('channel1,channel2,channel3', $result); } - public function testJoinChannelsWithEmptyArray() + public function testJoinChannelsWithEmptyArray(): void { $channels = []; @@ -92,7 +92,7 @@ public function testJoinChannelsWithEmptyArray() $this->assertEquals(',', $result); } - public function testJoinChannelsWithSpecialCharacters() + public function testJoinChannelsWithSpecialCharacters(): void { $channels = ['channel-1', 'channel.2', 'channel_3']; @@ -101,7 +101,7 @@ public function testJoinChannelsWithSpecialCharacters() $this->assertEquals('channel-1,channel.2,channel_3', $result); } - public function testJoinChannelsEncodesSpecialCharacters() + public function testJoinChannelsEncodesSpecialCharacters(): void { $channels = ['channel with spaces', 'channel#special']; @@ -115,7 +115,7 @@ public function testJoinChannelsEncodesSpecialCharacters() // joinItems() TESTS // ============================================================================ - public function testJoinItemsWithSingleItem() + public function testJoinItemsWithSingleItem(): void { $items = ['item1']; @@ -124,7 +124,7 @@ public function testJoinItemsWithSingleItem() $this->assertEquals('item1', $result); } - public function testJoinItemsWithMultipleItems() + public function testJoinItemsWithMultipleItems(): void { $items = ['item1', 'item2', 'item3']; @@ -133,7 +133,7 @@ public function testJoinItemsWithMultipleItems() $this->assertEquals('item1,item2,item3', $result); } - public function testJoinItemsWithEmptyArray() + public function testJoinItemsWithEmptyArray(): void { $items = []; @@ -142,7 +142,7 @@ public function testJoinItemsWithEmptyArray() $this->assertEquals('', $result); } - public function testJoinItemsWithNumericItems() + public function testJoinItemsWithNumericItems(): void { $items = ['1', '2', '3']; @@ -155,7 +155,7 @@ public function testJoinItemsWithNumericItems() // extendArray() TESTS - Already used in tests but testing edge cases // ============================================================================ - public function testExtendArrayWithArrays() + public function testExtendArrayWithArrays(): void { $existing = ['a', 'b']; $new = ['c', 'd']; @@ -165,7 +165,7 @@ public function testExtendArrayWithArrays() $this->assertEquals(['a', 'b', 'c', 'd'], $result); } - public function testExtendArrayWithString() + public function testExtendArrayWithString(): void { $existing = ['a', 'b']; $new = 'c,d'; @@ -175,7 +175,7 @@ public function testExtendArrayWithString() $this->assertEquals(['a', 'b', 'c', 'd'], $result); } - public function testExtendArrayWithEmptyExisting() + public function testExtendArrayWithEmptyExisting(): void { $existing = []; $new = ['a', 'b']; @@ -185,7 +185,7 @@ public function testExtendArrayWithEmptyExisting() $this->assertEquals(['a', 'b'], $result); } - public function testExtendArrayWithEmptyNew() + public function testExtendArrayWithEmptyNew(): void { $existing = ['a', 'b']; $new = []; @@ -195,7 +195,7 @@ public function testExtendArrayWithEmptyNew() $this->assertEquals(['a', 'b'], $result); } - public function testExtendArrayWithEmptyString() + public function testExtendArrayWithEmptyString(): void { $existing = ['a', 'b']; $new = ''; @@ -209,7 +209,7 @@ public function testExtendArrayWithEmptyString() // splitItems() TESTS // ============================================================================ - public function testSplitItemsWithSingleItem() + public function testSplitItemsWithSingleItem(): void { $items = 'item1'; @@ -218,7 +218,7 @@ public function testSplitItemsWithSingleItem() $this->assertEquals(['item1'], $result); } - public function testSplitItemsWithMultipleItems() + public function testSplitItemsWithMultipleItems(): void { $items = 'item1,item2,item3'; @@ -227,7 +227,7 @@ public function testSplitItemsWithMultipleItems() $this->assertEquals(['item1', 'item2', 'item3'], $result); } - public function testSplitItemsWithEmptyString() + public function testSplitItemsWithEmptyString(): void { $items = ''; @@ -236,7 +236,7 @@ public function testSplitItemsWithEmptyString() $this->assertEquals([], $result); } - public function testSplitItemsPreservesSpaces() + public function testSplitItemsPreservesSpaces(): void { $items = 'item 1,item 2'; @@ -245,7 +245,7 @@ public function testSplitItemsPreservesSpaces() $this->assertEquals(['item 1', 'item 2'], $result); } - public function testSplitItemsWithTrailingComma() + public function testSplitItemsWithTrailingComma(): void { $items = 'item1,item2,'; @@ -258,14 +258,14 @@ public function testSplitItemsWithTrailingComma() // uuid() TESTS // ============================================================================ - public function testUuidReturnsString() + public function testUuidReturnsString(): void { $uuid = PubNubUtil::uuid(); $this->assertIsString($uuid); } - public function testUuidHasCorrectFormat() + public function testUuidHasCorrectFormat(): void { $uuid = PubNubUtil::uuid(); @@ -276,7 +276,7 @@ public function testUuidHasCorrectFormat() ); } - public function testUuidIsUnique() + public function testUuidIsUnique(): void { $uuid1 = PubNubUtil::uuid(); $uuid2 = PubNubUtil::uuid(); @@ -284,7 +284,7 @@ public function testUuidIsUnique() $this->assertNotEquals($uuid1, $uuid2); } - public function testUuidGeneratesMultipleUniqueValues() + public function testUuidGeneratesMultipleUniqueValues(): void { $uuids = []; for ($i = 0; $i < 100; $i++) { @@ -295,7 +295,7 @@ public function testUuidGeneratesMultipleUniqueValues() $this->assertEquals(100, count(array_unique($uuids))); } - public function testUuidLength() + public function testUuidLength(): void { $uuid = PubNubUtil::uuid(); @@ -307,7 +307,7 @@ public function testUuidLength() // fetchPamPermissionsFrom() TESTS // ============================================================================ - public function testFetchPamPermissionsFromWithAllPermissions() + public function testFetchPamPermissionsFromWithAllPermissions(): void { $input = [ 'r' => 1, @@ -325,7 +325,7 @@ public function testFetchPamPermissionsFromWithAllPermissions() $this->assertEquals([true, true, true, true, true, true, true, 1440], $result); } - public function testFetchPamPermissionsFromWithNoPermissions() + public function testFetchPamPermissionsFromWithNoPermissions(): void { $input = [ 'r' => 0, @@ -343,7 +343,7 @@ public function testFetchPamPermissionsFromWithNoPermissions() $this->assertEquals([false, false, false, false, false, false, false, 0], $result); } - public function testFetchPamPermissionsFromWithPartialPermissions() + public function testFetchPamPermissionsFromWithPartialPermissions(): void { $input = [ 'r' => 1, @@ -357,7 +357,7 @@ public function testFetchPamPermissionsFromWithPartialPermissions() $this->assertEquals([true, false, true, null, null, null, null, 60], $result); } - public function testFetchPamPermissionsFromWithEmptyInput() + public function testFetchPamPermissionsFromWithEmptyInput(): void { $input = []; @@ -366,7 +366,7 @@ public function testFetchPamPermissionsFromWithEmptyInput() $this->assertEquals([null, null, null, null, null, null, null, null], $result); } - public function testFetchPamPermissionsFromWithOnlyTTL() + public function testFetchPamPermissionsFromWithOnlyTTL(): void { $input = ['ttl' => 120]; @@ -379,7 +379,7 @@ public function testFetchPamPermissionsFromWithOnlyTTL() // isAssoc() TESTS // ============================================================================ - public function testIsAssocWithIndexedArray() + public function testIsAssocWithIndexedArray(): void { $array = ['a', 'b', 'c']; @@ -388,7 +388,7 @@ public function testIsAssocWithIndexedArray() $this->assertFalse($result); } - public function testIsAssocWithAssociativeArray() + public function testIsAssocWithAssociativeArray(): void { $array = ['key1' => 'value1', 'key2' => 'value2']; @@ -397,7 +397,7 @@ public function testIsAssocWithAssociativeArray() $this->assertTrue($result); } - public function testIsAssocWithNumericKeys() + public function testIsAssocWithNumericKeys(): void { $array = [0 => 'a', 1 => 'b', 2 => 'c']; @@ -406,7 +406,7 @@ public function testIsAssocWithNumericKeys() $this->assertFalse($result); } - public function testIsAssocWithMixedKeys() + public function testIsAssocWithMixedKeys(): void { $array = [0 => 'a', 'key' => 'b', 2 => 'c']; @@ -415,7 +415,7 @@ public function testIsAssocWithMixedKeys() $this->assertTrue($result); } - public function testIsAssocWithEmptyArray() + public function testIsAssocWithEmptyArray(): void { $array = []; @@ -427,14 +427,14 @@ public function testIsAssocWithEmptyArray() $this->assertTrue($result); } - public function testIsAssocWithNonArray() + public function testIsAssocWithNonArray(): void { $result = PubNubUtil::isAssoc('not an array'); $this->assertFalse($result); } - public function testIsAssocWithNonSequentialKeys() + public function testIsAssocWithNonSequentialKeys(): void { $array = [1 => 'a', 3 => 'b', 5 => 'c']; @@ -447,7 +447,7 @@ public function testIsAssocWithNonSequentialKeys() // tokenEncode() TESTS // ============================================================================ - public function testTokenEncodeWithBasicString() + public function testTokenEncodeWithBasicString(): void { $token = 'mytoken123'; @@ -456,7 +456,7 @@ public function testTokenEncodeWithBasicString() $this->assertEquals('mytoken123', $result); } - public function testTokenEncodeConvertsSpacesToPercent20() + public function testTokenEncodeConvertsSpacesToPercent20(): void { $token = 'token with spaces'; @@ -466,7 +466,7 @@ public function testTokenEncodeConvertsSpacesToPercent20() $this->assertStringNotContainsString('+', $result); } - public function testTokenEncodeWithSpecialCharacters() + public function testTokenEncodeWithSpecialCharacters(): void { $token = 'token!@#$%'; @@ -475,7 +475,7 @@ public function testTokenEncodeWithSpecialCharacters() $this->assertIsString($result); } - public function testTokenEncodeWithPlusSign() + public function testTokenEncodeWithPlusSign(): void { $token = 'token+with+plus'; @@ -490,7 +490,7 @@ public function testTokenEncodeWithPlusSign() // convertIso8859ToUtf8() TESTS // ============================================================================ - public function testConvertIso8859ToUtf8WithAscii() + public function testConvertIso8859ToUtf8WithAscii(): void { $input = 'Hello World'; @@ -499,7 +499,7 @@ public function testConvertIso8859ToUtf8WithAscii() $this->assertEquals('Hello World', $result); } - public function testConvertIso8859ToUtf8WithExtendedCharacters() + public function testConvertIso8859ToUtf8WithExtendedCharacters(): void { // Test with some ISO-8859-1 characters $input = chr(0xA9); // Copyright symbol in ISO-8859-1 @@ -510,7 +510,7 @@ public function testConvertIso8859ToUtf8WithExtendedCharacters() $this->assertIsString($result); } - public function testConvertIso8859ToUtf8WithEmptyString() + public function testConvertIso8859ToUtf8WithEmptyString(): void { $input = ''; @@ -519,7 +519,7 @@ public function testConvertIso8859ToUtf8WithEmptyString() $this->assertEquals('', $result); } - public function testConvertIso8859ToUtf8PreservesAsciiCharacters() + public function testConvertIso8859ToUtf8PreservesAsciiCharacters(): void { $input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; @@ -528,7 +528,7 @@ public function testConvertIso8859ToUtf8PreservesAsciiCharacters() $this->assertEquals($input, $result); } - public function testConvertIso8859ToUtf8WithNumbers() + public function testConvertIso8859ToUtf8WithNumbers(): void { $input = '1234567890'; @@ -541,7 +541,7 @@ public function testConvertIso8859ToUtf8WithNumbers() // INTEGRATION TESTS // ============================================================================ - public function testChannelWorkflow() + public function testChannelWorkflow(): void { // Split channels from string $channelString = 'channel1,channel2,channel3'; @@ -555,7 +555,7 @@ public function testChannelWorkflow() $this->assertEquals('channel1,channel2,channel3', $joined); } - public function testArrayExtensionWorkflow() + public function testArrayExtensionWorkflow(): void { $existing = ['channel1', 'channel2']; $newString = 'channel3,channel4'; @@ -566,7 +566,7 @@ public function testArrayExtensionWorkflow() $this->assertEquals(['channel1', 'channel2', 'channel3', 'channel4'], $extended); } - public function testUrlBuildingWorkflow() + public function testUrlBuildingWorkflow(): void { $basePath = 'https://ps.pndsn.com'; $path = '/v2/subscribe/demo/my-channel/0'; diff --git a/tests/unit/PubNubUtilityMethodsTest.php b/tests/unit/PubNubUtilityMethodsTest.php index 8716755..2db306d 100644 --- a/tests/unit/PubNubUtilityMethodsTest.php +++ b/tests/unit/PubNubUtilityMethodsTest.php @@ -25,14 +25,14 @@ public function setUp(): void // TOKEN METHODS TESTS // ============================================================================ - public function testGetTokenReturnsNullByDefault() + public function testGetTokenReturnsNullByDefault(): void { $token = $this->pubnub->getToken(); $this->assertNull($token); } - public function testSetTokenAndGetToken() + public function testSetTokenAndGetToken(): void { $testToken = 'test-token-abc123'; @@ -41,7 +41,7 @@ public function testSetTokenAndGetToken() $this->assertEquals($testToken, $this->pubnub->getToken()); } - public function testSetTokenOverwritesPreviousToken() + public function testSetTokenOverwritesPreviousToken(): void { $this->pubnub->setToken('first-token'); $this->assertEquals('first-token', $this->pubnub->getToken()); @@ -50,14 +50,14 @@ public function testSetTokenOverwritesPreviousToken() $this->assertEquals('second-token', $this->pubnub->getToken()); } - public function testSetTokenWithEmptyString() + public function testSetTokenWithEmptyString(): void { $this->pubnub->setToken(''); $this->assertEquals('', $this->pubnub->getToken()); } - public function testSetTokenWithLongToken() + public function testSetTokenWithLongToken(): void { $longToken = 'qEF2AkF0GmFtet9DdHRsGDxDcmVzpURjaGFuoWpteS1jaGFubmVsGENDZ3JwoEN1c3KgQ3NwY6BEdXVpZKBDcGF0pURjaGFuoENnc' . 'nCgQ3VzcqBDc3BjoER1dWlkoERtZXRhoER1dWlkZ215LXV1aWRDc2lnWCAvUKKYbfc0vvvEhYqepG7-_lN5jh_yaA6eo98nAHV8Ug=='; @@ -67,7 +67,7 @@ public function testSetTokenWithLongToken() $this->assertEquals($longToken, $this->pubnub->getToken()); } - public function testSetTokenPersistsAcrossMultipleCalls() + public function testSetTokenPersistsAcrossMultipleCalls(): void { $token = 'persistent-token'; $this->pubnub->setToken($token); @@ -82,14 +82,14 @@ public function testSetTokenPersistsAcrossMultipleCalls() // TIMESTAMP METHOD TESTS // ============================================================================ - public function testTimestampReturnsInteger() + public function testTimestampReturnsInteger(): void { $timestamp = $this->pubnub->timestamp(); $this->assertIsInt($timestamp); } - public function testTimestampReturnsCurrentTime() + public function testTimestampReturnsCurrentTime(): void { $before = time(); $timestamp = $this->pubnub->timestamp(); @@ -100,7 +100,7 @@ public function testTimestampReturnsCurrentTime() $this->assertLessThanOrEqual($after, $timestamp); } - public function testTimestampReturnsUnixTimestamp() + public function testTimestampReturnsUnixTimestamp(): void { $timestamp = $this->pubnub->timestamp(); @@ -111,7 +111,7 @@ public function testTimestampReturnsUnixTimestamp() $this->assertLessThan(4102444800, $timestamp); // Jan 1, 2100 } - public function testTimestampChangesOverTime() + public function testTimestampChangesOverTime(): void { $timestamp1 = $this->pubnub->timestamp(); usleep(1100000); // Sleep for slightly over 1 second @@ -124,14 +124,14 @@ public function testTimestampChangesOverTime() // SEQUENCE ID TESTS // ============================================================================ - public function testGetSequenceIdReturnsInteger() + public function testGetSequenceIdReturnsInteger(): void { $sequenceId = $this->pubnub->getSequenceId(); $this->assertIsInt($sequenceId); } - public function testGetSequenceIdStartsAtOne() + public function testGetSequenceIdStartsAtOne(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -144,7 +144,7 @@ public function testGetSequenceIdStartsAtOne() $this->assertEquals(1, $sequenceId); } - public function testGetSequenceIdIncrementsOnEachCall() + public function testGetSequenceIdIncrementsOnEachCall(): void { $id1 = $this->pubnub->getSequenceId(); $id2 = $this->pubnub->getSequenceId(); @@ -154,7 +154,7 @@ public function testGetSequenceIdIncrementsOnEachCall() $this->assertEquals($id2 + 1, $id3); } - public function testGetSequenceIdWrapsAtMaxSequence() + public function testGetSequenceIdWrapsAtMaxSequence(): void { // Get sequence to near max for ($i = 0; $i < PubNub::$MAX_SEQUENCE; $i++) { @@ -167,7 +167,7 @@ public function testGetSequenceIdWrapsAtMaxSequence() $this->assertEquals(1, $sequenceId); } - public function testGetSequenceIdIsUnique() + public function testGetSequenceIdIsUnique(): void { $ids = []; for ($i = 0; $i < 100; $i++) { @@ -182,14 +182,14 @@ public function testGetSequenceIdIsUnique() // TELEMETRY MANAGER TESTS // ============================================================================ - public function testGetTelemetryManagerReturnsInstance() + public function testGetTelemetryManagerReturnsInstance(): void { $telemetryManager = $this->pubnub->getTelemetryManager(); $this->assertInstanceOf(\PubNub\Managers\TelemetryManager::class, $telemetryManager); } - public function testGetTelemetryManagerReturnsSameInstance() + public function testGetTelemetryManagerReturnsSameInstance(): void { $telemetryManager1 = $this->pubnub->getTelemetryManager(); $telemetryManager2 = $this->pubnub->getTelemetryManager(); @@ -201,14 +201,14 @@ public function testGetTelemetryManagerReturnsSameInstance() // CONFIGURATION GETTER TESTS // ============================================================================ - public function testGetConfigurationReturnsConfiguration() + public function testGetConfigurationReturnsConfiguration(): void { $config = $this->pubnub->getConfiguration(); $this->assertInstanceOf(PNConfiguration::class, $config); } - public function testGetConfigurationReturnsSameConfiguration() + public function testGetConfigurationReturnsSameConfiguration(): void { $config1 = $this->pubnub->getConfiguration(); $config2 = $this->pubnub->getConfiguration(); @@ -216,7 +216,7 @@ public function testGetConfigurationReturnsSameConfiguration() $this->assertSame($config1, $config2); } - public function testGetConfigurationReturnsCorrectValues() + public function testGetConfigurationReturnsCorrectValues(): void { $config = $this->pubnub->getConfiguration(); @@ -229,28 +229,28 @@ public function testGetConfigurationReturnsCorrectValues() // BASE PATH TESTS // ============================================================================ - public function testGetBasePathReturnsString() + public function testGetBasePathReturnsString(): void { $basePath = $this->pubnub->getBasePath(); $this->assertIsString($basePath); } - public function testGetBasePathReturnsValidUrl() + public function testGetBasePathReturnsValidUrl(): void { $basePath = $this->pubnub->getBasePath(); $this->assertStringStartsWith('http', $basePath); } - public function testGetBasePathWithCustomHost() + public function testGetBasePathWithCustomHost(): void { $basePath = $this->pubnub->getBasePath('custom.pubnub.com'); $this->assertEquals('https://custom.pubnub.com', $basePath); } - public function testGetBasePathUsesConfigurationOrigin() + public function testGetBasePathUsesConfigurationOrigin(): void { $config = new PNConfiguration(); $config->setSubscribeKey('demo'); @@ -267,14 +267,14 @@ public function testGetBasePathUsesConfigurationOrigin() // HTTP CLIENT TESTS // ============================================================================ - public function testGetClientReturnsClientInterface() + public function testGetClientReturnsClientInterface(): void { $client = $this->pubnub->getClient(); $this->assertInstanceOf(\Psr\Http\Client\ClientInterface::class, $client); } - public function testSetClientAndGetClient() + public function testSetClientAndGetClient(): void { $mockClient = $this->createMock(\Psr\Http\Client\ClientInterface::class); @@ -283,7 +283,7 @@ public function testSetClientAndGetClient() $this->assertSame($mockClient, $this->pubnub->getClient()); } - public function testGetClientReturnsSameInstanceByDefault() + public function testGetClientReturnsSameInstanceByDefault(): void { $client1 = $this->pubnub->getClient(); $client2 = $this->pubnub->getClient(); @@ -295,14 +295,14 @@ public function testGetClientReturnsSameInstanceByDefault() // REQUEST FACTORY TESTS // ============================================================================ - public function testGetRequestFactoryReturnsRequestFactoryInterface() + public function testGetRequestFactoryReturnsRequestFactoryInterface(): void { $requestFactory = $this->pubnub->getRequestFactory(); $this->assertInstanceOf(\Psr\Http\Message\RequestFactoryInterface::class, $requestFactory); } - public function testSetRequestFactoryAndGetRequestFactory() + public function testSetRequestFactoryAndGetRequestFactory(): void { $mockFactory = $this->createMock(\Psr\Http\Message\RequestFactoryInterface::class); @@ -311,7 +311,7 @@ public function testSetRequestFactoryAndGetRequestFactory() $this->assertSame($mockFactory, $this->pubnub->getRequestFactory()); } - public function testGetRequestFactoryReturnsSameInstanceByDefault() + public function testGetRequestFactoryReturnsSameInstanceByDefault(): void { $factory1 = $this->pubnub->getRequestFactory(); $factory2 = $this->pubnub->getRequestFactory(); @@ -323,14 +323,14 @@ public function testGetRequestFactoryReturnsSameInstanceByDefault() // LOGGER TESTS // ============================================================================ - public function testGetLoggerReturnsLoggerInterface() + public function testGetLoggerReturnsLoggerInterface(): void { $logger = $this->pubnub->getLogger(); $this->assertInstanceOf(LoggerInterface::class, $logger); } - public function testSetLoggerAndGetLogger() + public function testSetLoggerAndGetLogger(): void { $mockLogger = $this->createMock(LoggerInterface::class); @@ -339,7 +339,7 @@ public function testSetLoggerAndGetLogger() $this->assertSame($mockLogger, $this->pubnub->getLogger()); } - public function testGetLoggerReturnsSameInstanceByDefault() + public function testGetLoggerReturnsSameInstanceByDefault(): void { $logger1 = $this->pubnub->getLogger(); $logger2 = $this->pubnub->getLogger(); @@ -347,7 +347,7 @@ public function testGetLoggerReturnsSameInstanceByDefault() $this->assertSame($logger1, $logger2); } - public function testSetLoggerReplacesDefaultLogger() + public function testSetLoggerReplacesDefaultLogger(): void { $defaultLogger = $this->pubnub->getLogger(); $this->assertInstanceOf(\Psr\Log\NullLogger::class, $defaultLogger); diff --git a/tests/unit/StateManagerTest.php b/tests/unit/StateManagerTest.php index 94e09d2..e21ca6d 100644 --- a/tests/unit/StateManagerTest.php +++ b/tests/unit/StateManagerTest.php @@ -23,12 +23,12 @@ public function setUp(): void $this->stateManager = new StateManager($this->pubnub); } - public function testIsEmptyByDefault() + public function testIsEmptyByDefault(): void { $this->assertTrue($this->stateManager->isEmpty()); } - public function testAdaptSubscribeBuilderWithChannels() + public function testAdaptSubscribeBuilderWithChannels(): void { $operation = new SubscribeOperation( ['channel1', 'channel2'], @@ -42,7 +42,7 @@ public function testAdaptSubscribeBuilderWithChannels() $this->assertFalse($this->stateManager->isEmpty()); } - public function testAdaptSubscribeBuilderWithChannelGroups() + public function testAdaptSubscribeBuilderWithChannelGroups(): void { $operation = new SubscribeOperation( [], @@ -56,7 +56,7 @@ public function testAdaptSubscribeBuilderWithChannelGroups() $this->assertFalse($this->stateManager->isEmpty()); } - public function testAdaptSubscribeBuilderWithChannelsAndGroups() + public function testAdaptSubscribeBuilderWithChannelsAndGroups(): void { $operation = new SubscribeOperation( ['channel1'], @@ -70,7 +70,7 @@ public function testAdaptSubscribeBuilderWithChannelsAndGroups() $this->assertFalse($this->stateManager->isEmpty()); } - public function testPrepareChannelListWithoutPresence() + public function testPrepareChannelListWithoutPresence(): void { $operation = new SubscribeOperation( ['channel1', 'channel2'], @@ -87,7 +87,7 @@ public function testPrepareChannelListWithoutPresence() $this->assertContains('channel2', $channelList); } - public function testPrepareChannelListWithPresence() + public function testPrepareChannelListWithPresence(): void { $operation = new SubscribeOperation( ['channel1', 'channel2'], @@ -106,7 +106,7 @@ public function testPrepareChannelListWithPresence() $this->assertContains('channel2-pnpres', $channelList); } - public function testPrepareChannelGroupListWithoutPresence() + public function testPrepareChannelGroupListWithoutPresence(): void { $operation = new SubscribeOperation( [], @@ -123,7 +123,7 @@ public function testPrepareChannelGroupListWithoutPresence() $this->assertContains('group2', $groupList); } - public function testPrepareChannelGroupListWithPresence() + public function testPrepareChannelGroupListWithPresence(): void { $operation = new SubscribeOperation( [], @@ -142,7 +142,7 @@ public function testPrepareChannelGroupListWithPresence() $this->assertContains('group2-pnpres', $groupList); } - public function testAdaptUnsubscribeBuilderRemovesChannels() + public function testAdaptUnsubscribeBuilderRemovesChannels(): void { // First subscribe $subscribeOp = new SubscribeOperation( @@ -165,7 +165,7 @@ public function testAdaptUnsubscribeBuilderRemovesChannels() $this->assertNotContains('channel1', $channelList); } - public function testAdaptUnsubscribeBuilderRemovesChannelGroups() + public function testAdaptUnsubscribeBuilderRemovesChannelGroups(): void { // First subscribe $subscribeOp = new SubscribeOperation( @@ -188,7 +188,7 @@ public function testAdaptUnsubscribeBuilderRemovesChannelGroups() $this->assertNotContains('group1', $groupList); } - public function testAdaptUnsubscribeBuilderRemovesPresenceChannels() + public function testAdaptUnsubscribeBuilderRemovesPresenceChannels(): void { // Subscribe with presence $subscribeOp = new SubscribeOperation( @@ -214,7 +214,7 @@ public function testAdaptUnsubscribeBuilderRemovesPresenceChannels() $this->assertNotContains('channel1-pnpres', $channelList); } - public function testIsEmptyAfterUnsubscribingFromAll() + public function testIsEmptyAfterUnsubscribingFromAll(): void { // Subscribe $subscribeOp = new SubscribeOperation( @@ -235,7 +235,7 @@ public function testIsEmptyAfterUnsubscribingFromAll() $this->assertTrue($this->stateManager->isEmpty()); } - public function testMultipleSubscribeOperations() + public function testMultipleSubscribeOperations(): void { // First subscription $operation1 = new SubscribeOperation( @@ -262,7 +262,7 @@ public function testMultipleSubscribeOperations() $this->assertContains('channel2', $channelList); } - public function testResubscribeToSameChannel() + public function testResubscribeToSameChannel(): void { // Subscribe to channel1 $operation1 = new SubscribeOperation( @@ -288,7 +288,7 @@ public function testResubscribeToSameChannel() $this->assertContains('channel1', $channelList); } - public function testEmptyChannelListWhenNoChannels() + public function testEmptyChannelListWhenNoChannels(): void { $operation = new SubscribeOperation( [], @@ -303,7 +303,7 @@ public function testEmptyChannelListWhenNoChannels() $this->assertEmpty($channelList); } - public function testEmptyGroupListWhenNoGroups() + public function testEmptyGroupListWhenNoGroups(): void { $operation = new SubscribeOperation( ['channel1'], @@ -318,7 +318,7 @@ public function testEmptyGroupListWhenNoGroups() $this->assertEmpty($groupList); } - public function testUnsubscribeFromNonExistentChannel() + public function testUnsubscribeFromNonExistentChannel(): void { $operation = new SubscribeOperation( ['channel1'], diff --git a/tests/unit/TokenManagerTest.php b/tests/unit/TokenManagerTest.php index 71b3556..2b73d88 100644 --- a/tests/unit/TokenManagerTest.php +++ b/tests/unit/TokenManagerTest.php @@ -5,7 +5,7 @@ class TokenManagerTest extends TestCase { - public function testSetAndGetToken() + public function testSetAndGetToken(): void { $manager = new TokenManager(); $token = 'test-token-abc123'; @@ -15,14 +15,14 @@ public function testSetAndGetToken() $this->assertEquals($token, $manager->getToken()); } - public function testGetTokenReturnsNullByDefault() + public function testGetTokenReturnsNullByDefault(): void { $manager = new TokenManager(); $this->assertNull($manager->getToken()); } - public function testSetTokenOverwritesPreviousToken() + public function testSetTokenOverwritesPreviousToken(): void { $manager = new TokenManager(); @@ -33,7 +33,7 @@ public function testSetTokenOverwritesPreviousToken() $this->assertEquals('second-token', $manager->getToken()); } - public function testSetTokenWithEmptyString() + public function testSetTokenWithEmptyString(): void { $manager = new TokenManager(); @@ -42,7 +42,7 @@ public function testSetTokenWithEmptyString() $this->assertEquals('', $manager->getToken()); } - public function testSetTokenWithLongString() + public function testSetTokenWithLongString(): void { $manager = new TokenManager(); $longToken = str_repeat('a', 10000); @@ -52,7 +52,7 @@ public function testSetTokenWithLongString() $this->assertEquals($longToken, $manager->getToken()); } - public function testSetTokenWithSpecialCharacters() + public function testSetTokenWithSpecialCharacters(): void { $manager = new TokenManager(); $specialToken = 'token-with-special!@#$%^&*()_+-={}[]|\\:";\'<>?,./'; From 49927c46ab6472c951a371e43f188309beec4928 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 14:19:50 +0200 Subject: [PATCH 04/26] More linter --- tests/unit/PNConfigurationExtendedTest.php | 106 ++++++++++----------- tests/unit/PubNubCborDecodeTest.php | 106 ++++++++++----------- 2 files changed, 106 insertions(+), 106 deletions(-) diff --git a/tests/unit/PNConfigurationExtendedTest.php b/tests/unit/PNConfigurationExtendedTest.php index d79ddef..c7139e6 100644 --- a/tests/unit/PNConfigurationExtendedTest.php +++ b/tests/unit/PNConfigurationExtendedTest.php @@ -10,14 +10,14 @@ class PNConfigurationExtendedTest extends TestCase // TIMEOUT CONFIGURATION TESTS // ============================================================================ - public function testGetNonSubscribeRequestTimeoutReturnsDefault() + public function testGetNonSubscribeRequestTimeoutReturnsDefault(): void { $config = new PNConfiguration(); $this->assertEquals(10, $config->getNonSubscribeRequestTimeout()); } - public function testSetNonSubscribeRequestTimeout() + public function testSetNonSubscribeRequestTimeout(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -27,7 +27,7 @@ public function testSetNonSubscribeRequestTimeout() $this->assertEquals(20, $config->getNonSubscribeRequestTimeout()); } - public function testSetNonSubscribeRequestTimeoutWithZero() + public function testSetNonSubscribeRequestTimeoutWithZero(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -37,7 +37,7 @@ public function testSetNonSubscribeRequestTimeoutWithZero() $this->assertEquals(0, $config->getNonSubscribeRequestTimeout()); } - public function testSetNonSubscribeRequestTimeoutWithLargeValue() + public function testSetNonSubscribeRequestTimeoutWithLargeValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -47,14 +47,14 @@ public function testSetNonSubscribeRequestTimeoutWithLargeValue() $this->assertEquals(3600, $config->getNonSubscribeRequestTimeout()); } - public function testGetSubscribeTimeoutReturnsDefault() + public function testGetSubscribeTimeoutReturnsDefault(): void { $config = new PNConfiguration(); $this->assertEquals(310, $config->getSubscribeTimeout()); } - public function testSetSubscribeTimeout() + public function testSetSubscribeTimeout(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -64,7 +64,7 @@ public function testSetSubscribeTimeout() $this->assertEquals(400, $config->getSubscribeTimeout()); } - public function testSetSubscribeTimeoutWithMinimalValue() + public function testSetSubscribeTimeoutWithMinimalValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -74,7 +74,7 @@ public function testSetSubscribeTimeoutWithMinimalValue() $this->assertEquals(1, $config->getSubscribeTimeout()); } - public function testSetSubscribeTimeoutWithLargeValue() + public function testSetSubscribeTimeoutWithLargeValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -84,14 +84,14 @@ public function testSetSubscribeTimeoutWithLargeValue() $this->assertEquals(10000, $config->getSubscribeTimeout()); } - public function testGetConnectTimeoutReturnsDefault() + public function testGetConnectTimeoutReturnsDefault(): void { $config = new PNConfiguration(); $this->assertEquals(10, $config->getConnectTimeout()); } - public function testSetConnectTimeout() + public function testSetConnectTimeout(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -101,7 +101,7 @@ public function testSetConnectTimeout() $this->assertEquals(15, $config->getConnectTimeout()); } - public function testSetConnectTimeoutWithMinimalValue() + public function testSetConnectTimeoutWithMinimalValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -111,7 +111,7 @@ public function testSetConnectTimeoutWithMinimalValue() $this->assertEquals(1, $config->getConnectTimeout()); } - public function testSetConnectTimeoutWithLargeValue() + public function testSetConnectTimeoutWithLargeValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -121,7 +121,7 @@ public function testSetConnectTimeoutWithLargeValue() $this->assertEquals(300, $config->getConnectTimeout()); } - public function testAllTimeoutSettingsTogether() + public function testAllTimeoutSettingsTogether(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -139,14 +139,14 @@ public function testAllTimeoutSettingsTogether() // SECURITY CONFIGURATION TESTS // ============================================================================ - public function testIsSecureReturnsDefaultTrue() + public function testIsSecureReturnsDefaultTrue(): void { $config = new PNConfiguration(); $this->assertTrue($config->isSecure()); } - public function testSetSecureFalse() + public function testSetSecureFalse(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -156,7 +156,7 @@ public function testSetSecureFalse() $this->assertFalse($config->isSecure()); } - public function testSetSecureTrue() + public function testSetSecureTrue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -168,7 +168,7 @@ public function testSetSecureTrue() $this->assertTrue($config->isSecure()); } - public function testSetSecureDefaultsToTrue() + public function testSetSecureDefaultsToTrue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -179,7 +179,7 @@ public function testSetSecureDefaultsToTrue() $this->assertTrue($config->isSecure()); } - public function testSetSecureCanBeToggled() + public function testSetSecureCanBeToggled(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -197,14 +197,14 @@ public function testSetSecureCanBeToggled() // ORIGIN CONFIGURATION TESTS // ============================================================================ - public function testGetOriginReturnsNullByDefault() + public function testGetOriginReturnsNullByDefault(): void { $config = new PNConfiguration(); $this->assertNull($config->getOrigin()); } - public function testSetOriginAndGetOrigin() + public function testSetOriginAndGetOrigin(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -214,7 +214,7 @@ public function testSetOriginAndGetOrigin() $this->assertEquals('custom.pubnub.com', $config->getOrigin()); } - public function testSetOriginWithIPAddress() + public function testSetOriginWithIPAddress(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -224,7 +224,7 @@ public function testSetOriginWithIPAddress() $this->assertEquals('192.168.1.100', $config->getOrigin()); } - public function testSetOriginWithPort() + public function testSetOriginWithPort(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -234,7 +234,7 @@ public function testSetOriginWithPort() $this->assertEquals('localhost:8080', $config->getOrigin()); } - public function testSetOriginOverwritesPrevious() + public function testSetOriginOverwritesPrevious(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -250,14 +250,14 @@ public function testSetOriginOverwritesPrevious() // AUTH KEY CONFIGURATION TESTS // ============================================================================ - public function testGetAuthKeyReturnsNullByDefault() + public function testGetAuthKeyReturnsNullByDefault(): void { $config = new PNConfiguration(); $this->assertNull($config->getAuthKey()); } - public function testSetAuthKeyAndGetAuthKey() + public function testSetAuthKeyAndGetAuthKey(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -267,7 +267,7 @@ public function testSetAuthKeyAndGetAuthKey() $this->assertEquals('my-auth-key', $config->getAuthKey()); } - public function testSetAuthKeyWithEmptyString() + public function testSetAuthKeyWithEmptyString(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -277,7 +277,7 @@ public function testSetAuthKeyWithEmptyString() $this->assertEquals('', $config->getAuthKey()); } - public function testSetAuthKeyWithSpecialCharacters() + public function testSetAuthKeyWithSpecialCharacters(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -288,7 +288,7 @@ public function testSetAuthKeyWithSpecialCharacters() $this->assertEquals($authKey, $config->getAuthKey()); } - public function testSetAuthKeyOverwritesPrevious() + public function testSetAuthKeyOverwritesPrevious(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -304,14 +304,14 @@ public function testSetAuthKeyOverwritesPrevious() // FILTER EXPRESSION TESTS // ============================================================================ - public function testGetFilterExpressionReturnsNullByDefault() + public function testGetFilterExpressionReturnsNullByDefault(): void { $config = new PNConfiguration(); $this->assertNull($config->getFilterExpression()); } - public function testSetFilterExpressionAndGetFilterExpression() + public function testSetFilterExpressionAndGetFilterExpression(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -321,7 +321,7 @@ public function testSetFilterExpressionAndGetFilterExpression() $this->assertEquals('uuid == "user123"', $config->getFilterExpression()); } - public function testSetFilterExpressionWithComplexExpression() + public function testSetFilterExpressionWithComplexExpression(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -332,7 +332,7 @@ public function testSetFilterExpressionWithComplexExpression() $this->assertEquals($expression, $config->getFilterExpression()); } - public function testSetFilterExpressionOverwritesPrevious() + public function testSetFilterExpressionOverwritesPrevious(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -348,14 +348,14 @@ public function testSetFilterExpressionOverwritesPrevious() // CRYPTO CONFIGURATION TESTS // ============================================================================ - public function testIsAesEnabledReturnsFalseByDefault() + public function testIsAesEnabledReturnsFalseByDefault(): void { $config = new PNConfiguration(); $this->assertFalse($config->isAesEnabled()); } - public function testIsAesEnabledReturnsTrueWhenCipherKeySet() + public function testIsAesEnabledReturnsTrueWhenCipherKeySet(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -364,7 +364,7 @@ public function testIsAesEnabledReturnsTrueWhenCipherKeySet() $this->assertTrue($config->isAesEnabled()); } - public function testIsAesEnabledReturnsTrueWhenCryptoModuleSet() + public function testIsAesEnabledReturnsTrueWhenCryptoModuleSet(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -375,14 +375,14 @@ public function testIsAesEnabledReturnsTrueWhenCryptoModuleSet() $this->assertTrue($config->isAesEnabled()); } - public function testGetCryptoSafeReturnsNullWhenNotConfigured() + public function testGetCryptoSafeReturnsNullWhenNotConfigured(): void { $config = new PNConfiguration(); $this->assertNull($config->getCryptoSafe()); } - public function testGetCryptoSafeReturnsCryptoWhenConfigured() + public function testGetCryptoSafeReturnsCryptoWhenConfigured(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -393,7 +393,7 @@ public function testGetCryptoSafeReturnsCryptoWhenConfigured() $this->assertInstanceOf(CryptoModule::class, $crypto); } - public function testGetCryptoSafeDoesNotThrowException() + public function testGetCryptoSafeDoesNotThrowException(): void { $config = new PNConfiguration(); @@ -403,7 +403,7 @@ public function testGetCryptoSafeDoesNotThrowException() $this->assertNull($crypto); } - public function testSetCryptoModuleAndGetCryptoSafe() + public function testSetCryptoModuleAndGetCryptoSafe(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -416,14 +416,14 @@ public function testSetCryptoModuleAndGetCryptoSafe() $this->assertSame($cryptoModule, $crypto); } - public function testGetUseRandomIVReturnsDefaultTrue() + public function testGetUseRandomIVReturnsDefaultTrue(): void { $config = new PNConfiguration(); $this->assertTrue($config->getUseRandomIV()); } - public function testSetUseRandomIVFalse() + public function testSetUseRandomIVFalse(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -433,7 +433,7 @@ public function testSetUseRandomIVFalse() $this->assertFalse($config->getUseRandomIV()); } - public function testSetUseRandomIVTrue() + public function testSetUseRandomIVTrue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -448,14 +448,14 @@ public function testSetUseRandomIVTrue() // KEY GETTERS TESTS // ============================================================================ - public function testGetPublishKeyReturnsNull() + public function testGetPublishKeyReturnsNull(): void { $config = new PNConfiguration(); $this->assertNull($config->getPublishKey()); } - public function testGetPublishKeyReturnsSetValue() + public function testGetPublishKeyReturnsSetValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -464,14 +464,14 @@ public function testGetPublishKeyReturnsSetValue() $this->assertEquals('pub-key-123', $config->getPublishKey()); } - public function testGetSecretKeyReturnsNull() + public function testGetSecretKeyReturnsNull(): void { $config = new PNConfiguration(); $this->assertNull($config->getSecretKey()); } - public function testGetSecretKeyReturnsSetValue() + public function testGetSecretKeyReturnsSetValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -480,7 +480,7 @@ public function testGetSecretKeyReturnsSetValue() $this->assertEquals('sec-key-456', $config->getSecretKey()); } - public function testGetSubscribeKeyReturnsSetValue() + public function testGetSubscribeKeyReturnsSetValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -493,7 +493,7 @@ public function testGetSubscribeKeyReturnsSetValue() // CLONE METHOD TESTS // ============================================================================ - public function testCloneCreatesNewInstance() + public function testCloneCreatesNewInstance(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -504,7 +504,7 @@ public function testCloneCreatesNewInstance() $this->assertNotSame($config, $cloned); } - public function testClonePreservesValues() + public function testClonePreservesValues(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -526,7 +526,7 @@ public function testClonePreservesValues() $this->assertFalse($cloned->isSecure()); } - public function testClonePreservesTimeoutSettings() + public function testClonePreservesTimeoutSettings(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -541,7 +541,7 @@ public function testClonePreservesTimeoutSettings() $this->assertEquals(15, $cloned->getConnectTimeout()); } - public function testCloneCreatesUnlockedConfiguration() + public function testCloneCreatesUnlockedConfiguration(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); @@ -555,7 +555,7 @@ public function testCloneCreatesUnlockedConfiguration() $this->assertEquals('new-pub-key', $cloned->getPublishKey()); } - public function testCloneIsIndependent() + public function testCloneIsIndependent(): void { $config = new PNConfiguration(); $config->setUserId('original-user'); @@ -578,7 +578,7 @@ public function testCloneIsIndependent() // COMPREHENSIVE INTEGRATION TESTS // ============================================================================ - public function testFullConfigurationSetup() + public function testFullConfigurationSetup(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); diff --git a/tests/unit/PubNubCborDecodeTest.php b/tests/unit/PubNubCborDecodeTest.php index 8fa6ae8..1dbab61 100644 --- a/tests/unit/PubNubCborDecodeTest.php +++ b/tests/unit/PubNubCborDecodeTest.php @@ -9,7 +9,7 @@ class PubNubCborDecodeTest extends TestCase // UNSIGNED INTEGER TESTS // ============================================================================ - public function testDecodeUnsignedIntegerSmall() + public function testDecodeUnsignedIntegerSmall(): void { // Test small integers (0-23) which are encoded directly in the additional byte $this->assertEquals(0, PubNubCborDecode::decode('00')); @@ -18,7 +18,7 @@ public function testDecodeUnsignedIntegerSmall() $this->assertEquals(23, PubNubCborDecode::decode('17')); } - public function testDecodeUnsignedInteger1Byte() + public function testDecodeUnsignedInteger1Byte(): void { // Test 1-byte integers (24-255) $this->assertEquals(24, PubNubCborDecode::decode('1818')); @@ -26,7 +26,7 @@ public function testDecodeUnsignedInteger1Byte() $this->assertEquals(255, PubNubCborDecode::decode('18FF')); } - public function testDecodeUnsignedInteger2Bytes() + public function testDecodeUnsignedInteger2Bytes(): void { // Test 2-byte integers (256-65535) $this->assertEquals(256, PubNubCborDecode::decode('190100')); @@ -34,14 +34,14 @@ public function testDecodeUnsignedInteger2Bytes() $this->assertEquals(65535, PubNubCborDecode::decode('19FFFF')); } - public function testDecodeUnsignedInteger4Bytes() + public function testDecodeUnsignedInteger4Bytes(): void { // Test 4-byte integers $this->assertEquals(100000, PubNubCborDecode::decode('1A000186A0')); $this->assertEquals(1000000, PubNubCborDecode::decode('1A000F4240')); } - public function testDecodeUnsignedInteger8Bytes() + public function testDecodeUnsignedInteger8Bytes(): void { // Test 8-byte integers $this->assertEquals(1000000000, PubNubCborDecode::decode('1B000000003B9ACA00')); @@ -51,7 +51,7 @@ public function testDecodeUnsignedInteger8Bytes() // NEGATIVE INTEGER TESTS // ============================================================================ - public function testDecodeNegativeIntegerSmall() + public function testDecodeNegativeIntegerSmall(): void { // Negative integers: -1 to -24 encoded as 0x20-0x37 $this->assertEquals(-1, PubNubCborDecode::decode('20')); @@ -59,7 +59,7 @@ public function testDecodeNegativeIntegerSmall() $this->assertEquals(-24, PubNubCborDecode::decode('37')); } - public function testDecodeNegativeInteger1Byte() + public function testDecodeNegativeInteger1Byte(): void { // -25 to -256 $this->assertEquals(-25, PubNubCborDecode::decode('3818')); @@ -67,7 +67,7 @@ public function testDecodeNegativeInteger1Byte() $this->assertEquals(-256, PubNubCborDecode::decode('38FF')); } - public function testDecodeNegativeInteger2Bytes() + public function testDecodeNegativeInteger2Bytes(): void { // -257 to -65536 $this->assertEquals(-1000, PubNubCborDecode::decode('3903E7')); @@ -77,18 +77,18 @@ public function testDecodeNegativeInteger2Bytes() // BYTE STRING TESTS // ============================================================================ - public function testDecodeByteStringEmpty() + public function testDecodeByteStringEmpty(): void { $this->assertEquals('', PubNubCborDecode::decode('40')); } - public function testDecodeByteStringSmall() + public function testDecodeByteStringSmall(): void { // Byte string "hello" (68656C6C6F in hex) $this->assertEquals('hello', PubNubCborDecode::decode('4568656C6C6F')); } - public function testDecodeByteString1ByteLength() + public function testDecodeByteString1ByteLength(): void { // Byte string with 1-byte length indicator $decoded = PubNubCborDecode::decode('5818' . bin2hex(str_repeat('a', 24))); @@ -99,24 +99,24 @@ public function testDecodeByteString1ByteLength() // TEXT STRING TESTS // ============================================================================ - public function testDecodeTextStringEmpty() + public function testDecodeTextStringEmpty(): void { $this->assertEquals('', PubNubCborDecode::decode('60')); } - public function testDecodeTextStringSmall() + public function testDecodeTextStringSmall(): void { // Text string "IETF" $this->assertEquals('IETF', PubNubCborDecode::decode('6449455446')); } - public function testDecodeTextStringUnicode() + public function testDecodeTextStringUnicode(): void { // Text string with unicode $this->assertEquals('hello', PubNubCborDecode::decode('6568656C6C6F')); } - public function testDecodeTextString1ByteLength() + public function testDecodeTextString1ByteLength(): void { // Text string with 1-byte length $text = str_repeat('x', 24); @@ -128,32 +128,32 @@ public function testDecodeTextString1ByteLength() // ARRAY TESTS // ============================================================================ - public function testDecodeArrayEmpty() + public function testDecodeArrayEmpty(): void { $this->assertEquals([], PubNubCborDecode::decode('80')); } - public function testDecodeArrayWithIntegers() + public function testDecodeArrayWithIntegers(): void { // Array [1, 2, 3] $this->assertEquals([1, 2, 3], PubNubCborDecode::decode('83010203')); } - public function testDecodeArrayWithMixedTypes() + public function testDecodeArrayWithMixedTypes(): void { // Array [1, "hello"] $result = PubNubCborDecode::decode('82016568656C6C6F'); $this->assertEquals([1, 'hello'], $result); } - public function testDecodeArrayNested() + public function testDecodeArrayNested(): void { // Array [[1, 2], [3, 4]] $result = PubNubCborDecode::decode('828201028203 04'); $this->assertEquals([[1, 2], [3, 4]], $result); } - public function testDecodeArrayWithNegativeNumbers() + public function testDecodeArrayWithNegativeNumbers(): void { // Array [-1, -2, -3] $this->assertEquals([-1, -2, -3], PubNubCborDecode::decode('83202122')); @@ -163,33 +163,33 @@ public function testDecodeArrayWithNegativeNumbers() // HASHMAP (OBJECT) TESTS // ============================================================================ - public function testDecodeHashmapEmpty() + public function testDecodeHashmapEmpty(): void { $this->assertEquals([], PubNubCborDecode::decode('A0')); } - public function testDecodeHashmapWithStrings() + public function testDecodeHashmapWithStrings(): void { // Map {"a": "A"} $result = PubNubCborDecode::decode('A161616141'); $this->assertEquals(['a' => 'A'], $result); } - public function testDecodeHashmapWithNumbers() + public function testDecodeHashmapWithNumbers(): void { // Map {"a": 1, "b": 2} $result = PubNubCborDecode::decode('A26161016162 02'); $this->assertEquals(['a' => 1, 'b' => 2], $result); } - public function testDecodeHashmapNested() + public function testDecodeHashmapNested(): void { // Map {"a": {"b": "c"}} $result = PubNubCborDecode::decode('A16161A161626163'); $this->assertEquals(['a' => ['b' => 'c']], $result); } - public function testDecodeHashmapWithArray() + public function testDecodeHashmapWithArray(): void { // Map {"array": [1, 2, 3]} $result = PubNubCborDecode::decode('A16561727261798301 0203'); @@ -200,22 +200,22 @@ public function testDecodeHashmapWithArray() // SIMPLE VALUES TESTS // ============================================================================ - public function testDecodeSimpleValueFalse() + public function testDecodeSimpleValueFalse(): void { $this->assertFalse(PubNubCborDecode::decode('F4')); } - public function testDecodeSimpleValueTrue() + public function testDecodeSimpleValueTrue(): void { $this->assertTrue(PubNubCborDecode::decode('F5')); } - public function testDecodeSimpleValueNull() + public function testDecodeSimpleValueNull(): void { $this->assertNull(PubNubCborDecode::decode('F6')); } - public function testDecodeSimpleValueUndefined() + public function testDecodeSimpleValueUndefined(): void { // Undefined maps to null in PHP $this->assertNull(PubNubCborDecode::decode('F7')); @@ -225,7 +225,7 @@ public function testDecodeSimpleValueUndefined() // FLOAT TESTS // ============================================================================ - public function testDecodeFloat16Bit() + public function testDecodeFloat16Bit(): void { // Test 16-bit float (half-precision) // 1.0 in half precision: 0x3C00 @@ -233,7 +233,7 @@ public function testDecodeFloat16Bit() $this->assertEquals(1.0, $result); } - public function testDecodeFloat32Bit() + public function testDecodeFloat32Bit(): void { // Test 32-bit float (single precision) // 3.14159 approximately in single precision @@ -241,7 +241,7 @@ public function testDecodeFloat32Bit() $this->assertEqualsWithDelta(3.14159, $result, 0.00001); } - public function testDecodeFloat64Bit() + public function testDecodeFloat64Bit(): void { // Test 64-bit float (double precision) // 1.1 in double precision @@ -249,21 +249,21 @@ public function testDecodeFloat64Bit() $this->assertEqualsWithDelta(1.1, $result, 0.0000001); } - public function testDecodeFloatZero() + public function testDecodeFloatZero(): void { // 0.0 in half precision: 0x0000 $result = PubNubCborDecode::decode('F90000'); $this->assertEquals(0.0, $result); } - public function testDecodeFloatNegative() + public function testDecodeFloatNegative(): void { // -1.0 in half precision: 0xBC00 $result = PubNubCborDecode::decode('F9BC00'); $this->assertEquals(-1.0, $result); } - public function testDecodeFloatInfinity() + public function testDecodeFloatInfinity(): void { // Positive infinity in half precision: 0x7C00 $result = PubNubCborDecode::decode('F97C00'); @@ -274,7 +274,7 @@ public function testDecodeFloatInfinity() // COMPLEX DATA STRUCTURE TESTS // ============================================================================ - public function testDecodeComplexNestedStructure() + public function testDecodeComplexNestedStructure(): void { // Complex structure: {"users": [{"name": "Alice", "age": 30}]} $cbor = 'A1' . // Map with 1 entry @@ -295,7 +295,7 @@ public function testDecodeComplexNestedStructure() $this->assertEquals(30, $result['users'][0]['age']); } - public function testDecodeArrayOfMixedPrimitives() + public function testDecodeArrayOfMixedPrimitives(): void { // Array with: integer, string, boolean, null // [42, "test", true, null] @@ -314,21 +314,21 @@ public function testDecodeArrayOfMixedPrimitives() // INPUT SANITIZATION TESTS // ============================================================================ - public function testDecodeWithSpaces() + public function testDecodeWithSpaces(): void { // Should handle spaces in input $this->assertEquals(42, PubNubCborDecode::decode('18 2A')); $this->assertEquals([1, 2], PubNubCborDecode::decode('82 01 02')); } - public function testDecodeWithLowerCase() + public function testDecodeWithLowerCase(): void { // Should handle lowercase hex $this->assertEquals(255, PubNubCborDecode::decode('18ff')); $this->assertEquals('hello', PubNubCborDecode::decode('6568656c6c6f')); } - public function testDecodeWithMixedCase() + public function testDecodeWithMixedCase(): void { // Should handle mixed case hex $this->assertEquals(1000, PubNubCborDecode::decode('1903E8')); @@ -339,7 +339,7 @@ public function testDecodeWithMixedCase() // ERROR HANDLING TESTS // ============================================================================ - public function testDecodeInvalidHexCharacters() + public function testDecodeInvalidHexCharacters(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Input'); @@ -347,7 +347,7 @@ public function testDecodeInvalidHexCharacters() PubNubCborDecode::decode('GG'); } - public function testDecodeInvalidHexWithSpecialChars() + public function testDecodeInvalidHexWithSpecialChars(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Input'); @@ -355,7 +355,7 @@ public function testDecodeInvalidHexWithSpecialChars() PubNubCborDecode::decode('18@A'); } - public function testDecodeInvalidHexWithNonHexLetters() + public function testDecodeInvalidHexWithNonHexLetters(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Input'); @@ -367,32 +367,32 @@ public function testDecodeInvalidHexWithNonHexLetters() // EDGE CASES // ============================================================================ - public function testDecodeEmptyArray() + public function testDecodeEmptyArray(): void { $result = PubNubCborDecode::decode('80'); $this->assertIsArray($result); $this->assertEmpty($result); } - public function testDecodeEmptyMap() + public function testDecodeEmptyMap(): void { $result = PubNubCborDecode::decode('A0'); $this->assertIsArray($result); $this->assertEmpty($result); } - public function testDecodeEmptyString() + public function testDecodeEmptyString(): void { $this->assertEquals('', PubNubCborDecode::decode('60')); } - public function testDecodeLargeInteger() + public function testDecodeLargeInteger(): void { // Test maximum values for different byte sizes $this->assertEquals(4294967295, PubNubCborDecode::decode('1AFFFFFFFF')); } - public function testDecodeArrayWith1ByteLength() + public function testDecodeArrayWith1ByteLength(): void { // Array with length specified in 1 byte (25+ elements) $cbor = '9818'; // Array with length in next byte: 24 elements @@ -404,7 +404,7 @@ public function testDecodeArrayWith1ByteLength() $this->assertCount(24, $result); } - public function testDecodeMapWith1ByteLength() + public function testDecodeMapWith1ByteLength(): void { // Map with length specified in 1 byte $cbor = 'B818'; // Map with length in next byte: 24 entries @@ -418,28 +418,28 @@ public function testDecodeMapWith1ByteLength() $this->assertCount(24, $result); } - public function testDecodeMultipleNesting() + public function testDecodeMultipleNesting(): void { // Deep nesting: [[[1]]] $result = PubNubCborDecode::decode('818181 01'); $this->assertEquals([[[1]]], $result); } - public function testDecodeBooleanArray() + public function testDecodeBooleanArray(): void { // Array of booleans: [true, false, true] $result = PubNubCborDecode::decode('83F5F4F5'); $this->assertEquals([true, false, true], $result); } - public function testDecodeNullArray() + public function testDecodeNullArray(): void { // Array with nulls: [null, null] $result = PubNubCborDecode::decode('82F6F6'); $this->assertEquals([null, null], $result); } - public function testDecodeStringWithSpecialCharacters() + public function testDecodeStringWithSpecialCharacters(): void { // String with special chars like newline, tab $specialString = "test\nwith\ttabs"; From 92d25a6247f9682f24f9e8a45c40a81d7df17557 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 14:29:51 +0200 Subject: [PATCH 05/26] Linter + remove faulty test file --- tests/unit/PubNubFactoryMethodsTest.php | 2 +- tests/unit/StateManagerTest.php | 342 ------------------------ 2 files changed, 1 insertion(+), 343 deletions(-) delete mode 100644 tests/unit/StateManagerTest.php diff --git a/tests/unit/PubNubFactoryMethodsTest.php b/tests/unit/PubNubFactoryMethodsTest.php index d8effce..e1e1a18 100644 --- a/tests/unit/PubNubFactoryMethodsTest.php +++ b/tests/unit/PubNubFactoryMethodsTest.php @@ -17,7 +17,7 @@ public function testDemoReturnsValidPubNubInstance(): void $this->assertInstanceOf(PubNub::class, $pubnub); } - public function testDemoHasDemoKeys() + public function testDemoHasDemoKeys(): void { $pubnub = PubNub::demo(); $config = $pubnub->getConfiguration(); diff --git a/tests/unit/StateManagerTest.php b/tests/unit/StateManagerTest.php deleted file mode 100644 index e21ca6d..0000000 --- a/tests/unit/StateManagerTest.php +++ /dev/null @@ -1,342 +0,0 @@ -setSubscribeKey('demo'); - $config->setPublishKey('demo'); - $config->setUserId('test-user'); - - $this->pubnub = new PubNub($config); - $this->stateManager = new StateManager($this->pubnub); - } - - public function testIsEmptyByDefault(): void - { - $this->assertTrue($this->stateManager->isEmpty()); - } - - public function testAdaptSubscribeBuilderWithChannels(): void - { - $operation = new SubscribeOperation( - ['channel1', 'channel2'], - [], - false, - null - ); - - $this->stateManager->adaptSubscribeBuilder($operation); - - $this->assertFalse($this->stateManager->isEmpty()); - } - - public function testAdaptSubscribeBuilderWithChannelGroups(): void - { - $operation = new SubscribeOperation( - [], - ['group1', 'group2'], - false, - null - ); - - $this->stateManager->adaptSubscribeBuilder($operation); - - $this->assertFalse($this->stateManager->isEmpty()); - } - - public function testAdaptSubscribeBuilderWithChannelsAndGroups(): void - { - $operation = new SubscribeOperation( - ['channel1'], - ['group1'], - false, - null - ); - - $this->stateManager->adaptSubscribeBuilder($operation); - - $this->assertFalse($this->stateManager->isEmpty()); - } - - public function testPrepareChannelListWithoutPresence(): void - { - $operation = new SubscribeOperation( - ['channel1', 'channel2'], - [], - false, - null - ); - - $this->stateManager->adaptSubscribeBuilder($operation); - $channelList = $this->stateManager->prepareChannelList(false); - - $this->assertCount(2, $channelList); - $this->assertContains('channel1', $channelList); - $this->assertContains('channel2', $channelList); - } - - public function testPrepareChannelListWithPresence(): void - { - $operation = new SubscribeOperation( - ['channel1', 'channel2'], - [], - true, - null - ); - - $this->stateManager->adaptSubscribeBuilder($operation); - $channelList = $this->stateManager->prepareChannelList(true); - - $this->assertCount(4, $channelList); - $this->assertContains('channel1', $channelList); - $this->assertContains('channel2', $channelList); - $this->assertContains('channel1-pnpres', $channelList); - $this->assertContains('channel2-pnpres', $channelList); - } - - public function testPrepareChannelGroupListWithoutPresence(): void - { - $operation = new SubscribeOperation( - [], - ['group1', 'group2'], - false, - null - ); - - $this->stateManager->adaptSubscribeBuilder($operation); - $groupList = $this->stateManager->prepareChannelGroupList(false); - - $this->assertCount(2, $groupList); - $this->assertContains('group1', $groupList); - $this->assertContains('group2', $groupList); - } - - public function testPrepareChannelGroupListWithPresence(): void - { - $operation = new SubscribeOperation( - [], - ['group1', 'group2'], - true, - null - ); - - $this->stateManager->adaptSubscribeBuilder($operation); - $groupList = $this->stateManager->prepareChannelGroupList(true); - - $this->assertCount(4, $groupList); - $this->assertContains('group1', $groupList); - $this->assertContains('group2', $groupList); - $this->assertContains('group1-pnpres', $groupList); - $this->assertContains('group2-pnpres', $groupList); - } - - public function testAdaptUnsubscribeBuilderRemovesChannels(): void - { - // First subscribe - $subscribeOp = new SubscribeOperation( - ['channel1', 'channel2'], - [], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($subscribeOp); - - // Then unsubscribe from one channel - $unsubscribeOp = new UnsubscribeOperation(); - $unsubscribeOp->setChannels(['channel1']); - $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); - - $channelList = $this->stateManager->prepareChannelList(false); - - $this->assertCount(1, $channelList); - $this->assertContains('channel2', $channelList); - $this->assertNotContains('channel1', $channelList); - } - - public function testAdaptUnsubscribeBuilderRemovesChannelGroups(): void - { - // First subscribe - $subscribeOp = new SubscribeOperation( - [], - ['group1', 'group2'], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($subscribeOp); - - // Then unsubscribe from one group - $unsubscribeOp = new UnsubscribeOperation(); - $unsubscribeOp->setChannelGroups(['group1']); - $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); - - $groupList = $this->stateManager->prepareChannelGroupList(false); - - $this->assertCount(1, $groupList); - $this->assertContains('group2', $groupList); - $this->assertNotContains('group1', $groupList); - } - - public function testAdaptUnsubscribeBuilderRemovesPresenceChannels(): void - { - // Subscribe with presence - $subscribeOp = new SubscribeOperation( - ['channel1', 'channel2'], - [], - true, - null - ); - $this->stateManager->adaptSubscribeBuilder($subscribeOp); - - // Unsubscribe from channel1 - $unsubscribeOp = new UnsubscribeOperation(); - $unsubscribeOp->setChannels(['channel1']); - $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); - - $channelList = $this->stateManager->prepareChannelList(true); - - // Should have channel2 and channel2-pnpres, but not channel1 or channel1-pnpres - $this->assertCount(2, $channelList); - $this->assertContains('channel2', $channelList); - $this->assertContains('channel2-pnpres', $channelList); - $this->assertNotContains('channel1', $channelList); - $this->assertNotContains('channel1-pnpres', $channelList); - } - - public function testIsEmptyAfterUnsubscribingFromAll(): void - { - // Subscribe - $subscribeOp = new SubscribeOperation( - ['channel1'], - ['group1'], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($subscribeOp); - $this->assertFalse($this->stateManager->isEmpty()); - - // Unsubscribe from all - $unsubscribeOp = new UnsubscribeOperation(); - $unsubscribeOp->setChannels(['channel1']); - $unsubscribeOp->setChannelGroups(['group1']); - $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); - - $this->assertTrue($this->stateManager->isEmpty()); - } - - public function testMultipleSubscribeOperations(): void - { - // First subscription - $operation1 = new SubscribeOperation( - ['channel1'], - [], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($operation1); - - // Second subscription - $operation2 = new SubscribeOperation( - ['channel2'], - [], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($operation2); - - $channelList = $this->stateManager->prepareChannelList(false); - - $this->assertCount(2, $channelList); - $this->assertContains('channel1', $channelList); - $this->assertContains('channel2', $channelList); - } - - public function testResubscribeToSameChannel(): void - { - // Subscribe to channel1 - $operation1 = new SubscribeOperation( - ['channel1'], - [], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($operation1); - - // Subscribe again to channel1 (should overwrite, not duplicate) - $operation2 = new SubscribeOperation( - ['channel1'], - [], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($operation2); - - $channelList = $this->stateManager->prepareChannelList(false); - - $this->assertCount(1, $channelList); - $this->assertContains('channel1', $channelList); - } - - public function testEmptyChannelListWhenNoChannels(): void - { - $operation = new SubscribeOperation( - [], - ['group1'], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($operation); - - $channelList = $this->stateManager->prepareChannelList(false); - - $this->assertEmpty($channelList); - } - - public function testEmptyGroupListWhenNoGroups(): void - { - $operation = new SubscribeOperation( - ['channel1'], - [], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($operation); - - $groupList = $this->stateManager->prepareChannelGroupList(false); - - $this->assertEmpty($groupList); - } - - public function testUnsubscribeFromNonExistentChannel(): void - { - $operation = new SubscribeOperation( - ['channel1'], - [], - false, - null - ); - $this->stateManager->adaptSubscribeBuilder($operation); - - // Unsubscribe from channel that was never subscribed - $unsubscribeOp = new UnsubscribeOperation(); - $unsubscribeOp->setChannels(['channel2']); - $this->stateManager->adaptUnsubscribeBuilder($unsubscribeOp); - - $channelList = $this->stateManager->prepareChannelList(false); - - // channel1 should still be there - $this->assertCount(1, $channelList); - $this->assertContains('channel1', $channelList); - } -} From b607c465a96dc323c11dd245b3e6ad465fd48a7f Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 14:53:59 +0200 Subject: [PATCH 06/26] Mass PHP CBF apply --- .../AddChannelToChannelGroupTest.php | 3 +- .../ListChannelsInChannelGroupTest.php | 3 +- .../RemoveChannelFromChannelGroupTest.php | 3 +- tests/functional/RemoveChannelGroupTest.php | 3 +- tests/functional/SubscribeTest.php | 1 - tests/functional/TelemetryManagerTest.php | 3 +- .../integrational/PublishFileMessageTest.php | 92 ++++---- tests/integrational/TimeTest.php | 1 - .../GetChannelMetadataEndpointTest.php | 1 - .../RemoveChannelMetadataEndpointTest.php | 1 - .../uuid/GetAllUUIDMetadataEndpointTest.php | 5 +- .../uuid/RemoveUUIDMetadataEndpointTest.php | 1 - tests/unit/BasePathManagerTest.php | 60 +++--- tests/unit/CryptoCryptorGettersTest.php | 92 ++++---- tests/unit/ListenerManagerTest.php | 4 +- tests/unit/PNConfigurationExtendedTest.php | 184 ++++++++-------- tests/unit/PNConfigurationTest.php | 1 - tests/unit/PubNubCborDecodeTest.php | 22 +- tests/unit/PubNubCryptoMethodsTest.php | 120 +++++------ tests/unit/PubNubFactoryMethodsTest.php | 66 +++--- tests/unit/PubNubSdkInfoTest.php | 72 +++---- tests/unit/PubNubUtilExtendedTest.php | 198 +++++++++--------- tests/unit/PubNubUtilityMethodsTest.php | 90 ++++---- tests/unit/PublishTest.php | 1 - tests/unit/TelemetryManagerTest.php | 1 - tests/unit/TokenManagerTest.php | 22 +- tests/unit/UtilsTest.php | 1 - 27 files changed, 517 insertions(+), 534 deletions(-) diff --git a/tests/functional/AddChannelToChannelGroupTest.php b/tests/functional/AddChannelToChannelGroupTest.php index bdcb41e..29dce87 100644 --- a/tests/functional/AddChannelToChannelGroupTest.php +++ b/tests/functional/AddChannelToChannelGroupTest.php @@ -7,7 +7,6 @@ use PubNub\PubNub; use PubNub\PubNubUtil; - class AddChannelToChannelGroupTest extends \PubNubTestCase { public function testValidatesGroupNotEmpty() @@ -94,4 +93,4 @@ public function buildPath() { return parent::buildPath(); } -} \ No newline at end of file +} diff --git a/tests/functional/ListChannelsInChannelGroupTest.php b/tests/functional/ListChannelsInChannelGroupTest.php index cbad011..e47c772 100644 --- a/tests/functional/ListChannelsInChannelGroupTest.php +++ b/tests/functional/ListChannelsInChannelGroupTest.php @@ -7,7 +7,6 @@ use PubNub\PubNub; use PubNub\PubNubUtil; - class ListChannelsInChannelGroupTest extends \PubNubTestCase { public function testValidatesGroupNotEmpty() @@ -57,4 +56,4 @@ public function buildPath() { return parent::buildPath(); } -} \ No newline at end of file +} diff --git a/tests/functional/RemoveChannelFromChannelGroupTest.php b/tests/functional/RemoveChannelFromChannelGroupTest.php index 5c4e5e4..b644dde 100644 --- a/tests/functional/RemoveChannelFromChannelGroupTest.php +++ b/tests/functional/RemoveChannelFromChannelGroupTest.php @@ -7,7 +7,6 @@ use PubNub\PubNub; use PubNub\PubNubUtil; - class RemoveChannelFromChannelGroupTest extends \PubNubTestCase { public function testValidatesGroupNotEmpty() @@ -94,4 +93,4 @@ public function buildPath() { return parent::buildPath(); } -} \ No newline at end of file +} diff --git a/tests/functional/RemoveChannelGroupTest.php b/tests/functional/RemoveChannelGroupTest.php index 7fda245..93e6dab 100644 --- a/tests/functional/RemoveChannelGroupTest.php +++ b/tests/functional/RemoveChannelGroupTest.php @@ -8,7 +8,6 @@ use PubNub\PubNub; use PubNub\PubNubUtil; - class RemoveChannelGroupTest extends \PubNubTestCase { public function testValidatesGroupNotEmpty() @@ -58,4 +57,4 @@ public function buildPath() { return parent::buildPath(); } -} \ No newline at end of file +} diff --git a/tests/functional/SubscribeTest.php b/tests/functional/SubscribeTest.php index 2aeaaa7..b2661c9 100644 --- a/tests/functional/SubscribeTest.php +++ b/tests/functional/SubscribeTest.php @@ -7,7 +7,6 @@ use PubNub\PubNub; use PubNub\PubNubUtil; - class SubscribeTest extends \PubNubTestCase { /** @var ExposedSubscribe */ diff --git a/tests/functional/TelemetryManagerTest.php b/tests/functional/TelemetryManagerTest.php index 259c21a..563c7a2 100644 --- a/tests/functional/TelemetryManagerTest.php +++ b/tests/functional/TelemetryManagerTest.php @@ -5,7 +5,6 @@ use PubNub\Managers\TelemetryManager; use PubNub\Enums\PNOperationType; - class TelemetryManagerTest extends \PubNubTestCase { public function testCleanUpTest() @@ -29,4 +28,4 @@ public function testCleanUpTest() class TelemetryManagerExposed extends TelemetryManager { const MAXIMUM_LATENCY_DATA_AGE = 1; -} \ No newline at end of file +} diff --git a/tests/integrational/PublishFileMessageTest.php b/tests/integrational/PublishFileMessageTest.php index d8f6652..0854094 100644 --- a/tests/integrational/PublishFileMessageTest.php +++ b/tests/integrational/PublishFileMessageTest.php @@ -12,7 +12,7 @@ final class PublishFileMessageTest extends PubNubTestCase public function setUp(): void { parent::setUp(); - + // Create a temporary test file $this->testFilePath = sys_get_temp_dir() . '/test_file_' . uniqid() . '.txt'; file_put_contents($this->testFilePath, 'Test file content for publish file message'); @@ -24,7 +24,7 @@ public function tearDown(): void if (file_exists($this->testFilePath)) { unlink($this->testFilePath); } - + // Clean up uploaded files try { $listResponse = $this->pubnub->listFiles()->channel($this->channel)->sync(); @@ -38,7 +38,7 @@ public function tearDown(): void } catch (\Exception $e) { // Ignore cleanup errors } - + parent::tearDown(); } @@ -47,18 +47,18 @@ public function testPublishFileMessageWithBasicMessage(): void // First upload a file to get file ID $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("Initial file upload") ->sync(); - + fclose($file); - + $this->assertNotEmpty($uploadResponse->getFileId()); - + // Now publish a file message notification $response = $this->pubnub->publishFileMessage() ->channel($this->channel) @@ -66,7 +66,7 @@ public function testPublishFileMessageWithBasicMessage(): void ->fileName($fileName) ->message("File notification message") ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -76,23 +76,23 @@ public function testPublishFileMessageWithMetadata(): void // Upload a file first $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("File with metadata") ->sync(); - + fclose($file); - + // Publish file message with metadata $metadata = [ "author" => "test-user", "fileType" => "text", "importance" => "high" ]; - + $response = $this->pubnub->publishFileMessage() ->channel($this->channel) ->fileId($uploadResponse->getFileId()) @@ -100,7 +100,7 @@ public function testPublishFileMessageWithMetadata(): void ->message("File with metadata notification") ->meta($metadata) ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -110,16 +110,16 @@ public function testPublishFileMessageWithCustomMessageType(): void // Upload a file first $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("File upload") ->sync(); - + fclose($file); - + // Publish file message with custom message type $response = $this->pubnub->publishFileMessage() ->channel($this->channel) @@ -128,7 +128,7 @@ public function testPublishFileMessageWithCustomMessageType(): void ->message("Custom type notification") ->customMessageType("file_notification") ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -138,16 +138,16 @@ public function testPublishFileMessageWithTTL(): void // Upload a file first $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("File upload") ->sync(); - + fclose($file); - + // Publish file message with TTL $response = $this->pubnub->publishFileMessage() ->channel($this->channel) @@ -156,7 +156,7 @@ public function testPublishFileMessageWithTTL(): void ->message("Message with TTL") ->ttl(60) // 60 minutes ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -166,16 +166,16 @@ public function testPublishFileMessageWithShouldStore(): void // Upload a file first $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("File upload") ->sync(); - + fclose($file); - + // Publish file message with shouldStore flag $response = $this->pubnub->publishFileMessage() ->channel($this->channel) @@ -184,7 +184,7 @@ public function testPublishFileMessageWithShouldStore(): void ->message("Stored message") ->shouldStore(true) ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -194,22 +194,22 @@ public function testPublishFileMessageWithAllOptions(): void // Upload a file first $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("File upload") ->sync(); - + fclose($file); - + // Publish file message with all options $metadata = [ "category" => "documents", "tags" => ["important", "urgent"] ]; - + $response = $this->pubnub->publishFileMessage() ->channel($this->channel) ->fileId($uploadResponse->getFileId()) @@ -220,7 +220,7 @@ public function testPublishFileMessageWithAllOptions(): void ->ttl(120) ->shouldStore(true) ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -230,16 +230,16 @@ public function testPublishFileMessageWithEncryption(): void // Use encrypted pubnub instance $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub_enc->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("Encrypted file upload") ->sync(); - + fclose($file); - + // Publish encrypted file message $response = $this->pubnub_enc->publishFileMessage() ->channel($this->channel) @@ -247,7 +247,7 @@ public function testPublishFileMessageWithEncryption(): void ->fileName($fileName) ->message("Encrypted file notification") ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -257,16 +257,16 @@ public function testPublishFileMessageWithComplexMessage(): void // Upload a file first $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("File upload") ->sync(); - + fclose($file); - + // Publish file message with complex message structure $complexMessage = [ "type" => "file_uploaded", @@ -277,14 +277,14 @@ public function testPublishFileMessageWithComplexMessage(): void ], "actions" => ["review", "approve", "archive"] ]; - + $response = $this->pubnub->publishFileMessage() ->channel($this->channel) ->fileId($uploadResponse->getFileId()) ->fileName($fileName) ->message($complexMessage) ->sync(); - + $this->assertNotEmpty($response); $this->assertNotEmpty($response->getTimetoken()); } @@ -294,16 +294,16 @@ public function testPublishFileMessageMultipleTimes(): void // Upload a file first $file = fopen($this->testFilePath, "r"); $fileName = basename($this->testFilePath); - + $uploadResponse = $this->pubnub->sendFile() ->channel($this->channel) ->fileHandle($file) ->fileName($fileName) ->message("File upload") ->sync(); - + fclose($file); - + // Publish multiple file messages for the same file $response1 = $this->pubnub->publishFileMessage() ->channel($this->channel) @@ -311,14 +311,14 @@ public function testPublishFileMessageMultipleTimes(): void ->fileName($fileName) ->message("First notification") ->sync(); - + $response2 = $this->pubnub->publishFileMessage() ->channel($this->channel) ->fileId($uploadResponse->getFileId()) ->fileName($fileName) ->message("Second notification") ->sync(); - + $this->assertNotEmpty($response1->getTimetoken()); $this->assertNotEmpty($response2->getTimetoken()); $this->assertNotEquals($response1->getTimetoken(), $response2->getTimetoken()); @@ -327,7 +327,7 @@ public function testPublishFileMessageMultipleTimes(): void public function testPublishFileMessageWithInvalidFileId(): void { $this->expectException(\PubNub\Exceptions\PubNubServerException::class); - + // Try to publish with non-existent file ID $this->pubnub->publishFileMessage() ->channel($this->channel) @@ -340,7 +340,7 @@ public function testPublishFileMessageWithInvalidFileId(): void public function testPublishFileMessageWithEmptyChannel(): void { $this->expectException(\PubNub\Exceptions\PubNubValidationException::class); - + $this->pubnub->publishFileMessage() ->channel('') ->fileId('some-file-id') diff --git a/tests/integrational/TimeTest.php b/tests/integrational/TimeTest.php index 1a07594..e6abccb 100755 --- a/tests/integrational/TimeTest.php +++ b/tests/integrational/TimeTest.php @@ -2,7 +2,6 @@ namespace Tests\Integrational; - class TimeTest extends \PubNubTestCase { /** diff --git a/tests/integrational/objects/channel/GetChannelMetadataEndpointTest.php b/tests/integrational/objects/channel/GetChannelMetadataEndpointTest.php index e0dad56..f4fcabe 100644 --- a/tests/integrational/objects/channel/GetChannelMetadataEndpointTest.php +++ b/tests/integrational/objects/channel/GetChannelMetadataEndpointTest.php @@ -4,7 +4,6 @@ use PubNubTestCase; - class GetChannelMetadataEndpointTest extends PubNubTestCase { public function testGetMetadataFromChannel() diff --git a/tests/integrational/objects/channel/RemoveChannelMetadataEndpointTest.php b/tests/integrational/objects/channel/RemoveChannelMetadataEndpointTest.php index b1e4c8d..d4d4bb4 100644 --- a/tests/integrational/objects/channel/RemoveChannelMetadataEndpointTest.php +++ b/tests/integrational/objects/channel/RemoveChannelMetadataEndpointTest.php @@ -4,7 +4,6 @@ use PubNubTestCase; - class RemoveChannelMetadataEndpointTest extends PubNubTestCase { public function testRemoveMetadataFromChannel() diff --git a/tests/integrational/objects/uuid/GetAllUUIDMetadataEndpointTest.php b/tests/integrational/objects/uuid/GetAllUUIDMetadataEndpointTest.php index bd42278..bbbaf6a 100644 --- a/tests/integrational/objects/uuid/GetAllUUIDMetadataEndpointTest.php +++ b/tests/integrational/objects/uuid/GetAllUUIDMetadataEndpointTest.php @@ -4,7 +4,6 @@ use PubNubTestCase; - class GetAllUUIDMetadataEndpointTest extends PubNubTestCase { public function testGetAllUUIDMetadata() @@ -87,7 +86,7 @@ public function testGetAllUUIDMetadata() // $custom = $value->getCustom(); // $this->assertNotEmpty($custom); // $this->assertEquals("aa1", $custom->a); - // $this->assertEquals("bb1", $custom->b); + // $this->assertEquals("bb1", $custom->b); // $value = $data[2]; // $this->assertEquals("uuid2", $value->getId()); @@ -98,6 +97,6 @@ public function testGetAllUUIDMetadata() // $custom = $value->getCustom(); // $this->assertNotEmpty($custom); // $this->assertEquals("aa2", $custom->a); - // $this->assertEquals("bb2", $custom->b); + // $this->assertEquals("bb2", $custom->b); } } diff --git a/tests/integrational/objects/uuid/RemoveUUIDMetadataEndpointTest.php b/tests/integrational/objects/uuid/RemoveUUIDMetadataEndpointTest.php index e730f23..a111a07 100644 --- a/tests/integrational/objects/uuid/RemoveUUIDMetadataEndpointTest.php +++ b/tests/integrational/objects/uuid/RemoveUUIDMetadataEndpointTest.php @@ -4,7 +4,6 @@ use PubNubTestCase; - class RemoveUUIDMetadataEndpointTest extends PubNubTestCase { public function testRemoveMetadataFromUUID() diff --git a/tests/unit/BasePathManagerTest.php b/tests/unit/BasePathManagerTest.php index f6e701e..9e598ee 100644 --- a/tests/unit/BasePathManagerTest.php +++ b/tests/unit/BasePathManagerTest.php @@ -11,11 +11,11 @@ public function testGetBasePathWithDefaultSettings(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath(); - + $this->assertEquals('https://ps.pndsn.com', $basePath); } @@ -25,11 +25,11 @@ public function testGetBasePathWithCustomOrigin(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setOrigin('custom.pubnub.com'); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath(); - + $this->assertEquals('https://custom.pubnub.com', $basePath); } @@ -38,11 +38,11 @@ public function testGetBasePathWithCustomHost(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath('special.pubnub.com'); - + $this->assertEquals('https://special.pubnub.com', $basePath); } @@ -52,11 +52,11 @@ public function testGetBasePathWithCustomHostOverridesOrigin(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setOrigin('config-origin.pubnub.com'); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath('param-host.pubnub.com'); - + $this->assertEquals('https://param-host.pubnub.com', $basePath); } @@ -66,11 +66,11 @@ public function testGetBasePathWithInsecureConnection(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setSecure(false); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath(); - + $this->assertEquals('http://ps.pndsn.com', $basePath); } @@ -81,11 +81,11 @@ public function testGetBasePathWithInsecureAndCustomOrigin(): void $config->setUserId('test-user'); $config->setSecure(false); $config->setOrigin('insecure.pubnub.com'); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath(); - + $this->assertEquals('http://insecure.pubnub.com', $basePath); } @@ -95,11 +95,11 @@ public function testGetBasePathWithIPAddress(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setOrigin('192.168.1.100'); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath(); - + $this->assertEquals('https://192.168.1.100', $basePath); } @@ -109,11 +109,11 @@ public function testGetBasePathWithPortNumber(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setOrigin('localhost:8080'); - + $manager = new BasePathManager($config); - + $basePath = $manager->getBasePath(); - + $this->assertEquals('https://localhost:8080', $basePath); } @@ -122,13 +122,13 @@ public function testGetBasePathMultipleCalls(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $manager = new BasePathManager($config); - + $basePath1 = $manager->getBasePath(); $basePath2 = $manager->getBasePath(); $basePath3 = $manager->getBasePath(); - + $this->assertEquals($basePath1, $basePath2); $this->assertEquals($basePath2, $basePath3); } @@ -138,12 +138,12 @@ public function testGetBasePathWithDifferentCustomHosts(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $manager = new BasePathManager($config); - + $basePath1 = $manager->getBasePath('host1.pubnub.com'); $basePath2 = $manager->getBasePath('host2.pubnub.com'); - + $this->assertEquals('https://host1.pubnub.com', $basePath1); $this->assertEquals('https://host2.pubnub.com', $basePath2); } diff --git a/tests/unit/CryptoCryptorGettersTest.php b/tests/unit/CryptoCryptorGettersTest.php index 6acbcfe..bfd8a54 100644 --- a/tests/unit/CryptoCryptorGettersTest.php +++ b/tests/unit/CryptoCryptorGettersTest.php @@ -13,28 +13,28 @@ class CryptoCryptorGettersTest extends TestCase public function testAesCbcCryptorConstructor(): void { $cryptor = new AesCbcCryptor('test-key'); - + $this->assertInstanceOf(AesCbcCryptor::class, $cryptor); } public function testAesCbcCryptorGetCipherKey(): void { $cryptor = new AesCbcCryptor('my-cipher-key'); - + $this->assertEquals('my-cipher-key', $cryptor->getCipherKey()); } public function testAesCbcCryptorGetCipherKeyWithNullParameter(): void { $cryptor = new AesCbcCryptor('my-cipher-key'); - + $this->assertEquals('my-cipher-key', $cryptor->getCipherKey(null)); } public function testAesCbcCryptorGetCipherKeyWithCustomParameter(): void { $cryptor = new AesCbcCryptor('default-key'); - + // If a custom key is provided, it should return that instead $this->assertEquals('custom-key', $cryptor->getCipherKey('custom-key')); } @@ -43,7 +43,7 @@ public function testAesCbcCryptorGetIV(): void { $cryptor = new AesCbcCryptor('test-key'); $iv = $cryptor->getIV(); - + $this->assertIsString($iv); $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes } @@ -53,7 +53,7 @@ public function testAesCbcCryptorGetIVReturnsRandomValues(): void $cryptor = new AesCbcCryptor('test-key'); $iv1 = $cryptor->getIV(); $iv2 = $cryptor->getIV(); - + // Each call should return a different random IV $this->assertNotEquals($iv1, $iv2); } @@ -62,7 +62,7 @@ public function testAesCbcCryptorEncryptReturnsPayload(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); - + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $result); } @@ -70,7 +70,7 @@ public function testAesCbcCryptorEncryptPayloadHasCryptorId(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); - + $this->assertEquals('ACRH', $result->getCryptorId()); } @@ -78,7 +78,7 @@ public function testAesCbcCryptorEncryptPayloadHasData(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); - + $this->assertNotEmpty($result->getData()); } @@ -86,7 +86,7 @@ public function testAesCbcCryptorEncryptPayloadHasCryptorData(): void { $cryptor = new AesCbcCryptor('test-key'); $result = $cryptor->encrypt('test message'); - + // Cryptor data should contain the IV (16 bytes) $this->assertEquals(16, strlen($result->getCryptorData())); } @@ -95,10 +95,10 @@ public function testAesCbcCryptorEncryptDecryptRoundTrip(): void { $cryptor = new AesCbcCryptor('test-key'); $original = 'Hello, World!'; - + $encrypted = $cryptor->encrypt($original); $decrypted = $cryptor->decrypt($encrypted); - + $this->assertEquals($original, $decrypted); } @@ -106,7 +106,7 @@ public function testAesCbcCryptorWithDifferentKeys(): void { $cryptor1 = new AesCbcCryptor('key1'); $cryptor2 = new AesCbcCryptor('key2'); - + $this->assertEquals('key1', $cryptor1->getCipherKey()); $this->assertEquals('key2', $cryptor2->getCipherKey()); } @@ -118,21 +118,21 @@ public function testAesCbcCryptorWithDifferentKeys(): void public function testLegacyCryptorConstructor(): void { $cryptor = new LegacyCryptor('test-key', false); - + $this->assertInstanceOf(LegacyCryptor::class, $cryptor); } public function testLegacyCryptorConstructorWithRandomIV(): void { $cryptor = new LegacyCryptor('test-key', true); - + $this->assertInstanceOf(LegacyCryptor::class, $cryptor); } public function testLegacyCryptorGetCipherKey(): void { $cryptor = new LegacyCryptor('my-legacy-key', false); - + $this->assertEquals('my-legacy-key', $cryptor->getCipherKey()); } @@ -140,7 +140,7 @@ public function testLegacyCryptorGetIVWithStaticIV(): void { $cryptor = new LegacyCryptor('test-key', false); $iv = $cryptor->getIV(); - + $this->assertIsString($iv); $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes $this->assertEquals('0123456789012345', $iv); // Static IV @@ -151,7 +151,7 @@ public function testLegacyCryptorGetIVWithStaticIVIsConsistent(): void $cryptor = new LegacyCryptor('test-key', false); $iv1 = $cryptor->getIV(); $iv2 = $cryptor->getIV(); - + // With static IV, should return same value every time $this->assertEquals($iv1, $iv2); $this->assertEquals('0123456789012345', $iv1); @@ -161,7 +161,7 @@ public function testLegacyCryptorGetIVWithRandomIV(): void { $cryptor = new LegacyCryptor('test-key', true); $iv = $cryptor->getIV(); - + $this->assertIsString($iv); $this->assertEquals(16, strlen($iv)); // IV should be 16 bytes } @@ -171,7 +171,7 @@ public function testLegacyCryptorGetIVWithRandomIVReturnsRandomValues(): void $cryptor = new LegacyCryptor('test-key', true); $iv1 = $cryptor->getIV(); $iv2 = $cryptor->getIV(); - + // With random IV, each call should return different value $this->assertNotEquals($iv1, $iv2); } @@ -180,7 +180,7 @@ public function testLegacyCryptorEncryptReturnsPayload(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); - + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $result); } @@ -188,7 +188,7 @@ public function testLegacyCryptorEncryptPayloadHasCryptorId(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); - + $this->assertEquals('0000', $result->getCryptorId()); } @@ -196,7 +196,7 @@ public function testLegacyCryptorEncryptPayloadHasData(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); - + $this->assertNotEmpty($result->getData()); } @@ -204,7 +204,7 @@ public function testLegacyCryptorEncryptPayloadCryptorDataIsEmpty(): void { $cryptor = new LegacyCryptor('test-key', false); $result = $cryptor->encrypt('test message'); - + // Legacy cryptor uses empty string for cryptor data $this->assertEquals('', $result->getCryptorData()); } @@ -213,10 +213,10 @@ public function testLegacyCryptorEncryptDecryptRoundTripWithStaticIV(): void { $cryptor = new LegacyCryptor('test-key', false); $original = 'Hello, Legacy!'; - + $encrypted = $cryptor->encrypt($original); $decrypted = $cryptor->decrypt($encrypted); - + $this->assertEquals($original, $decrypted); } @@ -224,10 +224,10 @@ public function testLegacyCryptorEncryptDecryptRoundTripWithRandomIV(): void { $cryptor = new LegacyCryptor('test-key', true); $original = 'Hello, Random IV!'; - + $encrypted = $cryptor->encrypt($original); $decrypted = $cryptor->decrypt($encrypted); - + $this->assertEquals($original, $decrypted); } @@ -235,7 +235,7 @@ public function testLegacyCryptorWithDifferentKeys(): void { $cryptor1 = new LegacyCryptor('key1', false); $cryptor2 = new LegacyCryptor('key2', true); - + $this->assertEquals('key1', $cryptor1->getCipherKey()); $this->assertEquals('key2', $cryptor2->getCipherKey()); } @@ -248,10 +248,10 @@ public function testAesCbcCryptorAndLegacyCryptorHaveDifferentCryptorIds(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); - + $aesEncrypted = $aesCbc->encrypt('test'); $legacyEncrypted = $legacy->encrypt('test'); - + $this->assertEquals('ACRH', $aesEncrypted->getCryptorId()); $this->assertEquals('0000', $legacyEncrypted->getCryptorId()); $this->assertNotEquals($aesEncrypted->getCryptorId(), $legacyEncrypted->getCryptorId()); @@ -261,10 +261,10 @@ public function testBothCryptorsReturnPayloadObjects(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); - + $aesResult = $aesCbc->encrypt('test'); $legacyResult = $legacy->encrypt('test'); - + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $aesResult); $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $legacyResult); } @@ -273,10 +273,10 @@ public function testBothCryptorsHandleEmptyStrings(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); - + $aesResult = $aesCbc->encrypt(''); $legacyResult = $legacy->encrypt(''); - + $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $aesResult); $this->assertInstanceOf(\PubNub\Crypto\Payload::class, $legacyResult); } @@ -284,13 +284,13 @@ public function testBothCryptorsHandleEmptyStrings(): void public function testBothCryptorsHandleLongMessages(): void { $longMessage = str_repeat('A', 10000); // 10KB message - + $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); - + $aesEncrypted = $aesCbc->encrypt($longMessage); $legacyEncrypted = $legacy->encrypt($longMessage); - + $this->assertEquals($longMessage, $aesCbc->decrypt($aesEncrypted)); $this->assertEquals($longMessage, $legacy->decrypt($legacyEncrypted)); } @@ -298,13 +298,13 @@ public function testBothCryptorsHandleLongMessages(): void public function testBothCryptorsHandleUnicodeCharacters(): void { $unicodeMessage = '🔒 Encrypted 文字 مشفر'; - + $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); - + $aesEncrypted = $aesCbc->encrypt($unicodeMessage); $legacyEncrypted = $legacy->encrypt($unicodeMessage); - + $this->assertEquals($unicodeMessage, $aesCbc->decrypt($aesEncrypted)); $this->assertEquals($unicodeMessage, $legacy->decrypt($legacyEncrypted)); } @@ -313,10 +313,10 @@ public function testBothCryptorsHaveGetCipherKeyMethod(): void { $aesCbc = new AesCbcCryptor('key1'); $legacy = new LegacyCryptor('key2', false); - + $this->assertTrue(method_exists($aesCbc, 'getCipherKey')); $this->assertTrue(method_exists($legacy, 'getCipherKey')); - + $this->assertEquals('key1', $aesCbc->getCipherKey()); $this->assertEquals('key2', $legacy->getCipherKey()); } @@ -325,10 +325,10 @@ public function testBothCryptorsHaveGetIVMethod(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); - + $this->assertTrue(method_exists($aesCbc, 'getIV')); $this->assertTrue(method_exists($legacy, 'getIV')); - + $this->assertEquals(16, strlen($aesCbc->getIV())); $this->assertEquals(16, strlen($legacy->getIV())); } @@ -337,7 +337,7 @@ public function testBothCryptorsImplementEncryptAndDecrypt(): void { $aesCbc = new AesCbcCryptor('key'); $legacy = new LegacyCryptor('key', false); - + $this->assertTrue(method_exists($aesCbc, 'encrypt')); $this->assertTrue(method_exists($aesCbc, 'decrypt')); $this->assertTrue(method_exists($legacy, 'encrypt')); diff --git a/tests/unit/ListenerManagerTest.php b/tests/unit/ListenerManagerTest.php index f4ce19c..a76b580 100644 --- a/tests/unit/ListenerManagerTest.php +++ b/tests/unit/ListenerManagerTest.php @@ -1,6 +1,5 @@ assertEquals(10, $config->getNonSubscribeRequestTimeout()); } @@ -21,9 +21,9 @@ public function testSetNonSubscribeRequestTimeout(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setNonSubscribeRequestTimeout(20); - + $this->assertEquals(20, $config->getNonSubscribeRequestTimeout()); } @@ -31,9 +31,9 @@ public function testSetNonSubscribeRequestTimeoutWithZero(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setNonSubscribeRequestTimeout(0); - + $this->assertEquals(0, $config->getNonSubscribeRequestTimeout()); } @@ -41,16 +41,16 @@ public function testSetNonSubscribeRequestTimeoutWithLargeValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setNonSubscribeRequestTimeout(3600); - + $this->assertEquals(3600, $config->getNonSubscribeRequestTimeout()); } public function testGetSubscribeTimeoutReturnsDefault(): void { $config = new PNConfiguration(); - + $this->assertEquals(310, $config->getSubscribeTimeout()); } @@ -58,9 +58,9 @@ public function testSetSubscribeTimeout(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setSubscribeTimeout(400); - + $this->assertEquals(400, $config->getSubscribeTimeout()); } @@ -68,9 +68,9 @@ public function testSetSubscribeTimeoutWithMinimalValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setSubscribeTimeout(1); - + $this->assertEquals(1, $config->getSubscribeTimeout()); } @@ -78,16 +78,16 @@ public function testSetSubscribeTimeoutWithLargeValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setSubscribeTimeout(10000); - + $this->assertEquals(10000, $config->getSubscribeTimeout()); } public function testGetConnectTimeoutReturnsDefault(): void { $config = new PNConfiguration(); - + $this->assertEquals(10, $config->getConnectTimeout()); } @@ -95,9 +95,9 @@ public function testSetConnectTimeout(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setConnectTimeout(15); - + $this->assertEquals(15, $config->getConnectTimeout()); } @@ -105,9 +105,9 @@ public function testSetConnectTimeoutWithMinimalValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setConnectTimeout(1); - + $this->assertEquals(1, $config->getConnectTimeout()); } @@ -115,9 +115,9 @@ public function testSetConnectTimeoutWithLargeValue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setConnectTimeout(300); - + $this->assertEquals(300, $config->getConnectTimeout()); } @@ -125,11 +125,11 @@ public function testAllTimeoutSettingsTogether(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setNonSubscribeRequestTimeout(25); $config->setSubscribeTimeout(350); $config->setConnectTimeout(20); - + $this->assertEquals(25, $config->getNonSubscribeRequestTimeout()); $this->assertEquals(350, $config->getSubscribeTimeout()); $this->assertEquals(20, $config->getConnectTimeout()); @@ -142,7 +142,7 @@ public function testAllTimeoutSettingsTogether(): void public function testIsSecureReturnsDefaultTrue(): void { $config = new PNConfiguration(); - + $this->assertTrue($config->isSecure()); } @@ -150,9 +150,9 @@ public function testSetSecureFalse(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setSecure(false); - + $this->assertFalse($config->isSecure()); } @@ -160,10 +160,10 @@ public function testSetSecureTrue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setSecure(false); $this->assertFalse($config->isSecure()); - + $config->setSecure(true); $this->assertTrue($config->isSecure()); } @@ -172,10 +172,10 @@ public function testSetSecureDefaultsToTrue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setSecure(false); $config->setSecure(); // No parameter, should default to true - + $this->assertTrue($config->isSecure()); } @@ -183,12 +183,12 @@ public function testSetSecureCanBeToggled(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $this->assertTrue($config->isSecure()); - + $config->setSecure(false); $this->assertFalse($config->isSecure()); - + $config->setSecure(true); $this->assertTrue($config->isSecure()); } @@ -200,7 +200,7 @@ public function testSetSecureCanBeToggled(): void public function testGetOriginReturnsNullByDefault(): void { $config = new PNConfiguration(); - + $this->assertNull($config->getOrigin()); } @@ -208,9 +208,9 @@ public function testSetOriginAndGetOrigin(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setOrigin('custom.pubnub.com'); - + $this->assertEquals('custom.pubnub.com', $config->getOrigin()); } @@ -218,9 +218,9 @@ public function testSetOriginWithIPAddress(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setOrigin('192.168.1.100'); - + $this->assertEquals('192.168.1.100', $config->getOrigin()); } @@ -228,9 +228,9 @@ public function testSetOriginWithPort(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setOrigin('localhost:8080'); - + $this->assertEquals('localhost:8080', $config->getOrigin()); } @@ -238,10 +238,10 @@ public function testSetOriginOverwritesPrevious(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setOrigin('first-origin.com'); $this->assertEquals('first-origin.com', $config->getOrigin()); - + $config->setOrigin('second-origin.com'); $this->assertEquals('second-origin.com', $config->getOrigin()); } @@ -253,7 +253,7 @@ public function testSetOriginOverwritesPrevious(): void public function testGetAuthKeyReturnsNullByDefault(): void { $config = new PNConfiguration(); - + $this->assertNull($config->getAuthKey()); } @@ -261,9 +261,9 @@ public function testSetAuthKeyAndGetAuthKey(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setAuthKey('my-auth-key'); - + $this->assertEquals('my-auth-key', $config->getAuthKey()); } @@ -271,9 +271,9 @@ public function testSetAuthKeyWithEmptyString(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setAuthKey(''); - + $this->assertEquals('', $config->getAuthKey()); } @@ -281,10 +281,10 @@ public function testSetAuthKeyWithSpecialCharacters(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $authKey = 'auth!@#$%^&*()_+-={}[]|:;<>?,./'; $config->setAuthKey($authKey); - + $this->assertEquals($authKey, $config->getAuthKey()); } @@ -292,10 +292,10 @@ public function testSetAuthKeyOverwritesPrevious(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setAuthKey('first-key'); $this->assertEquals('first-key', $config->getAuthKey()); - + $config->setAuthKey('second-key'); $this->assertEquals('second-key', $config->getAuthKey()); } @@ -307,7 +307,7 @@ public function testSetAuthKeyOverwritesPrevious(): void public function testGetFilterExpressionReturnsNullByDefault(): void { $config = new PNConfiguration(); - + $this->assertNull($config->getFilterExpression()); } @@ -315,9 +315,9 @@ public function testSetFilterExpressionAndGetFilterExpression(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setFilterExpression('uuid == "user123"'); - + $this->assertEquals('uuid == "user123"', $config->getFilterExpression()); } @@ -325,10 +325,10 @@ public function testSetFilterExpressionWithComplexExpression(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $expression = 'uuid == "admin" && region == "us-east"'; $config->setFilterExpression($expression); - + $this->assertEquals($expression, $config->getFilterExpression()); } @@ -336,10 +336,10 @@ public function testSetFilterExpressionOverwritesPrevious(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setFilterExpression('first-expression'); $this->assertEquals('first-expression', $config->getFilterExpression()); - + $config->setFilterExpression('second-expression'); $this->assertEquals('second-expression', $config->getFilterExpression()); } @@ -351,7 +351,7 @@ public function testSetFilterExpressionOverwritesPrevious(): void public function testIsAesEnabledReturnsFalseByDefault(): void { $config = new PNConfiguration(); - + $this->assertFalse($config->isAesEnabled()); } @@ -360,7 +360,7 @@ public function testIsAesEnabledReturnsTrueWhenCipherKeySet(): void $config = new PNConfiguration(); $config->setUserId('test-user'); $config->setCipherKey('test-key'); - + $this->assertTrue($config->isAesEnabled()); } @@ -368,17 +368,17 @@ public function testIsAesEnabledReturnsTrueWhenCryptoModuleSet(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $cryptoModule = CryptoModule::legacyCryptor('key', false); $config->setCryptoModule($cryptoModule); - + $this->assertTrue($config->isAesEnabled()); } public function testGetCryptoSafeReturnsNullWhenNotConfigured(): void { $config = new PNConfiguration(); - + $this->assertNull($config->getCryptoSafe()); } @@ -387,19 +387,19 @@ public function testGetCryptoSafeReturnsCryptoWhenConfigured(): void $config = new PNConfiguration(); $config->setUserId('test-user'); $config->setCipherKey('test-key'); - + $crypto = $config->getCryptoSafe(); - + $this->assertInstanceOf(CryptoModule::class, $crypto); } public function testGetCryptoSafeDoesNotThrowException(): void { $config = new PNConfiguration(); - + // This should not throw an exception $crypto = $config->getCryptoSafe(); - + $this->assertNull($crypto); } @@ -407,19 +407,19 @@ public function testSetCryptoModuleAndGetCryptoSafe(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $cryptoModule = CryptoModule::aesCbcCryptor('my-key', true); $config->setCryptoModule($cryptoModule); - + $crypto = $config->getCryptoSafe(); - + $this->assertSame($cryptoModule, $crypto); } public function testGetUseRandomIVReturnsDefaultTrue(): void { $config = new PNConfiguration(); - + $this->assertTrue($config->getUseRandomIV()); } @@ -427,9 +427,9 @@ public function testSetUseRandomIVFalse(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setUseRandomIV(false); - + $this->assertFalse($config->getUseRandomIV()); } @@ -437,10 +437,10 @@ public function testSetUseRandomIVTrue(): void { $config = new PNConfiguration(); $config->setUserId('test-user'); - + $config->setUseRandomIV(false); $config->setUseRandomIV(true); - + $this->assertTrue($config->getUseRandomIV()); } @@ -451,7 +451,7 @@ public function testSetUseRandomIVTrue(): void public function testGetPublishKeyReturnsNull(): void { $config = new PNConfiguration(); - + $this->assertNull($config->getPublishKey()); } @@ -460,14 +460,14 @@ public function testGetPublishKeyReturnsSetValue(): void $config = new PNConfiguration(); $config->setUserId('test-user'); $config->setPublishKey('pub-key-123'); - + $this->assertEquals('pub-key-123', $config->getPublishKey()); } public function testGetSecretKeyReturnsNull(): void { $config = new PNConfiguration(); - + $this->assertNull($config->getSecretKey()); } @@ -476,7 +476,7 @@ public function testGetSecretKeyReturnsSetValue(): void $config = new PNConfiguration(); $config->setUserId('test-user'); $config->setSecretKey('sec-key-456'); - + $this->assertEquals('sec-key-456', $config->getSecretKey()); } @@ -485,7 +485,7 @@ public function testGetSubscribeKeyReturnsSetValue(): void $config = new PNConfiguration(); $config->setUserId('test-user'); $config->setSubscribeKey('sub-key-789'); - + $this->assertEquals('sub-key-789', $config->getSubscribeKey()); } @@ -498,9 +498,9 @@ public function testCloneCreatesNewInstance(): void $config = new PNConfiguration(); $config->setUserId('test-user'); $config->setSubscribeKey('demo'); - + $cloned = $config->clone(); - + $this->assertNotSame($config, $cloned); } @@ -514,9 +514,9 @@ public function testClonePreservesValues(): void $config->setOrigin('custom-origin.com'); $config->setAuthKey('auth-key'); $config->setSecure(false); - + $cloned = $config->clone(); - + $this->assertEquals('test-user', $cloned->getUserId()); $this->assertEquals('sub-key', $cloned->getSubscribeKey()); $this->assertEquals('pub-key', $cloned->getPublishKey()); @@ -533,9 +533,9 @@ public function testClonePreservesTimeoutSettings(): void $config->setNonSubscribeRequestTimeout(25); $config->setSubscribeTimeout(400); $config->setConnectTimeout(15); - + $cloned = $config->clone(); - + $this->assertEquals(25, $cloned->getNonSubscribeRequestTimeout()); $this->assertEquals(400, $cloned->getSubscribeTimeout()); $this->assertEquals(15, $cloned->getConnectTimeout()); @@ -547,9 +547,9 @@ public function testCloneCreatesUnlockedConfiguration(): void $config->setUserId('test-user'); $config->setSubscribeKey('demo'); $config->lock(); - + $cloned = $config->clone(); - + // Cloned config should not be locked, so this should not throw $cloned->setPublishKey('new-pub-key'); $this->assertEquals('new-pub-key', $cloned->getPublishKey()); @@ -560,15 +560,15 @@ public function testCloneIsIndependent(): void $config = new PNConfiguration(); $config->setUserId('original-user'); $config->setSubscribeKey('original-key'); - + $cloned = $config->clone(); $cloned->setUserId('cloned-user'); $cloned->setSubscribeKey('cloned-key'); - + // Original should be unchanged $this->assertEquals('original-user', $config->getUserId()); $this->assertEquals('original-key', $config->getSubscribeKey()); - + // Cloned should have new values $this->assertEquals('cloned-user', $cloned->getUserId()); $this->assertEquals('cloned-key', $cloned->getSubscribeKey()); @@ -594,7 +594,7 @@ public function testFullConfigurationSetup(): void $config->setFilterExpression('uuid != "bot"'); $config->setUseRandomIV(true); $config->setCipherKey('cipher-key'); - + // Verify all values $this->assertEquals('test-user', $config->getUserId()); $this->assertEquals('sub-key', $config->getSubscribeKey()); diff --git a/tests/unit/PNConfigurationTest.php b/tests/unit/PNConfigurationTest.php index ff880b6..adfe438 100644 --- a/tests/unit/PNConfigurationTest.php +++ b/tests/unit/PNConfigurationTest.php @@ -6,7 +6,6 @@ use PubNub\PNConfiguration; use PubNub\PubNubUtil; - class PNConfigurationTest extends TestCase { public function testInitWithUUID() diff --git a/tests/unit/PubNubCborDecodeTest.php b/tests/unit/PubNubCborDecodeTest.php index 1dbab61..6257b76 100644 --- a/tests/unit/PubNubCborDecodeTest.php +++ b/tests/unit/PubNubCborDecodeTest.php @@ -192,7 +192,7 @@ public function testDecodeHashmapNested(): void public function testDecodeHashmapWithArray(): void { // Map {"array": [1, 2, 3]} - $result = PubNubCborDecode::decode('A16561727261798301 0203'); + $result = PubNubCborDecode::decode('A16561727261798301 0203'); $this->assertEquals(['array' => [1, 2, 3]], $result); } @@ -285,9 +285,9 @@ public function testDecodeComplexNestedStructure(): void '65416C696365' . // value: "Alice" '63616765' . // key: "age" '181E'; // value: 30 - + $result = PubNubCborDecode::decode($cbor); - + $this->assertIsArray($result); $this->assertArrayHasKey('users', $result); $this->assertIsArray($result['users']); @@ -304,9 +304,9 @@ public function testDecodeArrayOfMixedPrimitives(): void '6474657374' . // "test" 'F5' . // true 'F6'; // null - + $result = PubNubCborDecode::decode($cbor); - + $this->assertEquals([42, 'test', true, null], $result); } @@ -343,7 +343,7 @@ public function testDecodeInvalidHexCharacters(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Input'); - + PubNubCborDecode::decode('GG'); } @@ -351,7 +351,7 @@ public function testDecodeInvalidHexWithSpecialChars(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Input'); - + PubNubCborDecode::decode('18@A'); } @@ -359,7 +359,7 @@ public function testDecodeInvalidHexWithNonHexLetters(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid Input'); - + PubNubCborDecode::decode('18ZZ'); } @@ -399,7 +399,7 @@ public function testDecodeArrayWith1ByteLength(): void for ($i = 0; $i < 24; $i++) { $cbor .= '0' . dechex($i % 16); // Add elements 0-15 repeated } - + $result = PubNubCborDecode::decode($cbor); $this->assertCount(24, $result); } @@ -413,7 +413,7 @@ public function testDecodeMapWith1ByteLength(): void $cbor .= '61' . bin2hex($key); // key $cbor .= '0' . dechex($i % 16); // value } - + $result = PubNubCborDecode::decode($cbor); $this->assertCount(24, $result); } @@ -446,7 +446,7 @@ public function testDecodeStringWithSpecialCharacters(): void $hex = bin2hex($specialString); $length = strlen($specialString); $cbor = '6' . dechex($length) . $hex; - + $result = PubNubCborDecode::decode($cbor); $this->assertEquals($specialString, $result); } diff --git a/tests/unit/PubNubCryptoMethodsTest.php b/tests/unit/PubNubCryptoMethodsTest.php index c833deb..5dc7048 100644 --- a/tests/unit/PubNubCryptoMethodsTest.php +++ b/tests/unit/PubNubCryptoMethodsTest.php @@ -16,9 +16,9 @@ public function testIsCryptoEnabledReturnsFalseByDefault(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); - + $this->assertFalse($pubnub->isCryptoEnabled()); } @@ -28,9 +28,9 @@ public function testIsCryptoEnabledReturnsTrueWhenCipherKeySet(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setCipherKey('test-cipher-key'); - + $pubnub = new PubNub($config); - + $this->assertTrue($pubnub->isCryptoEnabled()); } @@ -39,11 +39,11 @@ public function testIsCryptoEnabledReturnsTrueWhenCryptoModuleSet(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::legacyCryptor('test-key', false); $pubnub->setCrypto($cryptoModule); - + $this->assertTrue($pubnub->isCryptoEnabled()); } @@ -52,13 +52,13 @@ public function testIsCryptoEnabledAfterSettingCryptoOnPubNub(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $this->assertFalse($pubnub->isCryptoEnabled()); - + $cryptoModule = CryptoModule::aesCbcCryptor('my-key', true); $pubnub->setCrypto($cryptoModule); - + $this->assertTrue($pubnub->isCryptoEnabled()); } @@ -71,9 +71,9 @@ public function testGetCryptoReturnsNullWhenNotConfigured(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); - + $this->assertNull($pubnub->getCrypto()); } @@ -83,10 +83,10 @@ public function testGetCryptoReturnsModuleWhenCipherKeySet(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setCipherKey('test-cipher-key'); - + $pubnub = new PubNub($config); $crypto = $pubnub->getCrypto(); - + $this->assertInstanceOf(CryptoModule::class, $crypto); } @@ -95,13 +95,13 @@ public function testGetCryptoReturnsModuleWhenCryptoModuleSet(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::legacyCryptor('test-key', false); $pubnub->setCrypto($cryptoModule); - + $crypto = $pubnub->getCrypto(); - + $this->assertInstanceOf(CryptoModule::class, $crypto); $this->assertSame($cryptoModule, $crypto); } @@ -112,10 +112,10 @@ public function testGetCryptoReturnsConfigurationCryptoWhenNoPubNubCrypto(): voi $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setCipherKey('config-key'); - + $pubnub = new PubNub($config); $crypto = $pubnub->getCrypto(); - + $this->assertInstanceOf(CryptoModule::class, $crypto); } @@ -125,14 +125,14 @@ public function testGetCryptoPrefersInstanceCryptoOverConfiguration(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setCipherKey('config-key'); - + $pubnub = new PubNub($config); - + $instanceCrypto = CryptoModule::aesCbcCryptor('instance-key', true); $pubnub->setCrypto($instanceCrypto); - + $crypto = $pubnub->getCrypto(); - + $this->assertSame($instanceCrypto, $crypto); } @@ -145,12 +145,12 @@ public function testSetCryptoStoresModule(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::legacyCryptor('my-cipher-key', false); - + $pubnub->setCrypto($cryptoModule); - + $this->assertSame($cryptoModule, $pubnub->getCrypto()); } @@ -159,13 +159,13 @@ public function testSetCryptoOverwritesPreviousCrypto(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); - + $crypto1 = CryptoModule::legacyCryptor('key1', false); $pubnub->setCrypto($crypto1); $this->assertSame($crypto1, $pubnub->getCrypto()); - + $crypto2 = CryptoModule::aesCbcCryptor('key2', true); $pubnub->setCrypto($crypto2); $this->assertSame($crypto2, $pubnub->getCrypto()); @@ -176,13 +176,13 @@ public function testSetCryptoEnablesCrypto(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $this->assertFalse($pubnub->isCryptoEnabled()); - + $cryptoModule = CryptoModule::legacyCryptor('my-key', false); $pubnub->setCrypto($cryptoModule); - + $this->assertTrue($pubnub->isCryptoEnabled()); } @@ -191,12 +191,12 @@ public function testSetCryptoWithLegacyCryptor(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::legacyCryptor('legacy-key', false); - + $pubnub->setCrypto($cryptoModule); - + $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); } @@ -205,12 +205,12 @@ public function testSetCryptoWithAesCbcCryptor(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::aesCbcCryptor('aes-key', true); - + $pubnub->setCrypto($cryptoModule); - + $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); } @@ -219,12 +219,12 @@ public function testSetCryptoWithRandomIV(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::legacyCryptor('test-key', true); - + $pubnub->setCrypto($cryptoModule); - + $crypto = $pubnub->getCrypto(); $this->assertNotNull($crypto); } @@ -234,12 +234,12 @@ public function testSetCryptoWithStaticIV(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::legacyCryptor('test-key', false); - + $pubnub->setCrypto($cryptoModule); - + $crypto = $pubnub->getCrypto(); $this->assertNotNull($crypto); } @@ -254,9 +254,9 @@ public function testCryptoWorkflowConfigurationOnly(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setCipherKey('config-cipher-key'); - + $pubnub = new PubNub($config); - + $this->assertTrue($pubnub->isCryptoEnabled()); $this->assertInstanceOf(CryptoModule::class, $pubnub->getCrypto()); } @@ -266,13 +266,13 @@ public function testCryptoWorkflowInstanceOnly(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $this->assertFalse($pubnub->isCryptoEnabled()); - + $cryptoModule = CryptoModule::aesCbcCryptor('instance-key', true); $pubnub->setCrypto($cryptoModule); - + $this->assertTrue($pubnub->isCryptoEnabled()); $this->assertSame($cryptoModule, $pubnub->getCrypto()); } @@ -283,13 +283,13 @@ public function testCryptoWorkflowBothConfigurationAndInstance(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setCipherKey('config-key'); - + $pubnub = new PubNub($config); $this->assertTrue($pubnub->isCryptoEnabled()); - + $instanceCrypto = CryptoModule::legacyCryptor('instance-key', false); $pubnub->setCrypto($instanceCrypto); - + $this->assertTrue($pubnub->isCryptoEnabled()); $this->assertSame($instanceCrypto, $pubnub->getCrypto()); } @@ -299,17 +299,17 @@ public function testCryptoCanBeUsedForEncryptionDecryption(): void $config = new PNConfiguration(); $config->setSubscribeKey('demo'); $config->setUserId('test-user'); - + $pubnub = new PubNub($config); $cryptoModule = CryptoModule::aesCbcCryptor('encryption-key', false); $pubnub->setCrypto($cryptoModule); - + $crypto = $pubnub->getCrypto(); - + $plaintext = 'Hello, World!'; $encrypted = $crypto->encrypt($plaintext); $decrypted = $crypto->decrypt($encrypted); - + $this->assertEquals($plaintext, $decrypted); } @@ -321,14 +321,14 @@ public function testMultiplePubNubInstancesWithDifferentCrypto(): void $pubnub1 = new PubNub($config1); $crypto1 = CryptoModule::legacyCryptor('key1', false); $pubnub1->setCrypto($crypto1); - + $config2 = new PNConfiguration(); $config2->setSubscribeKey('demo'); $config2->setUserId('user2'); $pubnub2 = new PubNub($config2); $crypto2 = CryptoModule::aesCbcCryptor('key2', true); $pubnub2->setCrypto($crypto2); - + $this->assertNotSame($pubnub1->getCrypto(), $pubnub2->getCrypto()); $this->assertSame($crypto1, $pubnub1->getCrypto()); $this->assertSame($crypto2, $pubnub2->getCrypto()); @@ -340,14 +340,14 @@ public function testCryptoModuleCanBeRetrievedAndUsedDirectly(): void $config->setSubscribeKey('demo'); $config->setUserId('test-user'); $config->setCipherKey('direct-use-key'); - + $pubnub = new PubNub($config); $crypto = $pubnub->getCrypto(); - + // Use crypto module directly $message = 'Test message'; $encrypted = $crypto->encrypt($message); - + $this->assertNotEquals($message, $encrypted); $this->assertIsString($encrypted); } diff --git a/tests/unit/PubNubFactoryMethodsTest.php b/tests/unit/PubNubFactoryMethodsTest.php index e1e1a18..be7169b 100644 --- a/tests/unit/PubNubFactoryMethodsTest.php +++ b/tests/unit/PubNubFactoryMethodsTest.php @@ -13,7 +13,7 @@ class PubNubFactoryMethodsTest extends TestCase public function testDemoReturnsValidPubNubInstance(): void { $pubnub = PubNub::demo(); - + $this->assertInstanceOf(PubNub::class, $pubnub); } @@ -21,7 +21,7 @@ public function testDemoHasDemoKeys(): void { $pubnub = PubNub::demo(); $config = $pubnub->getConfiguration(); - + $this->assertEquals('demo', $config->getSubscribeKey()); $this->assertEquals('demo', $config->getPublishKey()); } @@ -30,17 +30,17 @@ public function testDemoHasDemoUserId(): void { $pubnub = PubNub::demo(); $config = $pubnub->getConfiguration(); - + $this->assertEquals('demo', $config->getUserId()); } public function testDemoIsImmediatelyUsable(): void { $pubnub = PubNub::demo(); - + // Should be able to call methods without configuration errors $config = $pubnub->getConfiguration(); - + $this->assertNotNull($config->getSubscribeKey()); $this->assertNotNull($config->getPublishKey()); $this->assertNotNull($config->getUserId()); @@ -50,7 +50,7 @@ public function testDemoCreatesNewInstanceEachTime(): void { $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); - + $this->assertNotSame($pubnub1, $pubnub2); } @@ -58,11 +58,11 @@ public function testDemoInstancesAreIndependent(): void { $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); - + // Modify one instance $pubnub1->setToken('token1'); $pubnub2->setToken('token2'); - + $this->assertEquals('token1', $pubnub1->getToken()); $this->assertEquals('token2', $pubnub2->getToken()); } @@ -71,7 +71,7 @@ public function testDemoConfigurationIsLocked(): void { $pubnub = PubNub::demo(); $config = $pubnub->getConfiguration(); - + // Configuration should be locked after being passed to PubNub constructor $this->expectException(\PubNub\Exceptions\PubNubConfigurationException::class); $config->setPublishKey('new-key'); @@ -80,7 +80,7 @@ public function testDemoConfigurationIsLocked(): void public function testDemoCanBeUsedForBasicOperations(): void { $pubnub = PubNub::demo(); - + // Should be able to create endpoint builders $this->assertNotNull($pubnub->publish()); $this->assertNotNull($pubnub->subscribe()); @@ -94,46 +94,46 @@ public function testDemoCanBeUsedForBasicOperations(): void public function testDemoKeysReturnsValidConfiguration(): void { $config = PNConfiguration::demoKeys(); - + $this->assertInstanceOf(PNConfiguration::class, $config); } public function testDemoKeysHasSubscribeKey(): void { $config = PNConfiguration::demoKeys(); - + $this->assertEquals('demo', $config->getSubscribeKey()); } public function testDemoKeysHasPublishKey(): void { $config = PNConfiguration::demoKeys(); - + $this->assertEquals('demo', $config->getPublishKey()); } public function testDemoKeysHasUserId(): void { $config = PNConfiguration::demoKeys(); - + $this->assertEquals('demo', $config->getUserId()); } public function testDemoKeysConfigurationIsNotLocked(): void { $config = PNConfiguration::demoKeys(); - + // Should be able to modify the configuration $config->setPublishKey('new-pub-key'); $this->assertEquals('new-pub-key', $config->getPublishKey()); - + $config->setSubscribeKey('new-sub-key'); $this->assertEquals('new-sub-key', $config->getSubscribeKey()); - + // Test other modifiable properties (userId has special handling due to UUID/UserId distinction) $config->setSecure(false); $this->assertFalse($config->isSecure()); - + $config->setOrigin('custom.origin.com'); $this->assertEquals('custom.origin.com', $config->getOrigin()); } @@ -142,7 +142,7 @@ public function testDemoKeysCreatesNewInstanceEachTime(): void { $config1 = PNConfiguration::demoKeys(); $config2 = PNConfiguration::demoKeys(); - + $this->assertNotSame($config1, $config2); } @@ -150,10 +150,10 @@ public function testDemoKeysInstancesAreIndependent(): void { $config1 = PNConfiguration::demoKeys(); $config2 = PNConfiguration::demoKeys(); - + $config1->setPublishKey('key1'); $config2->setPublishKey('key2'); - + $this->assertEquals('key1', $config1->getPublishKey()); $this->assertEquals('key2', $config2->getPublishKey()); } @@ -161,12 +161,12 @@ public function testDemoKeysInstancesAreIndependent(): void public function testDemoKeysCanBeCustomized(): void { $config = PNConfiguration::demoKeys(); - + // Customize the demo configuration $config->setSecure(false); $config->setOrigin('custom-origin.pubnub.com'); $config->setAuthKey('auth-key-123'); - + $this->assertFalse($config->isSecure()); $this->assertEquals('custom-origin.pubnub.com', $config->getOrigin()); $this->assertEquals('auth-key-123', $config->getAuthKey()); @@ -176,9 +176,9 @@ public function testDemoKeysCanBeUsedToCreatePubNub(): void { $config = PNConfiguration::demoKeys(); $pubnub = new PubNub($config); - + $this->assertInstanceOf(PubNub::class, $pubnub); - + $retrievedConfig = $pubnub->getConfiguration(); $this->assertEquals('demo', $retrievedConfig->getSubscribeKey()); $this->assertEquals('demo', $retrievedConfig->getPublishKey()); @@ -188,14 +188,14 @@ public function testDemoKeysCanBeUsedToCreatePubNub(): void public function testDemoKeysHasDefaultSecureSettings(): void { $config = PNConfiguration::demoKeys(); - + $this->assertTrue($config->isSecure()); } public function testDemoKeysHasDefaultTimeouts(): void { $config = PNConfiguration::demoKeys(); - + $this->assertEquals(10, $config->getNonSubscribeRequestTimeout()); $this->assertEquals(310, $config->getSubscribeTimeout()); $this->assertEquals(10, $config->getConnectTimeout()); @@ -209,9 +209,9 @@ public function testDemoMethodUsesDemoKeysInternally(): void { $demoConfig = PNConfiguration::demoKeys(); $demoPubNub = PubNub::demo(); - + $config = $demoPubNub->getConfiguration(); - + // Should have same values as demoKeys() $this->assertEquals($demoConfig->getSubscribeKey(), $config->getSubscribeKey()); $this->assertEquals($demoConfig->getPublishKey(), $config->getPublishKey()); @@ -223,7 +223,7 @@ public function testDemoKeysAndDemoProduceSimilarResults(): void $configFromDemoKeys = PNConfiguration::demoKeys(); $pubnubFromDemo = PubNub::demo(); $configFromDemo = $pubnubFromDemo->getConfiguration(); - + $this->assertEquals( $configFromDemoKeys->getSubscribeKey(), $configFromDemo->getSubscribeKey() @@ -242,7 +242,7 @@ public function testDemoKeysCanBeCloned(): void { $config = PNConfiguration::demoKeys(); $cloned = $config->clone(); - + $this->assertNotSame($config, $cloned); $this->assertEquals('demo', $cloned->getSubscribeKey()); $this->assertEquals('demo', $cloned->getPublishKey()); @@ -254,11 +254,11 @@ public function testMultipleDemoInstancesCanCoexist(): void $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); $pubnub3 = PubNub::demo(); - + $this->assertInstanceOf(PubNub::class, $pubnub1); $this->assertInstanceOf(PubNub::class, $pubnub2); $this->assertInstanceOf(PubNub::class, $pubnub3); - + $this->assertNotSame($pubnub1, $pubnub2); $this->assertNotSame($pubnub2, $pubnub3); $this->assertNotSame($pubnub1, $pubnub3); diff --git a/tests/unit/PubNubSdkInfoTest.php b/tests/unit/PubNubSdkInfoTest.php index 0223c85..8dd754d 100644 --- a/tests/unit/PubNubSdkInfoTest.php +++ b/tests/unit/PubNubSdkInfoTest.php @@ -12,21 +12,21 @@ class PubNubSdkInfoTest extends TestCase public function testGetSdkVersionReturnsString(): void { $version = PubNub::getSdkVersion(); - + $this->assertIsString($version); } public function testGetSdkVersionIsNotEmpty(): void { $version = PubNub::getSdkVersion(); - + $this->assertNotEmpty($version); } public function testGetSdkVersionFollowsSemanticVersioning(): void { $version = PubNub::getSdkVersion(); - + // Should match semantic versioning pattern (e.g., 7.1.0, 7.1.0-beta.1, etc.) $pattern = '/^\d+\.\d+\.\d+(-[a-zA-Z0-9\.\-]+)?$/'; $this->assertMatchesRegularExpression($pattern, $version); @@ -36,21 +36,21 @@ public function testGetSdkVersionIsConsistent(): void { $version1 = PubNub::getSdkVersion(); $version2 = PubNub::getSdkVersion(); - + $this->assertEquals($version1, $version2); } public function testGetSdkVersionStartsWithDigit(): void { $version = PubNub::getSdkVersion(); - + $this->assertMatchesRegularExpression('/^\d/', $version); } public function testGetSdkVersionContainsMajorMinorPatch(): void { $version = PubNub::getSdkVersion(); - + // Split by '.' and check we have at least 3 parts (major.minor.patch) $parts = explode('.', $version); $this->assertGreaterThanOrEqual(3, count($parts)); @@ -60,7 +60,7 @@ public function testGetSdkVersionMajorVersionIsNumeric(): void { $version = PubNub::getSdkVersion(); $parts = explode('.', $version); - + $this->assertIsNumeric($parts[0]); } @@ -68,7 +68,7 @@ public function testGetSdkVersionMinorVersionIsNumeric(): void { $version = PubNub::getSdkVersion(); $parts = explode('.', $version); - + $this->assertIsNumeric($parts[1]); } @@ -76,7 +76,7 @@ public function testGetSdkVersionPatchVersionIsNumeric(): void { $version = PubNub::getSdkVersion(); $parts = explode('.', $version); - + // Patch might have a pre-release suffix (e.g., 0-beta) // So we extract just the numeric part preg_match('/^(\d+)/', $parts[2], $matches); @@ -90,14 +90,14 @@ public function testGetSdkVersionPatchVersionIsNumeric(): void public function testGetSdkNameReturnsString(): void { $name = PubNub::getSdkName(); - + $this->assertIsString($name); } public function testGetSdkNameIsNotEmpty(): void { $name = PubNub::getSdkName(); - + $this->assertNotEmpty($name); } @@ -105,14 +105,14 @@ public function testGetSdkNameIsConsistent(): void { $name1 = PubNub::getSdkName(); $name2 = PubNub::getSdkName(); - + $this->assertEquals($name1, $name2); } public function testGetSdkNameContainsPHP(): void { $name = PubNub::getSdkName(); - + // SDK name should indicate it's a PHP SDK $this->assertMatchesRegularExpression('/php/i', $name); } @@ -120,7 +120,7 @@ public function testGetSdkNameContainsPHP(): void public function testGetSdkNameContainsPubNub(): void { $name = PubNub::getSdkName(); - + // SDK name should contain "PubNub" $this->assertMatchesRegularExpression('/pubnub/i', $name); } @@ -128,7 +128,7 @@ public function testGetSdkNameContainsPubNub(): void public function testGetSdkNameFormat(): void { $name = PubNub::getSdkName(); - + // Should be in format like "PubNub-PHP" or similar $this->assertMatchesRegularExpression('/^[a-zA-Z\-]+$/', $name); } @@ -136,7 +136,7 @@ public function testGetSdkNameFormat(): void public function testGetSdkNameDoesNotContainVersion(): void { $name = PubNub::getSdkName(); - + // Name should not contain version numbers $this->assertDoesNotMatchRegularExpression('/\d+\.\d+/', $name); } @@ -148,14 +148,14 @@ public function testGetSdkNameDoesNotContainVersion(): void public function testGetSdkFullNameReturnsString(): void { $fullName = PubNub::getSdkFullName(); - + $this->assertIsString($fullName); } public function testGetSdkFullNameIsNotEmpty(): void { $fullName = PubNub::getSdkFullName(); - + $this->assertNotEmpty($fullName); } @@ -163,7 +163,7 @@ public function testGetSdkFullNameIsConsistent(): void { $fullName1 = PubNub::getSdkFullName(); $fullName2 = PubNub::getSdkFullName(); - + $this->assertEquals($fullName1, $fullName2); } @@ -171,7 +171,7 @@ public function testGetSdkFullNameContainsSdkName(): void { $name = PubNub::getSdkName(); $fullName = PubNub::getSdkFullName(); - + $this->assertStringContainsString($name, $fullName); } @@ -179,14 +179,14 @@ public function testGetSdkFullNameContainsSdkVersion(): void { $version = PubNub::getSdkVersion(); $fullName = PubNub::getSdkFullName(); - + $this->assertStringContainsString($version, $fullName); } public function testGetSdkFullNameFormat(): void { $fullName = PubNub::getSdkFullName(); - + // Should be in format like "PubNub-PHP/7.1.0" or "PubNub-PHP-7.1.0" $pattern = '/^[a-zA-Z\-]+[\/\-]\d+\.\d+\.\d+/'; $this->assertMatchesRegularExpression($pattern, $fullName); @@ -197,7 +197,7 @@ public function testGetSdkFullNameIsConcatenationOfNameAndVersion(): void $name = PubNub::getSdkName(); $version = PubNub::getSdkVersion(); $fullName = PubNub::getSdkFullName(); - + // Full name should be name + separator + version $expectedPattern = '/' . preg_quote($name, '/') . '[\/\-]' . preg_quote($version, '/') . '/'; $this->assertMatchesRegularExpression($expectedPattern, $fullName); @@ -207,7 +207,7 @@ public function testGetSdkFullNameLongerThanName(): void { $name = PubNub::getSdkName(); $fullName = PubNub::getSdkFullName(); - + $this->assertGreaterThan(strlen($name), strlen($fullName)); } @@ -215,7 +215,7 @@ public function testGetSdkFullNameLongerThanVersion(): void { $version = PubNub::getSdkVersion(); $fullName = PubNub::getSdkFullName(); - + $this->assertGreaterThan(strlen($version), strlen($fullName)); } @@ -228,7 +228,7 @@ public function testSdkInfoMethodsAreAllConsistent(): void $name = PubNub::getSdkName(); $version = PubNub::getSdkVersion(); $fullName = PubNub::getSdkFullName(); - + $this->assertStringContainsString($name, $fullName); $this->assertStringContainsString($version, $fullName); } @@ -247,7 +247,7 @@ public function testSdkInfoMethodsReturnSameValuesAcrossInstances(): void { $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); - + // Static methods should return same values regardless of instance $this->assertEquals(PubNub::getSdkName(), PubNub::getSdkName()); $this->assertEquals(PubNub::getSdkVersion(), PubNub::getSdkVersion()); @@ -257,14 +257,14 @@ public function testSdkInfoMethodsReturnSameValuesAcrossInstances(): void public function testSdkVersionCanBeParsed(): void { $version = PubNub::getSdkVersion(); - + // Should be parsable as a version string $parts = explode('.', $version); - + $this->assertGreaterThanOrEqual(3, count($parts)); $this->assertIsNumeric($parts[0]); // Major $this->assertIsNumeric($parts[1]); // Minor - + // Patch might have pre-release suffix, extract numeric part preg_match('/^(\d+)/', $parts[2], $matches); $this->assertNotEmpty($matches); @@ -274,7 +274,7 @@ public function testSdkVersionCanBeParsed(): void public function testSdkFullNameIsUsableForUserAgent(): void { $fullName = PubNub::getSdkFullName(); - + // Should be a valid format for User-Agent headers (no spaces, special chars) $this->assertMatchesRegularExpression('/^[a-zA-Z0-9\-\.\/]+$/', $fullName); } @@ -282,7 +282,7 @@ public function testSdkFullNameIsUsableForUserAgent(): void public function testSdkNameIsUsableAsIdentifier(): void { $name = PubNub::getSdkName(); - + // Should be a valid identifier (no spaces, no version numbers) $this->assertMatchesRegularExpression('/^[a-zA-Z\-]+$/', $name); } @@ -290,14 +290,14 @@ public function testSdkNameIsUsableAsIdentifier(): void public function testSdkVersionIsValidSemanticVersion(): void { $version = PubNub::getSdkVersion(); - + // Validate against semantic versioning 2.0.0 spec $semverPattern = '/^' . '(\d+)\.(\d+)\.(\d+)' // Major.Minor.Patch . '(-[0-9A-Za-z\-\.]+)?' // Pre-release (optional) . '(\+[0-9A-Za-z\-\.]+)?' // Build metadata (optional) . '$/'; - + $this->assertMatchesRegularExpression($semverPattern, $version); } @@ -307,11 +307,11 @@ public function testSdkInfoDoesNotChangeAtRuntime(): void $name1 = PubNub::getSdkName(); $version1 = PubNub::getSdkVersion(); $fullName1 = PubNub::getSdkFullName(); - + // Create some PubNub instances $pubnub1 = PubNub::demo(); $pubnub2 = PubNub::demo(); - + // Values should remain the same $this->assertEquals($name1, PubNub::getSdkName()); $this->assertEquals($version1, PubNub::getSdkVersion()); diff --git a/tests/unit/PubNubUtilExtendedTest.php b/tests/unit/PubNubUtilExtendedTest.php index ea905d2..bd7a789 100644 --- a/tests/unit/PubNubUtilExtendedTest.php +++ b/tests/unit/PubNubUtilExtendedTest.php @@ -14,9 +14,9 @@ public function testBuildUrlWithBasicParams(): void $basePath = 'https://ps.pndsn.com'; $path = '/v2/subscribe/demo/ch1/0'; $params = ['uuid' => 'test-user', 'pnsdk' => 'PubNub-PHP/8.0.0']; - + $url = PubNubUtil::buildUrl($basePath, $path, $params); - + $this->assertStringStartsWith($basePath . $path, $url); $this->assertStringContainsString('uuid=test-user', $url); $this->assertStringContainsString('pnsdk=PubNub-PHP/8.0.0', $url); @@ -27,9 +27,9 @@ public function testBuildUrlWithEmptyParams(): void $basePath = 'https://ps.pndsn.com'; $path = '/v2/time/0'; $params = []; - + $url = PubNubUtil::buildUrl($basePath, $path, $params); - + $this->assertEquals($basePath . $path . '?', $url); } @@ -38,9 +38,9 @@ public function testBuildUrlWithSpecialCharactersInParams(): void $basePath = 'https://ps.pndsn.com'; $path = '/publish'; $params = ['message' => 'hello%20world']; - + $url = PubNubUtil::buildUrl($basePath, $path, $params); - + $this->assertStringContainsString('message=hello%20world', $url); } @@ -53,9 +53,9 @@ public function testBuildUrlWithMultipleParams(): void 'count' => '100', 'reverse' => 'false' ]; - + $url = PubNubUtil::buildUrl($basePath, $path, $params); - + $this->assertStringContainsString('channel=test-channel', $url); $this->assertStringContainsString('count=100', $url); $this->assertStringContainsString('reverse=false', $url); @@ -68,45 +68,45 @@ public function testBuildUrlWithMultipleParams(): void public function testJoinChannelsWithSingleChannel(): void { $channels = ['channel1']; - + $result = PubNubUtil::joinChannels($channels); - + $this->assertEquals('channel1', $result); } public function testJoinChannelsWithMultipleChannels(): void { $channels = ['channel1', 'channel2', 'channel3']; - + $result = PubNubUtil::joinChannels($channels); - + $this->assertEquals('channel1,channel2,channel3', $result); } public function testJoinChannelsWithEmptyArray(): void { $channels = []; - + $result = PubNubUtil::joinChannels($channels); - + $this->assertEquals(',', $result); } public function testJoinChannelsWithSpecialCharacters(): void { $channels = ['channel-1', 'channel.2', 'channel_3']; - + $result = PubNubUtil::joinChannels($channels); - + $this->assertEquals('channel-1,channel.2,channel_3', $result); } public function testJoinChannelsEncodesSpecialCharacters(): void { $channels = ['channel with spaces', 'channel#special']; - + $result = PubNubUtil::joinChannels($channels); - + $this->assertStringContainsString('channel+with+spaces', $result); $this->assertStringContainsString('channel%23special', $result); } @@ -118,36 +118,36 @@ public function testJoinChannelsEncodesSpecialCharacters(): void public function testJoinItemsWithSingleItem(): void { $items = ['item1']; - + $result = PubNubUtil::joinItems($items); - + $this->assertEquals('item1', $result); } public function testJoinItemsWithMultipleItems(): void { $items = ['item1', 'item2', 'item3']; - + $result = PubNubUtil::joinItems($items); - + $this->assertEquals('item1,item2,item3', $result); } public function testJoinItemsWithEmptyArray(): void { $items = []; - + $result = PubNubUtil::joinItems($items); - + $this->assertEquals('', $result); } public function testJoinItemsWithNumericItems(): void { $items = ['1', '2', '3']; - + $result = PubNubUtil::joinItems($items); - + $this->assertEquals('1,2,3', $result); } @@ -159,9 +159,9 @@ public function testExtendArrayWithArrays(): void { $existing = ['a', 'b']; $new = ['c', 'd']; - + $result = PubNubUtil::extendArray($existing, $new); - + $this->assertEquals(['a', 'b', 'c', 'd'], $result); } @@ -169,9 +169,9 @@ public function testExtendArrayWithString(): void { $existing = ['a', 'b']; $new = 'c,d'; - + $result = PubNubUtil::extendArray($existing, $new); - + $this->assertEquals(['a', 'b', 'c', 'd'], $result); } @@ -179,9 +179,9 @@ public function testExtendArrayWithEmptyExisting(): void { $existing = []; $new = ['a', 'b']; - + $result = PubNubUtil::extendArray($existing, $new); - + $this->assertEquals(['a', 'b'], $result); } @@ -189,9 +189,9 @@ public function testExtendArrayWithEmptyNew(): void { $existing = ['a', 'b']; $new = []; - + $result = PubNubUtil::extendArray($existing, $new); - + $this->assertEquals(['a', 'b'], $result); } @@ -199,9 +199,9 @@ public function testExtendArrayWithEmptyString(): void { $existing = ['a', 'b']; $new = ''; - + $result = PubNubUtil::extendArray($existing, $new); - + $this->assertEquals(['a', 'b'], $result); } @@ -212,45 +212,45 @@ public function testExtendArrayWithEmptyString(): void public function testSplitItemsWithSingleItem(): void { $items = 'item1'; - + $result = PubNubUtil::splitItems($items); - + $this->assertEquals(['item1'], $result); } public function testSplitItemsWithMultipleItems(): void { $items = 'item1,item2,item3'; - + $result = PubNubUtil::splitItems($items); - + $this->assertEquals(['item1', 'item2', 'item3'], $result); } public function testSplitItemsWithEmptyString(): void { $items = ''; - + $result = PubNubUtil::splitItems($items); - + $this->assertEquals([], $result); } public function testSplitItemsPreservesSpaces(): void { $items = 'item 1,item 2'; - + $result = PubNubUtil::splitItems($items); - + $this->assertEquals(['item 1', 'item 2'], $result); } public function testSplitItemsWithTrailingComma(): void { $items = 'item1,item2,'; - + $result = PubNubUtil::splitItems($items); - + $this->assertEquals(['item1', 'item2', ''], $result); } @@ -261,14 +261,14 @@ public function testSplitItemsWithTrailingComma(): void public function testUuidReturnsString(): void { $uuid = PubNubUtil::uuid(); - + $this->assertIsString($uuid); } public function testUuidHasCorrectFormat(): void { $uuid = PubNubUtil::uuid(); - + // UUID format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX $this->assertMatchesRegularExpression( '/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i', @@ -280,7 +280,7 @@ public function testUuidIsUnique(): void { $uuid1 = PubNubUtil::uuid(); $uuid2 = PubNubUtil::uuid(); - + $this->assertNotEquals($uuid1, $uuid2); } @@ -290,7 +290,7 @@ public function testUuidGeneratesMultipleUniqueValues(): void for ($i = 0; $i < 100; $i++) { $uuids[] = PubNubUtil::uuid(); } - + // All UUIDs should be unique $this->assertEquals(100, count(array_unique($uuids))); } @@ -298,7 +298,7 @@ public function testUuidGeneratesMultipleUniqueValues(): void public function testUuidLength(): void { $uuid = PubNubUtil::uuid(); - + // UUID with dashes is 36 characters $this->assertEquals(36, strlen($uuid)); } @@ -319,9 +319,9 @@ public function testFetchPamPermissionsFromWithAllPermissions(): void 'j' => 1, 'ttl' => 1440 ]; - + $result = PubNubUtil::fetchPamPermissionsFrom($input); - + $this->assertEquals([true, true, true, true, true, true, true, 1440], $result); } @@ -337,9 +337,9 @@ public function testFetchPamPermissionsFromWithNoPermissions(): void 'j' => 0, 'ttl' => 0 ]; - + $result = PubNubUtil::fetchPamPermissionsFrom($input); - + $this->assertEquals([false, false, false, false, false, false, false, 0], $result); } @@ -351,27 +351,27 @@ public function testFetchPamPermissionsFromWithPartialPermissions(): void 'm' => 1, 'ttl' => 60 ]; - + $result = PubNubUtil::fetchPamPermissionsFrom($input); - + $this->assertEquals([true, false, true, null, null, null, null, 60], $result); } public function testFetchPamPermissionsFromWithEmptyInput(): void { $input = []; - + $result = PubNubUtil::fetchPamPermissionsFrom($input); - + $this->assertEquals([null, null, null, null, null, null, null, null], $result); } public function testFetchPamPermissionsFromWithOnlyTTL(): void { $input = ['ttl' => 120]; - + $result = PubNubUtil::fetchPamPermissionsFrom($input); - + $this->assertEquals([null, null, null, null, null, null, null, 120], $result); } @@ -382,45 +382,45 @@ public function testFetchPamPermissionsFromWithOnlyTTL(): void public function testIsAssocWithIndexedArray(): void { $array = ['a', 'b', 'c']; - + $result = PubNubUtil::isAssoc($array); - + $this->assertFalse($result); } public function testIsAssocWithAssociativeArray(): void { $array = ['key1' => 'value1', 'key2' => 'value2']; - + $result = PubNubUtil::isAssoc($array); - + $this->assertTrue($result); } public function testIsAssocWithNumericKeys(): void { $array = [0 => 'a', 1 => 'b', 2 => 'c']; - + $result = PubNubUtil::isAssoc($array); - + $this->assertFalse($result); } public function testIsAssocWithMixedKeys(): void { $array = [0 => 'a', 'key' => 'b', 2 => 'c']; - + $result = PubNubUtil::isAssoc($array); - + $this->assertTrue($result); } public function testIsAssocWithEmptyArray(): void { $array = []; - + $result = PubNubUtil::isAssoc($array); - + // Empty array returns true because array_keys([]) !== range(0, count([]) - 1) // array_keys([]) = [], range(0, -1) = [] // But the comparison returns true (not equal) @@ -430,16 +430,16 @@ public function testIsAssocWithEmptyArray(): void public function testIsAssocWithNonArray(): void { $result = PubNubUtil::isAssoc('not an array'); - + $this->assertFalse($result); } public function testIsAssocWithNonSequentialKeys(): void { $array = [1 => 'a', 3 => 'b', 5 => 'c']; - + $result = PubNubUtil::isAssoc($array); - + $this->assertTrue($result); } @@ -450,18 +450,18 @@ public function testIsAssocWithNonSequentialKeys(): void public function testTokenEncodeWithBasicString(): void { $token = 'mytoken123'; - + $result = PubNubUtil::tokenEncode($token); - + $this->assertEquals('mytoken123', $result); } public function testTokenEncodeConvertsSpacesToPercent20(): void { $token = 'token with spaces'; - + $result = PubNubUtil::tokenEncode($token); - + $this->assertStringContainsString('%20', $result); $this->assertStringNotContainsString('+', $result); } @@ -469,18 +469,18 @@ public function testTokenEncodeConvertsSpacesToPercent20(): void public function testTokenEncodeWithSpecialCharacters(): void { $token = 'token!@#$%'; - + $result = PubNubUtil::tokenEncode($token); - + $this->assertIsString($result); } public function testTokenEncodeWithPlusSign(): void { $token = 'token+with+plus'; - + $result = PubNubUtil::tokenEncode($token); - + // Plus signs are first URL encoded to %2B, then the str_replace doesn't affect them // because str_replace looks for literal '+' which is already encoded $this->assertStringContainsString('%2B', $result); @@ -493,9 +493,9 @@ public function testTokenEncodeWithPlusSign(): void public function testConvertIso8859ToUtf8WithAscii(): void { $input = 'Hello World'; - + $result = PubNubUtil::convertIso8859ToUtf8($input); - + $this->assertEquals('Hello World', $result); } @@ -503,9 +503,9 @@ public function testConvertIso8859ToUtf8WithExtendedCharacters(): void { // Test with some ISO-8859-1 characters $input = chr(0xA9); // Copyright symbol in ISO-8859-1 - + $result = PubNubUtil::convertIso8859ToUtf8($input); - + $this->assertNotEmpty($result); $this->assertIsString($result); } @@ -513,27 +513,27 @@ public function testConvertIso8859ToUtf8WithExtendedCharacters(): void public function testConvertIso8859ToUtf8WithEmptyString(): void { $input = ''; - + $result = PubNubUtil::convertIso8859ToUtf8($input); - + $this->assertEquals('', $result); } public function testConvertIso8859ToUtf8PreservesAsciiCharacters(): void { $input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - + $result = PubNubUtil::convertIso8859ToUtf8($input); - + $this->assertEquals($input, $result); } public function testConvertIso8859ToUtf8WithNumbers(): void { $input = '1234567890'; - + $result = PubNubUtil::convertIso8859ToUtf8($input); - + $this->assertEquals($input, $result); } @@ -546,12 +546,12 @@ public function testChannelWorkflow(): void // Split channels from string $channelString = 'channel1,channel2,channel3'; $channels = PubNubUtil::splitItems($channelString); - + $this->assertCount(3, $channels); - + // Join channels back $joined = PubNubUtil::joinChannels($channels); - + $this->assertEquals('channel1,channel2,channel3', $joined); } @@ -559,9 +559,9 @@ public function testArrayExtensionWorkflow(): void { $existing = ['channel1', 'channel2']; $newString = 'channel3,channel4'; - + $extended = PubNubUtil::extendArray($existing, $newString); - + $this->assertCount(4, $extended); $this->assertEquals(['channel1', 'channel2', 'channel3', 'channel4'], $extended); } @@ -575,9 +575,9 @@ public function testUrlBuildingWorkflow(): void 'tt' => '0', 'pnsdk' => 'PubNub-PHP/8.0.0' ]; - + $url = PubNubUtil::buildUrl($basePath, $path, $params); - + $this->assertStringStartsWith('https://ps.pndsn.com', $url); $this->assertStringContainsString('uuid=user-123', $url); $this->assertStringContainsString('&', $url); diff --git a/tests/unit/PubNubUtilityMethodsTest.php b/tests/unit/PubNubUtilityMethodsTest.php index 2db306d..53abad9 100644 --- a/tests/unit/PubNubUtilityMethodsTest.php +++ b/tests/unit/PubNubUtilityMethodsTest.php @@ -17,7 +17,7 @@ public function setUp(): void $this->config->setSubscribeKey('demo'); $this->config->setPublishKey('demo'); $this->config->setUserId('test-user'); - + $this->pubnub = new PubNub($this->config); } @@ -28,16 +28,16 @@ public function setUp(): void public function testGetTokenReturnsNullByDefault(): void { $token = $this->pubnub->getToken(); - + $this->assertNull($token); } public function testSetTokenAndGetToken(): void { $testToken = 'test-token-abc123'; - + $this->pubnub->setToken($testToken); - + $this->assertEquals($testToken, $this->pubnub->getToken()); } @@ -45,7 +45,7 @@ public function testSetTokenOverwritesPreviousToken(): void { $this->pubnub->setToken('first-token'); $this->assertEquals('first-token', $this->pubnub->getToken()); - + $this->pubnub->setToken('second-token'); $this->assertEquals('second-token', $this->pubnub->getToken()); } @@ -53,7 +53,7 @@ public function testSetTokenOverwritesPreviousToken(): void public function testSetTokenWithEmptyString(): void { $this->pubnub->setToken(''); - + $this->assertEquals('', $this->pubnub->getToken()); } @@ -61,9 +61,9 @@ public function testSetTokenWithLongToken(): void { $longToken = 'qEF2AkF0GmFtet9DdHRsGDxDcmVzpURjaGFuoWpteS1jaGFubmVsGENDZ3JwoEN1c3KgQ3NwY6BEdXVpZKBDcGF0pURjaGFuoENnc' . 'nCgQ3VzcqBDc3BjoER1dWlkoERtZXRhoER1dWlkZ215LXV1aWRDc2lnWCAvUKKYbfc0vvvEhYqepG7-_lN5jh_yaA6eo98nAHV8Ug=='; - + $this->pubnub->setToken($longToken); - + $this->assertEquals($longToken, $this->pubnub->getToken()); } @@ -71,7 +71,7 @@ public function testSetTokenPersistsAcrossMultipleCalls(): void { $token = 'persistent-token'; $this->pubnub->setToken($token); - + // Call getToken multiple times $this->assertEquals($token, $this->pubnub->getToken()); $this->assertEquals($token, $this->pubnub->getToken()); @@ -85,7 +85,7 @@ public function testSetTokenPersistsAcrossMultipleCalls(): void public function testTimestampReturnsInteger(): void { $timestamp = $this->pubnub->timestamp(); - + $this->assertIsInt($timestamp); } @@ -94,7 +94,7 @@ public function testTimestampReturnsCurrentTime(): void $before = time(); $timestamp = $this->pubnub->timestamp(); $after = time(); - + // Timestamp should be between before and after $this->assertGreaterThanOrEqual($before, $timestamp); $this->assertLessThanOrEqual($after, $timestamp); @@ -103,10 +103,10 @@ public function testTimestampReturnsCurrentTime(): void public function testTimestampReturnsUnixTimestamp(): void { $timestamp = $this->pubnub->timestamp(); - + // Should be a reasonable Unix timestamp (after year 2020) $this->assertGreaterThan(1577836800, $timestamp); // Jan 1, 2020 - + // Should be before year 2100 $this->assertLessThan(4102444800, $timestamp); // Jan 1, 2100 } @@ -116,7 +116,7 @@ public function testTimestampChangesOverTime(): void $timestamp1 = $this->pubnub->timestamp(); usleep(1100000); // Sleep for slightly over 1 second $timestamp2 = $this->pubnub->timestamp(); - + $this->assertGreaterThan($timestamp1, $timestamp2); } @@ -127,7 +127,7 @@ public function testTimestampChangesOverTime(): void public function testGetSequenceIdReturnsInteger(): void { $sequenceId = $this->pubnub->getSequenceId(); - + $this->assertIsInt($sequenceId); } @@ -138,9 +138,9 @@ public function testGetSequenceIdStartsAtOne(): void $config->setPublishKey('demo'); $config->setUserId('test-user'); $pubnub = new PubNub($config); - + $sequenceId = $pubnub->getSequenceId(); - + $this->assertEquals(1, $sequenceId); } @@ -149,7 +149,7 @@ public function testGetSequenceIdIncrementsOnEachCall(): void $id1 = $this->pubnub->getSequenceId(); $id2 = $this->pubnub->getSequenceId(); $id3 = $this->pubnub->getSequenceId(); - + $this->assertEquals($id1 + 1, $id2); $this->assertEquals($id2 + 1, $id3); } @@ -160,10 +160,10 @@ public function testGetSequenceIdWrapsAtMaxSequence(): void for ($i = 0; $i < PubNub::$MAX_SEQUENCE; $i++) { $this->pubnub->getSequenceId(); } - + // Next call should wrap to 1 $sequenceId = $this->pubnub->getSequenceId(); - + $this->assertEquals(1, $sequenceId); } @@ -173,7 +173,7 @@ public function testGetSequenceIdIsUnique(): void for ($i = 0; $i < 100; $i++) { $ids[] = $this->pubnub->getSequenceId(); } - + // All IDs should be unique $this->assertEquals(100, count(array_unique($ids))); } @@ -185,7 +185,7 @@ public function testGetSequenceIdIsUnique(): void public function testGetTelemetryManagerReturnsInstance(): void { $telemetryManager = $this->pubnub->getTelemetryManager(); - + $this->assertInstanceOf(\PubNub\Managers\TelemetryManager::class, $telemetryManager); } @@ -193,7 +193,7 @@ public function testGetTelemetryManagerReturnsSameInstance(): void { $telemetryManager1 = $this->pubnub->getTelemetryManager(); $telemetryManager2 = $this->pubnub->getTelemetryManager(); - + $this->assertSame($telemetryManager1, $telemetryManager2); } @@ -204,7 +204,7 @@ public function testGetTelemetryManagerReturnsSameInstance(): void public function testGetConfigurationReturnsConfiguration(): void { $config = $this->pubnub->getConfiguration(); - + $this->assertInstanceOf(PNConfiguration::class, $config); } @@ -212,14 +212,14 @@ public function testGetConfigurationReturnsSameConfiguration(): void { $config1 = $this->pubnub->getConfiguration(); $config2 = $this->pubnub->getConfiguration(); - + $this->assertSame($config1, $config2); } public function testGetConfigurationReturnsCorrectValues(): void { $config = $this->pubnub->getConfiguration(); - + $this->assertEquals('demo', $config->getSubscribeKey()); $this->assertEquals('demo', $config->getPublishKey()); $this->assertEquals('test-user', $config->getUserId()); @@ -232,21 +232,21 @@ public function testGetConfigurationReturnsCorrectValues(): void public function testGetBasePathReturnsString(): void { $basePath = $this->pubnub->getBasePath(); - + $this->assertIsString($basePath); } public function testGetBasePathReturnsValidUrl(): void { $basePath = $this->pubnub->getBasePath(); - + $this->assertStringStartsWith('http', $basePath); } public function testGetBasePathWithCustomHost(): void { $basePath = $this->pubnub->getBasePath('custom.pubnub.com'); - + $this->assertEquals('https://custom.pubnub.com', $basePath); } @@ -256,10 +256,10 @@ public function testGetBasePathUsesConfigurationOrigin(): void $config->setSubscribeKey('demo'); $config->setUserId('test'); $config->setOrigin('my-origin.pubnub.com'); - + $pubnub = new PubNub($config); $basePath = $pubnub->getBasePath(); - + $this->assertEquals('https://my-origin.pubnub.com', $basePath); } @@ -270,16 +270,16 @@ public function testGetBasePathUsesConfigurationOrigin(): void public function testGetClientReturnsClientInterface(): void { $client = $this->pubnub->getClient(); - + $this->assertInstanceOf(\Psr\Http\Client\ClientInterface::class, $client); } public function testSetClientAndGetClient(): void { $mockClient = $this->createMock(\Psr\Http\Client\ClientInterface::class); - + $this->pubnub->setClient($mockClient); - + $this->assertSame($mockClient, $this->pubnub->getClient()); } @@ -287,7 +287,7 @@ public function testGetClientReturnsSameInstanceByDefault(): void { $client1 = $this->pubnub->getClient(); $client2 = $this->pubnub->getClient(); - + $this->assertSame($client1, $client2); } @@ -298,16 +298,16 @@ public function testGetClientReturnsSameInstanceByDefault(): void public function testGetRequestFactoryReturnsRequestFactoryInterface(): void { $requestFactory = $this->pubnub->getRequestFactory(); - + $this->assertInstanceOf(\Psr\Http\Message\RequestFactoryInterface::class, $requestFactory); } public function testSetRequestFactoryAndGetRequestFactory(): void { $mockFactory = $this->createMock(\Psr\Http\Message\RequestFactoryInterface::class); - + $this->pubnub->setRequestFactory($mockFactory); - + $this->assertSame($mockFactory, $this->pubnub->getRequestFactory()); } @@ -315,7 +315,7 @@ public function testGetRequestFactoryReturnsSameInstanceByDefault(): void { $factory1 = $this->pubnub->getRequestFactory(); $factory2 = $this->pubnub->getRequestFactory(); - + $this->assertSame($factory1, $factory2); } @@ -326,16 +326,16 @@ public function testGetRequestFactoryReturnsSameInstanceByDefault(): void public function testGetLoggerReturnsLoggerInterface(): void { $logger = $this->pubnub->getLogger(); - + $this->assertInstanceOf(LoggerInterface::class, $logger); } public function testSetLoggerAndGetLogger(): void { $mockLogger = $this->createMock(LoggerInterface::class); - + $this->pubnub->setLogger($mockLogger); - + $this->assertSame($mockLogger, $this->pubnub->getLogger()); } @@ -343,7 +343,7 @@ public function testGetLoggerReturnsSameInstanceByDefault(): void { $logger1 = $this->pubnub->getLogger(); $logger2 = $this->pubnub->getLogger(); - + $this->assertSame($logger1, $logger2); } @@ -351,10 +351,10 @@ public function testSetLoggerReplacesDefaultLogger(): void { $defaultLogger = $this->pubnub->getLogger(); $this->assertInstanceOf(\Psr\Log\NullLogger::class, $defaultLogger); - + $customLogger = $this->createMock(LoggerInterface::class); $this->pubnub->setLogger($customLogger); - + $this->assertNotSame($defaultLogger, $this->pubnub->getLogger()); $this->assertSame($customLogger, $this->pubnub->getLogger()); } diff --git a/tests/unit/PublishTest.php b/tests/unit/PublishTest.php index a5897aa..261763a 100644 --- a/tests/unit/PublishTest.php +++ b/tests/unit/PublishTest.php @@ -3,7 +3,6 @@ use PHPUnit\Framework\TestCase; use PubNub\PubNub; - class PublishTest extends TestCase { /** diff --git a/tests/unit/TelemetryManagerTest.php b/tests/unit/TelemetryManagerTest.php index 851a59a..f0fd27e 100644 --- a/tests/unit/TelemetryManagerTest.php +++ b/tests/unit/TelemetryManagerTest.php @@ -4,7 +4,6 @@ use PubNub\Managers\TelemetryManager; use PubNub\Enums\PNOperationType; - class TelemetryManagerTest extends TestCase { public function testAverageLatency() diff --git a/tests/unit/TokenManagerTest.php b/tests/unit/TokenManagerTest.php index 2b73d88..ebf4891 100644 --- a/tests/unit/TokenManagerTest.php +++ b/tests/unit/TokenManagerTest.php @@ -9,26 +9,26 @@ public function testSetAndGetToken(): void { $manager = new TokenManager(); $token = 'test-token-abc123'; - + $manager->setToken($token); - + $this->assertEquals($token, $manager->getToken()); } public function testGetTokenReturnsNullByDefault(): void { $manager = new TokenManager(); - + $this->assertNull($manager->getToken()); } public function testSetTokenOverwritesPreviousToken(): void { $manager = new TokenManager(); - + $manager->setToken('first-token'); $this->assertEquals('first-token', $manager->getToken()); - + $manager->setToken('second-token'); $this->assertEquals('second-token', $manager->getToken()); } @@ -36,9 +36,9 @@ public function testSetTokenOverwritesPreviousToken(): void public function testSetTokenWithEmptyString(): void { $manager = new TokenManager(); - + $manager->setToken(''); - + $this->assertEquals('', $manager->getToken()); } @@ -46,9 +46,9 @@ public function testSetTokenWithLongString(): void { $manager = new TokenManager(); $longToken = str_repeat('a', 10000); - + $manager->setToken($longToken); - + $this->assertEquals($longToken, $manager->getToken()); } @@ -56,9 +56,9 @@ public function testSetTokenWithSpecialCharacters(): void { $manager = new TokenManager(); $specialToken = 'token-with-special!@#$%^&*()_+-={}[]|\\:";\'<>?,./'; - + $manager->setToken($specialToken); - + $this->assertEquals($specialToken, $manager->getToken()); } } diff --git a/tests/unit/UtilsTest.php b/tests/unit/UtilsTest.php index 6d228a6..da83c23 100644 --- a/tests/unit/UtilsTest.php +++ b/tests/unit/UtilsTest.php @@ -4,7 +4,6 @@ use PubNub\Exceptions\PubNubBuildRequestException; use PubNub\PubNubUtil; - class UtilsTest extends TestCase { /** From 531cbd1a874ff5499ae9bf93cba37658d4e89a8e Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 15:10:17 +0200 Subject: [PATCH 07/26] Even more linter fixes --- tests/functional/AddChannelToChannelGroupTest.php | 2 +- tests/functional/ListChannelsInChannelGroupTest.php | 1 + tests/functional/RemoveChannelFromChannelGroupTest.php | 1 + tests/functional/RemoveChannelGroupTest.php | 1 + tests/functional/SubscribeTest.php | 1 + tests/functional/TelemetryManagerTest.php | 1 + tests/unit/BasePathManagerTest.php | 3 +++ tests/unit/CryptoCryptorGettersTest.php | 3 +++ tests/unit/ListenerManagerTest.php | 4 ++++ tests/unit/PNConfigurationExtendedTest.php | 3 +++ tests/unit/PNConfigurationTest.php | 3 +++ tests/unit/PubNubCborDecodeTest.php | 3 +++ tests/unit/PubNubCryptoMethodsTest.php | 3 +++ tests/unit/PubNubFactoryMethodsTest.php | 3 +++ tests/unit/PubNubSdkInfoTest.php | 3 +++ tests/unit/PubNubUtilExtendedTest.php | 3 +++ tests/unit/PubNubUtilityMethodsTest.php | 5 +++++ tests/unit/PublishTest.php | 3 +++ tests/unit/TelemetryManagerTest.php | 3 +++ tests/unit/TokenManagerTest.php | 3 +++ tests/unit/UtilsTest.php | 7 +++++++ 21 files changed, 58 insertions(+), 1 deletion(-) diff --git a/tests/functional/AddChannelToChannelGroupTest.php b/tests/functional/AddChannelToChannelGroupTest.php index 29dce87..a526773 100644 --- a/tests/functional/AddChannelToChannelGroupTest.php +++ b/tests/functional/AddChannelToChannelGroupTest.php @@ -1,5 +1,6 @@ assertEquals('', $this->pubnub->getToken()); } + //phpcs:disable public function testSetTokenWithLongToken(): void { $longToken = 'qEF2AkF0GmFtet9DdHRsGDxDcmVzpURjaGFuoWpteS1jaGFubmVsGENDZ3JwoEN1c3KgQ3NwY6BEdXVpZKBDcGF0pURjaGFuoENnc' . @@ -66,6 +70,7 @@ public function testSetTokenWithLongToken(): void $this->assertEquals($longToken, $this->pubnub->getToken()); } + //phpcs:enable public function testSetTokenPersistsAcrossMultipleCalls(): void { diff --git a/tests/unit/PublishTest.php b/tests/unit/PublishTest.php index 261763a..ff56dd2 100644 --- a/tests/unit/PublishTest.php +++ b/tests/unit/PublishTest.php @@ -1,6 +1,9 @@ expectException(PubNubBuildRequestException::class); $this->expectExceptionMessage("Value serialization error: Malformed UTF-8 characters, possibly incorrectly encoded"); PubNubUtil::writeValueAsString(["key" => "\xB1\x31"]); + //phpcs:enable } public function testPamEncode() @@ -38,12 +43,14 @@ public function testPamEncode() public function testSignSha256() { + //phpcs:disable $signInput = "sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f pub-c-98863562-19a6-4760-bf0b-d537d1f5c582 grant channel=asyncio-pam-FI2FCS0A&pnsdk=PubNub-Python-Asyncio%252F4.0.0&r=1×tamp=1468409553&uuid=a4dbf92e-e5cb-428f-b6e6-35cce03500a2&w=1"; $result = PubNubUtil::signSha256("my_key", $signInput); + //phpcs:enable self::assertEquals("Dq92jnwRTCikdeP2nUs1__gyJthF8NChwbs5aYy2r_I=", $result); } From eb3465d5b4a78a8273a4185241a67dcf5bfa2999 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 15:16:11 +0200 Subject: [PATCH 08/26] add missing semicolons --- tests/unit/BasePathManagerTest.php | 2 +- tests/unit/ListenerManagerTest.php | 2 +- tests/unit/PubNubUtilityMethodsTest.php | 2 +- tests/unit/TokenManagerTest.php | 2 +- tests/unit/UtilsTest.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/unit/BasePathManagerTest.php b/tests/unit/BasePathManagerTest.php index 9826eee..054be88 100644 --- a/tests/unit/BasePathManagerTest.php +++ b/tests/unit/BasePathManagerTest.php @@ -1,6 +1,6 @@ Date: Wed, 8 Oct 2025 15:20:26 +0200 Subject: [PATCH 09/26] last missing semicolon --- tests/unit/CryptoCryptorGettersTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/CryptoCryptorGettersTest.php b/tests/unit/CryptoCryptorGettersTest.php index 7b7d08f..9745cb4 100644 --- a/tests/unit/CryptoCryptorGettersTest.php +++ b/tests/unit/CryptoCryptorGettersTest.php @@ -1,6 +1,6 @@ Date: Wed, 8 Oct 2025 15:24:05 +0200 Subject: [PATCH 10/26] there better not be more missing semicolons --- tests/unit/PNConfigurationExtendedTest.php | 2 +- tests/unit/PNConfigurationTest.php | 2 +- tests/unit/PubNubCborDecodeTest.php | 2 +- tests/unit/PubNubCryptoMethodsTest.php | 2 +- tests/unit/PubNubFactoryMethodsTest.php | 2 +- tests/unit/PubNubSdkInfoTest.php | 2 +- tests/unit/PubNubUtilExtendedTest.php | 2 +- tests/unit/PublishTest.php | 2 +- tests/unit/TelemetryManagerTest.php | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/unit/PNConfigurationExtendedTest.php b/tests/unit/PNConfigurationExtendedTest.php index 7595c11..eef7815 100644 --- a/tests/unit/PNConfigurationExtendedTest.php +++ b/tests/unit/PNConfigurationExtendedTest.php @@ -1,6 +1,6 @@ Date: Wed, 8 Oct 2025 15:34:36 +0200 Subject: [PATCH 11/26] Test phpstan setting change --- phpstan.neon | 1 - 1 file changed, 1 deletion(-) diff --git a/phpstan.neon b/phpstan.neon index 8dafb33..c5709f1 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -5,4 +5,3 @@ parameters: level: 6 paths: - src - - tests From af9727356e95d5c0cbf79ffc8b5fe074ffffcf0d Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 15:36:10 +0200 Subject: [PATCH 12/26] More phpcbf --- tests/unit/BasePathManagerTest.php | 1 - tests/unit/CryptoCryptorGettersTest.php | 1 - tests/unit/PNConfigurationExtendedTest.php | 1 - tests/unit/PNConfigurationTest.php | 1 - tests/unit/PubNubCborDecodeTest.php | 1 - tests/unit/PubNubCryptoMethodsTest.php | 1 - tests/unit/PubNubFactoryMethodsTest.php | 1 - tests/unit/PubNubSdkInfoTest.php | 1 - tests/unit/PubNubUtilExtendedTest.php | 1 - tests/unit/PubNubUtilityMethodsTest.php | 1 - tests/unit/PublishTest.php | 1 - tests/unit/TelemetryManagerTest.php | 1 - tests/unit/TokenManagerTest.php | 1 - tests/unit/UtilsTest.php | 1 - 14 files changed, 14 deletions(-) diff --git a/tests/unit/BasePathManagerTest.php b/tests/unit/BasePathManagerTest.php index 054be88..a92c607 100644 --- a/tests/unit/BasePathManagerTest.php +++ b/tests/unit/BasePathManagerTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\Managers\BasePathManager; use PubNub\PNConfiguration; diff --git a/tests/unit/CryptoCryptorGettersTest.php b/tests/unit/CryptoCryptorGettersTest.php index 9745cb4..dc974ef 100644 --- a/tests/unit/CryptoCryptorGettersTest.php +++ b/tests/unit/CryptoCryptorGettersTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\Crypto\AesCbcCryptor; use PubNub\Crypto\LegacyCryptor; diff --git a/tests/unit/PNConfigurationExtendedTest.php b/tests/unit/PNConfigurationExtendedTest.php index eef7815..f2e550a 100644 --- a/tests/unit/PNConfigurationExtendedTest.php +++ b/tests/unit/PNConfigurationExtendedTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PNConfiguration; use PubNub\CryptoModule; diff --git a/tests/unit/PNConfigurationTest.php b/tests/unit/PNConfigurationTest.php index efb3155..eb3a423 100644 --- a/tests/unit/PNConfigurationTest.php +++ b/tests/unit/PNConfigurationTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\Exceptions\PubNubBuildRequestException; use PubNub\Exceptions\PubNubConfigurationException; use PubNub\PNConfiguration; diff --git a/tests/unit/PubNubCborDecodeTest.php b/tests/unit/PubNubCborDecodeTest.php index 44c91ca..dd6568c 100644 --- a/tests/unit/PubNubCborDecodeTest.php +++ b/tests/unit/PubNubCborDecodeTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PubNubCborDecode; class PubNubCborDecodeTest extends TestCase diff --git a/tests/unit/PubNubCryptoMethodsTest.php b/tests/unit/PubNubCryptoMethodsTest.php index 8068157..210416d 100644 --- a/tests/unit/PubNubCryptoMethodsTest.php +++ b/tests/unit/PubNubCryptoMethodsTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PNConfiguration; use PubNub\PubNub; use PubNub\CryptoModule; diff --git a/tests/unit/PubNubFactoryMethodsTest.php b/tests/unit/PubNubFactoryMethodsTest.php index 22d16c6..936648f 100644 --- a/tests/unit/PubNubFactoryMethodsTest.php +++ b/tests/unit/PubNubFactoryMethodsTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PubNub; use PubNub\PNConfiguration; diff --git a/tests/unit/PubNubSdkInfoTest.php b/tests/unit/PubNubSdkInfoTest.php index 0697f16..3a7a4c9 100644 --- a/tests/unit/PubNubSdkInfoTest.php +++ b/tests/unit/PubNubSdkInfoTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PubNub; class PubNubSdkInfoTest extends TestCase diff --git a/tests/unit/PubNubUtilExtendedTest.php b/tests/unit/PubNubUtilExtendedTest.php index 9e9107d..2e4a6c7 100644 --- a/tests/unit/PubNubUtilExtendedTest.php +++ b/tests/unit/PubNubUtilExtendedTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PubNubUtil; class PubNubUtilExtendedTest extends TestCase diff --git a/tests/unit/PubNubUtilityMethodsTest.php b/tests/unit/PubNubUtilityMethodsTest.php index a270c8e..26ba408 100644 --- a/tests/unit/PubNubUtilityMethodsTest.php +++ b/tests/unit/PubNubUtilityMethodsTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PNConfiguration; use PubNub\PubNub; use PubNub\CryptoModule; diff --git a/tests/unit/PublishTest.php b/tests/unit/PublishTest.php index 895f070..ef27c7d 100644 --- a/tests/unit/PublishTest.php +++ b/tests/unit/PublishTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\PubNub; class PublishTest extends TestCase diff --git a/tests/unit/TelemetryManagerTest.php b/tests/unit/TelemetryManagerTest.php index 6b09f64..f3451b4 100644 --- a/tests/unit/TelemetryManagerTest.php +++ b/tests/unit/TelemetryManagerTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\Managers\TelemetryManager; use PubNub\Enums\PNOperationType; diff --git a/tests/unit/TokenManagerTest.php b/tests/unit/TokenManagerTest.php index b4c52b2..597dee5 100644 --- a/tests/unit/TokenManagerTest.php +++ b/tests/unit/TokenManagerTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\Managers\TokenManager; class TokenManagerTest extends TestCase diff --git a/tests/unit/UtilsTest.php b/tests/unit/UtilsTest.php index 0a2c4ce..0037d64 100644 --- a/tests/unit/UtilsTest.php +++ b/tests/unit/UtilsTest.php @@ -3,7 +3,6 @@ namespace PubNubTests\unit; use PHPUnit\Framework\TestCase; - use PubNub\Exceptions\PubNubBuildRequestException; use PubNub\PubNubUtil; From 061a49fe3c2871d71562843e7407083c8318afa1 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 15:48:15 +0200 Subject: [PATCH 13/26] Fix wrong timestamp method call in tests --- .../integrational/PublishFileMessageTest.php | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/integrational/PublishFileMessageTest.php b/tests/integrational/PublishFileMessageTest.php index 0854094..4cc9a1d 100644 --- a/tests/integrational/PublishFileMessageTest.php +++ b/tests/integrational/PublishFileMessageTest.php @@ -68,7 +68,7 @@ public function testPublishFileMessageWithBasicMessage(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageWithMetadata(): void @@ -102,7 +102,7 @@ public function testPublishFileMessageWithMetadata(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageWithCustomMessageType(): void @@ -130,7 +130,7 @@ public function testPublishFileMessageWithCustomMessageType(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageWithTTL(): void @@ -158,7 +158,7 @@ public function testPublishFileMessageWithTTL(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageWithShouldStore(): void @@ -186,7 +186,7 @@ public function testPublishFileMessageWithShouldStore(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageWithAllOptions(): void @@ -222,7 +222,7 @@ public function testPublishFileMessageWithAllOptions(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageWithEncryption(): void @@ -249,7 +249,7 @@ public function testPublishFileMessageWithEncryption(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageWithComplexMessage(): void @@ -286,7 +286,7 @@ public function testPublishFileMessageWithComplexMessage(): void ->sync(); $this->assertNotEmpty($response); - $this->assertNotEmpty($response->getTimetoken()); + $this->assertNotEmpty($response->getTimestamp()); } public function testPublishFileMessageMultipleTimes(): void @@ -319,9 +319,9 @@ public function testPublishFileMessageMultipleTimes(): void ->message("Second notification") ->sync(); - $this->assertNotEmpty($response1->getTimetoken()); - $this->assertNotEmpty($response2->getTimetoken()); - $this->assertNotEquals($response1->getTimetoken(), $response2->getTimetoken()); + $this->assertNotEmpty($response1->getTimestamp()); + $this->assertNotEmpty($response2->getTimestamp()); + $this->assertNotEquals($response1->getTimestamp(), $response2->getTimestamp()); } public function testPublishFileMessageWithInvalidFileId(): void From c7f00f0270f39861dcff2f512b78c76365e349ef Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 15:56:59 +0200 Subject: [PATCH 14/26] Remove invalid test --- tests/integrational/PublishFileMessageTest.php | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/tests/integrational/PublishFileMessageTest.php b/tests/integrational/PublishFileMessageTest.php index 4cc9a1d..010a94b 100644 --- a/tests/integrational/PublishFileMessageTest.php +++ b/tests/integrational/PublishFileMessageTest.php @@ -324,19 +324,6 @@ public function testPublishFileMessageMultipleTimes(): void $this->assertNotEquals($response1->getTimestamp(), $response2->getTimestamp()); } - public function testPublishFileMessageWithInvalidFileId(): void - { - $this->expectException(\PubNub\Exceptions\PubNubServerException::class); - - // Try to publish with non-existent file ID - $this->pubnub->publishFileMessage() - ->channel($this->channel) - ->fileId('invalid-file-id-12345') - ->fileName('nonexistent.txt') - ->message("This should fail") - ->sync(); - } - public function testPublishFileMessageWithEmptyChannel(): void { $this->expectException(\PubNub\Exceptions\PubNubValidationException::class); From ad3431ae27f0a338acccf0e6f6ddf36f36d50d68 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 8 Oct 2025 16:42:03 +0200 Subject: [PATCH 15/26] Add missing snippets for docs --- examples/Configuration.php | 159 +++++++++++++++++++++++++++++++++++++ examples/Publishing.php | 13 +++ examples/Subscribing.php | 87 ++++++++++++++++++++ 3 files changed, 259 insertions(+) create mode 100644 examples/Configuration.php diff --git a/examples/Configuration.php b/examples/Configuration.php new file mode 100644 index 0000000..1a9bc79 --- /dev/null +++ b/examples/Configuration.php @@ -0,0 +1,159 @@ +setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); + +// Set publish key (only required if publishing) +$pnConfiguration->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo'); + +// Set UUID (required to connect) +$pnConfiguration->setUserId('php-config-demo-user'); +// snippet.end + +// snippet.basic_configuration +// Create a new configuration instance +$pnConfiguration = new PNConfiguration(); + +// Set subscribe key (required) +$pnConfiguration->setSubscribeKey("demo"); + +// Set publish key (only required if publishing) +$pnConfiguration->setPublishKey("demo"); + +// Set UUID (required to connect) +$pnConfiguration->setUserId("php-sdk-example-user"); + +// Set up cryptography for message encryption (optional) +// Uncomment the line below to enable encryption +// $pnConfiguration->setCryptoModule(CryptoModule::aesCbcCryptor("your-cipher-key", true)); + +// Set authentication key (optional, required only when using Access Manager) +// $pnConfiguration->setAuthKey("my_auth_key"); + +// Configure connection timeout in seconds +$pnConfiguration->setConnectTimeout(10); + +// Configure subscribe request timeout in seconds +$pnConfiguration->setSubscribeTimeout(310); + +// Configure non-subscribe request timeout in seconds +$pnConfiguration->setNonSubscribeRequestTimeout(10); + +// Set filter expression (optional) +// $pnConfiguration->setFilterExpression("channel == 'my-channel'"); + +// Create PubNub instance with the configured settings +$pubnub = new PubNub($pnConfiguration); + +// Display configuration information +echo "PubNub Configuration:\n"; +echo "Subscribe Key: " . $pnConfiguration->getSubscribeKey() . "\n"; +echo "Publish Key: " . $pnConfiguration->getPublishKey() . "\n"; +echo "User ID: " . $pnConfiguration->getUserId() . "\n"; +echo "Encryption: " . ($pnConfiguration->getCryptoSafe() ? "enabled" : "disabled") . "\n"; + +// Now you can use this PubNub instance to publish and subscribe + +// Example: Create a simple message +$message = ["text" => "Hello from PHP SDK!"]; + +// Example: Publish the message (uncomment to execute) +/* +$pubnub->publish() + ->channel("demo-channel") + ->message($message) + ->sync(); + +echo "Message published to 'demo-channel'\n"; +*/ + +// Keep this code running only if you plan to subscribe to messages +// Otherwise, the script will exit after publishing +// snippet.end + +// snippet.init_basic +$pnconf = new PNConfiguration(); + +$pnconf->setSubscribeKey("my-key"); +$pnconf->setPublishKey("my-key"); +$pnconf->setSecure(false); +$pnconf->setUserId("myUniqueUserId"); +$pubnub = new PubNub($pnconf); +// snippet.end + +// snippet.init_access_manager +$pnConfiguration = new PNConfiguration(); + +$pnConfiguration->setSubscribeKey("my_sub_key"); +$pnConfiguration->setPublishKey("my_pub_key"); +$pnConfiguration->setSecretKey("my_secret_key"); +$pnConfiguration->setUserId("myUniqueUserId"); +$pubnub = new PubNub($pnConfiguration); +// snippet.end + +// snippet.event_listeners +class MySubscribeCallback extends SubscribeCallback { + function status($pubnub, $status) { + if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) { + // This event happens when radio / connectivity is lost + } else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory){ + // Connect event. You can do stuff like publish, and know you'll get it // Or just use the connected event to confirm you are subscribed for // UI / internal notifications, etc + } else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory){ + // Handle message decryption error. Probably client configured to // encrypt messages and on live data feed it received plain text. + } + } + + function message($pubnub, $message){ + // Handle new message stored in message.message + } + function presence($pubnub, $presence){ + // handle incoming presence data + } +} + +$pnconf = new PNConfiguration(); +$pubnub = new PubNub($pnconf); + +$pnconf->setSubscribeKey("my_sub_key"); +$pnconf->setPublishKey("my_pub_key"); + +$subscribeCallback = new MySubscribeCallback(); + +$pubnub->addListener($subscribeCallback); + +// Subscribe to a channel, this is not async. +$pubnub->subscribe() +->channels("hello_world") +->execute(); + +// Use the publish command separately from the Subscribe code shown above. +// Subscribe is not async and will block the execution until complete. +$result = $pubnub->publish() +->channel("hello_world") +->message("Hello PubNub") +->sync(); + +print_r($result); +// snippet.end + +// snippet.set_filter_expression +$pnconf = new PNConfiguration(); + +$pnconf->setSubscribeKey("my_sub_key"); +$pnconf->setFilterExpression("userid == 'my_userid'"); + +$pubnub = new PubNub($pnconf); +// snippet.end + diff --git a/examples/Publishing.php b/examples/Publishing.php index fd5518e..8897fc3 100644 --- a/examples/Publishing.php +++ b/examples/Publishing.php @@ -119,3 +119,16 @@ assert($result->getTimetoken() > 0); echo "Signal timetoken: {$result->getTimetoken()}\n"; // snippet.end + +// snippet.publish_array +try { + $result = $pubnub->publish() + ->channel("my_channel") + ->message(["hello", "there"]) + ->meta(["name" => "Alex", "online" => true]) + ->sync(); + print_r($result->getTimetoken()); +} catch (PubNubException $error) { + echo "Error: " . $error->getMessage() . "\n"; +} +// snippet.end \ No newline at end of file diff --git a/examples/Subscribing.php b/examples/Subscribing.php index ac8958b..c94252e 100644 --- a/examples/Subscribing.php +++ b/examples/Subscribing.php @@ -101,6 +101,93 @@ function getHistory($pubnub, $channels) } // snippet.end +// snippet.basic_subscribe_with_logging +use Monolog\Handler\ErrorLogHandler; + +$pnconf = new PNConfiguration(); + +$pnconf->setPublishKey("demo"); +$pnconf->setSubscribeKey("demo"); +$pnconf->setUserId("php-subscriber-with-logging"); + +$pubnub = new PubNub($pnconf); + +$pubnub->getLogger()->pushHandler(new ErrorLogHandler()); + +$pubnub->subscribe()->channels("my_channel")->execute(); +// snippet.end + +// snippet.subscribe_with_state +class MySubscribeCallbackWithState extends SubscribeCallback { + function status($pubnub, $status) { + if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) { + $result = $pubnub->setState() + ->channels("awesomeChannel") + ->channelGroups("awesomeChannelGroup") + ->state([ + "fieldA" => "awesome", + "fieldB" => 10 + ]) + ->sync(); + print_r($result); + } + } + + function message($pubnub, $message) { + } + + function presence($pubnub, $presence) { + } +} + +$subscribeCallback = new MySubscribeCallbackWithState(); + +$pubnub->addListener($subscribeCallback); + +$pubnub->subscribe() + ->channels("my_channel") + ->execute(); +// snippet.end + +// snippet.unsubscribe_from_channel +use PubNub\Exceptions\PubNubUnsubscribeException; + +class MyUnsubscribeCallback extends SubscribeCallback { + function status($pubnub, $status) { + if ($this->checkUnsubscribeCondition()) { + throw (new PubNubUnsubscribeException())->setChannels("awesomeChannel"); + } + } + + function message($pubnub, $message) { + } + + function presence($pubnub, $presence) { + } + + function checkUnsubscribeCondition() { + // return true or false + return false; + } +} + +$pnconfig = new PNConfiguration(); + +$pnconfig->setPublishKey("demo"); +$pnconfig->setSubscribeKey("demo"); +$pnconfig->setUserId("php-unsubscribe-demo"); + +$pubnub = new PubNub($pnconfig); + +$subscribeCallback = new MyUnsubscribeCallback(); + +$pubnub->addListener($subscribeCallback); + +$pubnub->subscribe() + ->channels("awesomeChannel") + ->execute(); +// snippet.end + echo "Starting PubNub Subscriber...\n"; echo "Press Ctrl+C to exit\n"; From 62d2967af98c94feb92cf55fff548419c15735cd Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Thu, 9 Oct 2025 14:35:03 +0200 Subject: [PATCH 16/26] Examples linter --- examples/Configuration.php | 19 ++++++++++++------- examples/Publishing.php | 2 +- examples/Subscribing.php | 30 ++++++++++++++++++++---------- examples/Time.php | 1 - examples/handleServerSideError.php | 1 - 5 files changed, 33 insertions(+), 20 deletions(-) diff --git a/examples/Configuration.php b/examples/Configuration.php index 1a9bc79..0b7b4f2 100644 --- a/examples/Configuration.php +++ b/examples/Configuration.php @@ -1,5 +1,7 @@ getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) { // This event happens when radio / connectivity is lost - } else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory){ + } elseif ($status->getCategory() === PNStatusCategory::PNConnectedCategory) { // Connect event. You can do stuff like publish, and know you'll get it // Or just use the connected event to confirm you are subscribed for // UI / internal notifications, etc - } else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory){ + } elseif ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) { // Handle message decryption error. Probably client configured to // encrypt messages and on live data feed it received plain text. } } - function message($pubnub, $message){ + function message($pubnub, $message) + { // Handle new message stored in message.message } - function presence($pubnub, $presence){ + function presence($pubnub, $presence) + { // handle incoming presence data } } @@ -156,4 +162,3 @@ function presence($pubnub, $presence){ $pubnub = new PubNub($pnconf); // snippet.end - diff --git a/examples/Publishing.php b/examples/Publishing.php index 8897fc3..cad1d72 100644 --- a/examples/Publishing.php +++ b/examples/Publishing.php @@ -131,4 +131,4 @@ } catch (PubNubException $error) { echo "Error: " . $error->getMessage() . "\n"; } -// snippet.end \ No newline at end of file +// snippet.end diff --git a/examples/Subscribing.php b/examples/Subscribing.php index c94252e..43538ef 100644 --- a/examples/Subscribing.php +++ b/examples/Subscribing.php @@ -1,6 +1,7 @@ getCategory() === PNStatusCategory::PNConnectedCategory) { $result = $pubnub->setState() ->channels("awesomeChannel") @@ -133,10 +136,12 @@ function status($pubnub, $status) { } } - function message($pubnub, $message) { + function message($pubnub, $message) + { } - function presence($pubnub, $presence) { + function presence($pubnub, $presence) + { } } @@ -152,20 +157,25 @@ function presence($pubnub, $presence) { // snippet.unsubscribe_from_channel use PubNub\Exceptions\PubNubUnsubscribeException; -class MyUnsubscribeCallback extends SubscribeCallback { - function status($pubnub, $status) { +class MyUnsubscribeCallback extends SubscribeCallback +{ + function status($pubnub, $status) + { if ($this->checkUnsubscribeCondition()) { throw (new PubNubUnsubscribeException())->setChannels("awesomeChannel"); } } - function message($pubnub, $message) { + function message($pubnub, $message) + { } - function presence($pubnub, $presence) { + function presence($pubnub, $presence) + { } - function checkUnsubscribeCondition() { + function checkUnsubscribeCondition() + { // return true or false return false; } diff --git a/examples/Time.php b/examples/Time.php index 954dfc4..28dccbf 100755 --- a/examples/Time.php +++ b/examples/Time.php @@ -11,4 +11,3 @@ $result = $pubnub->time()->sync(); printf("Server Time is: %s", date("Y-m-d H:i:s", $result->getTimetoken())); - diff --git a/examples/handleServerSideError.php b/examples/handleServerSideError.php index ab8837f..66b8b08 100644 --- a/examples/handleServerSideError.php +++ b/examples/handleServerSideError.php @@ -33,4 +33,3 @@ } catch (\PubNub\Exceptions\PubNubException $exception) { print_r("Message: " . $exception->getMessage()); } - From 06a8fe1366752552ecf5fd330ec07e355ce719c6 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 14:57:11 +0200 Subject: [PATCH 17/26] Initial review fixes --- examples/Configuration.php | 1 + examples/Publishing.php | 20 +++++--- examples/Subscribing.php | 46 ++++++++++------- phpstan.neon | 1 + tests/unit/PubNubSdkInfoTest.php | 16 +----- tests/unit/PubNubUtilityMethodsTest.php | 41 +-------------- tests/unit/TokenManagerTest.php | 66 ------------------------- tests/unit/UtilsTest.php | 14 ------ 8 files changed, 45 insertions(+), 160 deletions(-) delete mode 100644 tests/unit/TokenManagerTest.php diff --git a/examples/Configuration.php b/examples/Configuration.php index 0b7b4f2..e6b30c8 100644 --- a/examples/Configuration.php +++ b/examples/Configuration.php @@ -100,6 +100,7 @@ $pnConfiguration->setSubscribeKey("my_sub_key"); $pnConfiguration->setPublishKey("my_pub_key"); +//NOTE: only server side should have secret key $pnConfiguration->setSecretKey("my_secret_key"); $pnConfiguration->setUserId("myUniqueUserId"); $pubnub = new PubNub($pnConfiguration); diff --git a/examples/Publishing.php b/examples/Publishing.php index cad1d72..ea0fd4b 100644 --- a/examples/Publishing.php +++ b/examples/Publishing.php @@ -72,10 +72,12 @@ // snippet.publish_with_post $result = $pubnub->publish() ->channel("my_channel") - ->message([ + ->message( + [ "text" => "Message using POST", "description" => str_repeat("Post allows to publish longer messages", 750) - ]) + ] + ) ->usePost(true) ->sync(); assert($result->getTimetoken() > 0); @@ -86,10 +88,12 @@ try { $result = $pubnub->publish() ->channel("my_channel") - ->message([ + ->message( + [ "text" => "Message using POST", "description" => str_repeat("Post allows to publish longer messages", 1410) - ]) + ] + ) ->usePost(true) ->sync(); assert($result->getTimetoken() > 0); @@ -123,10 +127,10 @@ // snippet.publish_array try { $result = $pubnub->publish() - ->channel("my_channel") - ->message(["hello", "there"]) - ->meta(["name" => "Alex", "online" => true]) - ->sync(); + ->channel("my_channel") + ->message(["hello", "there"]) + ->meta(["name" => "Alex", "online" => true]) + ->sync(); print_r($result->getTimetoken()); } catch (PubNubException $error) { echo "Error: " . $error->getMessage() . "\n"; diff --git a/examples/Subscribing.php b/examples/Subscribing.php index 43538ef..08c9990 100644 --- a/examples/Subscribing.php +++ b/examples/Subscribing.php @@ -1,7 +1,6 @@ subscribe()->channels("my_channel")->execute(); // snippet.end +// Disable for the "one class per file" rule +// phpcs:disable // snippet.subscribe_with_state class MySubscribeCallbackWithState extends SubscribeCallback { - function status($pubnub, $status) + public function status($pubnub, $status) { if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) { - $result = $pubnub->setState() - ->channels("awesomeChannel") - ->channelGroups("awesomeChannelGroup") - ->state([ - "fieldA" => "awesome", - "fieldB" => 10 - ]) - ->sync(); + $result = $pubnub + ->setState() + ->channels("awesomeChannel") + ->channelGroups("awesomeChannelGroup") + ->state([ + "fieldA" => "awesome", + "fieldB" => 10, + ]) + ->sync(); print_r($result); } } - function message($pubnub, $message) + public function message($pubnub, $message) { } - function presence($pubnub, $presence) + public function presence($pubnub, $presence) { } } @@ -153,28 +161,31 @@ function presence($pubnub, $presence) ->channels("my_channel") ->execute(); // snippet.end +// phpcs:enable +// Disable for the "one class per file" rule +// phpcs:disable // snippet.unsubscribe_from_channel use PubNub\Exceptions\PubNubUnsubscribeException; class MyUnsubscribeCallback extends SubscribeCallback { - function status($pubnub, $status) + public function status($pubnub, $status) { if ($this->checkUnsubscribeCondition()) { throw (new PubNubUnsubscribeException())->setChannels("awesomeChannel"); } } - function message($pubnub, $message) + public function message($pubnub, $message) { } - function presence($pubnub, $presence) + public function presence($pubnub, $presence) { } - function checkUnsubscribeCondition() + public function checkUnsubscribeCondition() { // return true or false return false; @@ -197,6 +208,7 @@ function checkUnsubscribeCondition() ->channels("awesomeChannel") ->execute(); // snippet.end +// phpcs:enable echo "Starting PubNub Subscriber...\n"; echo "Press Ctrl+C to exit\n"; diff --git a/phpstan.neon b/phpstan.neon index c5709f1..8dafb33 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -5,3 +5,4 @@ parameters: level: 6 paths: - src + - tests diff --git a/tests/unit/PubNubSdkInfoTest.php b/tests/unit/PubNubSdkInfoTest.php index 3a7a4c9..4426d70 100644 --- a/tests/unit/PubNubSdkInfoTest.php +++ b/tests/unit/PubNubSdkInfoTest.php @@ -11,17 +11,11 @@ class PubNubSdkInfoTest extends TestCase // getSdkVersion() TESTS // ============================================================================ - public function testGetSdkVersionReturnsString(): void - { - $version = PubNub::getSdkVersion(); - - $this->assertIsString($version); - } - public function testGetSdkVersionIsNotEmpty(): void { $version = PubNub::getSdkVersion(); + $this->assertIsString($version); $this->assertNotEmpty($version); } @@ -34,14 +28,6 @@ public function testGetSdkVersionFollowsSemanticVersioning(): void $this->assertMatchesRegularExpression($pattern, $version); } - public function testGetSdkVersionIsConsistent(): void - { - $version1 = PubNub::getSdkVersion(); - $version2 = PubNub::getSdkVersion(); - - $this->assertEquals($version1, $version2); - } - public function testGetSdkVersionStartsWithDigit(): void { $version = PubNub::getSdkVersion(); diff --git a/tests/unit/PubNubUtilityMethodsTest.php b/tests/unit/PubNubUtilityMethodsTest.php index 26ba408..34d07a6 100644 --- a/tests/unit/PubNubUtilityMethodsTest.php +++ b/tests/unit/PubNubUtilityMethodsTest.php @@ -86,19 +86,13 @@ public function testSetTokenPersistsAcrossMultipleCalls(): void // TIMESTAMP METHOD TESTS // ============================================================================ - public function testTimestampReturnsInteger(): void - { - $timestamp = $this->pubnub->timestamp(); - - $this->assertIsInt($timestamp); - } - public function testTimestampReturnsCurrentTime(): void { $before = time(); $timestamp = $this->pubnub->timestamp(); $after = time(); + $this->assertIsInt($timestamp); // Timestamp should be between before and after $this->assertGreaterThanOrEqual($before, $timestamp); $this->assertLessThanOrEqual($after, $timestamp); @@ -182,25 +176,6 @@ public function testGetSequenceIdIsUnique(): void $this->assertEquals(100, count(array_unique($ids))); } - // ============================================================================ - // TELEMETRY MANAGER TESTS - // ============================================================================ - - public function testGetTelemetryManagerReturnsInstance(): void - { - $telemetryManager = $this->pubnub->getTelemetryManager(); - - $this->assertInstanceOf(\PubNub\Managers\TelemetryManager::class, $telemetryManager); - } - - public function testGetTelemetryManagerReturnsSameInstance(): void - { - $telemetryManager1 = $this->pubnub->getTelemetryManager(); - $telemetryManager2 = $this->pubnub->getTelemetryManager(); - - $this->assertSame($telemetryManager1, $telemetryManager2); - } - // ============================================================================ // CONFIGURATION GETTER TESTS // ============================================================================ @@ -271,13 +246,6 @@ public function testGetBasePathUsesConfigurationOrigin(): void // HTTP CLIENT TESTS // ============================================================================ - public function testGetClientReturnsClientInterface(): void - { - $client = $this->pubnub->getClient(); - - $this->assertInstanceOf(\Psr\Http\Client\ClientInterface::class, $client); - } - public function testSetClientAndGetClient(): void { $mockClient = $this->createMock(\Psr\Http\Client\ClientInterface::class); @@ -299,13 +267,6 @@ public function testGetClientReturnsSameInstanceByDefault(): void // REQUEST FACTORY TESTS // ============================================================================ - public function testGetRequestFactoryReturnsRequestFactoryInterface(): void - { - $requestFactory = $this->pubnub->getRequestFactory(); - - $this->assertInstanceOf(\Psr\Http\Message\RequestFactoryInterface::class, $requestFactory); - } - public function testSetRequestFactoryAndGetRequestFactory(): void { $mockFactory = $this->createMock(\Psr\Http\Message\RequestFactoryInterface::class); diff --git a/tests/unit/TokenManagerTest.php b/tests/unit/TokenManagerTest.php deleted file mode 100644 index 597dee5..0000000 --- a/tests/unit/TokenManagerTest.php +++ /dev/null @@ -1,66 +0,0 @@ -setToken($token); - - $this->assertEquals($token, $manager->getToken()); - } - - public function testGetTokenReturnsNullByDefault(): void - { - $manager = new TokenManager(); - - $this->assertNull($manager->getToken()); - } - - public function testSetTokenOverwritesPreviousToken(): void - { - $manager = new TokenManager(); - - $manager->setToken('first-token'); - $this->assertEquals('first-token', $manager->getToken()); - - $manager->setToken('second-token'); - $this->assertEquals('second-token', $manager->getToken()); - } - - public function testSetTokenWithEmptyString(): void - { - $manager = new TokenManager(); - - $manager->setToken(''); - - $this->assertEquals('', $manager->getToken()); - } - - public function testSetTokenWithLongString(): void - { - $manager = new TokenManager(); - $longToken = str_repeat('a', 10000); - - $manager->setToken($longToken); - - $this->assertEquals($longToken, $manager->getToken()); - } - - public function testSetTokenWithSpecialCharacters(): void - { - $manager = new TokenManager(); - $specialToken = 'token-with-special!@#$%^&*()_+-={}[]|\\:";\'<>?,./'; - - $manager->setToken($specialToken); - - $this->assertEquals($specialToken, $manager->getToken()); - } -} diff --git a/tests/unit/UtilsTest.php b/tests/unit/UtilsTest.php index 0037d64..a4507bc 100644 --- a/tests/unit/UtilsTest.php +++ b/tests/unit/UtilsTest.php @@ -40,20 +40,6 @@ public function testPamEncode() self::assertEquals("abc=true&def=false&poq=4", $result); } - public function testSignSha256() - { - //phpcs:disable - $signInput = "sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f -pub-c-98863562-19a6-4760-bf0b-d537d1f5c582 -grant -channel=asyncio-pam-FI2FCS0A&pnsdk=PubNub-Python-Asyncio%252F4.0.0&r=1×tamp=1468409553&uuid=a4dbf92e-e5cb-428f-b6e6-35cce03500a2&w=1"; - - $result = PubNubUtil::signSha256("my_key", $signInput); - //phpcs:enable - - self::assertEquals("Dq92jnwRTCikdeP2nUs1__gyJthF8NChwbs5aYy2r_I=", $result); - } - public function testJoinQuery() { $elements = [ From 9084833671c6deb15727a66cab3d97696332ebaa Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 15:04:32 +0200 Subject: [PATCH 18/26] Linter fixes --- tests/unit/ListenerManagerTest.php | 13 ++++++++----- tests/unit/PNConfigurationTest.php | 8 ++++---- tests/unit/PublishTest.php | 2 +- tests/unit/TelemetryManagerTest.php | 4 ++-- tests/unit/UtilsTest.php | 8 ++++---- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/tests/unit/ListenerManagerTest.php b/tests/unit/ListenerManagerTest.php index 55e913b..d66df29 100644 --- a/tests/unit/ListenerManagerTest.php +++ b/tests/unit/ListenerManagerTest.php @@ -9,7 +9,7 @@ class ListenerManagerTest extends PubNubTestCase { - public function testUrlEncode() + public function testUrlEncode(): void { $listener = new ExposedListenerManager($this->pubnub); @@ -39,7 +39,7 @@ public function testUrlEncode() class ExposedListenerManager extends ListenerManager { - public function count() + public function count(): void { return count($this->listeners); } @@ -52,17 +52,20 @@ class MySubscribeCallback extends SubscribeCallback * @param \PubNub\Models\ResponseHelpers\PNStatus $status * @return mixed */ - function status($pubnub, $status) + /** @phpstan-ignore-next-line */ + function status($pubnub, $status): void { // TODO: Implement status() method. } - function message($pubnub, $message) + /** @phpstan-ignore-next-line */ + function message($pubnub, $message): void { // TODO: Implement message() method. } - function presence($pubnub, $presence) + /** @phpstan-ignore-next-line */ + function presence($pubnub, $presence): void { // TODO: Implement presence() method. } diff --git a/tests/unit/PNConfigurationTest.php b/tests/unit/PNConfigurationTest.php index eb3a423..0184775 100644 --- a/tests/unit/PNConfigurationTest.php +++ b/tests/unit/PNConfigurationTest.php @@ -10,21 +10,21 @@ class PNConfigurationTest extends TestCase { - public function testInitWithUUID() + public function testInitWithUUID(): void { $config = new PNConfiguration(); $config->setUuid('foo-bar-baz'); $this->assertEquals($config->getUuid(), 'foo-bar-baz'); } - public function testInitWithUserId() + public function testInitWithUserId(): void { $config = new PNConfiguration(); $config->setUserId('foo-bar-baz'); $this->assertEquals($config->getUserId(), 'foo-bar-baz'); } - public function testThrowOnUserIdAndUUID() + public function testThrowOnUserIdAndUUID(): void { $this->expectException(PubNubConfigurationException::class); $this->expectExceptionMessage("Cannot use UserId and UUID simultaneously"); @@ -33,7 +33,7 @@ public function testThrowOnUserIdAndUUID() $config->setUuid('foo-bar-baz'); } - public function testThrowOnEmptyUserId() + public function testThrowOnEmptyUserId(): void { $this->expectException(PubNubConfigurationException::class); $this->expectExceptionMessage("UserID should not be empty"); diff --git a/tests/unit/PublishTest.php b/tests/unit/PublishTest.php index ef27c7d..8c4d15b 100644 --- a/tests/unit/PublishTest.php +++ b/tests/unit/PublishTest.php @@ -11,7 +11,7 @@ class PublishTest extends TestCase * @group publish * @group publish-unit */ - public function testSequenceCounterRestartsAfterMaxReached() + public function testSequenceCounterRestartsAfterMaxReached(): void { $pubnub = PubNub::Demo(); $this->assertEquals(1, $pubnub->getSequenceId()); diff --git a/tests/unit/TelemetryManagerTest.php b/tests/unit/TelemetryManagerTest.php index f3451b4..1fbe57c 100644 --- a/tests/unit/TelemetryManagerTest.php +++ b/tests/unit/TelemetryManagerTest.php @@ -8,7 +8,7 @@ class TelemetryManagerTest extends TestCase { - public function testAverageLatency() + public function testAverageLatency(): void { $endpointLatencies = [ ["d" => 100, "l" => 10], @@ -23,7 +23,7 @@ public function testAverageLatency() $this->assertEquals(30, $averageLatency); } - public function testValidQueries() + public function testValidQueries(): void { $manager = new TelemetryManager(); diff --git a/tests/unit/UtilsTest.php b/tests/unit/UtilsTest.php index a4507bc..8b7f81f 100644 --- a/tests/unit/UtilsTest.php +++ b/tests/unit/UtilsTest.php @@ -12,13 +12,13 @@ class UtilsTest extends TestCase * @group time * @group time-integrational */ - public function testUrlEncode() + public function testUrlEncode(): void { $this->assertEquals('blah%2Bnjkl', PubNubUtil::urlEncode("blah+njkl")); $this->assertEquals('%7B%22value%22%3A%20%222%22%7D', PubNubUtil::urlEncode("{\"value\": \"2\"}")); } - public function testWriteValueAsString() + public function testWriteValueAsString(): void { //phpcs:disable $this->expectException(PubNubBuildRequestException::class); @@ -28,7 +28,7 @@ public function testWriteValueAsString() //phpcs:enable } - public function testPamEncode() + public function testPamEncode(): void { $params = [ 'abc' => true, @@ -40,7 +40,7 @@ public function testPamEncode() self::assertEquals("abc=true&def=false&poq=4", $result); } - public function testJoinQuery() + public function testJoinQuery(): void { $elements = [ 'a' => '2', From 6614f389b70626d65f906cf51b5a2536f6003239 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 15:09:21 +0200 Subject: [PATCH 19/26] Test return type fix --- tests/unit/ListenerManagerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/ListenerManagerTest.php b/tests/unit/ListenerManagerTest.php index d66df29..51e654c 100644 --- a/tests/unit/ListenerManagerTest.php +++ b/tests/unit/ListenerManagerTest.php @@ -39,7 +39,7 @@ public function testUrlEncode(): void class ExposedListenerManager extends ListenerManager { - public function count(): void + public function count(): int { return count($this->listeners); } From 4b9dfea45598a639ed17ca6806604b24ad8f273c Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 15:18:24 +0200 Subject: [PATCH 20/26] Potential PHPStan fixes --- tests/unit/ListenerManagerTest.php | 13 +++++-------- tests/unit/PNConfigurationTest.php | 8 ++++---- tests/unit/PublishTest.php | 2 +- tests/unit/TelemetryManagerTest.php | 4 ++-- tests/unit/UtilsTest.php | 8 ++++---- 5 files changed, 16 insertions(+), 19 deletions(-) diff --git a/tests/unit/ListenerManagerTest.php b/tests/unit/ListenerManagerTest.php index 51e654c..55e913b 100644 --- a/tests/unit/ListenerManagerTest.php +++ b/tests/unit/ListenerManagerTest.php @@ -9,7 +9,7 @@ class ListenerManagerTest extends PubNubTestCase { - public function testUrlEncode(): void + public function testUrlEncode() { $listener = new ExposedListenerManager($this->pubnub); @@ -39,7 +39,7 @@ public function testUrlEncode(): void class ExposedListenerManager extends ListenerManager { - public function count(): int + public function count() { return count($this->listeners); } @@ -52,20 +52,17 @@ class MySubscribeCallback extends SubscribeCallback * @param \PubNub\Models\ResponseHelpers\PNStatus $status * @return mixed */ - /** @phpstan-ignore-next-line */ - function status($pubnub, $status): void + function status($pubnub, $status) { // TODO: Implement status() method. } - /** @phpstan-ignore-next-line */ - function message($pubnub, $message): void + function message($pubnub, $message) { // TODO: Implement message() method. } - /** @phpstan-ignore-next-line */ - function presence($pubnub, $presence): void + function presence($pubnub, $presence) { // TODO: Implement presence() method. } diff --git a/tests/unit/PNConfigurationTest.php b/tests/unit/PNConfigurationTest.php index 0184775..eb3a423 100644 --- a/tests/unit/PNConfigurationTest.php +++ b/tests/unit/PNConfigurationTest.php @@ -10,21 +10,21 @@ class PNConfigurationTest extends TestCase { - public function testInitWithUUID(): void + public function testInitWithUUID() { $config = new PNConfiguration(); $config->setUuid('foo-bar-baz'); $this->assertEquals($config->getUuid(), 'foo-bar-baz'); } - public function testInitWithUserId(): void + public function testInitWithUserId() { $config = new PNConfiguration(); $config->setUserId('foo-bar-baz'); $this->assertEquals($config->getUserId(), 'foo-bar-baz'); } - public function testThrowOnUserIdAndUUID(): void + public function testThrowOnUserIdAndUUID() { $this->expectException(PubNubConfigurationException::class); $this->expectExceptionMessage("Cannot use UserId and UUID simultaneously"); @@ -33,7 +33,7 @@ public function testThrowOnUserIdAndUUID(): void $config->setUuid('foo-bar-baz'); } - public function testThrowOnEmptyUserId(): void + public function testThrowOnEmptyUserId() { $this->expectException(PubNubConfigurationException::class); $this->expectExceptionMessage("UserID should not be empty"); diff --git a/tests/unit/PublishTest.php b/tests/unit/PublishTest.php index 8c4d15b..ef27c7d 100644 --- a/tests/unit/PublishTest.php +++ b/tests/unit/PublishTest.php @@ -11,7 +11,7 @@ class PublishTest extends TestCase * @group publish * @group publish-unit */ - public function testSequenceCounterRestartsAfterMaxReached(): void + public function testSequenceCounterRestartsAfterMaxReached() { $pubnub = PubNub::Demo(); $this->assertEquals(1, $pubnub->getSequenceId()); diff --git a/tests/unit/TelemetryManagerTest.php b/tests/unit/TelemetryManagerTest.php index 1fbe57c..f3451b4 100644 --- a/tests/unit/TelemetryManagerTest.php +++ b/tests/unit/TelemetryManagerTest.php @@ -8,7 +8,7 @@ class TelemetryManagerTest extends TestCase { - public function testAverageLatency(): void + public function testAverageLatency() { $endpointLatencies = [ ["d" => 100, "l" => 10], @@ -23,7 +23,7 @@ public function testAverageLatency(): void $this->assertEquals(30, $averageLatency); } - public function testValidQueries(): void + public function testValidQueries() { $manager = new TelemetryManager(); diff --git a/tests/unit/UtilsTest.php b/tests/unit/UtilsTest.php index 8b7f81f..a4507bc 100644 --- a/tests/unit/UtilsTest.php +++ b/tests/unit/UtilsTest.php @@ -12,13 +12,13 @@ class UtilsTest extends TestCase * @group time * @group time-integrational */ - public function testUrlEncode(): void + public function testUrlEncode() { $this->assertEquals('blah%2Bnjkl', PubNubUtil::urlEncode("blah+njkl")); $this->assertEquals('%7B%22value%22%3A%20%222%22%7D', PubNubUtil::urlEncode("{\"value\": \"2\"}")); } - public function testWriteValueAsString(): void + public function testWriteValueAsString() { //phpcs:disable $this->expectException(PubNubBuildRequestException::class); @@ -28,7 +28,7 @@ public function testWriteValueAsString(): void //phpcs:enable } - public function testPamEncode(): void + public function testPamEncode() { $params = [ 'abc' => true, @@ -40,7 +40,7 @@ public function testPamEncode(): void self::assertEquals("abc=true&def=false&poq=4", $result); } - public function testJoinQuery(): void + public function testJoinQuery() { $elements = [ 'a' => '2', From 23793025200098b23682c1cd342409df0790b0a7 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 15:21:19 +0200 Subject: [PATCH 21/26] Revert "Potential PHPStan fixes" This reverts commit 4b9dfea45598a639ed17ca6806604b24ad8f273c. --- tests/unit/ListenerManagerTest.php | 13 ++++++++----- tests/unit/PNConfigurationTest.php | 8 ++++---- tests/unit/PublishTest.php | 2 +- tests/unit/TelemetryManagerTest.php | 4 ++-- tests/unit/UtilsTest.php | 8 ++++---- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/tests/unit/ListenerManagerTest.php b/tests/unit/ListenerManagerTest.php index 55e913b..51e654c 100644 --- a/tests/unit/ListenerManagerTest.php +++ b/tests/unit/ListenerManagerTest.php @@ -9,7 +9,7 @@ class ListenerManagerTest extends PubNubTestCase { - public function testUrlEncode() + public function testUrlEncode(): void { $listener = new ExposedListenerManager($this->pubnub); @@ -39,7 +39,7 @@ public function testUrlEncode() class ExposedListenerManager extends ListenerManager { - public function count() + public function count(): int { return count($this->listeners); } @@ -52,17 +52,20 @@ class MySubscribeCallback extends SubscribeCallback * @param \PubNub\Models\ResponseHelpers\PNStatus $status * @return mixed */ - function status($pubnub, $status) + /** @phpstan-ignore-next-line */ + function status($pubnub, $status): void { // TODO: Implement status() method. } - function message($pubnub, $message) + /** @phpstan-ignore-next-line */ + function message($pubnub, $message): void { // TODO: Implement message() method. } - function presence($pubnub, $presence) + /** @phpstan-ignore-next-line */ + function presence($pubnub, $presence): void { // TODO: Implement presence() method. } diff --git a/tests/unit/PNConfigurationTest.php b/tests/unit/PNConfigurationTest.php index eb3a423..0184775 100644 --- a/tests/unit/PNConfigurationTest.php +++ b/tests/unit/PNConfigurationTest.php @@ -10,21 +10,21 @@ class PNConfigurationTest extends TestCase { - public function testInitWithUUID() + public function testInitWithUUID(): void { $config = new PNConfiguration(); $config->setUuid('foo-bar-baz'); $this->assertEquals($config->getUuid(), 'foo-bar-baz'); } - public function testInitWithUserId() + public function testInitWithUserId(): void { $config = new PNConfiguration(); $config->setUserId('foo-bar-baz'); $this->assertEquals($config->getUserId(), 'foo-bar-baz'); } - public function testThrowOnUserIdAndUUID() + public function testThrowOnUserIdAndUUID(): void { $this->expectException(PubNubConfigurationException::class); $this->expectExceptionMessage("Cannot use UserId and UUID simultaneously"); @@ -33,7 +33,7 @@ public function testThrowOnUserIdAndUUID() $config->setUuid('foo-bar-baz'); } - public function testThrowOnEmptyUserId() + public function testThrowOnEmptyUserId(): void { $this->expectException(PubNubConfigurationException::class); $this->expectExceptionMessage("UserID should not be empty"); diff --git a/tests/unit/PublishTest.php b/tests/unit/PublishTest.php index ef27c7d..8c4d15b 100644 --- a/tests/unit/PublishTest.php +++ b/tests/unit/PublishTest.php @@ -11,7 +11,7 @@ class PublishTest extends TestCase * @group publish * @group publish-unit */ - public function testSequenceCounterRestartsAfterMaxReached() + public function testSequenceCounterRestartsAfterMaxReached(): void { $pubnub = PubNub::Demo(); $this->assertEquals(1, $pubnub->getSequenceId()); diff --git a/tests/unit/TelemetryManagerTest.php b/tests/unit/TelemetryManagerTest.php index f3451b4..1fbe57c 100644 --- a/tests/unit/TelemetryManagerTest.php +++ b/tests/unit/TelemetryManagerTest.php @@ -8,7 +8,7 @@ class TelemetryManagerTest extends TestCase { - public function testAverageLatency() + public function testAverageLatency(): void { $endpointLatencies = [ ["d" => 100, "l" => 10], @@ -23,7 +23,7 @@ public function testAverageLatency() $this->assertEquals(30, $averageLatency); } - public function testValidQueries() + public function testValidQueries(): void { $manager = new TelemetryManager(); diff --git a/tests/unit/UtilsTest.php b/tests/unit/UtilsTest.php index a4507bc..8b7f81f 100644 --- a/tests/unit/UtilsTest.php +++ b/tests/unit/UtilsTest.php @@ -12,13 +12,13 @@ class UtilsTest extends TestCase * @group time * @group time-integrational */ - public function testUrlEncode() + public function testUrlEncode(): void { $this->assertEquals('blah%2Bnjkl', PubNubUtil::urlEncode("blah+njkl")); $this->assertEquals('%7B%22value%22%3A%20%222%22%7D', PubNubUtil::urlEncode("{\"value\": \"2\"}")); } - public function testWriteValueAsString() + public function testWriteValueAsString(): void { //phpcs:disable $this->expectException(PubNubBuildRequestException::class); @@ -28,7 +28,7 @@ public function testWriteValueAsString() //phpcs:enable } - public function testPamEncode() + public function testPamEncode(): void { $params = [ 'abc' => true, @@ -40,7 +40,7 @@ public function testPamEncode() self::assertEquals("abc=true&def=false&poq=4", $result); } - public function testJoinQuery() + public function testJoinQuery(): void { $elements = [ 'a' => '2', From 1dfbeb87920f8f8eb08009577ba32e8c596381e8 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 15:27:35 +0200 Subject: [PATCH 22/26] Test phpstan neon file change --- phpstan-baseline.neon | 99 ------------------------------------------- 1 file changed, 99 deletions(-) diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 2944a1a..e2e479a 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -7110,102 +7110,3 @@ parameters: count: 1 path: tests/unit/CryptoTest.php - - - message: "#^Method ExposedListenerManager\\:\\:count\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method ListenerManagerTest\\:\\:testUrlEncode\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method MySubscribeCallback\\:\\:message\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method MySubscribeCallback\\:\\:message\\(\\) has parameter \\$message with no type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method MySubscribeCallback\\:\\:message\\(\\) has parameter \\$pubnub with no type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method MySubscribeCallback\\:\\:presence\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method MySubscribeCallback\\:\\:presence\\(\\) has parameter \\$presence with no type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method MySubscribeCallback\\:\\:presence\\(\\) has parameter \\$pubnub with no type specified\\.$#" - count: 1 - path: tests/unit/ListenerManagerTest.php - - - - message: "#^Method PNConfigurationTest\\:\\:testInitWithUUID\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/PNConfigurationTest.php - - - - message: "#^Method PNConfigurationTest\\:\\:testInitWithUserId\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/PNConfigurationTest.php - - - - message: "#^Method PNConfigurationTest\\:\\:testThrowOnEmptyUserId\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/PNConfigurationTest.php - - - - message: "#^Method PNConfigurationTest\\:\\:testThrowOnUserIdAndUUID\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/PNConfigurationTest.php - - - - message: "#^Method PublishTest\\:\\:testSequenceCounterRestartsAfterMaxReached\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/PublishTest.php - - - - message: "#^Method TelemetryManagerTest\\:\\:testAverageLatency\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/TelemetryManagerTest.php - - - - message: "#^Method TelemetryManagerTest\\:\\:testValidQueries\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/TelemetryManagerTest.php - - - - message: "#^Method UtilsTest\\:\\:testJoinQuery\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/UtilsTest.php - - - - message: "#^Method UtilsTest\\:\\:testPamEncode\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/UtilsTest.php - - - - message: "#^Method UtilsTest\\:\\:testSignSha256\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/UtilsTest.php - - - - message: "#^Method UtilsTest\\:\\:testUrlEncode\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/UtilsTest.php - - - - message: "#^Method UtilsTest\\:\\:testWriteValueAsString\\(\\) has no return type specified\\.$#" - count: 1 - path: tests/unit/UtilsTest.php From 1733bbfe17861ed76fe9012543eef4406b46997e Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 15:30:42 +0200 Subject: [PATCH 23/26] Remove ignore line --- tests/unit/ListenerManagerTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/ListenerManagerTest.php b/tests/unit/ListenerManagerTest.php index 51e654c..812109b 100644 --- a/tests/unit/ListenerManagerTest.php +++ b/tests/unit/ListenerManagerTest.php @@ -52,7 +52,6 @@ class MySubscribeCallback extends SubscribeCallback * @param \PubNub\Models\ResponseHelpers\PNStatus $status * @return mixed */ - /** @phpstan-ignore-next-line */ function status($pubnub, $status): void { // TODO: Implement status() method. From 74b1afc9bb772af200c990cdca9dd90c966cabbd Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 15:32:33 +0200 Subject: [PATCH 24/26] Return types tweak --- tests/unit/ListenerManagerTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unit/ListenerManagerTest.php b/tests/unit/ListenerManagerTest.php index 812109b..ffa2de2 100644 --- a/tests/unit/ListenerManagerTest.php +++ b/tests/unit/ListenerManagerTest.php @@ -52,19 +52,19 @@ class MySubscribeCallback extends SubscribeCallback * @param \PubNub\Models\ResponseHelpers\PNStatus $status * @return mixed */ - function status($pubnub, $status): void + function status($pubnub, $status) { // TODO: Implement status() method. } /** @phpstan-ignore-next-line */ - function message($pubnub, $message): void + function message($pubnub, $message) { // TODO: Implement message() method. } /** @phpstan-ignore-next-line */ - function presence($pubnub, $presence): void + function presence($pubnub, $presence) { // TODO: Implement presence() method. } From 714bbf01eecc5cedc0b5e49c274d7713b95f0032 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 16:31:55 +0200 Subject: [PATCH 25/26] Add configuration snippets verification --- examples/Configuration.php | 96 +++++++++++++++++++++------- tests/Examples/ConfigurationTest.php | 21 ++++++ 2 files changed, 94 insertions(+), 23 deletions(-) create mode 100644 tests/Examples/ConfigurationTest.php diff --git a/examples/Configuration.php b/examples/Configuration.php index e6b30c8..8e4a53f 100644 --- a/examples/Configuration.php +++ b/examples/Configuration.php @@ -24,15 +24,20 @@ $pnConfiguration->setUserId('php-config-demo-user'); // snippet.end +// Verify configuration was set correctly +assert($pnConfiguration->getSubscribeKey() === (getenv('SUBSCRIBE_KEY') ?? 'demo')); +assert($pnConfiguration->getPublishKey() === (getenv('PUBLISH_KEY') ?? 'demo')); +assert($pnConfiguration->getUserId() === 'php-config-demo-user'); + // snippet.basic_configuration // Create a new configuration instance $pnConfiguration = new PNConfiguration(); // Set subscribe key (required) -$pnConfiguration->setSubscribeKey("demo"); +$pnConfiguration->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); // Set publish key (only required if publishing) -$pnConfiguration->setPublishKey("demo"); +$pnConfiguration->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo'); // Set UUID (required to connect) $pnConfiguration->setUserId("php-sdk-example-user"); @@ -85,38 +90,63 @@ // Otherwise, the script will exit after publishing // snippet.end +// Verify configuration values +assert($pnConfiguration->getSubscribeKey() === getenv('SUBSCRIBE_KEY') ?? 'demo'); +assert($pnConfiguration->getPublishKey() === getenv('PUBLISH_KEY') ?? 'demo'); +assert($pnConfiguration->getUserId() === "php-sdk-example-user"); +assert($pnConfiguration->getConnectTimeout() === 10); +assert($pnConfiguration->getSubscribeTimeout() === 310); +assert($pnConfiguration->getNonSubscribeRequestTimeout() === 10); + +// Verify PubNub instance was created +assert($pubnub instanceof PubNub); + // snippet.init_basic $pnconf = new PNConfiguration(); -$pnconf->setSubscribeKey("my-key"); -$pnconf->setPublishKey("my-key"); +$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); +$pnconf->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo'); $pnconf->setSecure(false); $pnconf->setUserId("myUniqueUserId"); $pubnub = new PubNub($pnconf); + // snippet.end +// Verify configuration +assert($pnconf->getSubscribeKey() === getenv('SUBSCRIBE_KEY') ?? 'demo'); +assert($pnconf->getPublishKey() === getenv('PUBLISH_KEY') ?? 'demo'); +assert($pnconf->getUserId() === "myUniqueUserId"); +assert($pubnub instanceof PubNub); + // snippet.init_access_manager $pnConfiguration = new PNConfiguration(); -$pnConfiguration->setSubscribeKey("my_sub_key"); -$pnConfiguration->setPublishKey("my_pub_key"); +$pnConfiguration->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); +$pnConfiguration->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo'); //NOTE: only server side should have secret key -$pnConfiguration->setSecretKey("my_secret_key"); +$pnConfiguration->setSecretKey(getenv('SECRET_KEY') ?? 'demo'); $pnConfiguration->setUserId("myUniqueUserId"); $pubnub = new PubNub($pnConfiguration); // snippet.end +// Verify configuration +assert($pnConfiguration->getSubscribeKey() === getenv('SUBSCRIBE_KEY') ?? 'demo'); +assert($pnConfiguration->getPublishKey() === getenv('PUBLISH_KEY') ?? 'demo'); +assert($pnConfiguration->getSecretKey() === getenv('SECRET_KEY') ?? 'demo'); +assert($pnConfiguration->getUserId() === "myUniqueUserId"); +assert($pubnub instanceof PubNub); + // snippet.event_listeners class MySubscribeCallback extends SubscribeCallback { function status($pubnub, $status) { if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) { - // This event happens when radio / connectivity is lost + // This event happens when connectivity is lost } elseif ($status->getCategory() === PNStatusCategory::PNConnectedCategory) { - // Connect event. You can do stuff like publish, and know you'll get it // Or just use the connected event to confirm you are subscribed for // UI / internal notifications, etc + // Connect event. You can do stuff like publish, and know you'll get it } elseif ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) { - // Handle message decryption error. Probably client configured to // encrypt messages and on live data feed it received plain text. + // Handle message decryption error. } } @@ -131,35 +161,55 @@ function presence($pubnub, $presence) } $pnconf = new PNConfiguration(); -$pubnub = new PubNub($pnconf); -$pnconf->setSubscribeKey("my_sub_key"); -$pnconf->setPublishKey("my_pub_key"); +$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); +$pnconf->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo'); +$pnconf->setUserId("event-listener-demo-user"); + +$pubnub = new PubNub($pnconf); $subscribeCallback = new MySubscribeCallback(); $pubnub->addListener($subscribeCallback); // Subscribe to a channel, this is not async. -$pubnub->subscribe() -->channels("hello_world") -->execute(); +// Note: This would block +// $pubnub->subscribe() +// ->channels("hello_world") +// ->execute(); // Use the publish command separately from the Subscribe code shown above. // Subscribe is not async and will block the execution until complete. -$result = $pubnub->publish() -->channel("hello_world") -->message("Hello PubNub") -->sync(); - -print_r($result); +// Note: Commented out for testing to avoid network calls +// $result = $pubnub->publish() +// ->channel("hello_world") +// ->message("Hello PubNub") +// ->sync(); +// +// // Verify publish result +// assert($result->getTimetoken() > 0); +// +// print_r($result); // snippet.end // snippet.set_filter_expression $pnconf = new PNConfiguration(); -$pnconf->setSubscribeKey("my_sub_key"); +$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); +$pnconf->setUserId("filter-demo-user"); $pnconf->setFilterExpression("userid == 'my_userid'"); $pubnub = new PubNub($pnconf); // snippet.end + +// Verify configuration +assert($pnconf->getSubscribeKey() === "my_sub_key"); +assert($pnconf->getPublishKey() === "my_pub_key"); +assert($pnconf->getUserId() === "event-listener-demo-user"); +assert($pubnub instanceof PubNub); +// Verify callback instance +assert($subscribeCallback instanceof SubscribeCallback); +// Verify configuration +assert($pnconf->getSubscribeKey() === "my_sub_key"); +assert($pnconf->getFilterExpression() === "userid == 'my_userid'"); +assert($pubnub instanceof PubNub); diff --git a/tests/Examples/ConfigurationTest.php b/tests/Examples/ConfigurationTest.php new file mode 100644 index 0000000..273f012 --- /dev/null +++ b/tests/Examples/ConfigurationTest.php @@ -0,0 +1,21 @@ +assertTrue(true); // If we reach this point, all examples passed + } +} + From d734b475e61eba5f24d32d76a55a2b1862bb9247 Mon Sep 17 00:00:00 2001 From: "PUBNUB\\jakub.grzesiowski" Date: Wed, 15 Oct 2025 16:37:08 +0200 Subject: [PATCH 26/26] Remove whitespace --- tests/Examples/ConfigurationTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Examples/ConfigurationTest.php b/tests/Examples/ConfigurationTest.php index 273f012..2fa7e93 100644 --- a/tests/Examples/ConfigurationTest.php +++ b/tests/Examples/ConfigurationTest.php @@ -18,4 +18,3 @@ public function testExamples(): void $this->assertTrue(true); // If we reach this point, all examples passed } } -