1 | <?php |
||
10 | class WorkerManager |
||
11 | { |
||
12 | protected $workers; |
||
13 | protected $jobManager; |
||
14 | |||
15 | /** @var LoggerInterface */ |
||
16 | protected $logger; |
||
17 | protected $eventDispatcher; |
||
18 | protected $logFunc; |
||
19 | |||
20 | 2 | public function __construct(JobManagerInterface $jobManager, EventDispatcher $eventDispatcher) |
|
26 | |||
27 | public function setLogger(LoggerInterface $logger) |
||
31 | |||
32 | /** |
||
33 | * @param Worker $worker |
||
34 | * |
||
35 | * @throws DuplicateWorkerException |
||
36 | */ |
||
37 | 2 | public function addWorker(Worker $worker) |
|
38 | { |
||
39 | 2 | if ($this->logger) { |
|
40 | $this->logger->debug(__METHOD__." - Added worker: {$worker->getName()}"); |
||
41 | } |
||
42 | |||
43 | 2 | if (isset($this->workers[$worker->getName()])) { |
|
44 | throw new DuplicateWorkerException("{$worker->getName()} already exists in worker manager"); |
||
45 | } |
||
46 | |||
47 | 2 | $this->workers[$worker->getName()] = $worker; |
|
48 | 2 | } |
|
49 | |||
50 | 1 | public function getWorker($name) |
|
58 | |||
59 | public function getWorkers() |
||
63 | |||
64 | public function setLoggingFunc(callable $callable) |
||
65 | { |
||
66 | $this->logFunc = $callable; |
||
67 | } |
||
68 | |||
69 | public function log($level, $msg, array $context = []) |
||
70 | { |
||
71 | if ($this->logFunc) { |
||
72 | call_user_func_array($this->logFunc, [$level, $msg, $context]); |
||
73 | |||
74 | return; |
||
75 | } |
||
76 | |||
77 | if ($this->logger) { |
||
78 | $this->logger->$level($msg, $context); |
||
79 | |||
80 | return; |
||
81 | } |
||
82 | } |
||
83 | |||
84 | /** |
||
85 | * @param null $workerName |
||
86 | * @param null $methodName |
||
87 | * @param bool $prioritize |
||
88 | * |
||
89 | * @return null|Job |
||
90 | */ |
||
91 | public function run($workerName = null, $methodName = null, $prioritize = true, $runId = null) |
||
92 | { |
||
93 | $job = $this->jobManager->getJob($workerName, $methodName, $prioritize, $runId); |
||
94 | if (!$job) { |
||
95 | return null; // no job to run |
||
96 | } |
||
97 | |||
98 | return $this->runJob($job); |
||
99 | } |
||
100 | |||
101 | /** |
||
102 | * @param array $payload |
||
103 | * @param Job $job |
||
104 | */ |
||
105 | protected function handleException(array $payload, Job $job) |
||
120 | |||
121 | public function runJob(Job $job) |
||
122 | { |
||
123 | $event = new Event($job); |
||
157 | } |
||
158 |