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 |
||
6 | class WelcomeTemplate extends DataObject |
||
7 | { |
||
8 | private $usercode; |
||
9 | private $botcode; |
||
10 | |||
11 | private $usageCache; |
||
12 | |||
13 | /** |
||
14 | * Summary of getAll |
||
15 | * @param PdoDatabase $database |
||
16 | * @return WelcomeTemplate[] |
||
17 | */ |
||
18 | public static function getAll(PdoDatabase $database = null) |
||
19 | { |
||
20 | if ($database == null) { |
||
21 | $database = gGetDb(); |
||
22 | } |
||
23 | |||
24 | $statement = $database->prepare("SELECT * FROM welcometemplate;"); |
||
25 | |||
26 | $statement->execute(); |
||
27 | |||
28 | $result = array(); |
||
29 | /** @var WelcomeTemplate $v */ |
||
30 | foreach ($statement->fetchAll(PDO::FETCH_CLASS, get_called_class()) as $v) { |
||
31 | $v->isNew = false; |
||
32 | $v->setDatabase($database); |
||
33 | $result[] = $v; |
||
34 | } |
||
35 | |||
36 | return $result; |
||
37 | } |
||
38 | |||
39 | public function save() |
||
40 | { |
||
41 | if ($this->isNew) { |
||
42 | // insert |
||
43 | $statement = $this->dbObject->prepare("INSERT INTO welcometemplate (usercode, botcode) VALUES (:usercode, :botcode);"); |
||
44 | $statement->bindValue(":usercode", $this->usercode); |
||
45 | $statement->bindValue(":botcode", $this->botcode); |
||
46 | |||
47 | if ($statement->execute()) { |
||
48 | $this->isNew = false; |
||
49 | $this->id = $this->dbObject->lastInsertId(); |
||
|
|||
50 | } |
||
51 | else { |
||
52 | throw new Exception($statement->errorInfo()); |
||
53 | } |
||
54 | } |
||
55 | else { |
||
56 | // update |
||
57 | $statement = $this->dbObject->prepare("UPDATE `welcometemplate` SET usercode = :usercode, botcode = :botcode WHERE id = :id;"); |
||
58 | $statement->bindValue(":id", $this->id); |
||
59 | $statement->bindValue(":usercode", $this->usercode); |
||
60 | $statement->bindValue(":botcode", $this->botcode); |
||
61 | |||
62 | if (!$statement->execute()) { |
||
63 | throw new Exception($statement->errorInfo()); |
||
64 | } |
||
65 | } |
||
66 | } |
||
67 | |||
68 | public function getUserCode() |
||
71 | } |
||
72 | |||
73 | public function setUserCode($usercode) |
||
74 | { |
||
75 | $this->usercode = $usercode; |
||
76 | } |
||
77 | |||
78 | public function getBotCode() |
||
79 | { |
||
80 | return $this->botcode; |
||
81 | } |
||
82 | |||
83 | public function setBotCode($botcode) |
||
84 | { |
||
85 | $this->botcode = $botcode; |
||
86 | } |
||
87 | |||
88 | public function getUsersUsingTemplate() |
||
107 | } |
||
108 | |||
109 | public function getObjectDescription() |
||
110 | { |
||
112 | } |
||
113 | } |
||
114 |
This check looks for assignments to scalar types that may be of the wrong type.
To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.