Passed
Push — master ( 2664aa...44e705 )
by Joachim
02:31
created

DispatchMessageHandler::__invoke()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 60
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 36
c 2
b 0
f 0
dl 0
loc 60
ccs 0
cts 35
cp 0
rs 8.4106
cc 7
nc 11
nop 1
crap 56

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Setono\MessageSchedulerBundle\Message\Handler;
6
7
use Doctrine\Persistence\ManagerRegistry;
8
use Doctrine\Persistence\ObjectManager;
9
use RuntimeException;
10
use Safe\DateTime;
11
use function Safe\sprintf;
12
use Setono\MessageSchedulerBundle\Entity\ScheduledMessage;
13
use Setono\MessageSchedulerBundle\Message\Command\DispatchScheduledMessage;
14
use Setono\MessageSchedulerBundle\Repository\ScheduledMessageRepositoryInterface;
15
use Setono\MessageSchedulerBundle\Workflow\ScheduledMessageWorkflow;
16
use Symfony\Component\Messenger\Envelope;
17
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
18
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
19
use Symfony\Component\Messenger\RoutableMessageBus;
20
use Symfony\Component\Messenger\Stamp\BusNameStamp;
21
use Symfony\Component\Workflow\Registry;
22
use Throwable;
23
24
final class DispatchMessageHandler implements MessageHandlerInterface
25
{
26
    private ?ObjectManager $objectManager = null;
27
28
    private RoutableMessageBus $routableMessageBus;
29
30
    private ScheduledMessageRepositoryInterface $scheduledMessageRepository;
31
32
    private Registry $workflowRegistry;
33
34
    private ManagerRegistry $managerRegistry;
35
36 1
    public function __construct(
37
        RoutableMessageBus $routableMessageBus,
38
        ScheduledMessageRepositoryInterface $scheduledMessageRepository,
39
        Registry $workflowRegistry,
40
        ManagerRegistry $managerRegistry
41
    ) {
42 1
        $this->routableMessageBus = $routableMessageBus;
43 1
        $this->scheduledMessageRepository = $scheduledMessageRepository;
44 1
        $this->workflowRegistry = $workflowRegistry;
45 1
        $this->managerRegistry = $managerRegistry;
46 1
    }
47
48
    public function __invoke(DispatchScheduledMessage $message): void
49
    {
50
        /** @var ScheduledMessage|null $scheduledMessage */
51
        $scheduledMessage = $this->scheduledMessageRepository->find($message->getScheduledMessageId());
52
        if (null === $scheduledMessage) {
53
            throw new UnrecoverableMessageHandlingException(sprintf(
54
                'The scheduled message with id, "%s" does not exist', $message->getScheduledMessageId()
55
            ));
56
        }
57
58
        $now = new DateTime();
59
        if ($scheduledMessage->getDispatchAt() > $now) {
60
            throw new UnrecoverableMessageHandlingException(sprintf(
61
                'The scheduled message with id, "%s" is not eligible to be dispatched yet. The dispatch timestamp is %s, while the time now is %s',
62
                $message->getScheduledMessageId(), $scheduledMessage->getDispatchAt()->format(\DATE_ATOM), $now->format(\DATE_ATOM)
63
            ));
64
        }
65
66
        $workflow = $this->workflowRegistry->get($scheduledMessage, ScheduledMessageWorkflow::NAME);
67
        if (!$workflow->can($scheduledMessage, ScheduledMessageWorkflow::TRANSITION_PROCESS)) {
68
            throw new UnrecoverableMessageHandlingException(sprintf(
69
                'The scheduled message with id, "%s" could not enter the transition "%s". The state was: "%s"',
70
                $message->getScheduledMessageId(), ScheduledMessageWorkflow::TRANSITION_PROCESS, $scheduledMessage->getState()
71
            ));
72
        }
73
        $workflow->apply($scheduledMessage, ScheduledMessageWorkflow::TRANSITION_PROCESS);
74
75
        $objectManager = $this->getObjectManager($scheduledMessage);
76
        $objectManager->flush();
77
78
        /** @var object $messageToBeDispatched */
79
        $messageToBeDispatched = unserialize($scheduledMessage->getSerializedMessage(), [
80
            'allowed_classes' => [ScheduledMessage::class],
81
        ]);
82
83
        $stamps = [];
84
85
        $bus = $scheduledMessage->getBus();
86
        if (null !== $bus) {
87
            $stamps[] = new BusNameStamp($bus);
88
        }
89
90
        try {
91
            $this->routableMessageBus->dispatch(new Envelope($messageToBeDispatched, $stamps));
92
93
            $workflow->apply($scheduledMessage, ScheduledMessageWorkflow::TRANSITION_SUCCEED);
94
            $objectManager->flush();
95
        } catch (Throwable $e) {
96
            $originalException = $e;
97
98
            $workflow->apply($scheduledMessage, ScheduledMessageWorkflow::TRANSITION_FAIL);
99
100
            do {
101
                $scheduledMessage->addError($e->getMessage());
102
                $e = $e->getPrevious();
103
            } while (null !== $e);
104
105
            $objectManager->flush();
106
107
            throw $originalException;
108
        }
109
    }
110
111
    private function getObjectManager(object $object): ObjectManager
112
    {
113
        if (null === $this->objectManager) {
114
            $class = get_class($object);
115
            $manager = $this->managerRegistry->getManagerForClass($class);
116
117
            if (null === $manager) {
118
                throw new RuntimeException(sprintf('No object manager associated with the class, %s', $class));
119
            }
120
121
            $this->objectManager = $manager;
122
        }
123
124
        return $this->objectManager;
125
    }
126
}
127