File size: 2,196 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php

declare(strict_types=1);

namespace Shared\Infrastructure\CommandBus;

use Doctrine\ORM\EntityManagerInterface;
use Psr\Container\ContainerInterface;
use ReflectionObject;
use Shared\Infrastructure\CommandBus\Attributes\Handler;
use Shared\Infrastructure\CommandBus\Exception\NoHandlerFoundException;
use Throwable;

/**
 * Dispatcher class for command and query handlers.
 *
 * Dispatches a command or query to its appropriate handler.
 */
class Dispatcher
{
    /**
     * Constructor method for the Dispatcher class.
     *
     * @param ContainerInterface $container
     * The container used to manage dependencies.
     * @return void
     */
    public function __construct(
        private ContainerInterface $container
    ) {
    }

    /**
     * Method that dispatches a command or query to its appropriate handler.
     * 
     * @param object $cmd The command or query to be handled.
     * @return mixed The result of the command/query execution.
     * @throws NoHandlerFoundException If no appropriate handler is found.
     */
    public function dispatch(object $cmd): mixed
    {
        $handler = $this->getHandler($cmd);
        $resp =  $handler->handle($cmd);

        return $resp;
    }

    /**
     * Method that retrieves the handler for a given command/query object.
     *
     * @param object $cmd The command or query to retrieve a handler for.
     * @return object The handler for the given command/query.
     * @throws NoHandlerFoundException If no appropriate handler is found.
     */
    private function getHandler(object $cmd): object
    {
        $reflection = new ReflectionObject($cmd);

        while ($reflection) {
            $attributes = $reflection->getAttributes(Handler::class);

            foreach ($attributes as $attribute) {
                $ins = $attribute->newInstance();
                $className = $ins->className;

                // Retrieves the handler for the given command/query
                // from the container.
                return $this->container->get($className);
            }

            $reflection = $reflection->getParentClass();
        }

        throw new NoHandlerFoundException($cmd);
    }
}