|
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\Core\Exception\Container\ContainerException; |
|
10
|
|
|
use Spiral\Queue\Exception\InvalidArgumentException; |
|
11
|
|
|
use Spiral\Queue\QueueConnectionProviderInterface; |
|
12
|
|
|
use Spiral\Queue\QueueInterface; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @implements InjectorInterface<QueueInterface> |
|
16
|
|
|
*/ |
|
17
|
|
|
final class QueueInjector implements InjectorInterface |
|
18
|
|
|
{ |
|
19
|
|
|
private QueueConnectionProviderInterface $queueManager; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(QueueConnectionProviderInterface $queueManager) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->queueManager = $queueManager; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function createInjection(ReflectionClass $class, string $context = null): QueueInterface |
|
27
|
|
|
{ |
|
28
|
|
|
try { |
|
29
|
|
|
if ($context === null) { |
|
30
|
|
|
$connection = $this->queueManager->getConnection(); |
|
31
|
|
|
} else { |
|
32
|
|
|
// Get Queue by context |
|
33
|
|
|
try { |
|
34
|
|
|
$connection = $this->queueManager->getConnection($context); |
|
35
|
|
|
} catch (InvalidArgumentException $e) { |
|
36
|
|
|
// Case when context doesn't match to configured connections |
|
37
|
|
|
return $this->queueManager->getConnection(); |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
$this->matchType($class, $context, $connection); |
|
|
|
|
|
|
42
|
|
|
} catch (\Throwable $e) { |
|
43
|
|
|
throw new ContainerException(sprintf("Can't inject the required queue. %s", $e->getMessage()), 0, $e); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
return $connection; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Check the resolved connection implements required type |
|
51
|
|
|
* |
|
52
|
|
|
* @throws \RuntimeException |
|
53
|
|
|
*/ |
|
54
|
|
|
private function matchType(ReflectionClass $class, string $context, QueueInterface $connection): void |
|
55
|
|
|
{ |
|
56
|
|
|
$className = $class->getName(); |
|
57
|
|
|
if ($className !== QueueInterface::class && !$connection instanceof $className) { |
|
58
|
|
|
throw new \RuntimeException( |
|
59
|
|
|
\sprintf( |
|
60
|
|
|
"The queue obtained by the context `%s` doesn't match the type `%s`.", |
|
61
|
|
|
$context, |
|
62
|
|
|
$className |
|
63
|
|
|
) |
|
64
|
|
|
); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|