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

ContainerRegistry::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
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\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