Passed
Pull Request — master (#656)
by Abdul Malik
09:06 queued 02:28
created

ContainerRegistry::getHandler()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 13
ccs 0
cts 7
cp 0
crap 12
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Queue;
6
7
use Doctrine\Inflector\Inflector;
8
use Doctrine\Inflector\Rules\English\InflectorFactory;
9
use Psr\Container\ContainerInterface;
10
use Spiral\Core\Exception\Container\ContainerException;
11
use Spiral\Queue\Exception\JobException;
12
13
final class ContainerRegistry implements HandlerRegistryInterface
14
{
15
    private ContainerInterface $container;
16
    private Inflector $inflector;
17
18 2
    public function __construct(ContainerInterface $container)
19
    {
20 2
        $this->container = $container;
21 2
        $this->inflector = (new InflectorFactory())->build();
22
    }
23
24
    public function getHandler(string $jobType): HandlerInterface
25
    {
26
        try {
27
            $handler = $this->container->get($this->className($jobType));
28
        } catch (ContainerException $e) {
29
            throw new JobException($e->getMessage(), $e->getCode(), $e);
30
        }
31
32
        if (!$handler instanceof HandlerInterface) {
33
            throw new JobException("Unable to resolve job handler for `{$jobType}`");
34
        }
35
36
        return $handler;
37
    }
38
39
    private function className(string $jobType): string
40
    {
41
        $names = explode('.', $jobType);
42
        $names = array_map(fn(string $value) => $this->inflector->classify($value), $names);
43
44
        return implode('\\', $names);
45
    }
46
}
47