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 AntiSpoofCache extends DataObject |
||
| 7 | { |
||
| 8 | protected $username; |
||
| 9 | protected $data; |
||
| 10 | protected $timestamp; |
||
| 11 | |||
| 12 | public static function getByUsername($username, PdoDatabase $database) |
||
| 13 | { |
||
| 14 | $statement = $database->prepare(<<<SQL |
||
| 15 | SELECT * |
||
| 16 | FROM antispoofcache |
||
| 17 | WHERE username = :id AND timestamp > date_sub(now(), interval 3 hour) |
||
| 18 | LIMIT 1 |
||
| 19 | SQL |
||
| 20 | ); |
||
| 21 | $statement->bindValue(":id", $username); |
||
| 22 | |||
| 23 | $statement->execute(); |
||
| 24 | |||
| 25 | $resultObject = $statement->fetchObject(get_called_class()); |
||
| 26 | |||
| 27 | if ($resultObject != false) { |
||
| 28 | $resultObject->isNew = false; |
||
| 29 | $resultObject->setDatabase($database); |
||
| 30 | } |
||
| 31 | |||
| 32 | return $resultObject; |
||
| 33 | } |
||
| 34 | |||
| 35 | public function getUsername() |
||
| 36 | { |
||
| 37 | return $this->username; |
||
| 38 | } |
||
| 39 | |||
| 40 | public function setUsername($username) |
||
| 41 | { |
||
| 42 | $this->username = $username; |
||
| 43 | } |
||
| 44 | |||
| 45 | public function getData() |
||
| 48 | } |
||
| 49 | |||
| 50 | /** |
||
| 51 | * @param string $data |
||
| 52 | */ |
||
| 53 | public function setData($data) |
||
| 56 | } |
||
| 57 | |||
| 58 | public function getTimestamp() |
||
| 59 | { |
||
| 60 | return $this->timestamp; |
||
| 61 | } |
||
| 62 | |||
| 63 | public function save() |
||
| 80 | } |
||
| 81 | } |
||
| 82 | } |
||
| 83 | } |
||
| 84 |
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.