Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Extenders/VariantsCacheInvalidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function onVariantsDelete($output, $ids): void

private function bumpByVariantIds(array $variantIds): void
{
$variantIds = array_values(array_filter(array_map('intval', $variantIds)));
$variantIds = array_values(array_filter(array_map(intval(...), $variantIds)));
if (empty($variantIds)) {
return;
}
Expand Down
6 changes: 3 additions & 3 deletions Helpers/ProductsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public function attachImages(array $products)
if (empty($products) || !$this->redisCache->isEnabled()) {
return parent::attachImages($products);
}
$productIds = array_map('intval', array_keys($products));
$productIds = array_map(intval(...), array_keys($products));
sort($productIds);
if (count($productIds) > 20) {
return parent::attachImages($products);
Expand Down Expand Up @@ -165,7 +165,7 @@ public function attachMainImages(array $products)
if (count($imageIds) > 50 || count($products) > 50) {
return parent::attachMainImages($products);
}
$tags = $this->imageCacheTags(array_map('intval', array_keys($products)));
$tags = $this->imageCacheTags(array_map(intval(...), array_keys($products)));
$key = $this->redisCache->makeVersionedKey('products_attach_main_images', $tags, [$imageIds]);
$cached = $this->redisCache->get($key);

Expand Down Expand Up @@ -253,7 +253,7 @@ private function imageCacheTags(array $productIds): array
// Сортуємо: понад чотири теги вектор версій згортається в md5, тож
// порядок став би значущим і той самий набір товарів під різним
// сортуванням лістингу давав би різні ключі.
$productIds = array_values(array_unique(array_map('intval', $productIds)));
$productIds = array_values(array_unique(array_map(intval(...), $productIds)));
sort($productIds);

$tags = [CacheTags::PRODUCTS_ALL];
Expand Down
2 changes: 1 addition & 1 deletion Init/module.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"Okay": "4.5.3",
"version": "1.0.10",
"version": "1.0.11",
"name": "Redis cache",
"description": "Кешування Redis",
"vendor": {
Expand Down
14 changes: 7 additions & 7 deletions Services/CacheTags.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

final class CacheTags
{
public const PRODUCT_VERSION = 'pver:';
public const PRODUCTS_ALL = 'pall:global';
public const PRODUCTS_LIST = 'plist:global';
public const CATEGORIES = 'cver:global';
public const BRANDS = 'bver:global';
public const AUTHORS_BLOG = 'aver:global';
public const MONEY = 'mver:global';
public const string PRODUCT_VERSION = 'pver:';
public const string PRODUCTS_ALL = 'pall:global';
public const string PRODUCTS_LIST = 'plist:global';
public const string CATEGORIES = 'cver:global';
public const string BRANDS = 'bver:global';
public const string AUTHORS_BLOG = 'aver:global';
public const string MONEY = 'mver:global';

public static function product(int $productId): string
{
Expand Down
40 changes: 19 additions & 21 deletions Services/RedisCacheService.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class RedisCacheService
{
private const VERSION_KEY_PREFIX = 'helpers:ver:';
private const string VERSION_KEY_PREFIX = 'helpers:ver:';

private Settings $settings;
private $client = null;
Expand All @@ -19,29 +19,29 @@ class RedisCacheService
* з TTL, тож запис без нього зробив би кеш невиселюваним — і тиск пішов
* би на лічильники версій, виселення яких «воскрешає» старі дані.
*/
private const MIN_TTL = 60;
private const int MIN_TTL = 60;

/** Понад стільки тегів вектор версій згортається в хеш. */
private const MAX_INLINE_TAGS = 4;
private const int MAX_INLINE_TAGS = 4;

/** Скільки протухле значення ще можна віддавати, поки йде перерахунок. */
private const SWR_GRACE = 3600;
private const int SWR_GRACE = 3600;

/** Замок на перерахунок; переживає час самого перерахунку з запасом. */
private const SWR_LOCK_TTL = 60;
private const int SWR_LOCK_TTL = 60;

/**
* Конверти лежать під власним іменем. Інакше відкат модуля віддав би
* конверт старому коду, який чекає на голе значення, — і це не помилка
* кешу, а TypeError у викликача.
*/
private const SWR_NAME_SUFFIX = ':swr';
private const string SWR_NAME_SUFFIX = ':swr';

/** @var array<string, true> ключі, перерахунок яких уже заплановано в цьому запиті */
private array $refreshing = [];

/** Вікно схлопування повторних bump одного тега, секунди. */
private const BUMP_COLLAPSE_WINDOW = 1.0;
private const float BUMP_COLLAPSE_WINDOW = 1.0;

/**
* Скільки не торкатись Redis після провалу з'єднання.
Expand All @@ -51,16 +51,16 @@ class RedisCacheService
* запитами цю ціну платить кожен запит, тобто сайт формально живий і
* фактично лежить.
*/
private const BREAKER_TTL = 10;
private const int BREAKER_TTL = 10;

/**
* Стеля списку недоставлених bump. Довший простій дешевше й надійніше
* закрити повним скиданням кешу, ніж тягнути список без краю.
*/
private const PENDING_BUMPS_BYTES = 16384;
private const int PENDING_BUMPS_BYTES = 16384;

/** Мітка «лік втрачено»: на відновленні скидаємо кеш цілком. */
private const PENDING_OVERFLOW = '*';
private const string PENDING_OVERFLOW = '*';

private array $helperTtlCache = [];
private array $versionMemo = [];
Expand Down Expand Up @@ -283,7 +283,7 @@ private function authenticateRedis(object $redis, ?string $username, ?string $pa
if (self::$authSupportsTwoArgs) {
return (bool) $redis->auth($user, $passStr);
}
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
// fallthrough
}
if (!method_exists($redis, 'rawCommand')) {
Expand Down Expand Up @@ -326,9 +326,7 @@ protected function connectBare(bool $applyKeyPrefix = true, bool $persistent = f
$redis->setOption($optReadTimeout, 0.5);
}
if (!$this->authenticateRedis($redis, $config['username'], $config['auth'])) {
if ($this->lastError === null) {
$this->lastError = 'Redis auth failed';
}
$this->lastError ??= 'Redis auth failed';
return null;
}
// Безумовно: у persistent-з'єднанні обраний номер БД лишається від
Expand Down Expand Up @@ -381,7 +379,7 @@ public function testConnection(bool $allowWhenDisabled = false): bool
$this->lastError = $e->getMessage();
return false;
} finally {
try { $client->close(); } catch (\Throwable $e) {}
try { $client->close(); } catch (\Throwable) {}
}
}

Expand All @@ -405,7 +403,7 @@ public function flushAll(): bool

return false;
} finally {
try { $client->close(); } catch (\Throwable $e) {}
try { $client->close(); } catch (\Throwable) {}
}
}

Expand Down Expand Up @@ -452,7 +450,7 @@ private function getContext(): array
if ($sl->hasService(\Okay\Core\Languages::class)) {
$langId = (int) $sl->getService(\Okay\Core\Languages::class)->getLangId();
}
} catch (\Throwable $e) {}
} catch (\Throwable) {}

$currencyId = isset($_SESSION['currency_id']) ? (int) $_SESSION['currency_id'] : 0;
$groupId = 0;
Expand All @@ -468,7 +466,7 @@ private function getContext(): array
}
}
}
} catch (\Throwable $e) {}
} catch (\Throwable) {}

$this->context = ['lang' => $langId ?? 0, 'currency' => $currencyId, 'group' => $groupId];
return $this->context;
Expand Down Expand Up @@ -535,7 +533,7 @@ public function version(string $tag): int

public function versions(array $tags): array
{
$tags = array_values(array_unique(array_filter(array_map('strval', $tags))));
$tags = array_values(array_unique(array_filter(array_map(strval(...), $tags))));
if ($tags === []) {
return [];
}
Expand Down Expand Up @@ -746,7 +744,7 @@ protected function now(): float
private function dropClient(): void
{
if ($this->client !== null) {
try { $this->client->close(); } catch (\Throwable $e) {}
try { $this->client->close(); } catch (\Throwable) {}
}
$this->client = null;

Expand Down Expand Up @@ -996,7 +994,7 @@ public function get(string $key)

public function mGet(array $keys): array
{
$keys = array_values(array_filter(array_map('strval', $keys), static fn($k) => $k !== ''));
$keys = array_values(array_filter(array_map(strval(...), $keys), static fn($k) => $k !== ''));
if ($keys === []) {
return [];
}
Expand Down
Loading