Files
boursecu_server/app/Services/PriceBroadcastService.php
T

90 lines
2.5 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
{
2026-06-18 16:12:53 +03:30
private const LAST_HASH_KEY = 'price_broadcast:last_hash';
2026-06-17 12:12:35 +03:30
2026-06-18 16:12:53 +03:30
private const LIST_HASH_KEY = 'price_broadcast:list_hash';
2026-06-17 12:12:35 +03:30
/**
2026-06-18 16:12:53 +03:30
* برادکست SSE — payload کامل last/list وقتی داده عوض شود.
2026-06-18 15:25:49 +03:30
*
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
{
2026-06-18 16:12:53 +03:30
$stream = app(PriceStreamService::class);
if (! $stream->isEnabled()) {
2026-06-18 15:25:49 +03:30
return;
}
2026-06-17 12:12:35 +03:30
if ($lastPayload === null) {
$cache = app(LivePriceCacheService::class);
$lastPayload = $cache->get() ?? $cache->buildFromDatabase();
}
2026-06-18 16:12:53 +03:30
if ($force) {
if (is_array($lastPayload) && $lastPayload !== []) {
$stream->publish('last', $lastPayload);
}
$listPayload = $this->buildProductListPayload();
if ($listPayload !== null) {
$stream->publish('list', $listPayload);
}
return;
}
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);
2026-06-18 16:12:53 +03:30
if ($lastChanged) {
$stream->publish('last', $lastPayload);
}
if ($listChanged) {
$stream->publish('list', $listPayload);
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;
}
}