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; |
12
|
|
|
|
13
|
|
|
use Daikon\EventSourcing\EventStore\CommitInterface; |
14
|
|
|
use Daikon\EventSourcing\EventStore\StreamRevision; |
15
|
|
|
use Daikon\EventSourcing\EventStore\UnitOfWorkInterface; |
16
|
|
|
use Daikon\MessageBus\Channel\Subscription\MessageHandler\MessageHandlerInterface; |
17
|
|
|
use Daikon\MessageBus\EnvelopeInterface; |
18
|
|
|
use Daikon\MessageBus\MessageBusInterface; |
19
|
|
|
use Daikon\MessageBus\Metadata\Metadata; |
20
|
|
|
|
21
|
|
|
abstract class CommandHandler implements MessageHandlerInterface |
22
|
|
|
{ |
23
|
|
|
/** @var MessageBusInterface */ |
24
|
|
|
private $messageBus; |
25
|
|
|
|
26
|
|
|
/** @var UnitOfWorkInterface */ |
27
|
|
|
private $unitOfWork; |
28
|
|
|
|
29
|
2 |
|
public function __construct(UnitOfWorkInterface $unitOfWork, MessageBusInterface $messageBus) |
30
|
|
|
{ |
31
|
2 |
|
$this->messageBus = $messageBus; |
32
|
2 |
|
$this->unitOfWork = $unitOfWork; |
33
|
2 |
|
} |
34
|
|
|
|
35
|
2 |
|
public function handle(EnvelopeInterface $envelope): bool |
36
|
|
|
{ |
37
|
2 |
|
$commandMessage = $envelope->getMessage(); |
38
|
2 |
|
$handlerName = (new \ReflectionClass($commandMessage))->getShortName(); |
39
|
2 |
|
$handlerMethod = "handle".ucfirst($handlerName); |
40
|
2 |
|
$handler = [ $this, $handlerMethod ]; |
41
|
2 |
|
if (!is_callable($handler)) { |
42
|
|
|
throw new \Exception("Handler '$handlerMethod' isn't callable on ".static::class); |
43
|
|
|
} |
44
|
2 |
|
return call_user_func($handler, $commandMessage, $envelope->getMetadata()); |
45
|
|
|
} |
46
|
|
|
|
47
|
2 |
|
protected function commit(AggregateRootInterface $aggregateRoot, Metadata $metadata): bool |
48
|
|
|
{ |
49
|
2 |
|
$committed = false; |
50
|
2 |
|
foreach ($this->unitOfWork->commit($aggregateRoot, $metadata) as $newCommit) { |
51
|
1 |
|
if ($this->messageBus->publish($newCommit, "commits") && !$committed) { |
52
|
1 |
|
$committed = true; |
53
|
|
|
} |
54
|
|
|
} |
55
|
2 |
|
return $committed; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function checkout( |
59
|
|
|
AggregateIdInterface $aggregateId, |
60
|
|
|
AggregateRevision $revision = null |
61
|
|
|
): AggregateRootInterface { |
62
|
|
|
return $this->unitOfWork->checkout($aggregateId, $revision); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.
We recommend to add an additional type check (or disallow null for the parameter):