Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
23 / 23 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| SyncQueryBus | |
100.00% |
23 / 23 |
|
100.00% |
3 / 3 |
5 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| dispatch | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
1 | |||
| resolveHandler | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | // ╔════════════════════════════════════════════════════════════╗ |
| 4 | // ║ MIT Licence (#Expat) - https://opensource.org/licenses/MIT ║ |
| 5 | // ║ Copyright 2026 Frederic Poeydomenge <dyno@phexium.com> ║ |
| 6 | // ╚════════════════════════════════════════════════════════════╝ |
| 7 | |
| 8 | declare(strict_types=1); |
| 9 | |
| 10 | namespace Phexium\Plugin\QueryBus\Adapter; |
| 11 | |
| 12 | use InvalidArgumentException; |
| 13 | use Override; |
| 14 | use Phexium\Application\Query\QueryHandlerInterface; |
| 15 | use Phexium\Application\Query\QueryInterface; |
| 16 | use Phexium\Application\Query\QueryResponseInterface; |
| 17 | use Phexium\Plugin\Logger\Port\LoggerInterface; |
| 18 | use Phexium\Plugin\QueryBus\Internal\QueryHandlerNamingConvention; |
| 19 | use Phexium\Plugin\QueryBus\Port\QueryBusInterface; |
| 20 | use Psr\Container\ContainerInterface; |
| 21 | |
| 22 | final readonly class SyncQueryBus implements QueryBusInterface |
| 23 | { |
| 24 | public function __construct( |
| 25 | private ContainerInterface $container, |
| 26 | private LoggerInterface $logger |
| 27 | ) {} |
| 28 | |
| 29 | #[Override] |
| 30 | public function dispatch(QueryInterface $query): QueryResponseInterface |
| 31 | { |
| 32 | $queryClass = $query::class; |
| 33 | |
| 34 | $this->logger->debug('QueryBus: Dispatching query', [ |
| 35 | 'query' => $queryClass, |
| 36 | ]); |
| 37 | |
| 38 | $handler = $this->resolveHandler($queryClass); |
| 39 | |
| 40 | return $handler->handle($query); |
| 41 | } |
| 42 | |
| 43 | private function resolveHandler(string $queryClass): QueryHandlerInterface |
| 44 | { |
| 45 | $handlerClass = QueryHandlerNamingConvention::resolveHandlerClass($queryClass); |
| 46 | |
| 47 | if (!class_exists($handlerClass)) { |
| 48 | throw new InvalidArgumentException( |
| 49 | sprintf( |
| 50 | 'Handler not found for query %s. Expected class: %s', |
| 51 | $queryClass, |
| 52 | $handlerClass |
| 53 | ) |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | $handler = $this->container->get($handlerClass); |
| 58 | |
| 59 | if (!$handler instanceof QueryHandlerInterface) { |
| 60 | throw new InvalidArgumentException(sprintf( |
| 61 | 'Handler must implement %s.', |
| 62 | QueryHandlerInterface::class |
| 63 | )); |
| 64 | } |
| 65 | |
| 66 | return $handler; |
| 67 | } |
| 68 | } |