/
CallQueuedListener.php
executable file
·141 lines (121 loc) · 2.84 KB
/
CallQueuedListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
<?php
namespace Skytells\Events;
use Skytells\Container\Container;
use Skytells\Contracts\Queue\Job;
use Skytells\Queue\InteractsWithQueue;
use Skytells\Contracts\Queue\ShouldQueue;
class CallQueuedListener implements ShouldQueue
{
use InteractsWithQueue;
/**
* The listener class name.
*
* @var string
*/
public $class;
/**
* The listener method.
*
* @var string
*/
public $method;
/**
* The data to be passed to the listener.
*
* @var array
*/
public $data;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout;
/**
* Create a new job instance.
*
* @param string $class
* @param string $method
* @param array $data
* @return void
*/
public function __construct($class, $method, $data)
{
$this->data = $data;
$this->class = $class;
$this->method = $method;
}
/**
* Handle the queued job.
*
* @param \Skytells\Container\Container $container
* @return void
*/
public function handle(Container $container)
{
$this->prepareData();
$handler = $this->setJobInstanceIfNecessary(
$this->job, $container->make($this->class)
);
call_user_func_array(
[$handler, $this->method], $this->data
);
}
/**
* Set the job instance of the given class if necessary.
*
* @param \Skytells\Contracts\Queue\Job $job
* @param mixed $instance
* @return mixed
*/
protected function setJobInstanceIfNecessary(Job $job, $instance)
{
if (in_array(InteractsWithQueue::class, class_uses_recursive(get_class($instance)))) {
$instance->setJob($job);
}
return $instance;
}
/**
* Call the failed method on the job instance.
*
* The event instance and the exception will be passed.
*
* @param \Exception $e
* @return void
*/
public function failed($e)
{
$this->prepareData();
$handler = Container::getInstance()->make($this->class);
$parameters = array_merge($this->data, [$e]);
if (method_exists($handler, 'failed')) {
call_user_func_array([$handler, 'failed'], $parameters);
}
}
/**
* Unserialize the data if needed.
*
* @return void
*/
protected function prepareData()
{
if (is_string($this->data)) {
$this->data = unserialize($this->data);
}
}
/**
* Get the display name for the queued job.
*
* @return string
*/
public function displayName()
{
return $this->class;
}
}