Completed
Pull Request — master (#447)
by Alexandru
01:34
created

PresencelyChannelable::getChannelData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace BeyondCode\LaravelWebSockets\Concerns;
4
5
use BeyondCode\LaravelWebSockets\Concerns\Channelable;
6
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature;
7
use Ratchet\ConnectionInterface;
8
use stdClass;
9
10
trait PresencelyChannelable
11
{
12
    /**
13
     * Data for the users connected to this channel.
14
     *
15
     * Note: If replication is enabled, this will only contain entries
16
     * for the users directly connected to this server instance. Requests
17
     * for data for all users in the channel should be routed through
18
     * ReplicationInterface.
19
     *
20
     * @var string[]
21
     */
22
    protected $users = [];
23
24
    /**
25
     * Get the members in the presence channel.
26
     *
27
     * @param  string  $appId
28
     * @return PromiseInterface
29
     */
30
    public function getUsers($appId)
31
    {
32
        return $this->replicator->channelMembers($appId, $this->channelName);
0 ignored issues
show
Bug introduced by
The property replicator does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property channelName does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
33
    }
34
35
    /**
36
     * Subscribe the connection to the channel.
37
     *
38
     * @param  ConnectionInterface  $connection
39
     * @param  stdClass  $payload
40
     * @return void
41
     * @throws InvalidSignature
42
     * @see     https://pusher.com/docs/pusher_protocol#presence-channel-events
43
     */
44
    public function subscribe(ConnectionInterface $connection, stdClass $payload)
45
    {
46
        $this->verifySignature($connection, $payload);
0 ignored issues
show
Bug introduced by
It seems like verifySignature() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
47
48
        $this->saveConnection($connection);
0 ignored issues
show
Bug introduced by
It seems like saveConnection() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
49
50
        $channelData = json_decode($payload->channel_data);
51
        $this->users[$connection->socketId] = $channelData;
0 ignored issues
show
Bug introduced by
Accessing socketId on the interface Ratchet\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
52
53
        // Add the connection as a member of the channel
54
        $this->replicator->joinChannel(
55
            $connection->app->id,
0 ignored issues
show
Bug introduced by
Accessing app on the interface Ratchet\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
56
            $this->channelName,
57
            $connection->socketId,
0 ignored issues
show
Bug introduced by
Accessing socketId on the interface Ratchet\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
58
            json_encode($channelData)
59
        );
60
61
        // We need to pull the channel data from the replication backend,
62
        // otherwise we won't be sending the full details of the channel
63
        $this->replicator
64
            ->channelMembers($connection->app->id, $this->channelName)
0 ignored issues
show
Bug introduced by
Accessing app on the interface Ratchet\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
65
            ->then(function ($users) use ($connection) {
66
                $connection->send(json_encode([
67
                    'event' => 'pusher_internal:subscription_succeeded',
68
                    'channel' => $this->channelName,
69
                    'data' => json_encode($this->getChannelData($users)),
70
                ]));
71
            });
72
73
        $this->broadcastToOthers($connection, (object) [
0 ignored issues
show
Bug introduced by
It seems like broadcastToOthers() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
74
            'event' => 'pusher_internal:member_added',
75
            'channel' => $this->channelName,
76
            'data' => json_encode($channelData),
77
        ]);
78
    }
79
80
    /**
81
     * Unsubscribe the connection from the Presence channel.
82
     *
83
     * @param  ConnectionInterface  $connection
84
     * @return void
85
     */
86
    public function unsubscribe(ConnectionInterface $connection)
87
    {
88
        parent::unsubscribe($connection);
89
90
        if (! isset($this->users[$connection->socketId])) {
0 ignored issues
show
Bug introduced by
Accessing socketId on the interface Ratchet\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
91
            return;
92
        }
93
94
        // Remove the connection as a member of the channel
95
        $this->replicator
96
            ->leaveChannel(
97
                $connection->app->id,
0 ignored issues
show
Bug introduced by
Accessing app on the interface Ratchet\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
98
                $this->channelName,
99
                $connection->socketId
0 ignored issues
show
Bug introduced by
Accessing socketId on the interface Ratchet\ConnectionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
100
            );
101
102
        $this->broadcastToOthers($connection, (object) [
0 ignored issues
show
Bug introduced by
It seems like broadcastToOthers() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
103
            'event' => 'pusher_internal:member_removed',
104
            'channel' => $this->channelName,
105
            'data' => json_encode([
106
                'user_id' => $this->users[$connection->socketId]->user_id,
107
            ]),
108
        ]);
109
110
        unset($this->users[$connection->socketId]);
111
    }
112
113
    /**
114
     * Get the Presence Channel to array.
115
     *
116
     * @param  string|null  $appId
117
     * @return PromiseInterface
118
     */
119
    public function toArray($appId = null)
120
    {
121
        return $this->replicator
122
            ->channelMembers($appId, $this->channelName)
123
            ->then(function ($users) {
124
                return array_merge(parent::toArray(), [
125
                    'user_count' => count($users),
126
                ]);
127
            });
128
    }
129
130
    /**
131
     * Get the Presence channel data.
132
     *
133
     * @param  array  $users
134
     * @return array
135
     */
136
    protected function getChannelData(array $users): array
137
    {
138
        return [
139
            'presence' => [
140
                'ids' => $this->getUserIds($users),
141
                'hash' => $this->getHash($users),
142
                'count' => count($users),
143
            ],
144
        ];
145
    }
146
147
    /**
148
     * Get the Presence Channel's users.
149
     *
150
     * @param  array  $users
151
     * @return array
152
     */
153
    protected function getUserIds(array $users): array
154
    {
155
        $userIds = array_map(function ($channelData) {
156
            return (string) $channelData->user_id;
157
        }, $users);
158
159
        return array_values($userIds);
160
    }
161
162
    /**
163
     * Compute the hash for the presence channel integrity.
164
     *
165
     * @param  array  $users
166
     * @return array
167
     */
168
    protected function getHash(array $users): array
169
    {
170
        $hash = [];
171
172
        foreach ($users as $socketId => $channelData) {
173
            $hash[$channelData->user_id] = $channelData->user_info ?? [];
174
        }
175
176
        return $hash;
177
    }
178
}
179