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 |
||
| 5 | class OneTimeIdentity extends Identity |
||
| 6 | { |
||
| 7 | |||
| 8 | const HASH_ALGO = PASSWORD_BCRYPT; |
||
| 9 | const HASH_COST = 12; |
||
| 10 | |||
| 11 | const NONCE_SIZE = 16; |
||
| 12 | const KEY_SIZE = 32; |
||
| 13 | |||
| 14 | private $nonce; |
||
| 15 | private $hash; |
||
| 16 | |||
| 17 | protected $type = Identity::TYPE_ONETIME; |
||
| 18 | |||
| 19 | |||
| 20 | public function setNonce($nonce) |
||
| 24 | |||
| 25 | |||
| 26 | public function getNonce() |
||
| 30 | |||
| 31 | |||
| 32 | public function generateNewNonce() |
||
| 36 | |||
| 37 | |||
| 38 | public function getFingerprint() |
||
| 39 | { |
||
| 40 | return hash('sha384', $this->nonce); |
||
| 41 | } |
||
| 42 | |||
| 43 | |||
| 44 | /** |
||
| 45 | * Sets a new key and resets the hash. |
||
| 46 | */ |
||
| 47 | public function generateNewKey() |
||
| 53 | |||
| 54 | |||
| 55 | private function makeHash($key) |
||
| 61 | |||
| 62 | |||
| 63 | public function matchKey($key) |
||
| 67 | |||
| 68 | |||
| 69 | /** |
||
| 70 | * Assignes a new identification key and resets a the hash. |
||
| 71 | * |
||
| 72 | * @param string $key |
||
| 73 | */ |
||
| 74 | View Code Duplication | public function setKey($key) |
|
| 86 | |||
| 87 | |||
| 88 | public function getKey() |
||
| 92 | |||
| 93 | |||
| 94 | public function setHash($hash) |
||
| 98 | |||
| 99 | /** |
||
| 100 | * @codeCoverageIgnore |
||
| 101 | * @return string |
||
| 102 | */ |
||
| 103 | public function getHash() |
||
| 107 | } |
||
| 108 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: