Passed
Pull Request — master (#756)
by Maxim
07:24
created

ContainerRegistry   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 20%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 36
ccs 3
cts 15
cp 0.2
rs 10
c 1
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getHandler() 0 13 3
A className() 0 8 1
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Queue;
6
7
use Doctrine\Inflector\Rules\English\InflectorFactory;
8
use Psr\Container\ContainerInterface;
9
use Spiral\Core\Exception\Container\ContainerException;
10
use Spiral\Queue\Exception\JobException;
11
12
final class ContainerRegistry implements HandlerRegistryInterface
13
{
14
    /** @var ContainerInterface  */
15
    private $container;
16
    /** @var \Doctrine\Inflector\Inflector */
17
    private $inflector;
18
19 2
    public function __construct(ContainerInterface $container)
20
    {
21 2
        $this->container = $container;
22 2
        $this->inflector = (new InflectorFactory())->build();
23
    }
24
25
    public function getHandler(string $jobType): HandlerInterface
26
    {
27
        try {
28
            $handler = $this->container->get($this->className($jobType));
29
        } catch (ContainerException $e) {
30
            throw new JobException($e->getMessage(), $e->getCode(), $e);
31
        }
32
33
        if (!$handler instanceof HandlerInterface) {
34
            throw new JobException("Unable to resolve job handler for `{$jobType}`");
35
        }
36
37
        return $handler;
38
    }
39
40
    private function className(string $jobType): string
41
    {
42
        $names = explode('.', $jobType);
43
        $names = array_map(function (string $value) {
44
            return $this->inflector->classify($value);
45
        }, $names);
46
47
        return implode('\\', $names);
48
    }
49
}
50