chart fixed
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user