Completed
Pull Request — master (#31)
by
unknown
14:55
created

RedisRestart::shouldRestart()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Tomaj\Hermes\Restart;
5
6
use DateTime;
7
use InvalidArgumentException;
8
9
/**
10
 * Class RedisRestart provides redis implementation of Tomaj\Hermes\Restart\RestartInterface
11
 *
12
 * Set UNIX timestamp (as `string`) to key `$key` (default `hermes_restart`) to restart Hermes.
13
 */
14
class RedisRestart implements RestartInterface
15
{
16
    /** @var string */
17
    private $key;
18
19
    /** @var \Predis\Client|\Redis */
20
    private $redis;
21
22
    public function __construct($redis, string $key = 'hermes_restart')
23
    {
24
        if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
25
            throw new InvalidArgumentException('Predis\Client or Redis instance required');
26
        }
27
28
        $this->key = $key;
29
        $this->redis = $redis;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     *
35
     * Returns true:
36
     *
37
     * - if restart timestamp is set,
38
     * - and timestamp is not in future,
39
     * - and hermes was started ($startTime) before timestamp
40
     */
41
    public function shouldRestart(DateTime $startTime): bool
42
    {
43
        // load UNIX timestamp from redis
44
        $restartTime = $this->redis->get($this->key);
0 ignored issues
show
Bug introduced by
The method get does only exist in Redis, but not in Predis\Client.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
45
        if ($restartTime === null) {
46
            return false;
47
        }
48
        $restartTime = (int) $restartTime;
49
50
        // do not restart if restart time is in future
51
        if ($restartTime > time()) {
52
            return false;
53
        }
54
55
        // do not restart if hermes started after restart time
56
        if ($restartTime < $startTime->getTimestamp()) {
57
            return false;
58
        }
59
60
        return true;
61
    }
62
}
63