Passed
Push — trunk ( 6aa0cb...9bfd5f )
by SuperNova.WS
04:09
created

_SnCacheInternal::cache_queries_unset_all()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by Gorlum 31.10.2017 2:04
4
 */
5
6
/**
7
 * Class _SnCacheInternal
8
 *
9
 * Внутренний кэшер отдельных записей из БД в память PHP
10
 */
11
class _SnCacheInternal {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
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) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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 />");
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
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() {
75
    _SnCacheInternal::$queries = [];
76
  }
77
78
//  public static function cache_clear_all($hard = true) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
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) {
95
    return isset(_SnCacheInternal::$data[$location_type][$record_id]) && _SnCacheInternal::$data[$location_type][$record_id] !== null;
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) {
0 ignored issues
show
Unused Code introduced by
The parameter $record_id is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

109
  public static function cache_set($location_type, /** @scrutinizer ignore-unused */ $record_id, $record, $force_overwrite = false, $skip_lock = false) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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) {
153
    if (isset(_SnCacheInternal::$locks[$location_type][$record_id])) {
154
      unset(_SnCacheInternal::$locks[$location_type][$record_id]);
155
    }
156
157
    return true; // Не всегда - от результата
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) {
197
    $result = false;
198
    if (_SnCacheInternal::unit_locatorIsArray($location_type, $location_id)) {
199
      foreach (_SnCacheInternal::$locator[LOC_UNIT][$location_type][$location_id] as $key => $value) {
200
        $result[$key] = $value;
201
      }
202
    }
203
204
    return $result;
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) {
215
    $allUnits = _SnCacheInternal::unit_locatorGetAllFromLocation($location_type, $location_id);
216
217
    return isset($allUnits[$unit_snid]) ? $allUnits[$unit_snid] : null;
218
  }
219
}
220