Passed
Pull Request — master (#464)
by Kirill
04:42
created

JobHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 45
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getHandlerMethod() 0 3 1
A handle() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Jobs;
6
7
use Spiral\Core\ResolverInterface;
8
use Spiral\Jobs\Exception\JobException;
9
10
/**
11
 * Handler which can invoke itself.
12
 */
13
abstract class JobHandler implements HandlerInterface
14
{
15
    /**
16
     * Default function with method injection.
17
     *
18
     * @var string
19
     */
20
    protected const HANDLE_FUNCTION = 'invoke';
21
22
    /**
23
     * @var ResolverInterface
24
     */
25
    protected ResolverInterface $resolver;
26
27
    /**
28
     * @param ResolverInterface $resolver
29
     */
30
    public function __construct(ResolverInterface $resolver)
31
    {
32
        $this->resolver = $resolver;
33
    }
34
35
    /**
36
     * @inheritdoc
37
     */
38
    public function handle(string $name, string $id, array $payload): void
39
    {
40
        $method = new \ReflectionMethod($this, $this->getHandlerMethod());
41
        $method->setAccessible(true);
42
43
        try {
44
            $parameters = \array_merge(['payload' => $payload, 'id' => $id], $payload);
45
            $method->invokeArgs($this, $this->resolver->resolveArguments($method, $parameters));
46
        } catch (\Throwable $e) {
47
            $message = \sprintf('[%s] %s', \get_class($this), $e->getMessage());
48
            throw new JobException($message, (int)$e->getCode(), $e);
49
        }
50
    }
51
52
    /**
53
     * @return string
54
     */
55
    protected function getHandlerMethod(): string
56
    {
57
        return static::HANDLE_FUNCTION;
58
    }
59
}
60