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

ContainerRegistry   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 21.43%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 32
ccs 3
cts 14
cp 0.2143
rs 10
c 1
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A className() 0 6 1
A getHandler() 0 13 3
A __construct() 0 4 1
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