1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the daikon-cqrs/cqrs project. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
declare(strict_types=1); |
10
|
|
|
|
11
|
|
|
namespace Daikon\EventSourcing\Aggregate\Command; |
12
|
|
|
|
13
|
|
|
use Daikon\EventSourcing\Aggregate\AggregateIdInterface; |
14
|
|
|
use Daikon\EventSourcing\Aggregate\AggregateRevision; |
15
|
|
|
use Daikon\EventSourcing\Aggregate\AggregateRootInterface; |
16
|
|
|
use Daikon\EventSourcing\EventStore\UnitOfWorkInterface; |
17
|
|
|
use Daikon\MessageBus\Channel\Subscription\MessageHandler\MessageHandlerInterface; |
18
|
|
|
use Daikon\MessageBus\EnvelopeInterface; |
19
|
|
|
use Daikon\MessageBus\MessageBusInterface; |
20
|
|
|
use Daikon\MessageBus\Metadata\Metadata; |
21
|
|
|
|
22
|
|
|
abstract class CommandHandler implements MessageHandlerInterface |
23
|
|
|
{ |
24
|
|
|
/** @var MessageBusInterface */ |
25
|
|
|
private $messageBus; |
26
|
|
|
|
27
|
|
|
/** @var UnitOfWorkInterface */ |
28
|
|
|
private $unitOfWork; |
29
|
|
|
|
30
|
1 |
|
public function __construct(UnitOfWorkInterface $unitOfWork, MessageBusInterface $messageBus) |
31
|
|
|
{ |
32
|
1 |
|
$this->messageBus = $messageBus; |
33
|
1 |
|
$this->unitOfWork = $unitOfWork; |
34
|
1 |
|
} |
35
|
|
|
|
36
|
1 |
|
public function handle(EnvelopeInterface $envelope): bool |
37
|
|
|
{ |
38
|
1 |
|
$commandMessage = $envelope->getMessage(); |
39
|
1 |
|
$handlerName = (new \ReflectionClass($commandMessage))->getShortName(); |
40
|
1 |
|
$handlerMethod = 'handle'.ucfirst($handlerName); |
41
|
|
|
/** @var callable $handler */ |
42
|
1 |
|
$handler = [ $this, $handlerMethod ]; |
43
|
1 |
|
if (!is_callable($handler)) { |
44
|
|
|
throw new \Exception(sprintf('Handler "%s" is not callable on '.static::class, $handlerMethod)); |
45
|
|
|
} |
46
|
1 |
|
return $this->commit(...call_user_func($handler, $commandMessage, $envelope->getMetadata())); |
|
|
|
|
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
protected function commit(AggregateRootInterface $aggregateRoot, Metadata $metadata): bool |
50
|
|
|
{ |
51
|
1 |
|
$committed = false; |
52
|
1 |
|
foreach ($this->unitOfWork->commit($aggregateRoot, $metadata) as $newCommit) { |
53
|
1 |
|
if ($this->messageBus->publish($newCommit, 'commits') && !$committed) { |
54
|
1 |
|
$committed = true; |
55
|
|
|
} |
56
|
|
|
} |
57
|
1 |
|
return $committed; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
protected function checkout( |
61
|
|
|
AggregateIdInterface $aggregateId, |
62
|
|
|
AggregateRevision $revision |
63
|
|
|
): AggregateRootInterface { |
64
|
|
|
return $this->unitOfWork->checkout($aggregateId, $revision); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
This check looks for function calls that miss required arguments.