QueryServiceRouter::getQueryServiceFor()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Explicit Architecture POC,
7
 * which is created on top of the Symfony Demo application.
8
 *
9
 * (c) Herberto Graça <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Acme\App\Core\Port\Persistence;
16
17
use Acme\App\Core\Port\Persistence\Exception\QueryServiceIsNotCallableException;
18
use Acme\App\Core\Port\Persistence\Exception\UnableToHandleQueryException;
19
20
/**
21
 * This is the query service that will be used throughout the application, it's the entry point for querying.
22
 * It will receive a query object and route it to one of the underlying query services,
23
 * which is configured to handle that specific type of query objects.
24
 */
25
final class QueryServiceRouter implements QueryServiceRouterInterface
26
{
27
    /**
28
     * @var QueryServiceInterface|callable[]
29
     */
30
    private $queryServiceList = [];
31
32
    public function __construct(QueryServiceInterface ...$queryServiceList)
33
    {
34
        foreach ($queryServiceList as $queryService) {
35
            $this->addQueryService($queryService);
36
        }
37
    }
38
39
    public function query(QueryInterface $query): ResultCollectionInterface
40
    {
41
        return $this->getQueryServiceFor($query)($query);
42
    }
43
44
    private function addQueryService(QueryServiceInterface $queryService): void
45
    {
46
        if (!\is_callable($queryService)) {
47
            throw new QueryServiceIsNotCallableException($queryService);
48
        }
49
50
        $this->queryServiceList[$queryService->canHandle()] = $queryService;
51
    }
52
53
    private function getQueryServiceFor(QueryInterface $query): QueryServiceInterface
54
    {
55
        if (!$this->canHandle($query)) {
56
            throw new UnableToHandleQueryException($query);
57
        }
58
59
        return $this->queryServiceList[\get_class($query)];
60
    }
61
62
    private function canHandle(QueryInterface $query): bool
63
    {
64
        return isset($this->queryServiceList[\get_class($query)]);
65
    }
66
}
67