resq/src/Service/FCMSender.php
2023-07-19 16:14:49 +08:00

94 lines
2.4 KiB
PHP

<?php
namespace App\Service;
use Symfony\Contracts\Translation\TranslatorInterface;
use Fcm\FcmClient;
use Fcm\Push\Notification;
use App\Entity\JobOrder;
class FCMSender
{
protected $client;
protected $translator;
public function __construct(TranslatorInterface $translator, $server_key, $sender_id)
{
$this->client = new FcmClient($server_key, $sender_id);
$this->translator = $translator;
}
public function send($recipients, $title, $body, $data = [], $color = null, $sound = null, $badge = null)
{
$notification = new Notification();
$notification->setTitle($title)
->setBody($body);
foreach ($recipients as $recipient) {
$notification->addRecipient($recipient);
}
if (!empty($color)) {
$notification->setColor($color);
}
if (!empty($sound)) {
$notification->setSound($sound);
}
if (!empty($color)) {
$notification->setColor($color);
}
if (!empty($badge)) {
$notification->setBadge($badge);
}
if (!empty($data)) {
$notification->addDataArray($data);
}
return $this->client->send($notification);
}
public function sendJoEvent(JobOrder $job_order, $title, $body, $data = [])
{
// get all v2 sessions
$sessions = [];
$cust_user = $job_order->getCustomer()->getCustomerUser();
if (!empty($cust_user)) {
$sessions = $cust_user->getMobileSessions();
}
if (empty($sessions)) {
error_log("no sessions to send fcm notification to");
return;
}
$device_ids = [];
// send to every customer session
foreach ($sessions as $sess) {
$device_id = $sess->getDevicePushID();
if (!empty($device_id) && !isset($device_ids[$device_id])) {
// send fcm notification
$device_ids[$device_id] = true;
}
}
if (empty($device_ids)) {
error_log("no devices to send fcm notification to");
return;
}
// attach jo info
$data['jo_id'] = $job_order->getID();
$data['jo_status'] = $job_order->getStatus();
// send fcm notification
$result = $this->send(array_keys($device_ids), $this->translator->trans($title), $this->translator->trans($body), $data);
return $result;
}
}