90 lines
2.5 KiB
PHP
90 lines
2.5 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 = 'price_broadcast:last_hash';
|
|
|
|
private const LIST_HASH_KEY = 'price_broadcast:list_hash';
|
|
|
|
/**
|
|
* برادکست SSE — payload کامل last/list وقتی داده عوض شود.
|
|
*
|
|
* @param array<string, mixed>|null $lastPayload
|
|
*/
|
|
public function broadcastAfterPriceUpdate(?array $lastPayload = null, bool $force = false): void
|
|
{
|
|
$stream = app(PriceStreamService::class);
|
|
if (! $stream->isEnabled()) {
|
|
return;
|
|
}
|
|
|
|
if ($lastPayload === null) {
|
|
$cache = app(LivePriceCacheService::class);
|
|
$lastPayload = $cache->get() ?? $cache->buildFromDatabase();
|
|
}
|
|
|
|
if ($force) {
|
|
if (is_array($lastPayload) && $lastPayload !== []) {
|
|
$stream->publish('last', $lastPayload);
|
|
}
|
|
|
|
$listPayload = $this->buildProductListPayload();
|
|
if ($listPayload !== null) {
|
|
$stream->publish('list', $listPayload);
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
$lastChanged = is_array($lastPayload) && $lastPayload !== []
|
|
&& $this->rememberHashIfChanged(self::LAST_HASH_KEY, $lastPayload);
|
|
|
|
$listPayload = $this->buildProductListPayload();
|
|
$listChanged = $listPayload !== null
|
|
&& $this->rememberHashIfChanged(self::LIST_HASH_KEY, $listPayload);
|
|
|
|
if ($lastChanged) {
|
|
$stream->publish('last', $lastPayload);
|
|
}
|
|
|
|
if ($listChanged) {
|
|
$stream->publish('list', $listPayload);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed>|array<int, mixed> $payload
|
|
*/
|
|
private function rememberHashIfChanged(string $cacheKey, array $payload): bool
|
|
{
|
|
$hash = md5(json_encode($payload, JSON_UNESCAPED_UNICODE));
|
|
if (Cache::get($cacheKey) === $hash) {
|
|
return false;
|
|
}
|
|
|
|
Cache::put($cacheKey, $hash, now()->addHour());
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @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;
|
|
}
|
|
}
|