1
|
|
|
<?php |
2
|
|
|
namespace Disque\Command\Response; |
3
|
|
|
|
4
|
|
|
use Disque\Command\Argument\ArrayChecker; |
5
|
|
|
|
6
|
|
|
class JobsResponse extends BaseResponse implements ResponseInterface |
7
|
|
|
{ |
8
|
|
|
use ArrayChecker; |
9
|
|
|
|
10
|
|
|
const KEY_ID = 'id'; |
11
|
|
|
const KEY_BODY = 'body'; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* The position where a node prefix starts in the job ID |
15
|
|
|
*/ |
16
|
|
|
const ID_NODE_PREFIX_START = 2; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Job details for each job |
20
|
|
|
* |
21
|
|
|
* The values in this array must follow these rules: |
22
|
|
|
* - The number of the values must be the same as the number of rows |
23
|
|
|
* returned from the respective Disque command |
24
|
|
|
* - The order of the values must follow the rows returned by Disque |
25
|
|
|
* |
26
|
|
|
* The values in $jobDetails will be used as keys in the final response |
27
|
|
|
* the command returns. |
28
|
|
|
* |
29
|
|
|
* @see self::parse() |
30
|
|
|
* |
31
|
|
|
* @var array |
32
|
|
|
*/ |
33
|
|
|
protected $jobDetails = []; |
34
|
|
|
|
35
|
|
|
public function __construct() |
36
|
|
|
{ |
37
|
|
|
$this->jobDetails = [self::KEY_ID, self::KEY_BODY]; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @inheritdoc |
42
|
|
|
*/ |
43
|
|
|
public function setBody($body) |
44
|
|
|
{ |
45
|
|
|
if (is_null($body)) { |
46
|
|
|
$body = []; |
47
|
|
|
} |
48
|
|
|
if (!is_array($body)) { |
49
|
|
|
throw new InvalidResponseException($this->command, $body); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$jobDetailCount = count($this->jobDetails); |
53
|
|
|
foreach ($body as $job) { |
54
|
|
|
if (!$this->checkFixedArray($job, $jobDetailCount)) { |
55
|
|
|
throw new InvalidResponseException($this->command, $body); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$idPosition = array_search(self::KEY_ID, $this->jobDetails); |
59
|
|
|
$id = $job[$idPosition]; |
60
|
|
|
if (strpos($id, 'D-') !== 0 || strlen($id) < 10) { |
61
|
|
|
throw new InvalidResponseException($this->command, $body); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
parent::setBody($body); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @inheritdoc |
70
|
|
|
*/ |
71
|
|
|
public function parse() |
72
|
|
|
{ |
73
|
|
|
$jobs = []; |
74
|
|
|
foreach ($this->body as $job) { |
75
|
|
|
// To describe this crucial moment in detail: $jobDetails as well as |
76
|
|
|
// the $job are numeric arrays with the same number of values. |
77
|
|
|
// array_combine() combines them in a new array so that values |
78
|
|
|
// from $jobDetails become the keys and values from $job the values. |
79
|
|
|
// It's very important that $jobDetails are present in the same |
80
|
|
|
// order as the response from Disque. |
81
|
|
|
$jobs[] = array_combine($this->jobDetails, $job); |
82
|
|
|
} |
83
|
|
|
return $jobs; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|