Completed
Pull Request — master (#447)
by Marcel
03:06 queued 01:18
created

PresencelyChannelable::toArray()   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\WebSockets\Exceptions\InvalidSignature;
6
use Ratchet\ConnectionInterface;
7
use stdClass;
8
9
trait PresencelyChannelable
10
{
11
    /**
12
     * Data for the users connected to this channel.
13
     *
14
     * Note: If replication is enabled, this will only contain entries
15
     * for the users directly connected to this server instance. Requests
16
     * for data for all users in the channel should be routed through
17
     * ReplicationInterface.
18
     *
19
     * @var string[]
20
     */
21
    protected $users = [];
22
23
    /**
24
     * Get the members in the presence channel.
25
     *
26
     * @param  string  $appId
27
     * @return PromiseInterface
28
     */
29
    public function getUsers($appId)
30
    {
31
        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...
32
    }
33
34
    /**
35
     * Subscribe the connection to the channel.
36
     *
37
     * @param  ConnectionInterface  $connection
38
     * @param  stdClass  $payload
39
     * @return void
40
     * @throws InvalidSignature
41
     * @see     https://pusher.com/docs/pusher_protocol#presence-channel-events
42
     */
43
    public function subscribe(ConnectionInterface $connection, stdClass $payload)
44
    {
45
        $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...
46
47
        $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...
48
49
        $channelData = json_decode($payload->channel_data);
50
        $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...
51
52
        // Add the connection as a member of the channel
53
        $this->replicator->joinChannel(
54
            $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...
55
            $this->channelName,
56
            $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...
57
            json_encode($channelData)
58
        );
59
60
        // We need to pull the channel data from the replication backend,
61
        // otherwise we won't be sending the full details of the channel
62
        $this->replicator
63
            ->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...
64
            ->then(function ($users) use ($connection) {
65
                $connection->send(json_encode([
66
                    'event' => 'pusher_internal:subscription_succeeded',
67
                    'channel' => $this->channelName,
68
                    'data' => json_encode($this->getChannelData($users)),
69
                ]));
70
            });
71
72
        $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...
73
            'event' => 'pusher_internal:member_added',
74
            'channel' => $this->channelName,
75
            'data' => json_encode($channelData),
76
        ]);
77
    }
78
79
    /**
80
     * Unsubscribe the connection from the Presence channel.
81
     *
82
     * @param  ConnectionInterface  $connection
83
     * @return void
84
     */
85
    public function unsubscribe(ConnectionInterface $connection)
86
    {
87
        parent::unsubscribe($connection);
88
89
        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...
90
            return;
91
        }
92
93
        // Remove the connection as a member of the channel
94
        $this->replicator
95
            ->leaveChannel(
96
                $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...
97
                $this->channelName,
98
                $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...
99
            );
100
101
        $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...
102
            'event' => 'pusher_internal:member_removed',
103
            'channel' => $this->channelName,
104
            'data' => json_encode([
105
                'user_id' => $this->users[$connection->socketId]->user_id,
106
            ]),
107
        ]);
108
109
        unset($this->users[$connection->socketId]);
110
    }
111
112
    /**
113
     * Get the Presence Channel to array.
114
     *
115
     * @param  string|null  $appId
116
     * @return PromiseInterface
117
     */
118
    public function toArray($appId = null)
119
    {
120
        return $this->replicator
121
            ->channelMembers($appId, $this->channelName)
122
            ->then(function ($users) {
123
                return array_merge(parent::toArray(), [
124
                    'user_count' => count($users),
125
                ]);
126
            });
127
    }
128
129
    /**
130
     * Get the Presence channel data.
131
     *
132
     * @param  array  $users
133
     * @return array
134
     */
135
    protected function getChannelData(array $users): array
136
    {
137
        return [
138
            'presence' => [
139
                'ids' => $this->getUserIds($users),
140
                'hash' => $this->getHash($users),
141
                'count' => count($users),
142
            ],
143
        ];
144
    }
145
146
    /**
147
     * Get the Presence Channel's users.
148
     *
149
     * @param  array  $users
150
     * @return array
151
     */
152
    protected function getUserIds(array $users): array
153
    {
154
        $userIds = array_map(function ($channelData) {
155
            return (string) $channelData->user_id;
156
        }, $users);
157
158
        return array_values($userIds);
159
    }
160
161
    /**
162
     * Compute the hash for the presence channel integrity.
163
     *
164
     * @param  array  $users
165
     * @return array
166
     */
167
    protected function getHash(array $users): array
168
    {
169
        $hash = [];
170
171
        foreach ($users as $socketId => $channelData) {
172
            $hash[$channelData->user_id] = $channelData->user_info ?? [];
173
        }
174
175
        return $hash;
176
    }
177
}
178