| Total Complexity | 44 |
| Total Lines | 207 |
| Duplicated Lines | 8.21 % |
| Coverage | 0% |
| Changes | 0 | ||
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 _SnCacheInternal 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.
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 _SnCacheInternal, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 11 | class _SnCacheInternal { |
||
|
|
|||
| 12 | public static $data = array(); // Кэш данных - юзера, планеты, юниты, очередь, альянсы итд |
||
| 13 | public static $locks = array(); // Информация о блокировках |
||
| 14 | public static $queries = array(); // Кэш запросов |
||
| 15 | |||
| 16 | // Массив $locator - хранит отношения между записями для быстрого доступа по тип_записи:тип_локации:ид_локации:внутренний_ид_записи=>информация |
||
| 17 | // Для LOC_UNIT внутренний ИД - это SNID, а информация - это ссылка на запись `unit` |
||
| 18 | // Для LOC_QUE внутренний ИД - это тип очереди, а информация - массив ссылок на `que` |
||
| 19 | protected static $locator = array(); // Кэширует соответствия между расположением объектов - в частности юнитов и очередей |
||
| 20 | |||
| 21 | |||
| 22 | View Code Duplication | public static function array_repack(&$array, $level = 0) { |
|
| 23 | // TODO $lock_table не нужна тут |
||
| 24 | if (!is_array($array)) { |
||
| 25 | return; |
||
| 26 | } |
||
| 27 | |||
| 28 | foreach ($array as $key => &$value) { |
||
| 29 | if ($value === null) { |
||
| 30 | unset($array[$key]); |
||
| 31 | } elseif ($level > 0 && is_array($value)) { |
||
| 32 | _SnCacheInternal::array_repack($value, $level - 1); |
||
| 33 | if (empty($value)) { |
||
| 34 | unset($array[$key]); |
||
| 35 | } |
||
| 36 | } |
||
| 37 | } |
||
| 38 | } |
||
| 39 | |||
| 40 | public static function cache_repack($location_type, $record_id = 0) { |
||
| 41 | // Если есть $user_id - проверяем, а надо ли перепаковывать? |
||
| 42 | if ($record_id && isset(_SnCacheInternal::$data[$location_type][$record_id]) && _SnCacheInternal::$data[$location_type][$record_id] !== null) { |
||
| 43 | return; |
||
| 44 | } |
||
| 45 | |||
| 46 | _SnCacheInternal::array_repack(_SnCacheInternal::$data[$location_type]); |
||
| 47 | _SnCacheInternal::array_repack(_SnCacheInternal::$locator[$location_type], 3); // TODO У каждого типа локации - своя глубина!!!! Но можно и глубже ??? |
||
| 48 | _SnCacheInternal::array_repack(_SnCacheInternal::$queries[$location_type], 1); |
||
| 49 | } |
||
| 50 | |||
| 51 | public static function cache_clear($location_type, $hard = true) { |
||
| 52 | //print("<br />CACHE CLEAR {$cache_id} " . ($hard ? 'HARD' : 'SOFT') . "<br />"); |
||
| 53 | if ($hard && !empty(_SnCacheInternal::$data[$location_type])) { |
||
| 54 | // Здесь нельзя делать unset - надо записывать NULL, что бы это отразилось на зависимых записях |
||
| 55 | array_walk(_SnCacheInternal::$data[$location_type], function (&$item) { $item = null; }); |
||
| 56 | } |
||
| 57 | _SnCacheInternal::$locator[$location_type] = []; |
||
| 58 | _SnCacheInternal::$queries[$location_type] = []; |
||
| 59 | _SnCacheInternal::cache_repack($location_type); // Перепаковываем внутренние структуры, если нужно |
||
| 60 | } |
||
| 61 | |||
| 62 | public static function cache_lock_unset_all() { |
||
| 63 | // Когда будем работать с xcache - это понадобиться, что бы снимать в xcache блокировки с записей |
||
| 64 | // Пройти по массиву - снять блокировки для кэшера в памяти |
||
| 65 | _SnCacheInternal::$locks = array(); |
||
| 66 | |||
| 67 | return true; // Не всегда - от результата |
||
| 68 | } |
||
| 69 | |||
| 70 | public static function cache_locator_unset_all() { |
||
| 71 | _SnCacheInternal::$locator = []; |
||
| 72 | } |
||
| 73 | |||
| 74 | public static function cache_queries_unset_all() { |
||
| 76 | } |
||
| 77 | |||
| 78 | // public static function cache_clear_all($hard = true) { |
||
| 79 | // //print('<br />CACHE CLEAR ALL<br />'); |
||
| 80 | // if($hard) { |
||
| 81 | // _SnCacheInternal::$data = array(); |
||
| 82 | // _SnCacheInternal::cache_lock_unset_all(); |
||
| 83 | // } |
||
| 84 | // _SnCacheInternal::$locator = array(); |
||
| 85 | // _SnCacheInternal::$queries = array(); |
||
| 86 | // } |
||
| 87 | |||
| 88 | |||
| 89 | // TODO - this code is currently unused (!) |
||
| 90 | public static function cache_get($location_type, $record_id) { |
||
| 91 | return isset(_SnCacheInternal::$data[$location_type][$record_id]) ? _SnCacheInternal::$data[$location_type][$record_id] : null; |
||
| 92 | } |
||
| 93 | |||
| 94 | public static function cache_isset($location_type, $record_id) { |
||
| 96 | } |
||
| 97 | |||
| 98 | /* Кэшируем запись в соответствующий кэш |
||
| 99 | |||
| 100 | Писать в кэш: |
||
| 101 | 1. Если записи не существует в кэше |
||
| 102 | 2. Если стоит $force_overwrite |
||
| 103 | 3. Если во время транзакции существующая запись не заблокирована |
||
| 104 | |||
| 105 | Блокировать запись: |
||
| 106 | 1. Если идет транзакция и запись не заблокирована |
||
| 107 | 2. Если не стоит скип-лок |
||
| 108 | */ |
||
| 109 | public static function cache_set($location_type, $record_id, $record, $force_overwrite = false, $skip_lock = false) { |
||
| 110 | // нет идентификатора - выход |
||
| 111 | if (!($record_id = $record[classSupernova::$location_info[$location_type][P_ID]])) { |
||
| 112 | return; |
||
| 113 | } |
||
| 114 | |||
| 115 | $in_transaction = classSupernova::db_transaction_check(false); |
||
| 116 | if ( |
||
| 117 | $force_overwrite |
||
| 118 | || |
||
| 119 | // Не заменяются заблокированные записи во время транзакции |
||
| 120 | ($in_transaction && !_SnCacheInternal::cache_lock_get($location_type, $record_id)) |
||
| 121 | || |
||
| 122 | !_SnCacheInternal::cache_isset($location_type, $record_id) |
||
| 123 | ) { |
||
| 124 | _SnCacheInternal::$data[$location_type][$record_id] = $record; |
||
| 125 | if ($in_transaction && !$skip_lock) { |
||
| 126 | _SnCacheInternal::cache_lock_set($location_type, $record_id); |
||
| 127 | } |
||
| 128 | } |
||
| 129 | } |
||
| 130 | |||
| 131 | // TODO - 1 вхождение |
||
| 132 | public static function cache_unset($cache_id, $safe_record_id) { |
||
| 133 | // $record_id должен быть проверен заранее ! |
||
| 134 | if (isset(_SnCacheInternal::$data[$cache_id][$safe_record_id]) && _SnCacheInternal::$data[$cache_id][$safe_record_id] !== null) { |
||
| 135 | // Выставляем запись в null |
||
| 136 | _SnCacheInternal::$data[$cache_id][$safe_record_id] = null; |
||
| 137 | // Очищаем кэш мягко - что бы удалить очистить связанные данные - кэш локаций и кэш запоросов и всё, что потребуется впредь |
||
| 138 | _SnCacheInternal::cache_clear($cache_id, false); |
||
| 139 | } |
||
| 140 | } |
||
| 141 | |||
| 142 | public static function cache_lock_get($location_type, $record_id) { |
||
| 143 | return isset(_SnCacheInternal::$locks[$location_type][$record_id]); |
||
| 144 | } |
||
| 145 | |||
| 146 | // TODO - 1 вхождение |
||
| 147 | public static function cache_lock_set($location_type, $record_id) { |
||
| 148 | return _SnCacheInternal::$locks[$location_type][$record_id] = true; // Не всегда - от результата |
||
| 149 | } |
||
| 150 | |||
| 151 | // TODO - unused |
||
| 152 | public static function cache_lock_unset($location_type, $record_id) { |
||
| 158 | } |
||
| 159 | |||
| 160 | |||
| 161 | /** |
||
| 162 | * @param array $unit |
||
| 163 | * @param int|string $unit_db_id |
||
| 164 | */ |
||
| 165 | public static function unit_linkLocatorToData($unit, $unit_db_id) { |
||
| 166 | _SnCacheInternal::$locator[LOC_UNIT][$unit['unit_location_type']][$unit['unit_location_id']][$unit['unit_snid']] = &_SnCacheInternal::$data[LOC_UNIT][$unit_db_id]; |
||
| 167 | } |
||
| 168 | |||
| 169 | |||
| 170 | /** |
||
| 171 | * @param $location_type |
||
| 172 | * @param $location_id |
||
| 173 | * |
||
| 174 | * @return bool |
||
| 175 | */ |
||
| 176 | public static function unit_locatorIsSet($location_type, $location_id) { |
||
| 177 | return isset(_SnCacheInternal::$locator[LOC_UNIT][$location_type][$location_id]); |
||
| 178 | } |
||
| 179 | |||
| 180 | /** |
||
| 181 | * @param $location_type |
||
| 182 | * @param $location_id |
||
| 183 | * |
||
| 184 | * @return bool |
||
| 185 | */ |
||
| 186 | public static function unit_locatorIsArray($location_type, $location_id) { |
||
| 187 | return is_array(_SnCacheInternal::$locator[LOC_UNIT][$location_type][$location_id]); |
||
| 188 | } |
||
| 189 | |||
| 190 | /** |
||
| 191 | * @param $location_type |
||
| 192 | * @param $location_id |
||
| 193 | * |
||
| 194 | * @return array|false |
||
| 195 | */ |
||
| 196 | public static function unit_locatorGetAllFromLocation($location_type, $location_id) { |
||
| 205 | } |
||
| 206 | |||
| 207 | /** |
||
| 208 | * @param $location_type |
||
| 209 | * @param $location_id |
||
| 210 | * @param $unit_snid |
||
| 211 | * |
||
| 212 | * @return array|null |
||
| 213 | */ |
||
| 214 | public static function unit_locatorGetUnitFromLocation($location_type, $location_id, $unit_snid) { |
||
| 218 | } |
||
| 219 | } |
||
| 220 |
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.