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 |
||
| 19 | class AntiSpoofCache extends DataObject |
||
| 20 | { |
||
| 21 | /** @var string */ |
||
| 22 | protected $username; |
||
| 23 | /** @var string */ |
||
| 24 | protected $data; |
||
| 25 | /** @var string */ |
||
| 26 | protected $timestamp; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * @param string $username |
||
| 30 | * @param PdoDatabase $database |
||
| 31 | * |
||
| 32 | * @return AntiSpoofCache|false |
||
| 33 | */ |
||
| 34 | View Code Duplication | public static function getByUsername($username, PdoDatabase $database) |
|
|
|
|||
| 35 | { |
||
| 36 | $statement = $database->prepare(<<<SQL |
||
| 37 | SELECT * |
||
| 38 | FROM antispoofcache |
||
| 39 | WHERE username = :id AND timestamp > date_sub(now(), INTERVAL 3 HOUR) |
||
| 40 | LIMIT 1 |
||
| 41 | SQL |
||
| 42 | ); |
||
| 43 | $statement->bindValue(":id", $username); |
||
| 44 | |||
| 45 | $statement->execute(); |
||
| 46 | |||
| 47 | $resultObject = $statement->fetchObject(get_called_class()); |
||
| 48 | |||
| 49 | if ($resultObject != false) { |
||
| 50 | $resultObject->setDatabase($database); |
||
| 51 | } |
||
| 52 | |||
| 53 | return $resultObject; |
||
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @return string |
||
| 58 | */ |
||
| 59 | public function getUsername() |
||
| 63 | |||
| 64 | /** |
||
| 65 | * @param string $username |
||
| 66 | */ |
||
| 67 | public function setUsername($username) |
||
| 71 | |||
| 72 | /** |
||
| 73 | * @return string |
||
| 74 | */ |
||
| 75 | public function getData() |
||
| 79 | |||
| 80 | /** |
||
| 81 | * @param string $data |
||
| 82 | */ |
||
| 83 | public function setData($data) |
||
| 87 | |||
| 88 | /** |
||
| 89 | * @return DateTimeImmutable |
||
| 90 | */ |
||
| 91 | public function getTimestamp() |
||
| 95 | |||
| 96 | /** |
||
| 97 | * @throws Exception |
||
| 98 | */ |
||
| 99 | View Code Duplication | public function save() |
|
| 118 | } |
||
| 119 |
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.