Files
boursecu_server/app/Services/PriceBroadcastService.php
T
2026-06-17 12:12:35 +03:30

82 lines
2.3 KiB
PHP

<?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';
/**
* @param array<string, mixed>|null $lastPayload
*/
public function broadcastAfterPriceUpdate(?array $lastPayload = null): void
{
$ws = app(WebsocketBroadcastService::class);
if (! $ws->isEnabled()) {
return;
}
if ($lastPayload === null) {
$cache = app(LivePriceCacheService::class);
$lastPayload = $cache->get() ?? $cache->buildFromDatabase();
}
if (is_array($lastPayload) && $lastPayload !== []) {
$this->broadcastLastIfChanged($lastPayload);
}
$listPayload = $this->buildProductListPayload();
if ($listPayload !== null) {
$this->broadcastListIfChanged($listPayload);
}
}
/**
* @param array<string, mixed> $payload
*/
public function broadcastLastIfChanged(array $payload): void
{
$hash = md5(json_encode($payload, JSON_UNESCAPED_UNICODE));
if (Cache::get(self::LAST_HASH_KEY) === $hash) {
return;
}
Cache::put(self::LAST_HASH_KEY, $hash, now()->addHour());
app(WebsocketBroadcastService::class)->sendEvent('last', $payload);
}
/**
* @param array<int, mixed> $products
*/
public function broadcastListIfChanged(array $products): void
{
$hash = md5(json_encode($products, JSON_UNESCAPED_UNICODE));
if (Cache::get(self::LIST_HASH_KEY) === $hash) {
return;
}
Cache::put(self::LIST_HASH_KEY, $hash, now()->addHour());
app(WebsocketBroadcastService::class)->sendEvent('list', ['data' => $products]);
}
/**
* @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;
}
}