Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 15 | abstract class AggregateRoot implements AggregateRootInterface |
||
| 16 | { |
||
| 17 | /** |
||
| 18 | * @var [] |
||
| 19 | */ |
||
| 20 | private $uncommittedEvents = []; |
||
| 21 | |||
| 22 | private $playHead = -1; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @param Event $event |
||
| 26 | */ |
||
| 27 | 18 | public function apply(Event $event) |
|
| 28 | { |
||
| 29 | 18 | $this->handleRecursively($event); |
|
| 30 | |||
| 31 | 18 | $this->playHead++; |
|
| 32 | 18 | $this->uncommittedEvents[] = DomainMessage::recordNow( |
|
| 33 | 18 | $this->getAggregateRootId(), |
|
| 34 | 18 | $this->playHead, |
|
| 35 | 18 | new Metadata(array()), |
|
| 36 | $event |
||
| 37 | ); |
||
| 38 | 18 | } |
|
| 39 | |||
| 40 | |||
| 41 | /** |
||
| 42 | * Handles event if capable. |
||
| 43 | * |
||
| 44 | * @param $event |
||
| 45 | */ |
||
| 46 | 24 | View Code Duplication | protected function handle(Event $event) |
| 54 | |||
| 55 | /** |
||
| 56 | * @param Event $event |
||
| 57 | */ |
||
| 58 | 24 | protected function handleRecursively(Event $event) |
|
| 59 | { |
||
| 60 | 24 | $this->handle($event); |
|
| 61 | |||
| 62 | 24 | foreach ($this->getChildren() as $child) { |
|
| 63 | 6 | $child->registerAggregateRoot($this); |
|
| 64 | 6 | $child->handleRecursively($event); |
|
| 65 | } |
||
| 66 | 24 | } |
|
| 67 | |||
| 68 | /** |
||
| 69 | * @param Event $event |
||
| 70 | * @return string |
||
| 71 | */ |
||
| 72 | 24 | private function getApplyMethod(Event $event) |
|
| 78 | |||
| 79 | /** |
||
| 80 | * @return DomainEventStream |
||
| 81 | */ |
||
| 82 | 15 | public function getUncommittedEvents() |
|
| 90 | |||
| 91 | /** |
||
| 92 | * @param DomainEventStream $stream |
||
| 93 | */ |
||
| 94 | 6 | public function initializeState(DomainEventStream $stream) |
|
| 95 | { |
||
| 96 | 6 | foreach ($stream as $message) { |
|
| 97 | 6 | $this->playHead++; |
|
| 98 | 6 | $this->handleRecursively($message->getPayload()); |
|
| 99 | } |
||
| 100 | 6 | } |
|
| 101 | |||
| 102 | /** |
||
| 103 | * @return EntityInterface[] $entity |
||
| 104 | */ |
||
| 105 | 15 | public function getChildren() |
|
| 109 | } |