Completed
Pull Request — master (#226)
by
unknown
03:49
created

Connection::doHigh()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 9
loc 9
rs 9.6666
c 1
b 0
f 1
cc 2
eloc 5
nc 2
nop 3
1
<?php
2
namespace PHPDaemon\Clients\Gearman;
3
4
use PHPDaemon\Core\Daemon;
5
use PHPDaemon\Network\ClientConnection;
6
use PHPDaemon\Structures\StackCallbacks;
7
use PHPDaemon\Utils\Binary;
8
9
/**
10
 * Class Connection асинхронный класс для работы с Gearmanом
11
 *
12
 * TODO Сделать проверку данных
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
13
 *
14
 * @package PHPDaemon\YouServer\YOUGearman
15
 */
16
class  Connection extends ClientConnection {
0 ignored issues
show
Coding Style introduced by
Expected 1 space between class keyword and class name; 2 found
Loading history...
17
18
    /**
19
     * Request codes
20
     *
21
     * @var array
22
     */
23
    private $requestCommandList = array(
24
        'CAN_DO' => array (1),
25
        'CANT_DO' => array (2),
26
        'RESET_ABILITIES' => array (3),
27
        'PRE_SLEEP' => array (4),
28
        'SUBMIT_JOB' => array (7),
29
        'GRAB_JOB' => array (9),
30
        'WORK_STATUS' => array (12),
31
        'WORK_COMPLETE' => array (13),
32
        'WORK_FAIL' => array (14),
33
        'GET_STATUS' => array (15),
34
        'ECHO_REQ' => array (16),
35
        'SUBMIT_JOB_BG' => array (18),
36
        'SUBMIT_JOB_HIGH' => array (21),
37
        'SET_CLIENT_ID' => array (22),
38
        'CAN_DO_TIMEOUT' => array (23),
39
        'ALL_YOURS' => array (24),
40
        'WORK_EXCEPTION' => array (25),
41
        'OPTION_REQ' => array (26),
42
        'OPTION_RES' => array (27),
43
        'WORK_DATA' => array (28),
44
        'WORK_WARNING' => array (29),
45
        'GRAB_JOB_UNIQ' => array (30),
46
        'SUBMIT_JOB_HIGH_BG' => array (32),
47
        'SUBMIT_JOB_LOW' => array (33),
48
        'SUBMIT_JOB_LOW_BG' => array (34),
49
        'SUBMIT_JOB_SCHED' => array (35),
50
        'SUBMIT_JOB_EPOCH' => array (36),
51
    );
52
53
    /**
54
     * Response codes
55
     *
56
     * @var array
57
     */
58
    private $responseCommandList = array(
59
        'NOOP' => array (6),
60
        'JOB_CREATED' => array (8),
61
        'NO_JOB' => array (10),
62
        'JOB_ASSIGN' => array (11),
63
        'WORK_STATUS' => array (12),
64
        'WORK_COMPLETE' => array (13),
65
        'WORK_FAIL' => array (14),
66
        'ECHO_RES' => array (17),
67
        'ERROR' => array (19),
68
        'STATUS_RES' => array (20),
69
        'WORK_EXCEPTION' => array (25),
70
        'OPTION_RES' => array (27),
71
        'WORK_WARNING' => array (29),
72
        'JOB_ASSIGN_UNIQ' => array (31)
73
    );
74
75
    const MAGIC_REQUEST         = "\0REQ";
76
77
    const MAGIC_RESPONSE        = "\0RES";
78
79
    const HEADER_LENGTH         = 12;
80
81
    const HEADER_WRITE_FORMAT   = "a4NN";
82
83
    const HEADER_READ_FORMAT    = "a4magic/Ntype/Nsize";
84
85
    const ARGS_DELIMITER        = "\0";
86
87
88
    private $jobAwaitResult = false;
89
90
    /**
91
     * Called when new data received
92
     * 
93
     * @return void
94
     */
95
    public function onRead() {
96
97
        $head = $this->read($this::HEADER_LENGTH);
98
        $head = unpack($this::HEADER_READ_FORMAT, $head);
99
        list($magic, $type, $size) = array_values($head);
100
101
        $type_array = $magic === $this::MAGIC_RESPONSE ? $this->responseCommandList : $this->requestCommandList;
102
        $TYPE_CODE = NULL;
103
104
        foreach ($type_array as $key => $info) {
105
            if (intval($info[0]) === intval($type)) {
106
                $TYPE_CODE = $key;
107
                break;
108
            }
109
        }
110
        $this->log($head, $TYPE_CODE);
0 ignored issues
show
Documentation introduced by
$head is of type array, 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...
Unused Code introduced by
The call to Connection::log() has too many arguments starting with $TYPE_CODE.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
111
112
        if (!$this->jobAwaitResult || 'WORK_COMPLETE' === $TYPE_CODE) {
113
            $body = $this->read($size);
114
            $argv = strlen($body) ? explode($this::ARGS_DELIMITER, $body) : [];
115
116
            $this->drain($this::HEADER_LENGTH + $size);
117
118
119
            /*
120
                TODO Сделать проверку на количество значений присланных в ответе в некоторых случаях с учетом входных значений
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
121
                TODO Обработка ERROR
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
122
            */
123
            $this->jobAwaitResult = false;
124
            $this->onResponse->executeOne($this, $argv);
125
            $this->checkFree();
126
            //$this->close();
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
127
            return ;
128
        }
129
130
        $this->drain($this::HEADER_LENGTH + $size);
131
    }
132
133
    /**
134
     * Function send ECHO
135
     *
136
     * @param $payload
137
     * @param callable|null $cb
138
     */
139
    public function sendEcho ($payload, callable $cb = null) {
140
        $this->sendCommand('ECHO_REQ', $payload, $cb);
141
    }
142
143
    /**
144
     * Function run task and whait result in callback
145
     *
146
     * @param $function_name
147
     * @param $payload
148
     * @param null $context
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
149
     * @param null $unique
150
     */
151 View Code Duplication
    public function runJob($function_name, $payload, $unique = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
152
153
        if ($unique) {
154
            $unique = uuid_create();
155
        }
156
157
        $cb = func_get_arg(func_num_args() - 1);
158
        $this->jobAwaitResult = true;
159
160
        $this->sendCommand("SUBMIT_JOB", [$function_name, $unique,  $payload], $cb);
161
    }
162
163
    /**
164
     * Function run task and whait result in callback
165
     *
166
     * @param $function_name
167
     * @param $payload
168
     * @param null $context
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
169
     * @param null $unique
170
     */
171 View Code Duplication
    public function doNormal($function_name, $payload, $unique = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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
173
        if ($unique) {
174
            $unique = uuid_create();
175
        }
176
177
        $cb = func_get_arg(func_num_args() - 1);
178
        $this->sendCommand("SUBMIT_JOB", [$function_name, $unique,  $payload], $cb);
179
    }
180
181
    /**
182
     * Function run task in background
183
     *
184
     * @param $function_name
185
     * @param $payload
186
     * @param null $context
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
187
     * @param null $unique
188
     */
189 View Code Duplication
    public function doBackground($function_name, $payload, $unique = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
190
191
        if ($unique) {
192
            $unique = uuid_create();
193
        }
194
195
        $cb = func_get_arg(func_num_args() - 1);
196
        $this->sendCommand("SUBMIT_JOB_BG", [$function_name, $unique,  $payload], $cb);
197
    }
198
199
    /**
200
     * Function run task with high prority
201
     *
202
     * @param $function_name
203
     * @param $payload
204
     * @param null $context
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
205
     * @param null $unique
206
     */
207 View Code Duplication
    public function doHigh($function_name, $payload, $unique = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
208
209
        if ($unique) {
210
            $unique = uuid_create();
211
        }
212
213
        $cb = func_get_arg(func_num_args() - 1);
214
        $this->sendCommand("SUBMIT_JOB_HIGH", [$function_name, $unique,  $payload], $cb);
215
    }
216
217
    /**
218
     * Function run task in background with high prority
219
     *
220
     * @param $function_name
221
     * @param $payload
222
     * @param null $context
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
223
     * @param null $unique
224
     */
225 View Code Duplication
    public function doHighBackground($function_name, $payload, $unique = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
226
227
        if ($unique) {
228
            $unique = uuid_create();
229
        }
230
231
        $cb = func_get_arg(func_num_args() - 1);
232
        $this->sendCommand("SUBMIT_JOB_HIGH_BG", [$function_name, $unique,  $payload], $cb);
233
    }
234
235
    /**
236
     * Function run task with low prority
237
     *
238
     * @param $function_name
239
     * @param $payload
240
     * @param null $context
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
241
     * @param null $unique
242
     */
243 View Code Duplication
    public function doLow($function_name, $payload, $unique = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
244
245
        if ($unique) {
246
            $unique = uuid_create();
247
        }
248
249
        $cb = func_get_arg(func_num_args() - 1);
250
        $this->sendCommand("SUBMIT_JOB_LOW", [$function_name, $unique,  $payload], $cb);
251
    }
252
253
    /**
254
     * Function run task in background with low prority
255
     *
256
     * @param $function_name
257
     * @param $payload
258
     * @param null $context
0 ignored issues
show
Bug introduced by
There is no parameter named $context. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
259
     * @param null $unique
260
     */
261 View Code Duplication
    public function doLowBackground($function_name, $payload, $unique = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
262
263
        if ($unique) {
264
            $unique = uuid_create();
265
        }
266
267
        $cb = func_get_arg(func_num_args() - 1);
268
        $this->sendCommand("SUBMIT_JOB_LOW_BG", [$function_name, $unique,  $payload], $cb);
269
    }
270
271
    /**
272
     * Функция исполняет удаленно таск
273
     * @param $job_handle Job handle that was given in JOB_CREATED packet.
274
     *
275
     */
276
    public function doStatus($job_handle) {
277
278
        $cb = func_get_arg(func_num_args() - 1);
279
        $this->sendCommand("GET_STATUS", [$job_handle], $cb);
280
    }
281
282
    /**
283
     * Function set settings for current connection
284
     * Available settings
285
     * "exceptions" - Forward WORK_EXCEPTION packets to the client.
286
     *
287
     * @url http://gearman.org/protocol/
288
     *
289
     *
290
     * @param int $option_name
291
     * @param callable $doneCallback
292
     */
293
    public function setConnectionOption($option_name, callable $doneCallback) {
294
        $this->sendCommand("OPTION_RES", [$option_name], $doneCallback);
295
    }
296
297
298
    /**
299
     * Low level commands sender
300
     *
301
     * @param $commandName
302
     * @param $payload
303
     * @param callable|null $doneCallback
304
     */
305
    private function sendCommand($commandName, $payload, callable $doneCallback = null) {
306
307
        $payload = (array) $payload;
308
        $payload = array_map(function($item){ return !is_scalar($item) ? serialize($item) : $item; }, $payload);
309
        $payload = implode($this::ARGS_DELIMITER, $payload);
310
311
        $len = strlen($payload);
312
313
        list($command_id) = $this->requestCommandList[$commandName];
314
        $this->onResponse->push($doneCallback);
0 ignored issues
show
Bug introduced by
It seems like $doneCallback defined by parameter $doneCallback on line 305 can also be of type null; however, PHPDaemon\Structures\StackCallbacks::push() does only seem to accept callable, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
315
316
        $sendData = pack($this::HEADER_WRITE_FORMAT, "\0REQ", $command_id, $len);
317
        $sendData .= $payload;
318
319
        $this->write($sendData);
320
    }
321
}