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 |
||
16 | class ConversationEvent extends AbstractMessage |
||
17 | { |
||
18 | /** |
||
19 | * The event |
||
20 | * @var Event |
||
21 | */ |
||
22 | protected $event; |
||
23 | |||
24 | /** |
||
25 | * {@inheritdoc} |
||
26 | */ |
||
27 | protected function assignResult($event) |
||
28 | { |
||
29 | parent::assignResult($event); |
||
30 | |||
31 | if ($this->type === null) { |
||
32 | throw new Exception("A message cannot be represented by the ConversationEvent class."); |
||
33 | } |
||
34 | |||
35 | $this->event = unserialize($event['message']); |
||
36 | } |
||
37 | |||
38 | /** |
||
39 | * Get the event object |
||
40 | * @return Event |
||
41 | */ |
||
42 | public function getEvent() |
||
46 | |||
47 | /** |
||
48 | * Get the type of the event |
||
49 | * |
||
50 | * Do not use ConversationEvent::getType(), as it returns the name of the class |
||
51 | * (i.e. conversationEvent) |
||
52 | * |
||
53 | * @return int |
||
54 | */ |
||
55 | public function getCategory() |
||
59 | |||
60 | /** |
||
61 | * {@inheritdoc} |
||
62 | */ |
||
63 | public function isMessage() |
||
64 | { |
||
65 | return false; |
||
66 | } |
||
67 | |||
68 | /** |
||
69 | * Store a conversation event in the database |
||
70 | * |
||
71 | * @param int $conversation The ID of the conversation |
||
72 | * @param Event $event The event |
||
73 | * @param string $type The type of the event |
||
74 | * @param mixed $timestamp The timestamp when the event took place |
||
75 | * @param string $status The status of the event, can be 'visible', 'hidden', 'deleted' or 'reported' |
||
76 | * @return ConversationEvent |
||
77 | */ |
||
78 | View Code Duplication | public static function storeEvent($conversation, $event, $type, $timestamp = 'now', $status = 'visible') |
|
|
|||
79 | { |
||
80 | return self::create(array( |
||
81 | "conversation_to" => $conversation, |
||
82 | "message" => serialize($event), |
||
83 | "event_type" => $type, |
||
84 | "timestamp" => TimeDate::from($timestamp)->toMysql(), |
||
85 | "status" => $status |
||
86 | )); |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * Get a query builder for events |
||
91 | * @return QueryBuilder |
||
92 | */ |
||
93 | public static function getQueryBuilder() |
||
97 | } |
||
98 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.