MultiEval::execute()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
nc 3
nop 0
1
<?php
2
namespace PHPDaemon\Clients\Redis;
3
4
use PHPDaemon\Core\CallbackWrapper;
5
6
/**
7
 * Easy wrapper for queue of eval's
8
 *
9
 * @package    NetworkClients
10
 * @subpackage RedisClient
11
 * @author     Efimenko Dmitriy <[email protected]>
12
 *
13
 * Use exampe 1:
14
 * var $eval = $this->redis->meval($cb);
15
 * $eval->add('redis.call("set",KEYS[1],ARGV[1])', [$key1], [$arg1]);
16
 * $eval->add('redis.call("del",KEYS[1])', [$key2]);
17
 * $eval->add('redis.call("expireat",KEYS[1],ARGV[1])', $key1, $arg2);
18
 * $eval->exec();
19
 *
20
 * Use exampe 2:
21
 * var $eval = $this->redis->meval($cb);
22
 * $eval('redis.call("set",KEYS[1],ARGV[1])', [$key1], [$arg1]);
23
 * $eval('redis.call("del",KEYS[1])', [$key2]);
24
 * $eval('redis.call("expireat",KEYS[1],ARGV[1])', $key1, $arg2);
25
 * $eval();
26
 *
27
 * Result request:
28
 * eval 'redis.call("set",KEYS[1],ARGV[1]);redis.call("del",KEYS[2]);redis.call("expireat",KEYS[1],ARGV[2])' 2 $key1 $key2 $arg1 $arg2
29
 */
30
class MultiEval
31
{
32
    use \PHPDaemon\Traits\ClassWatchdog;
33
    use \PHPDaemon\Traits\StaticObjectWatchdog;
34
35
    /**
36
     * @var array Listeners
37
     */
38
    public $listeners = [];
39
    protected $pool;
40
    protected $stack = [];
41
    protected $cachedParams = false;
42
43
    /**
44
     * Constructor
45
     * @param callable $cb Callback
46
     * @param Pool $pool Redis pool
47
     */
48
    public function __construct($cb, $pool)
49
    {
50
        $this->pool = $pool;
51
        if ($cb !== null) {
52
            $this->addListener($cb);
53
        }
54
    }
55
56
    /**
57
     * Adds listener
58
     * @param callable $cb
59
     */
60
    public function addListener($cb)
61
    {
62
        $this->listeners[] = CallbackWrapper::wrap($cb);
63
    }
64
65
    /**
66
     * Clean up
67
     */
68
    public function cleanup()
69
    {
70
        $this->listeners = [];
71
    }
72
73
    /**
74
     * Adds eval command or calls execute() method
75
     * @return void
76
     */
77
    public function __invoke(...$args)
78
    {
79
        if (!count($args)) {
80
            $this->execute();
81
            return;
82
        }
83
        $this->add(...$args);
0 ignored issues
show
Documentation introduced by
$args is of type array<integer,?>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
84
    }
85
86
    /**
87
     * Runs the stack of commands
88
     */
89
    public function execute()
90
    {
91
        if (!count($this->stack)) {
92
            foreach ($this->listeners as $cb) {
93
                $cb($this->pool);
94
            }
95
            return;
96
        }
97
98
        $params = $this->getParams();
99
        $params[] = function ($redis) {
100
            foreach ($this->listeners as $cb) {
101
                $cb($redis);
102
            }
103
        };
104
        $this->pool->eval(...$params);
0 ignored issues
show
Documentation Bug introduced by
The method eval does not exist on object<PHPDaemon\Clients\Redis\Pool>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
105
    }
106
107
    /**
108
     * Return params for eval command
109
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|array<string|integer>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
110
     */
111
    public function getParams()
112
    {
113
        if ($this->cachedParams) {
114
            return $this->cachedParams;
115
        }
116
117
        $CMDS = [];
118
        $KEYS = [];
119
        $ARGV = [];
120
        $KEYNUM = 0;
121
        $ARGNUM = 0;
122
123
        foreach ($this->stack as $part) {
124
            list($cmd, $keys, $argv) = $part;
125
126 View Code Duplication
            if (!empty($keys)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
127
                $cmd = preg_replace_callback('~KEYS\[(\d+)\]~', function ($m) use (&$KEYS, &$KEYNUM, $keys) {
128
                    $key = $keys[$m[1] - 1];
129
                    if (!isset($KEYS[$key])) {
130
                        $KEYS[$key] = ++$KEYNUM;
131
                    }
132
                    return 'KEYS[' . $KEYS[$key] . ']';
133
                }, $cmd);
134
            }
135
136 View Code Duplication
            if (!empty($argv)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
                $cmd = preg_replace_callback('~ARGV\[(\d+)\]~', function ($m) use (&$ARGV, &$ARGNUM, $argv) {
138
                    $arg = $argv[$m[1] - 1];
139
                    if (!isset($ARGV[$arg])) {
140
                        $ARGV[$arg] = ++$ARGNUM;
141
                    }
142
                    return 'ARGV[' . $ARGV[$arg] . ']';
143
                }, $cmd);
144
            }
145
146
            $CMDS[] = $cmd;
147
        }
148
149
        return $this->cachedParams = array_merge(
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge(array(implod...YS), array_keys($ARGV)) of type array<integer,string|int...string","1":"integer"}> is incompatible with the declared type boolean of property $cachedParams.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
150
            [implode(';', $CMDS), count($KEYS)],
151
            array_keys($KEYS),
152
            array_keys($ARGV)
153
        );
154
    }
155
156
    /**
157
     * Adds eval command in stack
158
     * @param string $cmd Lua script
159
     * @param mixed $keys Keys
160
     * @param mixed $argv Arguments
161
     */
162
    public function add($cmd, $keys = null, $argv = null)
163
    {
164 View Code Duplication
        if ($keys !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
165
            if (is_scalar($keys)) {
166
                $keys = [(string)$keys];
167
            } elseif (!is_array($keys)) {
168
                throw new \Exception("Keys must be an array or scalar");
169
            }
170
        }
171 View Code Duplication
        if ($argv !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
172
            if (is_scalar($argv)) {
173
                $argv = [(string)$argv];
174
            } elseif (!is_array($argv)) {
175
                throw new \Exception("Argv must be an array or scalar");
176
            }
177
        }
178
179
        $this->cachedParams = false;
180
        $this->stack[] = [$cmd, $keys, $argv];
181
    }
182
}
183