1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Spiral Framework. |
5
|
|
|
* |
6
|
|
|
* @license MIT |
7
|
|
|
* @author Anton Titov (Wolfy-J) |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Spiral\Jobs; |
13
|
|
|
|
14
|
|
|
use Spiral\Core\ResolverInterface; |
15
|
|
|
use Spiral\Jobs\Exception\JobException; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Handler which can invoke itself. |
19
|
|
|
*/ |
20
|
|
|
abstract class JobHandler implements HandlerInterface, SerializerInterface |
21
|
|
|
{ |
22
|
|
|
// default function with method injection |
23
|
|
|
protected const HANDLE_FUNCTION = 'invoke'; |
24
|
|
|
|
25
|
|
|
/** @var ResolverInterface */ |
26
|
|
|
protected $resolver; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param ResolverInterface $resolver |
30
|
|
|
*/ |
31
|
|
|
public function __construct(ResolverInterface $resolver) |
32
|
|
|
{ |
33
|
|
|
$this->resolver = $resolver; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @inheritdoc |
38
|
|
|
*/ |
39
|
|
|
public function handle(string $jobType, string $jobID, string $payload): void |
40
|
|
|
{ |
41
|
|
|
$payloadData = $this->unserialize($jobType, $payload); |
42
|
|
|
|
43
|
|
|
$method = new \ReflectionMethod($this, static::HANDLE_FUNCTION); |
44
|
|
|
$method->setAccessible(true); |
45
|
|
|
|
46
|
|
|
try { |
47
|
|
|
$parameters = array_merge(['payload' => $payloadData, 'id' => $jobID], $payloadData); |
48
|
|
|
$method->invokeArgs($this, $this->resolver->resolveArguments($method, $parameters)); |
49
|
|
|
} catch (\Throwable $e) { |
50
|
|
|
throw new JobException( |
51
|
|
|
sprintf('[%s] %s', get_class($this), $e->getMessage()), |
52
|
|
|
$e->getCode(), |
53
|
|
|
$e |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @inheritdoc |
60
|
|
|
*/ |
61
|
|
|
public function serialize(string $jobType, array $payload): string |
62
|
|
|
{ |
63
|
|
|
return json_encode($payload); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string $jobType |
68
|
|
|
* @param string $payload |
69
|
|
|
* @return array |
70
|
|
|
*/ |
71
|
|
|
public function unserialize(string $jobType, string $payload): array |
72
|
|
|
{ |
73
|
|
|
return json_decode($payload, true); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|