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 |
||
| 9 | class UpcastedEventStub implements Event |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @var AggregateRootId |
||
| 13 | */ |
||
| 14 | private $aggregateRootId; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * @var PointInTime |
||
| 18 | */ |
||
| 19 | private $timeOfRecording; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var string |
||
| 23 | */ |
||
| 24 | private $property; |
||
| 25 | |||
| 26 | public function __construct(AggregateRootId $aggregateRootId, PointInTime $timeOfRecording, string $property) |
||
| 27 | { |
||
| 28 | $this->aggregateRootId = $aggregateRootId; |
||
| 29 | $this->timeOfRecording = $timeOfRecording; |
||
| 30 | $this->property = $property; |
||
| 31 | } |
||
| 32 | |||
| 33 | public function aggregateRootId(): AggregateRootId |
||
| 34 | { |
||
| 35 | return $this->aggregateRootId; |
||
| 36 | } |
||
| 37 | |||
| 38 | public function eventVersion(): int |
||
| 39 | { |
||
| 40 | return 1; |
||
| 41 | } |
||
| 42 | |||
| 43 | public function timeOfRecording(): PointInTime |
||
| 44 | { |
||
| 45 | return $this->timeOfRecording; |
||
| 46 | } |
||
| 47 | |||
| 48 | public function toPayload(): array |
||
| 49 | { |
||
| 50 | return ['property' => $this->property]; |
||
| 51 | } |
||
| 52 | |||
| 53 | public static function fromPayload(array $payload, AggregateRootId $aggregateRootId, PointInTime $timeOfRecording): Event |
||
| 54 | { |
||
| 55 | return new UpcastedEventStub($aggregateRootId, $timeOfRecording, $payload['property'] ?? 'undefined'); |
||
| 56 | } |
||
| 57 | } |