Files
citrus-cms/app/Jobs/TriggerNaksSyncJob.php
T
2026-04-28 21:14:25 +03:00

103 lines
3.0 KiB
PHP

<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Services\NaksSyncService;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class TriggerNaksSyncJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $payload;
/**
* Create a new job instance.
*
* @param array $payload ['module' => string, 'source_project' => string]
* @return void
*/
public function __construct(array $payload)
{
$this->payload = $payload;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(NaksSyncService $syncService)
{
$logPrefix = "[TriggerNaksSyncJob]";
Log::info("$logPrefix Starting sync trigger propagation", $this->payload);
try {
// Get all project URLs
$projects = $syncService->getProjectUrls();
$currentUrl = config('app.url');
foreach ($projects as $project) {
// Normalize URLs for comparison
$targetUrl = rtrim($project['url'], '/');
$myUrl = rtrim($currentUrl, '/');
// Skip self
if ($this->urlsMatch($targetUrl, $myUrl)) {
continue;
}
$this->triggerProject($targetUrl, $syncService);
}
} catch (\Exception $e) {
Log::error("$logPrefix Failed to propagate trigger: " . $e->getMessage());
}
}
protected function triggerProject($baseUrl, NaksSyncService $syncService)
{
$endpoint = "$baseUrl/api/naks/trigger-sync";
Log::info("[TriggerNaksSyncJob] Sending trigger to: $endpoint");
try {
// We need to authenticate to convert the request
// Or assumes the endpoint is protected by Sanctum and we act as a User.
// Using NaksSyncService's auth logic
$token = $syncService->authenticate($baseUrl);
if (!$token) {
Log::warning("[TriggerNaksSyncJob] Auth failed for $baseUrl");
return;
}
$response = Http::withToken($token)
->timeout(10)
->post($endpoint, $this->payload);
if ($response->successful()) {
Log::info("[TriggerNaksSyncJob] Successfully triggered $baseUrl");
} else {
Log::warning("[TriggerNaksSyncJob] Failed response from $baseUrl: " . $response->status());
}
} catch (\Exception $e) {
Log::error("[TriggerNaksSyncJob] Exception calling $baseUrl: " . $e->getMessage());
}
}
protected function urlsMatch($url1, $url2)
{
$host1 = parse_url($url1, PHP_URL_HOST);
$host2 = parse_url($url2, PHP_URL_HOST);
return $host1 === $host2;
}
}