diff --git a/examples/AccessManagerV2.php b/examples/AccessManagerV2.php new file mode 100644 index 0000000..0677675 --- /dev/null +++ b/examples/AccessManagerV2.php @@ -0,0 +1,120 @@ +setSecretKey(getenv('SECRET_KEY') ?: 'demo'); +$config->setPublishKey(getenv('PUBLISH_KEY') ?: 'demo'); +$config->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?: 'demo'); +$config->setUserId('example'); + +$pubnub = new PubNub($config); +// snippet.end + +// snippet.grant_channel_authkey +$channels = ["ch1", "ch2"]; +$auth_key = "blah"; +$read = true; +$write = false; +$ttl_mins = 15; +try { + $result = $pubnub->grant() + ->channels($channels) + ->authKeys($auth_key) + ->read($read) + ->write($write) + ->ttl($ttl_mins) + ->sync(); + print("Grant successful\n"); +} catch (\PubNub\Exceptions\PubNubServerException $exception) { + print_r("Message: " . $exception->getMessage() . "\n"); + print_r("Status: " . $exception->getStatusCode() . "\n"); + echo "Original message: "; + print_r($exception->getBody()); +} catch (\PubNub\Exceptions\PubNubException $exception) { + print_r("Message: " . $exception->getMessage()); +} +// snippet.end + +// snippet.grant_all_channels +$pubnub->grant() + ->read(true) + ->write(true) + ->sync(); +// snippet.end + +// snippet.grant_specific_channel +$pubnub->grant() + ->channels("my_channel") + ->read(true) + ->write(true) + ->sync(); +// snippet.end + +// snippet.grant_channel_with_authkey +$pubnub->grant() + ->channels("my_channel") + ->read(true) + ->write(false) + ->authKeys("my_ro_authkey") + ->ttl(5) + ->sync(); +// snippet.end + +// snippet.grant_presence_channel +$pubnub->grant() + ->channels("my_channel-pnpres") + ->read(true) + ->write(true) + ->sync(); +// snippet.end + +// snippet.grant_channel_group +$result = $pubnub->grant() + ->channelGroups(["cg1", "cg2", "cg3"]) + ->authKeys(["key1", "key2", "auth3"]) + ->read(true) + ->write(true) + ->manage(true) + ->ttl(12237) + ->sync(); +// snippet.end + +// snippet.grant_application_level +try { + $result = $pubnub->grant() + ->read(true) + ->write(true) + ->sync(); + + print_r($result); +} catch (\PubNub\Exceptions\PubNubServerException $exception) { + print_r($exception->getMessage() . "\n"); + print_r($exception->getStatusCode() . "\n"); + print_r($exception->getBody()); +} catch (\PubNub\Exceptions\PubNubException $exception) { + print_r($exception->getMessage()); +} +// snippet.end + +// snippet.grant_channel_level +$result = $pubnub->grant() + ->channels("my_channel") + ->read(true) + ->write(true) + ->sync(); +// snippet.end + +// snippet.grant_user_level +$result = $pubnub->grant() + ->channels("my_channel") + ->authKeys("my_authkey") + ->read(true) + ->write(true) + ->ttl(5) + ->sync(); +// snippet.end diff --git a/examples/AppContext.php b/examples/AppContext.php index 7679fc2..44bbf6f 100644 --- a/examples/AppContext.php +++ b/examples/AppContext.php @@ -198,6 +198,19 @@ assert($updateChannelMetadataResult->getName() === $sampleChannels[0]['name'] . ' - Updated'); // snippet.end +// snippet.write_updated_metadata_back +// Writing the updated object back to the server +$pubnub->setChannelMetadata() + ->channel($sampleChannels[0]['id']) + ->meta([ + "name" => $updateChannelMetadataResult->getName(), + "description" => $updateChannelMetadataResult->getDescription(), + "custom" => $updatedChannelCustom, + ]) + ->sync(); +print("Object has been updated.\n"); +// snippet.end + // snippet.remove_channel_metadata $removeChannelMetadataResult = $pubnub->removeChannelMetadata() ->channel($sampleChannels[1]['id']) diff --git a/examples/ChannelGroups.php b/examples/ChannelGroups.php new file mode 100644 index 0000000..2c6d3e8 --- /dev/null +++ b/examples/ChannelGroups.php @@ -0,0 +1,46 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-channel-group-demo"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); +// snippet.end + +// snippet.add_channels +$result = $pubnub->addChannelToChannelGroup() + ->channels(["news", "sports"]) + ->channelGroup("my-group") + ->sync(); + +echo "Channels added to group successfully!" . PHP_EOL; +// snippet.end + +// snippet.list_channels +$result = $pubnub->listChannelsInChannelGroup() + ->channelGroup("cg1") + ->sync(); +// snippet.end + +// snippet.remove_channels +$pubnub->removeChannelFromChannelGroup() + ->channels("son") + ->channelGroup("family") + ->sync(); +// snippet.end + +// snippet.delete_channel_group +$pubnub->removeChannelGroup() + ->channelGroup("family") + ->sync(); +// snippet.end diff --git a/examples/Configuration.php b/examples/Configuration.php index 8f26f77..342c774 100644 --- a/examples/Configuration.php +++ b/examples/Configuration.php @@ -7,8 +7,12 @@ use PubNub\PNConfiguration; use PubNub\PubNub; use PubNub\CryptoModule; +use PubNub\Crypto\AesCbcCryptor; +use PubNub\Crypto\LegacyCryptor; use PubNub\Enums\PNStatusCategory; use PubNub\Callbacks\SubscribeCallback; +use PubNub\PubNubCrypto; +use PubNub\PubNubCryptoLegacy; // snippet.setup // Create a new configuration instance @@ -202,6 +206,103 @@ function presence($pubnub, $presence) $pubnub = new PubNub($pnconf); // snippet.end +// snippet.init_non_secure +$pnConfiguration = new PNConfiguration(); + +$pnConfiguration->setSubscribeKey("my_sub_key"); +$pnConfiguration->setPublishKey("my_pub_key"); +$pnConfiguration->setSecure(false); +$pnConfiguration->setUserId("myUniqueUserId"); +$pubnub = new PubNub($pnConfiguration); +// snippet.end + +// snippet.init_read_only +$pnConfiguration = new PNConfiguration(); + +$pnConfiguration->setUserId("myUniqueUserId"); +$pnConfiguration->setSubscribeKey("my_sub_key"); + +$pubnub = new PubNub($pnConfiguration); +// snippet.end + +// snippet.use_custom_uuid +$pnconf = new PNConfiguration(); + +$pnconf->setSubscribeKey("mySubscribeKey"); +$pnconf->setPublishKey("myPublishKey"); +$pnconf->setUserId("myUniqueUserId"); + +$pubnub = new PubNub($pnconf); +// snippet.end + +// snippet.remove_listeners +$subscribeCallback = new MySubscribeCallback(); + +$pubnub->addListener($subscribeCallback); + +// some time later +$pubnub->removeListener($subscribeCallback); +// snippet.end + +// snippet.set_user_id +$pnconf = new PNConfiguration(); +$pnconf->setUserId("myUniqueUserId"); +// snippet.end + +// snippet.get_user_id +$pubnub->getConfiguration() + ->getUserId(); +// snippet.end + +// snippet.set_auth_key +$pubnub->getConfiguration() + ->setAuthKey("my_newauthkey"); +// snippet.end + +// snippet.get_auth_key +$pubnub->getConfiguration() + ->getAuthKey(); +// snippet.end + +// snippet.get_filter_expression +$pubnub->getConfiguration()->getFilterExpression(); +// snippet.end + +// snippet.disable_immutable_check +$config = new PNConfiguration(); +$config->setPublishKey('demo'); +$config->setSubscribeKey('demo'); +$config->setUserId('demo'); +// not recommended, disables config immutability +$config->disableImmutableCheck(); + +$pn = new PubNub($config); +// snippet.end + +// snippet.crypto_module_setup +// encrypts using 256-bit AES-CBC cipher (recommended) +// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers +$pnConfiguration = new PNConfiguration(); +$pnConfiguration->setSubscribeKey('demo'); +$pnConfiguration->setPublishKey('demo'); +$pnConfiguration->setUserId('crypto-demo'); +$cryptoModule = CryptoModule::aesCbcCryptor("enigma", true); +$pnConfiguration->setCryptoModule($cryptoModule); + +$pubnub = new PubNub($pnConfiguration); + +// encrypts with 128-bit cipher key entropy(legacy) +// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers +$pnConfiguration2 = new PNConfiguration(); +$pnConfiguration2->setSubscribeKey('demo'); +$pnConfiguration2->setPublishKey('demo'); +$pnConfiguration2->setUserId('crypto-demo-legacy'); +$legacyCryptoModule = CryptoModule::legacyCryptor("enigma", true); +$pnConfiguration2->setCryptoModule($legacyCryptoModule); + +$pubnub2 = new PubNub($pnConfiguration2); +// snippet.end + // Verify configuration assert($pnconf->getSubscribeKey() === (getenv('SUBSCRIBE_KEY') ?: 'demo')); assert($pnconf->getUserId() === "filter-demo-user"); diff --git a/examples/MessageActions.php b/examples/MessageActions.php index 3f60d9e..47b4de7 100644 --- a/examples/MessageActions.php +++ b/examples/MessageActions.php @@ -491,3 +491,45 @@ function tagForAnalytics($pubnub, $channel, $messageTimetoken, $tag, $value) } echo "\n=== MESSAGE ACTIONS DEMO COMPLETE ===\n"; + +// snippet.fetch_messages_with_paging +function getMessageActionsWithPaging($pubnub, $channel, $start = null) +{ + $allActions = []; + $currentStart = $start; + + do { + $builder = $pubnub->getMessageActions() + ->channel($channel); + + if ($currentStart !== null) { + $builder->setStart($currentStart); + } + + $result = $builder->sync(); + $actions = $result->actions; + + if (!empty($actions)) { + $allActions = array_merge($allActions, $actions); + // Get the timetoken of the last action for pagination + $lastAction = end($actions); + $currentStart = $lastAction->actionTimetoken; + } else { + break; + } + } while (!empty($actions) && count($allActions) < 20); // Limit to 20 for demo + + return $allActions; +} + +// Usage example +$actions = getMessageActionsWithPaging($pubnub, 'my_channel'); +foreach ($actions as $action) { + echo "Type: " . $action->getType() . "\n"; + echo "Value: " . $action->getValue() . "\n"; + echo "UUID: " . $action->getUuid() . "\n"; + echo "Message Timetoken: " . $action->getMessageTimetoken() . "\n"; + echo "Action Timetoken: " . $action->getActionTimetoken() . "\n"; + echo "---\n"; +} +// snippet.end diff --git a/examples/MessagePersistance.php b/examples/MessagePersistance.php index 8c00a0e..a372e49 100644 --- a/examples/MessagePersistance.php +++ b/examples/MessagePersistance.php @@ -237,12 +237,13 @@ public function demoHistoryReverse() echo "Retrieving oldest 3 messages first...\n"; try { + // snippet.history_reverse $result = $this->pubnub->history() - ->channel($this->demoChannel) + ->channel("my_channel") ->count(3) ->reverse(true) - ->includeTimetoken(true) ->sync(); + // snippet.end echo " 📊 Reverse History Results:\n"; $messages = $result->getMessages(); diff --git a/examples/MobilePush.php b/examples/MobilePush.php index 6d0e49a..b8a1498 100644 --- a/examples/MobilePush.php +++ b/examples/MobilePush.php @@ -271,6 +271,19 @@ private function demonstrateRemoveAllChannelsFromDevice($device) ->deviceId($device['deviceId']) ->sync(); // snippet.end + + // snippet.remove_all_channels_response_check + $response = $this->pubnub->removeAllPushChannelsForDevice() + ->pushType(PNPushType::APNS2) + ->deviceId("yourDeviceId") + ->sync(); + + if ($response->isSuccessful()) { + echo "Successfully removed all push channels from device."; + } else { + echo "Failed to remove push channels."; + } + // snippet.end } echo " ✅ Successfully removed all push channels from device\n\n"; diff --git a/examples/Publishing.php b/examples/Publishing.php index ea0fd4b..d49d8b1 100644 --- a/examples/Publishing.php +++ b/examples/Publishing.php @@ -72,12 +72,10 @@ // 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); @@ -88,12 +86,10 @@ 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); diff --git a/examples/Snippets.php b/examples/Snippets.php new file mode 100644 index 0000000..45e231e --- /dev/null +++ b/examples/Snippets.php @@ -0,0 +1,179 @@ +setSubscribeKey(getenv('SUBSCRIBE_KEY') ?: 'demo'); +$config->setPublishKey(getenv('PUBLISH_KEY') ?: 'demo'); +$config->setSecretKey(getenv('SECRET_KEY') ?: 'demo'); +$config->setUserId('snippets-demo'); +$pubnub = new PubNub($config); + +// MESSAGE PERSISTENCE SNIPPETS + +// snippet.history_newer_than_timetoken +$pubnub->history() + ->channel("my_channel") + ->start(13847168620721752) + ->reverse(true) + ->sync(); +// snippet.end + +// snippet.history_until_timetoken +$pubnub->history() + ->channel("my_channel") + ->count(100) + ->start(-1) + ->end(13847168819178600) + ->reverse(true) + ->sync(); +// snippet.end + +// snippet.history_include_timetoken +$pubnub->history() + ->channel("my_channel") + ->count(5) + ->includeTimetoken(true) + ->sync(); +// snippet.end + +// snippet.delete_specific_message +$pubnub->deleteMessages() + ->channel("my_channel") + ->start(15957709532217050) + ->end(15957709532217050) + ->sync(); +// snippet.end + +// snippet.message_counts_different_timetokens +$pubnub->messageCounts() + ->channels(["my_channel1", "my_channel2"]) + ->channelsTimetoken([ + "my_channel1" => 15614559062344052, + "my_channel2" => 15614559062344053 + ]) + ->sync(); +// snippet.end + +// PRESENCE SNIPPETS + +// snippet.here_now_with_state +$result = $pubnub->hereNow() + ->channels("my_channel") + ->includeUuids(true) + ->includeState(true) + ->sync(); +// snippet.end + +// snippet.here_now_occupancy_only +$result = $pubnub->hereNow() + ->channels("my_channel") + ->includeUuids(false) + ->includeState(false) + ->sync(); +// snippet.end + +// snippet.here_now_channel_groups +$pubnub->hereNow() + ->channelGroups(["cg1", "cg2", "cg3"]) + ->includeUuids(true) + ->includeState(true) + ->sync(); +// snippet.end + +// snippet.where_now +$result = $pubnub->whereNow() + ->sync(); +// snippet.end + +// snippet.where_now_specific_uuid +$result = $pubnub->whereNow() + ->uuid("his-uuid") + ->sync(); +// snippet.end + +// snippet.set_state +$pubnub->setState() + ->channels(["ch1", "ch2", "ch3"]) + ->state(["age" => 30]) + ->sync(); +// snippet.end + +// snippet.get_state +$pubnub->getState() + ->channels(["ch1", "ch2", "ch3"]) + ->sync(); +// snippet.end + +// snippet.set_state_channel_group +$pubnub->setState() + ->channelGroups(["cg1", "cg2", "cg3"]) + ->state(["age" => 30]) + ->sync(); +// snippet.end + +// ACCESS MANAGER V3 SNIPPETS + +// snippet.grant_different_access_levels +$pubnub->grantToken() + ->ttl(15) + ->authorizedUuid('my-authorized-uuid') + ->addChannelResources([ + 'channel-a' => ['read' => true], + 'channel-b' => ['read' => true, 'write' => true], + 'channel-c' => ['read' => true, 'write' => true], + 'channel-d' => ['read' => true, 'write' => true], + ]) + ->addChannelGroupResources([ + 'channel-group-b' => ['read' => true], + ]) + ->addUuidResources([ + 'uuid-c' => ['get' => true], + 'uuid-d' => ['get' => true, 'update' => true], + ]) + ->sync(); +// snippet.end + +// snippet.grant_regex_channels +$pubnub->grantToken() + ->ttl(15) + ->authorizedUuid('my-authorized-uuid') + ->addChannelPatterns([ + '^channel-[A-Za-z0-9]$' => ['read' => true], + ]) + ->sync(); +// snippet.end + +// snippet.grant_combined_regex +$pubnub->grantToken() + ->ttl(15) + ->authorizedUuid('my-authorized-uuid') + ->addChannelResources([ + 'channel-a' => ['read' => true], + 'channel-b' => ['read' => true, 'write' => true], + 'channel-c' => ['read' => true, 'write' => true], + 'channel-d' => ['read' => true, 'write' => true], + ]) + ->addChannelGroupResources([ + 'channel-group-b' => ['read' => true], + ]) + ->addUuidResources([ + 'uuid-c' => ['get' => true], + 'uuid-d' => ['get' => true, 'update' => true], + ]) + ->addChannelPatterns([ + '^channel-[A-Za-z0-9]$' => ['read' => true], + ]); +// snippet.end + +// Disabling phpcs to keep token as one line +// phpcs:disable +// snippet.permissions_object_example +$pubnub->parseToken("p0F2AkF0Gl2BEIJDdHRsGGRDcmVzpERjaGFuoENncnCgQ3VzcqBDc3BjoENwYXSkRGNoYW6gQ2dycKBDdXNyomZeZW1wLSoDZl5tZ3ItKhgbQ3NwY6JpXnB1YmxpYy0qA2pecHJpdmF0ZS0qGBtEbWV0YaBDc2lnWCAsvzGmd2rcgtr9rcs4r2tqC87YSppSYqs9CKfaM5IRZA") + ->getChannelResource('my-channel'); +// snippet.end +// phpcs:enable diff --git a/examples/Subscribing.php b/examples/Subscribing.php index 08c9990..0780374 100644 --- a/examples/Subscribing.php +++ b/examples/Subscribing.php @@ -23,6 +23,12 @@ $pubnub = new PubNub($pnconfig); // snippet.end +// snippet.subscribe_single_channel +$pubnub->subscribe() + ->channels("my_channel") + ->execute(); +// snippet.end + // Disable for "one class per file" rule // phpcs:disable // snippet.callback @@ -210,21 +216,90 @@ public function checkUnsubscribeCondition() // snippet.end // phpcs:enable -echo "Starting PubNub Subscriber...\n"; -echo "Press Ctrl+C to exit\n"; +// snippet.subscribe_multiple_channels +$pubnub->subscribe() + ->channels(["my_channel1", "my_channel2"]) + ->execute(); +// snippet.end + +// snippet.subscribe_presence_channel +$pubnub->subscribe() + ->channels("my_channel") + ->withPresence() + ->execute(); +// snippet.end + +// snippet.wildcard_subscribe +$pubnub->subscribe() + ->channels("foo.*") + ->execute(); +// snippet.end + +// snippet.subscribe_channel_group +$pubnub->subscribe() + ->channelGroups(["cg1", "cg2"]) + ->execute(); +// snippet.end + +// snippet.subscribe_presence_channel_group +$pubnub->subscribe() + ->channelGroups("awesome_channel_group") + ->withPresence() + ->execute(); +// snippet.end + +//Disabling code sniffer for whole snippet to not include single-line disable in docs +// phpcs:disable +// snippet.unsubscribe_multiple_channels +class MyUnsubscribeMultipleCallback extends SubscribeCallback +{ + public function status($pubnub, $status) + { + if ($this->checkUnsubscribeCondition()) { + throw (new PubNubUnsubscribeException())->setChannels(["channel1", "channel2", "channel3"]); + } + } + + public function message($pubnub, $message) + { + } -// Main loop -$lastHistoryTime = 0; + public function presence($pubnub, $presence) + { + } -while (true) { - $currentTime = time(); + public function checkUnsubscribeCondition() + { + return false; + } +} +// snippet.end +//phpcs:enable - // Check history every 15 seconds - if ($currentTime - $lastHistoryTime >= 15) { - getHistory($pubnub, $channels); - $lastHistoryTime = $currentTime; +//Disabling code sniffer for whole snippet to not include single-line disable in docs +// phpcs:disable +// snippet.unsubscribe_channel_group +class MyUnsubscribeChannelGroupCallback extends SubscribeCallback +{ + public function status($pubnub, $status) + { + if ($this->checkUnsubscribeCondition()) { + throw (new PubNubUnsubscribeException())->setChannelGroups(["cg1", "cg2"]); + } + } + + public function message($pubnub, $message) + { + } + + public function presence($pubnub, $presence) + { } - // Small sleep to prevent CPU overuse - usleep(100000); // 100ms + public function checkUnsubscribeCondition() + { + return false; + } } +// snippet.end +// phpcs:enable diff --git a/examples/basic_usage/channel_groups.php b/examples/basic_usage/channel_groups.php index a201178..c0f0672 100644 --- a/examples/basic_usage/channel_groups.php +++ b/examples/basic_usage/channel_groups.php @@ -7,6 +7,7 @@ use PubNub\PubNub; use PubNub\Exceptions\PubNubServerException; +// snippet.setup // Create configuration $pnConfig = new PNConfiguration(); $pnConfig->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); @@ -15,6 +16,7 @@ // Initialize PubNub instance $pubnub = new PubNub($pnConfig); +// snippet.end try { // Add channels to channel group diff --git a/tests/Examples/AccessManagerV2Test.php b/tests/Examples/AccessManagerV2Test.php new file mode 100644 index 0000000..756ce15 --- /dev/null +++ b/tests/Examples/AccessManagerV2Test.php @@ -0,0 +1,20 @@ +assertTrue(true); // If we reach this point, all examples passed + } +} diff --git a/tests/Examples/ChannelGroupsTest.php b/tests/Examples/ChannelGroupsTest.php new file mode 100644 index 0000000..938aeb7 --- /dev/null +++ b/tests/Examples/ChannelGroupsTest.php @@ -0,0 +1,20 @@ +assertTrue(true); // If we reach this point, all examples passed + } +} diff --git a/tests/Examples/SnippetsTest.php b/tests/Examples/SnippetsTest.php new file mode 100644 index 0000000..0dcbd76 --- /dev/null +++ b/tests/Examples/SnippetsTest.php @@ -0,0 +1,20 @@ +assertTrue(true); // If we reach this point, all examples passed + } +}