Files
boursecu_server/app/Services/PriceBroadcastService.php
T

79 lines
2.2 KiB
PHP
Raw Normal View History

2026-06-17 12:12:35 +03:30
<?php
namespace App\Services;
use App\Http\Controllers\Admin\ProductController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class PriceBroadcastService
{
private const LAST_HASH_KEY = 'ws_broadcast:last_hash';
private const LIST_HASH_KEY = 'ws_broadcast:list_hash';
/**
2026-06-18 15:25:49 +03:30
* montzar فقط trigger «price_update» را به کلاینت‌ها relay می‌کند.
*
2026-06-17 12:12:35 +03:30
* @param array<string, mixed>|null $lastPayload
*/
2026-06-18 15:25:49 +03:30
public function broadcastAfterPriceUpdate(?array $lastPayload = null, bool $force = false): void
2026-06-17 12:12:35 +03:30
{
$ws = app(WebsocketBroadcastService::class);
if (! $ws->isEnabled()) {
return;
}
2026-06-18 15:25:49 +03:30
if ($force) {
$ws->sendEvent('price_update', []);
return;
}
2026-06-17 12:12:35 +03:30
if ($lastPayload === null) {
$cache = app(LivePriceCacheService::class);
$lastPayload = $cache->get() ?? $cache->buildFromDatabase();
}
2026-06-18 15:25:49 +03:30
$lastChanged = is_array($lastPayload) && $lastPayload !== []
&& $this->rememberHashIfChanged(self::LAST_HASH_KEY, $lastPayload);
2026-06-17 12:12:35 +03:30
$listPayload = $this->buildProductListPayload();
2026-06-18 15:25:49 +03:30
$listChanged = $listPayload !== null
&& $this->rememberHashIfChanged(self::LIST_HASH_KEY, $listPayload);
if ($lastChanged || $listChanged) {
$ws->sendEvent('price_update', []);
2026-06-17 12:12:35 +03:30
}
}
/**
2026-06-18 15:25:49 +03:30
* @param array<string, mixed>|array<int, mixed> $payload
2026-06-17 12:12:35 +03:30
*/
2026-06-18 15:25:49 +03:30
private function rememberHashIfChanged(string $cacheKey, array $payload): bool
2026-06-17 12:12:35 +03:30
{
$hash = md5(json_encode($payload, JSON_UNESCAPED_UNICODE));
2026-06-18 15:25:49 +03:30
if (Cache::get($cacheKey) === $hash) {
return false;
2026-06-17 12:12:35 +03:30
}
2026-06-18 15:25:49 +03:30
Cache::put($cacheKey, $hash, now()->addHour());
2026-06-17 12:12:35 +03:30
2026-06-18 15:25:49 +03:30
return true;
2026-06-17 12:12:35 +03:30
}
/**
* @return array<int, mixed>|null
*/
private function buildProductListPayload(): ?array
{
$request = Request::create('/customer/product/list', 'GET');
app()->instance('request', $request);
$response = app(ProductController::class)->listProduct();
$decoded = json_decode($response->getContent(), true);
return is_array($decoded) ? $decoded : null;
}
}