Test Failed
Pull Request — develop (#34)
by
unknown
02:25
created

Resque_Job::getPrefix()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Resque job.
4
 *
5
 * @package		Resque/Job
6
 * @author		Chris Boulton <[email protected]>
7
 * @license		http://www.opensource.org/licenses/mit-license.php
8
 */
9
class Resque_Job
10
{
11
	/**
12
	 * @var string The name of the queue that this job belongs to.
13
	 */
14
	public $queue;
15
16
	/**
17
	 * @var Resque_Worker Instance of the Resque worker running this job.
18
	 */
19
	public $worker;
20
21
	/**
22
	 * @var array Array containing details of the job.
23
	 */
24
	public $payload;
25
26
	/**
27
	 * @var object|Resque_JobInterface Instance of the class performing work for this job.
28
	 */
29
	private $instance;
30
31
	/**
32
	 * @var Resque_Job_FactoryInterface
33
	 */
34
	private $jobFactory;
35
36
	/**
37
	 * Instantiate a new instance of a job.
38
	 *
39
	 * @param string $queue The queue that the job belongs to.
40
	 * @param array $payload array containing details of the job.
41
	 */
42 35
	public function __construct($queue, $payload)
43
	{
44 35
		$this->queue = $queue;
45 35
		$this->payload = $payload;
46 35
	}
47
48
	/**
49
	 * Create a new job and save it to the specified queue.
50
	 *
51
	 * @param string $queue The name of the queue to place the job in.
52
	 * @param string $class The name of the class that contains the code to execute the job.
53
	 * @param array $args Any optional arguments that should be passed when the job is executed.
54
	 * @param boolean $monitor Set to true to be able to monitor the status of a job.
55
	 * @param string $id Unique identifier for tracking the job. Generated if not supplied.
56
	 * @param string $prefix The prefix needs to be set for the status key
57
	 *
58
	 * @return string
59
	 * @throws \InvalidArgumentException
60
	 */
61 47
	public static function create($queue, $class, $args = null, $monitor = false, $id = null, $prefix = "")
62
	{
63 47
		if (is_null($id)) {
64
			$id = Resque::generateJobId();
65
		}
66
67 47
		if($args !== null && !is_array($args)) {
0 ignored issues
show
introduced by
The condition is_array($args) is always true.
Loading history...
68 1
			throw new InvalidArgumentException(
69 1
				'Supplied $args must be an array.'
70
			);
71
		}
72 46
		Resque::push($queue, array(
73 46
			'class'	     => $class,
74 46
			'args'	     => array($args),
75 46
			'id'	     => $id,
76 46
			'prefix'     => $prefix,
77 46
			'queue_time' => microtime(true),
78
		));
79
80 45
		if($monitor) {
81 10
			Resque_Job_Status::create($id, $prefix);
82
		}
83
84 45
		return $id;
85
	}
86
87
	/**
88
	 * Find the next available job from the specified queue and return an
89
	 * instance of Resque_Job for it.
90
	 *
91
	 * @param string $queue The name of the queue to check for a job in.
92
	 * @return false|object Null when there aren't any waiting jobs, instance of Resque_Job when a job was found.
93
	 */
94 26
	public static function reserve($queue)
95
	{
96 26
		$payload = Resque::pop($queue);
97 26
		if(!is_array($payload)) {
0 ignored issues
show
introduced by
The condition is_array($payload) is always true.
Loading history...
98 17
			return false;
99
		}
100
101 22
		return new Resque_Job($queue, $payload);
102
	}
103
104
	/**
105
	 * Find the next available job from the specified queues using blocking list pop
106
	 * and return an instance of Resque_Job for it.
107
	 *
108
	 * @param array             $queues
109
	 * @param int               $timeout
110
	 * @return false|object Null when there aren't any waiting jobs, instance of Resque_Job when a job was found.
111
	 */
112 1
	public static function reserveBlocking(array $queues, $timeout = null)
113
	{
114 1
		$item = Resque::blpop($queues, $timeout);
115
116 1
		if(!is_array($item)) {
117
			return false;
118
		}
119
120 1
		return new Resque_Job($item['queue'], $item['payload']);
121
	}
122
123
	/**
124
	 * Update the status of the current job.
125
	 *
126
	 * @param int $status Status constant from Resque_Job_Status indicating the current status of a job.
127
	 */
128 18
	public function updateStatus($status, $result = null)
129
	{
130 18
		if(empty($this->payload['id'])) {
131 7
			return;
132
		}
133
134 12
		$statusInstance = new Resque_Job_Status($this->payload['id'], $this->getPrefix());
135 12
		$statusInstance->update($status, $result);
136 12
	}
137
138
	/**
139
	 * Return the status of the current job.
140
	 *
141
	 * @return int|null The status of the job as one of the Resque_Job_Status constants or null if job is not being tracked.
142
	 */
143 10
	public function getStatus()
144
	{
145 10
		if(empty($this->payload['id'])) {
146 10
			return null;
147
		}
148
149
		$status = new Resque_Job_Status($this->payload['id'], $this->getPrefix());
150
		return $status->get();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $status->get() could also return false which is incompatible with the documented return type integer|null. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
151
	}
152
153
	/**
154 16
	 * Get the arguments supplied to this job.
155
	 *
156 16
	 * @return array Array of arguments.
157 2
	 */
158
	public function getArguments()
159
	{
160 14
		if (!isset($this->payload['args'])) {
161
			return array();
162
		}
163
164
		return $this->payload['args'][0];
165
	}
166
167
	/**
168 12
	 * Get the instantiated object for this job that will be performing work.
169
	 * @return Resque_JobInterface Instance of the object that this job belongs to.
170 12
	 * @throws Resque_Exception
171
	 */
172
	public function getInstance()
173
	{
174 12
		if (!is_null($this->instance)) {
175 10
			return $this->instance;
176 10
		}
177
178
        $this->instance = $this->getJobFactory()->create($this->payload['class'], $this->getArguments(), $this->queue);
179
        $this->instance->job = $this;
0 ignored issues
show
Bug introduced by
Accessing job on the interface Resque_JobInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
180
        return $this->instance;
181
	}
182
183
	/**
184
	 * Actually execute a job by calling the perform method on the class
185
	 * associated with the job with the supplied arguments.
186 10
	 *
187
	 * @return bool
188 10
	 * @throws Resque_Exception When the job's class could not be found or it does not contain a perform method.
189
	 */
190 10
	public function perform()
191
	{
192 9
		$result = true;
193 7
		try {
194 1
			Resque_Event::trigger('beforePerform', $this);
195
196
			$instance = $this->getInstance();
197 7
			if(is_callable([$instance, 'setUp'])) {
198
				$instance->setUp();
0 ignored issues
show
Bug introduced by
The method setUp() does not exist on Resque_JobInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

198
				$instance->/** @scrutinizer ignore-call */ 
199
               setUp();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
199 6
			}
200 1
201
			$result = $instance->perform();
202
203 6
			if(is_callable([$instance, 'tearDown'])) {
204
				$instance->tearDown();
0 ignored issues
show
Bug introduced by
The method tearDown() does not exist on Resque_JobInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

204
				$instance->/** @scrutinizer ignore-call */ 
205
               tearDown();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
205
			}
206 4
207 1
			Resque_Event::trigger('afterPerform', $this);
208
		}
209
		// beforePerform/setUp have said don't perform this job. Return.
210 7
		catch(Resque_Job_DontPerform $e) {
211
			$result = false;
212
		}
213
214
		return $result;
215
	}
216
217
	/**
218 3
	 * Mark the current job as having failed.
219
	 *
220 3
	 * @param $exception
221 3
	 */
222 3
	public function fail($exception)
223
	{
224
		Resque_Event::trigger('onFailure', array(
225 3
			'exception' => $exception,
226 3
			'job' => $this,
227
		));
228
229
		$this->updateStatus(Resque_Job_Status::STATUS_FAILED);
230
		if ($exception instanceof Error) {
231
			Resque_Failure::createFromError(
232
				$this->payload,
233
				$exception,
234 3
				$this->worker,
235 3
				$this->queue
236 3
			);
237 3
		} else {
238 3
			Resque_Failure::create(
239
				$this->payload,
240
				$exception,
241 3
				$this->worker,
242 3
				$this->queue
243 3
			);
244
		}
245
		Resque_Stat::incr('failed');
246
		Resque_Stat::incr('failed:' . $this->worker);
247
	}
248
249 2
	/**
250
	 * Re-queue the current job.
251 2
	 * @return string
252 2
	 */
253 2
	public function recreate()
254 1
	{
255
		$monitor = false;
256
		if (!empty($this->payload['id'])) {
257 2
			$status = new Resque_Job_Status($this->payload['id'], $this->getPrefix());
258
			if($status->isTracking()) {
259
				$monitor = true;
260
			}
261
		}
262
263
		return self::create($this->queue, $this->payload['class'], $this->getArguments(), $monitor, null, $this->getPrefix());
264
	}
265 13
266
	/**
267
	 * Generate a string representation used to describe the current job.
268 13
	 *
269
	 * @return string The string representation of the job.
270 13
	 */
271 9
	public function __toString()
272
	{
273 13
		$name = array(
274 13
			'Job{' . $this->queue .'}'
275 12
		);
276
		if(!empty($this->payload['id'])) {
277 13
			$name[] = 'ID: ' . $this->payload['id'];
278
		}
279
		$name[] = $this->payload['class'];
280
		if(!empty($this->payload['args'])) {
281
			$name[] = json_encode($this->payload['args']);
282
		}
283
		return '(' . implode(' | ', $name) . ')';
284 1
	}
285
286 1
	/**
287
	 * @param Resque_Job_FactoryInterface $jobFactory
288 1
	 * @return Resque_Job
289
	 */
290
	public function setJobFactory(Resque_Job_FactoryInterface $jobFactory)
291
	{
292
		$this->jobFactory = $jobFactory;
293
294 12
		return $this;
295
	}
296 12
297 11
    /**
298
     * @return Resque_Job_FactoryInterface
299 12
     */
300
    public function getJobFactory()
301
    {
302 1
        if ($this->jobFactory === null) {
303
            $this->jobFactory = new Resque_Job_Factory();
304
        }
305
        return $this->jobFactory;
306
    }
307
308
    /**
309
     * @return string
310
     */
311
    private function getPrefix()
312
    {
313
    	if (isset($this->payload['prefix'])) {
314
    		return $this->payload['prefix'];
315
    	}
316
317
    	return '';
318
    }
319
}
320