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 RDnsCache extends DataObject |
||
| 7 | { |
||
| 8 | private $address; |
||
| 9 | private $data; |
||
| 10 | private $creation; |
||
| 11 | |||
| 12 | /** |
||
| 13 | * @param string $address |
||
| 14 | * @param PdoDatabase $database |
||
| 15 | * @return RDnsCache |
||
| 16 | */ |
||
| 17 | public static function getByAddress($address, PdoDatabase $database) |
||
| 18 | { |
||
| 19 | $statement = $database->prepare("SELECT * FROM rdnscache WHERE address = :id LIMIT 1;"); |
||
| 20 | $statement->bindValue(":id", $address); |
||
| 21 | |||
| 22 | $statement->execute(); |
||
| 23 | |||
| 24 | $resultObject = $statement->fetchObject(get_called_class()); |
||
| 25 | |||
| 26 | if ($resultObject != false) { |
||
| 27 | $resultObject->isNew = false; |
||
| 28 | $resultObject->setDatabase($database); |
||
| 29 | } |
||
| 30 | |||
| 31 | return $resultObject; |
||
| 32 | } |
||
| 33 | |||
| 34 | public function save() |
||
| 35 | { |
||
| 36 | if ($this->isNew) { |
||
| 37 | // insert |
||
| 38 | $statement = $this->dbObject->prepare("INSERT INTO `rdnscache` (address, data) VALUES (:address, :data);"); |
||
| 39 | $statement->bindValue(":address", $this->address); |
||
| 40 | $statement->bindValue(":data", $this->data); |
||
| 41 | if ($statement->execute()) { |
||
| 42 | $this->isNew = false; |
||
| 43 | $this->id = $this->dbObject->lastInsertId(); |
||
|
|
|||
| 44 | } |
||
| 45 | else { |
||
| 46 | throw new Exception($statement->errorInfo()); |
||
| 47 | } |
||
| 48 | } |
||
| 49 | else { |
||
| 50 | // update |
||
| 51 | $statement = $this->dbObject->prepare("UPDATE `rdnscache` SET address = :address, data = :data WHERE id = :id;"); |
||
| 52 | $statement->bindValue(":address", $this->address); |
||
| 53 | $statement->bindValue(":id", $this->id); |
||
| 54 | $statement->bindValue(":data", $this->data); |
||
| 55 | |||
| 56 | if (!$statement->execute()) { |
||
| 57 | throw new Exception($statement->errorInfo()); |
||
| 58 | } |
||
| 59 | } |
||
| 60 | } |
||
| 61 | |||
| 62 | public function getAddress() |
||
| 63 | { |
||
| 64 | return $this->address; |
||
| 65 | } |
||
| 66 | |||
| 67 | /** |
||
| 68 | * @param string $address |
||
| 69 | */ |
||
| 70 | public function setAddress($address) |
||
| 73 | } |
||
| 74 | |||
| 75 | public function getData() |
||
| 76 | { |
||
| 77 | return unserialize($this->data); |
||
| 78 | } |
||
| 79 | |||
| 80 | public function setData($data) |
||
| 81 | { |
||
| 82 | $this->data = serialize($data); |
||
| 83 | } |
||
| 84 | |||
| 85 | public function getCreation() |
||
| 88 | } |
||
| 89 | } |
||
| 90 |
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.