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 |
||
11 | class EloquentStoredEventRepository implements StoredEventRepository |
||
12 | { |
||
13 | public function retrieveAll(string $uuid = null, int $startingFrom = null): Collection |
||
29 | |||
30 | public function persist(ShouldBeStored $event, string $uuid = null): StoredEvent |
||
31 | { |
||
32 | $eloquentStoredEvent = new EloquentStoredEvent(); |
||
33 | |||
34 | $eloquentStoredEvent->setRawAttributes([ |
||
35 | 'event_properties' => app(EventSerializer::class)->serialize(clone $event), |
||
36 | 'aggregate_uuid' => $uuid, |
||
37 | 'event_class' => self::getEventClass(get_class($event)), |
||
38 | 'meta_data' => json_encode([]), |
||
39 | 'created_at' => Carbon::now(), |
||
40 | ]); |
||
41 | |||
42 | $eloquentStoredEvent->save(); |
||
43 | |||
44 | return $eloquentStoredEvent->toStoredEvent(); |
||
45 | } |
||
46 | |||
47 | public function persistMany(array $events, string $uuid = null): Collection |
||
48 | { |
||
49 | $storedEvents = []; |
||
50 | |||
51 | foreach ($events as $event) { |
||
52 | $storedEvents[] = self::persist($event, $uuid); |
||
53 | } |
||
54 | |||
55 | return collect($storedEvents); |
||
56 | } |
||
57 | |||
58 | public function update(StoredEvent $storedEvent): StoredEvent |
||
59 | { |
||
60 | /** @var EloquentStoredEvent $storedEvent */ |
||
61 | $eloquentStoredEvent = EloquentStoredEvent::find($storedEvent->id); |
||
62 | |||
63 | $eloquentStoredEvent->update($storedEvent->toArray()); |
||
64 | |||
65 | return $eloquentStoredEvent->toStoredEvent(); |
||
66 | } |
||
67 | |||
68 | View Code Duplication | private function getEventClass(string $class): string |
|
78 | } |
||
79 |
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: