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:
Complex classes like SnDbCachedOperator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SnDbCachedOperator, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
6 | class SnDbCachedOperator { |
||
7 | // Кэш индексов - ключ MD5-строка от суммы ключевых строк через | - менять | на что-то другое перед поиском и назад - после поиска |
||
8 | // Так же в индексах могут быть двойные вхождения - например, названия планет да и вообще |
||
9 | // Придумать спецсимвол для NULL |
||
10 | |||
11 | /* |
||
12 | TODO Кэш: |
||
13 | 1. Всегда дешевле использовать процессор, чем локальную память |
||
14 | 2. Всегда дешевле использовать локальную память, чем общую память всех процессов |
||
15 | 3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД |
||
16 | |||
17 | Кэш - многоуровневый: локальная память-общая память-БД |
||
18 | БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД |
||
19 | Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память |
||
20 | */ |
||
21 | |||
22 | // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице |
||
23 | public static $location_info = array( |
||
24 | LOC_USER => array( |
||
25 | P_TABLE_NAME => 'users', |
||
26 | P_ID => 'id', |
||
27 | P_OWNER_INFO => array(), |
||
28 | ), |
||
29 | |||
30 | LOC_PLANET => array( |
||
31 | P_TABLE_NAME => 'planets', |
||
32 | P_ID => 'id', |
||
33 | P_OWNER_INFO => array( |
||
34 | LOC_USER => array( |
||
35 | P_LOCATION => LOC_USER, |
||
36 | P_OWNER_FIELD => 'id_owner', |
||
37 | ), |
||
38 | ), |
||
39 | ), |
||
40 | |||
41 | LOC_UNIT => array( |
||
42 | P_TABLE_NAME => 'unit', |
||
43 | P_ID => 'unit_id', |
||
44 | P_OWNER_INFO => array( |
||
45 | LOC_USER => array( |
||
46 | P_LOCATION => LOC_USER, |
||
47 | P_OWNER_FIELD => 'unit_player_id', |
||
48 | ), |
||
49 | ), |
||
50 | ), |
||
51 | |||
52 | LOC_QUE => array( |
||
53 | P_TABLE_NAME => 'que', |
||
54 | P_ID => 'que_id', |
||
55 | P_OWNER_INFO => array( |
||
56 | array( |
||
57 | P_LOCATION => LOC_USER, |
||
58 | P_OWNER_FIELD => 'que_player_id', |
||
59 | ), |
||
60 | |||
61 | array( |
||
62 | P_LOCATION => LOC_PLANET, |
||
63 | P_OWNER_FIELD => 'que_planet_id_origin', |
||
64 | ), |
||
65 | |||
66 | array( |
||
67 | P_LOCATION => LOC_PLANET, |
||
68 | P_OWNER_FIELD => 'que_planet_id', |
||
69 | ), |
||
70 | ), |
||
71 | ), |
||
72 | |||
73 | LOC_FLEET => array( |
||
74 | P_TABLE_NAME => 'fleets', |
||
75 | P_ID => 'fleet_id', |
||
76 | P_OWNER_INFO => array( |
||
77 | array( |
||
78 | P_LOCATION => LOC_USER, |
||
79 | P_OWNER_FIELD => 'fleet_owner', |
||
80 | ), |
||
81 | |||
82 | array( |
||
83 | P_LOCATION => LOC_USER, |
||
84 | P_OWNER_FIELD => 'fleet_target_owner', |
||
85 | ), |
||
86 | |||
87 | array( |
||
88 | P_LOCATION => LOC_PLANET, |
||
89 | P_OWNER_FIELD => 'fleet_start_planet_id', |
||
90 | ), |
||
91 | |||
92 | array( |
||
93 | P_LOCATION => LOC_PLANET, |
||
94 | P_OWNER_FIELD => 'fleet_end_planet_id', |
||
95 | ), |
||
96 | ), |
||
97 | ), |
||
98 | ); |
||
99 | |||
100 | /** |
||
101 | * @var db_mysql $db |
||
102 | */ |
||
103 | protected $db; |
||
104 | |||
105 | /** |
||
106 | * @var \SnCache $snCache |
||
107 | */ |
||
108 | protected $snCache; |
||
109 | |||
110 | /** |
||
111 | * SnDbCachedOperator constructor. |
||
112 | * |
||
113 | * @param \Common\GlobalContainer $gc |
||
114 | */ |
||
115 | public function __construct($gc) { |
||
119 | |||
120 | public function db_del_record_by_id($location_type, $safe_record_id) { |
||
138 | |||
139 | /** |
||
140 | * @param int $location_type |
||
141 | * @param array $condition |
||
142 | * |
||
143 | * @return array|bool|mysqli_result|null |
||
144 | */ |
||
145 | public function db_del_record_list($location_type, $condition) { |
||
146 | if (!is_array($condition) || empty($condition)) { |
||
147 | return false; |
||
148 | } |
||
149 | |||
150 | $table_name = static::$location_info[$location_type][P_TABLE_NAME]; |
||
151 | |||
152 | if ($result = $this->db->doDeleteWhere($table_name, $condition)) { |
||
153 | // Обновляем данные только если ряд был затронут |
||
154 | if ($this->db->db_affected_rows()) { |
||
155 | // Обнуление кэша, потому что непонятно, что поменялось |
||
156 | // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям |
||
157 | $this->snCache->cache_clear($location_type); |
||
158 | } |
||
159 | } |
||
160 | |||
161 | return $result; |
||
162 | } |
||
163 | |||
164 | /** |
||
165 | * Возвращает информацию о записи по её ID |
||
166 | * |
||
167 | * @param int $location_type |
||
168 | * @param int|array $record_id_unsafe |
||
169 | * <p>int - ID записи</p> |
||
170 | * <p>array - запись пользователя с установленным полем P_ID</p> |
||
171 | * @param bool $for_update @deprecated |
||
172 | * @param string $fields @deprecated список полей или '*'/'' для всех полей |
||
173 | * @param bool $skip_lock Указывает на то, что не нужно блокировать запись //TODO и не нужно сохранять в кэше |
||
174 | * |
||
175 | * @return array|false |
||
176 | * <p>false - Нет записи с указанным ID</p> |
||
177 | * <p>array - запись</p> |
||
178 | */ |
||
179 | public function db_get_record_by_id($location_type, $record_id_unsafe, $for_update = false, $fields = '*', $skip_lock = false) { |
||
185 | |||
186 | /** |
||
187 | * @param $location_type |
||
188 | * @param string|array $filter |
||
189 | * @param bool $fetch |
||
190 | * @param bool $no_return |
||
191 | * |
||
192 | * @return bool|mixed |
||
193 | */ |
||
194 | // TODO - Change $filter to only array class |
||
195 | public function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) { |
||
307 | |||
308 | /** |
||
309 | * @param int $location_type |
||
310 | * @param int $record_id |
||
311 | * @param array $set - SQL SET structure |
||
312 | * @param array $adjust - SQL ADJUST structure |
||
313 | * |
||
314 | * @return array|bool|mysqli_result|null |
||
315 | */ |
||
316 | public function db_upd_record_by_id($location_type, $record_id, $set, $adjust) { |
||
349 | |||
350 | |||
351 | /** |
||
352 | * @param int $location_type |
||
353 | * @param array $set |
||
354 | * @param array $adjust |
||
355 | * |
||
356 | * @param array $where |
||
357 | * |
||
358 | * @return array|bool|mysqli_result|null |
||
359 | */ |
||
360 | public function db_upd_record_list($location_type, $set, $adjust, $where, $whereDanger = array()) { |
||
384 | |||
385 | /** |
||
386 | * This calls is DANGER 'cause $condition contains direct variable injections and should be rewrote |
||
387 | * |
||
388 | * This call just a proxy to easier to locate code for rewrite |
||
389 | * |
||
390 | * @param int $location_type |
||
391 | * @param array $set |
||
392 | * @param array $adjust |
||
393 | * @param array $where |
||
394 | * @param array $whereDanger |
||
395 | * |
||
396 | * @return array|bool|mysqli_result|null |
||
397 | * @deprecated |
||
398 | */ |
||
399 | public function db_upd_record_list_DANGER($location_type, $set, $adjust, $where, $whereDanger) { |
||
402 | |||
403 | |||
404 | /** |
||
405 | * @param int $location_type |
||
406 | * @param array $set |
||
407 | * |
||
408 | * @return array|bool|false|mysqli_result|null |
||
409 | */ |
||
410 | View Code Duplication | public function db_ins_record($location_type, $set) { |
|
427 | |||
428 | |||
429 | View Code Duplication | public function db_ins_field_set($location_type, $field_set) { |
|
446 | |||
447 | |||
448 | /** |
||
449 | * Блокирует указанные таблицу/список таблиц |
||
450 | * |
||
451 | * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов |
||
452 | * <p>string - название таблицы для блокировки</p> |
||
453 | * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p> |
||
454 | */ |
||
455 | public function db_lock_tables($tables) { |
||
461 | } |
||
462 |
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.