KTVCentral/app/Services/MachineStatusForwarder.php
allen.yan 13b5e3e3e1 BUG 包廂控制畫面開不啟來問題
加入驗証包廂是否在線
20250605
2025-06-05 11:15:24 +08:00

54 lines
1.6 KiB
PHP

<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Client\Response;
use App\Services\ApiClient;
class MachineStatusForwarder
{
protected string $externalUrl;
protected string $endpoint;
protected array $validated;
protected ?User $user = null;
public function __construct(string $externalUrl, string $endpoint, array $validated)
{
$this->externalUrl = $externalUrl;
$this->endpoint = $endpoint;
$this->validated = $validated;
}
public function forward(): ?Response
{
$response = null;
$parsed = parse_url($this->externalUrl);
$hostParts = explode('.', $parsed['host']);
$mainDomain = count($hostParts) >= 3
? implode('.', array_slice($hostParts, 1))
: $parsed['host'];
$mainDomainUrl = "{$parsed['scheme']}://{$mainDomain}";
$this->user = User::find(2); // 或用 dependency injection 把 User 帶進來
if ($this->user && $this->user->api_plain_token) {
$client = new ApiClient($mainDomainUrl, $this->user->api_plain_token);
$response = $client->post($this->endpoint, $this->validated);
Log::info('✅ Machine status forwarded', [
'endpoint' => $this->endpoint,
'request' => $this->validated,
'status' => $response->status(),
'body' => $response->json(),
]);
} else {
Log::warning("🔒 User with ID 2 not found or missing token");
}
return $response;
}
}