1+ <?php
2+
3+ namespace PubNubTests \helpers ;
4+
5+ use PubNub \PubNub ;
6+ use PubNub \Callbacks \SubscribeCallback ;
7+ use PubNub \Models \Consumer \PubSub \PNMessageResult ;
8+ use PubNub \Models \Consumer \PubSub \PNPresenceEventResult ;
9+ use PubNub \Models \ResponseHelpers \PNStatus ;
10+ use PubNub \Enums \PNStatusCategory ;
11+ use PubNub \Exceptions \PubNubUnsubscribeException ;
12+
13+ /**
14+ * Simple callback that maintains presence for a specified duration
15+ */
16+ class PresenceCallback extends SubscribeCallback
17+ {
18+ private int $ startTime ;
19+ private int $ duration ;
20+
21+ public function __construct (int $ duration )
22+ {
23+ $ this ->startTime = time ();
24+ $ this ->duration = $ duration ;
25+ }
26+
27+ /**
28+ * @param PubNub $pubnub
29+ * @param PNStatus $status
30+ * @return void
31+ */
32+ public function status ($ pubnub , $ status ): void
33+ {
34+ // Exit if connected and duration exceeded
35+ if ($ status ->getCategory () === PNStatusCategory::PNConnectedCategory) {
36+ fwrite (STDOUT , "Connected: {$ pubnub ->getConfiguration ()->getUuid ()}\n" );
37+ flush ();
38+ }
39+
40+ // Check if we should exit
41+ if (time () - $ this ->startTime > $ this ->duration ) {
42+ throw new PubNubUnsubscribeException ();
43+ }
44+ }
45+
46+ /**
47+ * @param PubNub $pubnub
48+ * @param PNMessageResult $message
49+ * @return void
50+ */
51+ public function message ($ pubnub , $ message ): void
52+ {
53+ // Check if we should exit
54+ if (time () - $ this ->startTime > $ this ->duration ) {
55+ throw new PubNubUnsubscribeException ();
56+ }
57+ }
58+
59+ /**
60+ * @param PubNub $pubnub
61+ * @param PNPresenceEventResult $presence
62+ * @return void
63+ */
64+ public function presence ($ pubnub , $ presence ): void
65+ {
66+ // Do nothing
67+ }
68+ }
0 commit comments