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 UserIdentifiers |
||
6 | { |
||
7 | /* @var string */ |
||
8 | protected $id; |
||
9 | |||
10 | /* @var \stdClass */ |
||
11 | protected $data; |
||
12 | |||
13 | /** |
||
14 | * UserIdentifiers constructor. |
||
15 | * |
||
16 | * @param \stdClass $data |
||
17 | */ |
||
18 | public function __construct($id, $data = null) |
||
23 | |||
24 | /** |
||
25 | * Get a flat array of all the user IDs. |
||
26 | * |
||
27 | * @param string $status (Default: 'ACTIVE'). |
||
28 | * |
||
29 | * @return string[] |
||
30 | */ |
||
31 | View Code Duplication | public function all($status='ACTIVE') |
|
42 | |||
43 | /** |
||
44 | * Get all active user identifiers of a given type, like 'BARCODE' or 'UNIV_ID'. |
||
45 | * |
||
46 | * @param string $value |
||
47 | * |
||
48 | * @return null|string |
||
49 | */ |
||
50 | View Code Duplication | public function allOfType($value, $status = 'ACTIVE') |
|
60 | |||
61 | /** |
||
62 | * Get the first active user identifier of a given type, like 'BARCODE' or 'UNIV_ID'. |
||
63 | * |
||
64 | * @param string $value |
||
65 | * |
||
66 | * @return null|string |
||
67 | */ |
||
68 | public function firstOfType($value, $status = 'ACTIVE') |
||
76 | |||
77 | /** |
||
78 | * Get the first active barcode. |
||
79 | * |
||
80 | * @return null|string |
||
81 | */ |
||
82 | public function getBarcode() |
||
86 | |||
87 | /** |
||
88 | * Get all active barcodes. |
||
89 | * |
||
90 | * @return string[] |
||
91 | */ |
||
92 | public function getBarcodes() |
||
96 | |||
97 | /** |
||
98 | * Get the first active university id. |
||
99 | * |
||
100 | * @return null|string |
||
101 | */ |
||
102 | public function getUniversityId() |
||
106 | |||
107 | /** |
||
108 | * Get all active university ids. |
||
109 | * |
||
110 | * @return string[] |
||
111 | */ |
||
112 | public function getUniversityIds() |
||
116 | |||
117 | public function __get($key) |
||
124 | } |
||
125 |
Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.
For example, imagine you have a variable
$accountId
that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to theid
property of an instance of theAccount
class. This class holds a proper account, so the id value must no longer be false.Either this assignment is in error or a type check should be added for that assignment.