Skip to content

Commit 1e90495

Browse files
author
Karel Wintersky
committed
0.99.0
- [R] PHP 8.* compatible release - добавлен хэлпер-метод `addRules()` - типизация - required `"psr/log": "^1 | ^2 | ^3"`
1 parent 859ad3b commit 1e90495

File tree

4 files changed

+80
-57
lines changed

4 files changed

+80
-57
lines changed

composer.json

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,16 @@
1515
}
1616
],
1717
"require": {
18-
"php": ">=7.4.0",
18+
"php": "^7.4 | 8.*",
1919
"ext-pdo": "*",
2020
"ext-json": "*",
21+
"ext-mbstring": "*",
2122
"ext-redis": "*",
22-
"psr/log": "^1.1",
23-
"ext-mbstring": "*"
23+
"psr/log": "^1 | ^2 | ^3"
2424
},
2525
"require-dev": {
26-
"karelwintersky/arris": "^1.63.0",
27-
"karelwintersky/arris.helpers": "^0.4.0",
26+
"karelwintersky/arris": "^2",
27+
"karelwintersky/arris.helpers": "^0",
2828
"vlucas/phpdotenv": "^3.3"
2929
}
3030
}

src/Cache.php

Lines changed: 64 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -20,43 +20,43 @@ class Cache implements CacheInterface
2020
/**
2121
* @var RedisClient $redis_connector
2222
*/
23-
private static $redis_connector;
23+
private static RedisClient $redis_connector;
2424

2525
/**
2626
* @var bool $is_redis_connected
2727
*/
28-
public static $is_redis_connected = false;
28+
public static bool $is_redis_connected = false;
2929

3030
/**
3131
* @var LoggerInterface|null $logger
3232
*/
33-
private static $logger;
33+
private static ?LoggerInterface $logger;
3434

3535
/**
36-
* @var PDO|null $pdo
36+
* НЕ задаем тип, поскольку может прийти как PDO, так и DBWrapper
37+
* Тем более что UNION Types возможны с PHP 8.1+
38+
*
39+
* @var $pdo
3740
*/
3841
private static $pdo;
3942

40-
/**
41-
* @var
42-
*/
43-
public static $log_rules_define = [];
44-
4543
/**
4644
* @var array
4745
*/
46+
public static array $log_rules_define = [];
47+
4848
/*private static $connection_options = [];*/
4949

5050
/*private static $connectors = [];*/
5151

5252
/**
5353
* @var array
5454
*/
55-
public static $repository = [];
55+
public static array $repository = [];
5656

57-
public static function init(array $credentials = [], array $rules = [], $PDO = null, LoggerInterface $logger = null)
57+
public static function init(array $credentials = [], array $rules = [], $PDO = null, ?LoggerInterface $logger = null)
5858
{
59-
self::$logger = is_null($logger) ? new NullLogger() : $logger;
59+
self::$logger = \is_null($logger) ? new NullLogger() : $logger;
6060
self::$is_redis_connected = false;
6161
self::$pdo = $PDO;
6262

@@ -81,7 +81,7 @@ public static function init(array $credentials = [], array $rules = [], $PDO = n
8181
}
8282
}
8383

84-
if (!is_null($PDO)) {
84+
if (!\is_null($PDO)) {
8585
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
8686
}
8787

@@ -97,7 +97,7 @@ public static function init(array $credentials = [], array $rules = [], $PDO = n
9797

9898
} // init
9999

100-
public static function getConnector()
100+
public static function getConnector(): RedisClient
101101
{
102102
return self::$redis_connector;
103103
}
@@ -116,6 +116,13 @@ public static function getConnector()
116116
return $connector;
117117
}*/
118118

119+
public static function addRules(array $rules)
120+
{
121+
foreach ($rules as $name => $rule) {
122+
self::addRule($name, $rule);
123+
}
124+
}
125+
119126
public static function addRule(string $rule_name, $rule_definition):string
120127
{
121128
$message = self::defineRule($rule_name, $rule_definition);
@@ -129,7 +136,7 @@ public static function addRule(string $rule_name, $rule_definition):string
129136

130137
public static function getAllLocalKeys():array
131138
{
132-
return array_keys(self::$repository);
139+
return \array_keys(self::$repository);
133140
}
134141

135142
public static function getAllRedisKeys():array
@@ -140,7 +147,7 @@ public static function getAllRedisKeys():array
140147
}
141148

142149
$keys = self::$redis_connector->keys('*');
143-
$keys_count = count($keys);
150+
$keys_count = \count($keys);
144151

145152
self::$logger->debug("[getAllRedisKeys] Returned {$keys_count} key(s)");
146153

@@ -154,8 +161,12 @@ public static function getAllKeys(bool $use_keys_from_redis):array
154161
return [];
155162
}
156163

157-
$keys = $use_keys_from_redis ? self::$redis_connector->keys('*') : array_keys(self::$repository);
158-
$keys_count = count($keys);
164+
$keys
165+
= $use_keys_from_redis
166+
? self::$redis_connector->keys('*')
167+
: \array_keys(self::$repository);
168+
169+
$keys_count = \count($keys);
159170

160171
self::$logger->debug("[getAllKeys] Returned {$keys_count} key(s)");
161172

@@ -179,13 +190,13 @@ public static function set(string $key, $data)
179190

180191
public static function check(string $key): bool
181192
{
182-
return array_key_exists($key, self::$repository);
193+
return \array_key_exists($key, self::$repository);
183194
}
184195

185196
public static function unset(string $key)
186197
{
187198
if (self::check($key)) {
188-
unset( self::$repository[$key]);
199+
unset(self::$repository[$key]);
189200
}
190201
}
191202

@@ -198,7 +209,7 @@ public static function flushAll(string $mask = '*')
198209

199210
public static function flush(string $key, bool $clean_redis = true):string
200211
{
201-
if (strpos($key, '*') === false) {
212+
if (\strpos($key, '*') === false) {
202213
self::unset($key);
203214
if (self::$redis_connector && $clean_redis) {
204215
self::$redis_connector->del($key);
@@ -207,7 +218,7 @@ public static function flush(string $key, bool $clean_redis = true):string
207218
} else {
208219
$custom_mask = self::createMask($key);
209220
$all_keys = $clean_redis ? self::getAllRedisKeys() : self::getAllLocalKeys();
210-
$custom_list = preg_grep($custom_mask, $all_keys);
221+
$custom_list = \preg_grep($custom_mask, $all_keys);
211222
foreach ($custom_list as $k) {
212223
self::flush($k, $clean_redis);
213224
}
@@ -224,7 +235,7 @@ public static function redisFetch(string $key_name, bool $use_json_decode = true
224235
$value = self::$redis_connector->get($key_name);
225236

226237
if ($use_json_decode && !empty($value)) {
227-
$value = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
238+
$value = \json_decode($value, true, 512, JSON_THROW_ON_ERROR);
228239
}
229240

230241
return $value;
@@ -260,12 +271,12 @@ public static function redisDel(string $key_name)
260271
if ($key_name === '*') {
261272
self::$redis_connector->flushDb();
262273
$deleted = [ '*' ];
263-
} elseif (strpos($key_name, '*') === false) {
274+
} elseif (\strpos($key_name, '*') === false) {
264275
self::$redis_connector->del($key_name);
265276
$deleted = [ $key_name ];
266277
} else {
267278
$custom_mask = self::createMask($key_name);
268-
$custom_list = preg_grep($custom_mask, self::$redis_connector->keys('*'));
279+
$custom_list = \preg_grep($custom_mask, self::$redis_connector->keys('*'));
269280

270281
foreach ($custom_list as $k) {
271282
$deleted[] = self::redisDel($k);
@@ -311,7 +322,7 @@ public static function addCounter(string $key, int $initial = 0, int $ttl = 0):i
311322

312323
public static function incrCounter(string $key, int $diff = 1):int
313324
{
314-
if (!array_key_exists($key, self::$repository)) {
325+
if (!\array_key_exists($key, self::$repository)) {
315326
self::set($key, 0);
316327
}
317328

@@ -325,7 +336,7 @@ public static function incrCounter(string $key, int $diff = 1):int
325336

326337
public static function decrCounter(string $key, int $diff = 1):int
327338
{
328-
if (!array_key_exists($key, self::$repository)) {
339+
if (!\array_key_exists($key, self::$repository)) {
329340
self::set($key, 0);
330341
}
331342

@@ -370,15 +381,15 @@ private static function defineRule($rule_name, $rule_definition)
370381
$rule_value = self::$redis_connector->get($rule_name);
371382

372383
if ($rule_value !== false) {
373-
self::set($rule_name, json_decode($rule_value, true, 512, JSON_THROW_ON_ERROR));
384+
self::set($rule_name, \json_decode($rule_value, true, 512, JSON_THROW_ON_ERROR));
374385
return "[INFO] Loaded `{$rule_name}` from redis, stored to cache";
375386
}
376387
}
377388

378389
// определяем action и TTL
379-
$enabled = array_key_exists('enabled', $rule_definition) ? $rule_definition['enabled'] : true;
380-
$ttl = array_key_exists('ttl', $rule_definition) ? $rule_definition['ttl'] : 0;
381-
$action = array_key_exists('action', $rule_definition) ? $rule_definition['action'] : null; // оператор `??` менее нагляден, поэтому оставлено так
390+
$enabled = \array_key_exists('enabled', $rule_definition) ? $rule_definition['enabled'] : true;
391+
$ttl = \array_key_exists('ttl', $rule_definition) ? $rule_definition['ttl'] : 0;
392+
$action = \array_key_exists('action', $rule_definition) ? $rule_definition['action'] : null; // оператор `??` менее нагляден, поэтому оставлено так
382393

383394
if ($enabled === false) {
384395
return "Rule `{$rule_name}` disabled";
@@ -395,7 +406,7 @@ private static function defineRule($rule_name, $rule_definition)
395406

396407
case self::RULE_SOURCE_SQL: {
397408
// коннекта к БД нет: кладем в репозиторий null и продолжаем
398-
if (is_null(self::$pdo)) {
409+
if (\is_null(self::$pdo)) {
399410
$message = '[ERROR] Key not found, Action is SQL, but PDO not connected';
400411
self::set($rule_name, null);
401412
return $message;
@@ -424,7 +435,7 @@ private static function defineRule($rule_name, $rule_definition)
424435
[$actor, $params] = self::compileCallbackHandler($rule_definition['action']);
425436

426437
try {
427-
$data = call_user_func_array($actor, $params);
438+
$data = \call_user_func_array($actor, $params);
428439
$message = "Data for `{$rule_name}` fetched from callback";
429440

430441
} catch (\PDOException $e) {
@@ -458,7 +469,7 @@ public static function isRedisConnected():bool
458469

459470
/**
460471
* "Компилирует" параметры коллбэка
461-
* (@todo: обновить в Arris\Router)
472+
* (@todo: обновить в Arris\Router ?)
462473
*
463474
* @param $actor
464475
* @return array
@@ -480,36 +491,39 @@ private static function compileCallbackHandler($actor)
480491
// 1 - массив параметров
481492
if (is_array($actor)) {
482493
$handler = $actor[0];
483-
$params = (count($actor) > 1) ? $actor[1] : [];
494+
$params
495+
= \count($actor) > 1
496+
? $actor[1]
497+
: [];
484498

485-
if (!is_string($handler)) {
499+
if (!\is_string($handler)) {
486500
throw new CacheCallbackException("First argument of callback array is NOT a string");
487501
}
488502

489-
if (strpos($handler, '@') > 0) {
503+
if (\strpos($handler, '@') > 0) {
490504
// dynamic class
491-
[$class, $method] = explode('@', $handler, 2);
505+
[$class, $method] = \explode('@', $handler, 2);
492506

493-
if (!class_exists($class)) {
507+
if (!\class_exists($class)) {
494508
self::$logger->error("Class {$class} not defined.", [ $class ]);
495509
throw new CacheCallbackException("Class {$class} not defined.", 500);
496510
}
497511

498-
if (!method_exists($class, $method)) {
512+
if (!\method_exists($class, $method)) {
499513
self::$logger->error("Method {$method} not declared at {$class} class.", [ $class, $method ]);
500514
throw new CacheCallbackException("Method {$method} not declared at {$class} class", 500);
501515
}
502516

503517
$actor = [ new $class, $method ];
504-
} elseif (strpos($handler, '::') > 0) {
518+
} elseif (\strpos($handler, '::') > 0) {
505519
[$class, $method] = explode('::', $handler, 2);
506520

507-
if (!class_exists($class)) {
521+
if (!\class_exists($class)) {
508522
self::$logger->error("Class {$class} not defined.", [ $class ]);
509523
throw new CacheCallbackException("Class {$class} not defined.", 500);
510524
}
511525

512-
if (!method_exists($class, $method)) {
526+
if (!\method_exists($class, $method)) {
513527
self::$logger->error("Static method {$method} not declared at {$class} class.", [ $class, $method ]);
514528
throw new CacheCallbackException("Static method {$method} not declared at {$class} class", 500);
515529
}
@@ -537,13 +551,13 @@ private static function compileCallbackHandler($actor)
537551
*/
538552
private static function createMask($mask)
539553
{
540-
$mask = str_replace('**', '*', $mask);
541-
$mask = str_replace("\\", '\\\\', $mask); // должно быть первым
542-
$mask = str_replace('/', '\/', $mask);
543-
$mask = str_replace('.', '\.', $mask);
544-
$mask = str_replace('*', '.*', $mask);
545-
$mask = str_replace('[', '\[', $mask);
546-
$mask = str_replace(']', '\]', $mask);
554+
$mask = \str_replace('**', '*', $mask);
555+
$mask = \str_replace("\\", '\\\\', $mask); // должно быть первым
556+
$mask = \str_replace('/', '\/', $mask);
557+
$mask = \str_replace('.', '\.', $mask);
558+
$mask = \str_replace('*', '.*', $mask);
559+
$mask = \str_replace('[', '\[', $mask);
560+
$mask = \str_replace(']', '\]', $mask);
547561

548562
return '/^' . $mask . '/m';
549563
}

src/CacheInterface.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,16 @@ interface CacheInterface
3535
* @param LoggerInterface|null $logger
3636
* @throws JsonException
3737
*/
38-
public static function init(array $credentials = [], array $rules = [], $PDO = null, LoggerInterface $logger = null);
38+
public static function init(array $credentials = [], array $rules = [], $PDO = null, ?LoggerInterface $logger = null);
39+
40+
/**
41+
* Добавляет в репозиторий массив правил
42+
*
43+
* @param array $rules
44+
* @return void
45+
* @throws JsonException
46+
*/
47+
public static function addRules(array $rules);
3948

4049
/**
4150
* Добавляет в репозиторий новое ключ-значение (с логгированием)

src/Exceptions/RedisClientException.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ class RedisClientException extends \RuntimeException
99

1010
public function __construct($message, $code = 0, $exception = NULL)
1111
{
12-
if ($exception && $exception instanceof \RedisException && strpos($message,'read error on connection') === 0) {
12+
if ($exception instanceof \RedisException && strpos($message,'read error on connection') === 0) {
1313
$code = self::CODE_DISCONNECTED;
1414
}
1515
parent::__construct($message, $code, $exception);

0 commit comments

Comments
 (0)