Passed
Pull Request — master (#592)
by Aleksei
05:28
created

QueueInjector   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 36
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A createInjection() 0 27 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Queue\Core;
6
7
use ReflectionClass;
8
use Spiral\Core\Container\InjectorInterface;
9
use Spiral\Queue\Exception\InvalidArgumentException;
10
use Spiral\Queue\QueueConnectionProviderInterface;
11
use Spiral\Queue\QueueInterface;
12
13
class QueueInjector implements InjectorInterface
14
{
15
    private QueueConnectionProviderInterface $queueManager;
16
17
    public function __construct(QueueConnectionProviderInterface $queueManager)
18
    {
19
        $this->queueManager = $queueManager;
20
    }
21
22
    public function createInjection(ReflectionClass $class, string $context = null): QueueInterface
23
    {
24
        // Get Queue by context
25
        if ($context === null) {
26
            $connection = $this->queueManager->getConnection();
27
        } else {
28
            try {
29
                $connection = $this->queueManager->getConnection($context);
30
            } catch (InvalidArgumentException $e) {
31
                // Case when context doesn't match to configured connections
32
                return $this->queueManager->getConnection();
33
            }
34
        }
35
36
        // User specified a specific class type
37
        $className = $class->getName();
38
        if ($className !== QueueInterface::class && !$connection instanceof $className) {
39
            throw new \RuntimeException(
40
                \sprintf(
41
                    "The queue obtained by the context `%s` doesn't match the type `%s`.",
42
                    $context,
43
                    $className
44
                )
45
            );
46
        }
47
48
        return $connection;
49
    }
50
}
51