Completed
Push — integration-tests ( ccbef3...cd7ccc )
by Cy
07:46 queued 03:20
created

PredisConnection::createSubscription()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 11
nc 3
nop 3
1
<?php
2
3
namespace Monospice\LaravelRedisSentinel\Connections;
4
5
use Closure;
6
use Illuminate\Redis\Connections\PredisConnection as LaravelPredisConnection;
7
use Monospice\SpicyIdentifiers\DynamicMethod;
8
use Predis\ClientInterface as Client;
9
use Predis\CommunicationException;
10
use RuntimeException;
11
12
/**
13
 * Executes Redis commands using the Predis client.
14
 *
15
 * This package extends Laravel's PredisConnection class to work around issues
16
 * experienced when using the Predis client to send commands over "aggregate"
17
 * connections (in this case, Sentinel connections).
18
 *
19
 * @category Package
20
 * @package  Monospice\LaravelRedisSentinel
21
 * @author   @pdbreen, Cy Rossignol <[email protected]>
22
 * @license  See LICENSE file
23
 * @link     https://github.com/monospice/laravel-redis-sentinel-drivers
24
 */
25
class PredisConnection extends LaravelPredisConnection
26
{
27
    /**
28
     * The number of times the client attempts to retry a command when it fails
29
     * to connect to a Redis instance behind Sentinel.
30
     *
31
     * @var int
32
     */
33
    protected $retryLimit = 20;
34
35
    /**
36
     * The time in milliseconds to wait before the client retries a failed
37
     * command.
38
     *
39
     * @var int
40
     */
41
    protected $retryWait = 1000;
42
43
    /**
44
     * Create a Redis Sentinel connection using a Predis client.
45
     *
46
     * @param Client $client          The Redis client to wrap.
47
     * @param array  $sentinelOptions Sentinel-specific connection options.
48
     */
49
    public function __construct(Client $client, array $sentinelOptions = [ ])
50
    {
51
        parent::__construct($client);
0 ignored issues
show
Compatibility introduced by
$client of type object<Predis\ClientInterface> is not a sub-type of object<Predis\Client>. It seems like you assume a concrete implementation of the interface Predis\ClientInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
52
53
        // Set the Sentinel-specific connection options on the Predis Client
54
        // connection and the current instance of this class.
55
        foreach ($sentinelOptions as $option => $value) {
56
            DynamicMethod::parseFromUnderscore($option)
57
                ->prepend('set')
58
                ->callOn($this, [ $value ]);
59
        }
60
    }
61
62
    /**
63
     * Set the default amount of time to wait before determining that a
64
     * connection attempt to a Sentinel server failed.
65
     *
66
     * @param float $seconds The timeout value in seconds.
67
     *
68
     * @return $this The current instance for method chaining.
69
     */
70
    public function setSentinelTimeout($seconds)
71
    {
72
        $this->client->getConnection()->setSentinelTimeout($seconds);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Predis\Connection\ConnectionInterface as the method setSentinelTimeout() does only exist in the following implementations of said interface: Predis\Connection\Aggregate\SentinelReplication.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
73
74
        return $this;
75
    }
76
77
    /**
78
     * Set the default number of attempts to retry a command when the client
79
     * fails to connect to a Redis instance behind Sentinel.
80
     *
81
     * @param int $attempts With a value of 0, throw an exception after the
82
     * first failed attempt. Pass a value of -1 to retry connections forever.
83
     *
84
     * @return $this The current instance for method chaining.
85
     */
86
    public function setRetryLimit($attempts)
87
    {
88
        $this->retryLimit = (int) $attempts;
89
        $this->client->getConnection()->setRetryLimit($attempts);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Predis\Connection\ConnectionInterface as the method setRetryLimit() does only exist in the following implementations of said interface: Predis\Connection\Aggregate\RedisCluster, Predis\Connection\Aggregate\SentinelReplication.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
90
91
        return $this;
92
    }
93
94
    /**
95
     * Set the time to wait before retrying a command after a connection
96
     * attempt failed.
97
     *
98
     * @param int $milliseconds The wait time in milliseconds. When 0, retry
99
     * a failed command immediately.
100
     *
101
     * @return $this The current instance for method chaining.
102
     */
103
    public function setRetryWait($milliseconds)
104
    {
105
        $this->retryWait = (int) $milliseconds;
106
        $this->client->getConnection()->setRetryWait($milliseconds);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Predis\Connection\ConnectionInterface as the method setRetryWait() does only exist in the following implementations of said interface: Predis\Connection\Aggregate\SentinelReplication.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
107
108
        return $this;
109
    }
110
111
    /**
112
     * Set whether the client should update the list of known Sentinels each
113
     * time it needs to connect to a Redis server behind Sentinel.
114
     *
115
     * @param bool $enable If TRUE, fetch the updated Sentinel list.
116
     *
117
     * @return $this The current instance for method chaining.
118
     */
119
    public function setUpdateSentinels($enable)
120
    {
121
        $this->client->getConnection()->setUpdateSentinels($enable);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Predis\Connection\ConnectionInterface as the method setUpdateSentinels() does only exist in the following implementations of said interface: Predis\Connection\Aggregate\SentinelReplication.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
122
123
        return $this;
124
    }
125
126
    /**
127
     * Subscribe to a set of given channels for messages.
128
     *
129
     * @param  array|string $channels The names of the channels to subscribe to.
130
     * @param  Closure      $callback Executed for each message. Receives the
131
     * message string in the first argument and the message channel as the
132
     * second argument.
133
     * @param  string       $method   The subscription command ("subscribe" or
134
     * "psubscribe").
135
     *
136
     * @return void
137
     */
138
    public function createSubscription(
139
        $channels,
140
        Closure $callback,
141
        $method = 'subscribe'
142
    ) {
143
        // Messages published to the master propagate to each of the slaves. We
144
        // pick a random slave to distribute load away from the master:
145
        $loop = $this->retryOnFailure(function () {
146
            return $this->getRandomSlave()->pubSubLoop();
147
        });
148
149
        call_user_func_array([$loop, $method], (array) $channels);
150
151
        foreach ($loop as $message) {
152
            if ($message->kind === 'message' || $message->kind === 'pmessage') {
153
                call_user_func($callback, $message->payload, $message->channel);
154
            }
155
        }
156
157
        unset($loop);
158
    }
159
160
    /**
161
     * Execute commands in a transaction.
162
     *
163
     * This package overrides the transaction() method to work around a
164
     * limitation in the Predis API that disallows transactions on "aggregate"
165
     * connections like Sentinel. Note that transactions execute on the Redis
166
     * master instance.
167
     *
168
     * @param callable $callback Contains the Redis commands to execute in the
0 ignored issues
show
Documentation introduced by
Should the type for parameter $callback not be null|callable? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
169
     * transaction. The callback receives a Predis\Transaction\MultiExec
170
     * transaction abstraction as the only argument. We use this object to
171
     * execute Redis commands by calling its methods just like we would with
172
     * the Laravel Redis service.
173
     *
174
     * @return array|Predis\Transaction\MultiExec An array containing the
175
     * result for each command executed during the transaction. If no callback
176
     * provided, returns an instance of the Predis transaction abstraction.
177
     */
178
    public function transaction(callable $callback = null)
179
    {
180
        return $this->retryOnFailure(function () use ($callback) {
181
            return $this->getMaster()->transaction($callback);
182
        });
183
    }
184
185
    /**
186
     * Attempt to retry the provided operation when the client fails to connect
187
     * to a Redis server.
188
     *
189
     * We adapt Predis' Sentinel connection failure handling logic here to
190
     * reproduce the high-availability mode provided by the actual client. To
191
     * work around "aggregate" connection limitations in Predis, this class
192
     * provides methods that don't use the high-level Sentinel connection API
193
     * of Predis directly, so it needs to handle connection failures itself.
194
     *
195
     * @param callable $callback The operation to execute.
196
     *
197
     * @return mixed The result of the first successful attempt.
198
     */
199
    protected function retryOnFailure(callable $callback)
200
    {
201
        $attempts = 0;
202
203
        do {
204
            try {
205
                return $callback();
206
            } catch (CommunicationException $exception) {
207
                $exception->getConnection()->disconnect();
208
                $this->client->getConnection()->querySentinel();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Predis\Connection\ConnectionInterface as the method querySentinel() does only exist in the following implementations of said interface: Predis\Connection\Aggregate\SentinelReplication.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
209
210
                usleep($this->retryWait * 1000);
211
212
                $attempts++;
213
            }
214
        } while ($attempts <= $this->retryLimit);
215
216
        throw $exception;
217
    }
218
219
    /**
220
     * Get a Predis client instance for the master.
221
     *
222
     * @return Client The client instance for the current master.
1 ignored issue
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use \Predis\Client.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
223
     */
224
    protected function getMaster()
225
    {
226
        return $this->client->getClientFor('master');
227
    }
228
229
    /**
230
     * Get a Predis client instance for a random slave.
231
     *
232
     * @param bool $fallbackToMaster If TRUE, return a client for the master
233
     * if the connection does not include any slaves.
234
     *
235
     * @return Client The client instance for the selected slave.
236
     */
237
    protected function getRandomSlave($fallbackToMaster = true)
238
    {
239
        $slaves = $this->client->getConnection()->getSlaves();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Predis\Connection\ConnectionInterface as the method getSlaves() does only exist in the following implementations of said interface: Predis\Connection\Aggregate\MasterSlaveReplication, Predis\Connection\Aggregate\SentinelReplication.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
240
241
        if (count($slaves) > 0) {
242
            $slave = $slaves[rand(1, count($slaves)) - 1];
243
244
            return $this->client->getClientFor($slave->getParameters()->alias);
245
        }
246
247
        if ($fallbackToMaster) {
248
            return $client->getClientFor('master');
0 ignored issues
show
Bug introduced by
The variable $client does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
249
        }
250
251
        throw new RuntimeException('No slave present on connection.');
252
    }
253
}
254