Files
approagency/app/Jobs/SendPushJob.php
T
2026-06-10 08:30:03 +00:00

79 lines
1.9 KiB
PHP
Executable File

<?php
namespace App\Jobs;
use App\Models\PackageName;
use App\Models\Reminder;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
class SendPushJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public User $user,
public $title,
public PackageName $packageName,
public string $description = '',
public array $data = []
) {}
/**
* Execute the job.
*/
public function handle(): void
{
$firebaseFile = $this->getFirebaseJsonPath();
$factory = (new Factory)
->withServiceAccount($firebaseFile);
$push = $factory->createMessaging();
$relation = $this->user->packageNames()
->where('package_names.id', $this->packageName->id)
->first();
if (!$relation || !$relation->pivot?->fcm_token) {
return; // skip if no token
}
$fcmToken = $relation->pivot->fcm_token;
if (!$fcmToken) {
return;
}
$message = CloudMessage::fromArray([
'token' => $fcmToken,
'notification' => [
'title' => $this->title,
'body' => $this->description,
],
'data' => $this->data
]);
$push->send($message);
}
/**
* Get Firebase JSON file path from Media Library for the package.
*/
private function getFirebaseJsonPath(): ?string
{
$media = $this->packageName->getFirstMedia('firebase_json');
if (!$media) {
return null;
}
return $media->getPath();
}
}