Passed
Pull Request — master (#592)
by Aleksei
06:09
created

QueueInjector::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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
/**
14
 * @implements InjectorInterface<QueueInterface>
15
 */
16
class QueueInjector implements InjectorInterface
17
{
18
    private QueueConnectionProviderInterface $queueManager;
19
20
    public function __construct(QueueConnectionProviderInterface $queueManager)
21
    {
22
        $this->queueManager = $queueManager;
23
    }
24
25
    public function createInjection(ReflectionClass $class, string $context = null): QueueInterface
26
    {
27
        if ($context === null) {
28
            $connection = $this->queueManager->getConnection();
29
        } else {
30
            // Get Queue by context
31
            try {
32
                $connection = $this->queueManager->getConnection($context);
33
            } catch (InvalidArgumentException $e) {
34
                // Case when context doesn't match to configured connections
35
                return $this->queueManager->getConnection();
36
            }
37
        }
38
39
        // User specified a specific class type
40
        $className = $class->getName();
41
        if ($className !== QueueInterface::class && !$connection instanceof $className) {
42
            throw new \RuntimeException(
43
                \sprintf(
44
                    "The queue obtained by the context `%s` doesn't match the type `%s`.",
45
                    $context,
46
                    $className
47
                )
48
            );
49
        }
50
51
        return $connection;
52
    }
53
}
54