Skip to content

Commit 9241e64

Browse files
Add more test coverage and missing dynamic snippets for docs (#120)
* First batch of new tests * Fix linter errors * Fix linter errors * More linter * Linter + remove faulty test file * Mass PHP CBF apply * Even more linter fixes * add missing semicolons * last missing semicolon * there better not be more missing semicolons * Test phpstan setting change * More phpcbf * Fix wrong timestamp method call in tests * Remove invalid test * Add missing snippets for docs * Examples linter * Initial review fixes * Linter fixes * Test return type fix * Potential PHPStan fixes * Revert "Potential PHPStan fixes" This reverts commit 4b9dfea. * Test phpstan neon file change * Remove ignore line * Return types tweak * Add configuration snippets verification * Remove whitespace
1 parent 2cd05ff commit 9241e64

33 files changed

+4160
-155
lines changed

examples/Configuration.php

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
<?php
2+
3+
// @phpstan-ignore-file
4+
// phpcs:ignoreFile
5+
require_once __DIR__ . '/../vendor/autoload.php';
6+
7+
use PubNub\PNConfiguration;
8+
use PubNub\PubNub;
9+
use PubNub\CryptoModule;
10+
use PubNub\Enums\PNStatusCategory;
11+
use PubNub\Callbacks\SubscribeCallback;
12+
13+
// snippet.setup
14+
// Create a new configuration instance
15+
$pnConfiguration = new PNConfiguration();
16+
17+
// Set subscribe key (required)
18+
$pnConfiguration->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo');
19+
20+
// Set publish key (only required if publishing)
21+
$pnConfiguration->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo');
22+
23+
// Set UUID (required to connect)
24+
$pnConfiguration->setUserId('php-config-demo-user');
25+
// snippet.end
26+
27+
// Verify configuration was set correctly
28+
assert($pnConfiguration->getSubscribeKey() === (getenv('SUBSCRIBE_KEY') ?? 'demo'));
29+
assert($pnConfiguration->getPublishKey() === (getenv('PUBLISH_KEY') ?? 'demo'));
30+
assert($pnConfiguration->getUserId() === 'php-config-demo-user');
31+
32+
// snippet.basic_configuration
33+
// Create a new configuration instance
34+
$pnConfiguration = new PNConfiguration();
35+
36+
// Set subscribe key (required)
37+
$pnConfiguration->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo');
38+
39+
// Set publish key (only required if publishing)
40+
$pnConfiguration->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo');
41+
42+
// Set UUID (required to connect)
43+
$pnConfiguration->setUserId("php-sdk-example-user");
44+
45+
// Set up cryptography for message encryption (optional)
46+
// Uncomment the line below to enable encryption
47+
// $pnConfiguration->setCryptoModule(CryptoModule::aesCbcCryptor("your-cipher-key", true));
48+
49+
// Set authentication key (optional, required only when using Access Manager)
50+
// $pnConfiguration->setAuthKey("my_auth_key");
51+
52+
// Configure connection timeout in seconds
53+
$pnConfiguration->setConnectTimeout(10);
54+
55+
// Configure subscribe request timeout in seconds
56+
$pnConfiguration->setSubscribeTimeout(310);
57+
58+
// Configure non-subscribe request timeout in seconds
59+
$pnConfiguration->setNonSubscribeRequestTimeout(10);
60+
61+
// Set filter expression (optional)
62+
// $pnConfiguration->setFilterExpression("channel == 'my-channel'");
63+
64+
// Create PubNub instance with the configured settings
65+
$pubnub = new PubNub($pnConfiguration);
66+
67+
// Display configuration information
68+
echo "PubNub Configuration:\n";
69+
echo "Subscribe Key: " . $pnConfiguration->getSubscribeKey() . "\n";
70+
echo "Publish Key: " . $pnConfiguration->getPublishKey() . "\n";
71+
echo "User ID: " . $pnConfiguration->getUserId() . "\n";
72+
echo "Encryption: " . ($pnConfiguration->getCryptoSafe() ? "enabled" : "disabled") . "\n";
73+
74+
// Now you can use this PubNub instance to publish and subscribe
75+
76+
// Example: Create a simple message
77+
$message = ["text" => "Hello from PHP SDK!"];
78+
79+
// Example: Publish the message (uncomment to execute)
80+
/*
81+
$pubnub->publish()
82+
->channel("demo-channel")
83+
->message($message)
84+
->sync();
85+
86+
echo "Message published to 'demo-channel'\n";
87+
*/
88+
89+
// Keep this code running only if you plan to subscribe to messages
90+
// Otherwise, the script will exit after publishing
91+
// snippet.end
92+
93+
// Verify configuration values
94+
assert($pnConfiguration->getSubscribeKey() === getenv('SUBSCRIBE_KEY') ?? 'demo');
95+
assert($pnConfiguration->getPublishKey() === getenv('PUBLISH_KEY') ?? 'demo');
96+
assert($pnConfiguration->getUserId() === "php-sdk-example-user");
97+
assert($pnConfiguration->getConnectTimeout() === 10);
98+
assert($pnConfiguration->getSubscribeTimeout() === 310);
99+
assert($pnConfiguration->getNonSubscribeRequestTimeout() === 10);
100+
101+
// Verify PubNub instance was created
102+
assert($pubnub instanceof PubNub);
103+
104+
// snippet.init_basic
105+
$pnconf = new PNConfiguration();
106+
107+
$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo');
108+
$pnconf->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo');
109+
$pnconf->setSecure(false);
110+
$pnconf->setUserId("myUniqueUserId");
111+
$pubnub = new PubNub($pnconf);
112+
113+
// snippet.end
114+
115+
// Verify configuration
116+
assert($pnconf->getSubscribeKey() === getenv('SUBSCRIBE_KEY') ?? 'demo');
117+
assert($pnconf->getPublishKey() === getenv('PUBLISH_KEY') ?? 'demo');
118+
assert($pnconf->getUserId() === "myUniqueUserId");
119+
assert($pubnub instanceof PubNub);
120+
121+
// snippet.init_access_manager
122+
$pnConfiguration = new PNConfiguration();
123+
124+
$pnConfiguration->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo');
125+
$pnConfiguration->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo');
126+
//NOTE: only server side should have secret key
127+
$pnConfiguration->setSecretKey(getenv('SECRET_KEY') ?? 'demo');
128+
$pnConfiguration->setUserId("myUniqueUserId");
129+
$pubnub = new PubNub($pnConfiguration);
130+
// snippet.end
131+
132+
// Verify configuration
133+
assert($pnConfiguration->getSubscribeKey() === getenv('SUBSCRIBE_KEY') ?? 'demo');
134+
assert($pnConfiguration->getPublishKey() === getenv('PUBLISH_KEY') ?? 'demo');
135+
assert($pnConfiguration->getSecretKey() === getenv('SECRET_KEY') ?? 'demo');
136+
assert($pnConfiguration->getUserId() === "myUniqueUserId");
137+
assert($pubnub instanceof PubNub);
138+
139+
// snippet.event_listeners
140+
class MySubscribeCallback extends SubscribeCallback
141+
{
142+
function status($pubnub, $status)
143+
{
144+
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
145+
// This event happens when connectivity is lost
146+
} elseif ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
147+
// Connect event. You can do stuff like publish, and know you'll get it
148+
} elseif ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
149+
// Handle message decryption error.
150+
}
151+
}
152+
153+
function message($pubnub, $message)
154+
{
155+
// Handle new message stored in message.message
156+
}
157+
function presence($pubnub, $presence)
158+
{
159+
// handle incoming presence data
160+
}
161+
}
162+
163+
$pnconf = new PNConfiguration();
164+
165+
$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo');
166+
$pnconf->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo');
167+
$pnconf->setUserId("event-listener-demo-user");
168+
169+
$pubnub = new PubNub($pnconf);
170+
171+
$subscribeCallback = new MySubscribeCallback();
172+
173+
$pubnub->addListener($subscribeCallback);
174+
175+
// Subscribe to a channel, this is not async.
176+
// Note: This would block
177+
// $pubnub->subscribe()
178+
// ->channels("hello_world")
179+
// ->execute();
180+
181+
// Use the publish command separately from the Subscribe code shown above.
182+
// Subscribe is not async and will block the execution until complete.
183+
// Note: Commented out for testing to avoid network calls
184+
// $result = $pubnub->publish()
185+
// ->channel("hello_world")
186+
// ->message("Hello PubNub")
187+
// ->sync();
188+
//
189+
// // Verify publish result
190+
// assert($result->getTimetoken() > 0);
191+
//
192+
// print_r($result);
193+
// snippet.end
194+
195+
// snippet.set_filter_expression
196+
$pnconf = new PNConfiguration();
197+
198+
$pnconf->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo');
199+
$pnconf->setUserId("filter-demo-user");
200+
$pnconf->setFilterExpression("userid == 'my_userid'");
201+
202+
$pubnub = new PubNub($pnconf);
203+
// snippet.end
204+
205+
// Verify configuration
206+
assert($pnconf->getSubscribeKey() === "my_sub_key");
207+
assert($pnconf->getPublishKey() === "my_pub_key");
208+
assert($pnconf->getUserId() === "event-listener-demo-user");
209+
assert($pubnub instanceof PubNub);
210+
// Verify callback instance
211+
assert($subscribeCallback instanceof SubscribeCallback);
212+
// Verify configuration
213+
assert($pnconf->getSubscribeKey() === "my_sub_key");
214+
assert($pnconf->getFilterExpression() === "userid == 'my_userid'");
215+
assert($pubnub instanceof PubNub);

examples/Publishing.php

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,12 @@
7272
// snippet.publish_with_post
7373
$result = $pubnub->publish()
7474
->channel("my_channel")
75-
->message([
75+
->message(
76+
[
7677
"text" => "Message using POST",
7778
"description" => str_repeat("Post allows to publish longer messages", 750)
78-
])
79+
]
80+
)
7981
->usePost(true)
8082
->sync();
8183
assert($result->getTimetoken() > 0);
@@ -86,10 +88,12 @@
8688
try {
8789
$result = $pubnub->publish()
8890
->channel("my_channel")
89-
->message([
91+
->message(
92+
[
9093
"text" => "Message using POST",
9194
"description" => str_repeat("Post allows to publish longer messages", 1410)
92-
])
95+
]
96+
)
9397
->usePost(true)
9498
->sync();
9599
assert($result->getTimetoken() > 0);
@@ -119,3 +123,16 @@
119123
assert($result->getTimetoken() > 0);
120124
echo "Signal timetoken: {$result->getTimetoken()}\n";
121125
// snippet.end
126+
127+
// snippet.publish_array
128+
try {
129+
$result = $pubnub->publish()
130+
->channel("my_channel")
131+
->message(["hello", "there"])
132+
->meta(["name" => "Alex", "online" => true])
133+
->sync();
134+
print_r($result->getTimetoken());
135+
} catch (PubNubException $error) {
136+
echo "Error: " . $error->getMessage() . "\n";
137+
}
138+
// snippet.end

examples/Subscribing.php

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
$pubnub = new PubNub($pnconfig);
2424
// snippet.end
2525

26+
// Disable for "one class per file" rule
27+
// phpcs:disable
2628
// snippet.callback
2729
// Create a custom callback class to handle messages and status updates
2830
class MySubscribeCallback extends SubscribeCallback
@@ -62,6 +64,7 @@ public function presence($pubnub, $presence)
6264
}
6365
}
6466
// snippet.end
67+
// phpcs:enable
6568

6669
// snippet.subscribe
6770
// Add the callback to PubNub
@@ -80,6 +83,8 @@ public function presence($pubnub, $presence)
8083
}
8184
// snippet.end
8285

86+
// Disable for the "declare symbols vs side effects" rule
87+
// phpcs:disable
8388
// snippet.history
8489
// Get message history
8590
function getHistory($pubnub, $channels)
@@ -100,6 +105,110 @@ function getHistory($pubnub, $channels)
100105
}
101106
}
102107
// snippet.end
108+
// phpcs:enable
109+
110+
// snippet.basic_subscribe_with_logging
111+
use Monolog\Handler\ErrorLogHandler;
112+
113+
$pnconf = new PNConfiguration();
114+
115+
$pnconf->setPublishKey("demo");
116+
$pnconf->setSubscribeKey("demo");
117+
$pnconf->setUserId("php-subscriber-with-logging");
118+
119+
$pubnub = new PubNub($pnconf);
120+
121+
$pubnub->getLogger()->pushHandler(new ErrorLogHandler());
122+
123+
$pubnub->subscribe()->channels("my_channel")->execute();
124+
// snippet.end
125+
126+
// Disable for the "one class per file" rule
127+
// phpcs:disable
128+
// snippet.subscribe_with_state
129+
class MySubscribeCallbackWithState extends SubscribeCallback
130+
{
131+
public function status($pubnub, $status)
132+
{
133+
if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
134+
$result = $pubnub
135+
->setState()
136+
->channels("awesomeChannel")
137+
->channelGroups("awesomeChannelGroup")
138+
->state([
139+
"fieldA" => "awesome",
140+
"fieldB" => 10,
141+
])
142+
->sync();
143+
print_r($result);
144+
}
145+
}
146+
147+
public function message($pubnub, $message)
148+
{
149+
}
150+
151+
public function presence($pubnub, $presence)
152+
{
153+
}
154+
}
155+
156+
$subscribeCallback = new MySubscribeCallbackWithState();
157+
158+
$pubnub->addListener($subscribeCallback);
159+
160+
$pubnub->subscribe()
161+
->channels("my_channel")
162+
->execute();
163+
// snippet.end
164+
// phpcs:enable
165+
166+
// Disable for the "one class per file" rule
167+
// phpcs:disable
168+
// snippet.unsubscribe_from_channel
169+
use PubNub\Exceptions\PubNubUnsubscribeException;
170+
171+
class MyUnsubscribeCallback extends SubscribeCallback
172+
{
173+
public function status($pubnub, $status)
174+
{
175+
if ($this->checkUnsubscribeCondition()) {
176+
throw (new PubNubUnsubscribeException())->setChannels("awesomeChannel");
177+
}
178+
}
179+
180+
public function message($pubnub, $message)
181+
{
182+
}
183+
184+
public function presence($pubnub, $presence)
185+
{
186+
}
187+
188+
public function checkUnsubscribeCondition()
189+
{
190+
// return true or false
191+
return false;
192+
}
193+
}
194+
195+
$pnconfig = new PNConfiguration();
196+
197+
$pnconfig->setPublishKey("demo");
198+
$pnconfig->setSubscribeKey("demo");
199+
$pnconfig->setUserId("php-unsubscribe-demo");
200+
201+
$pubnub = new PubNub($pnconfig);
202+
203+
$subscribeCallback = new MyUnsubscribeCallback();
204+
205+
$pubnub->addListener($subscribeCallback);
206+
207+
$pubnub->subscribe()
208+
->channels("awesomeChannel")
209+
->execute();
210+
// snippet.end
211+
// phpcs:enable
103212

104213
echo "Starting PubNub Subscriber...\n";
105214
echo "Press Ctrl+C to exit\n";

0 commit comments

Comments
 (0)