resq/src/Service/FCMSender.php

115 lines
2.9 KiB
PHP

<?php
namespace App\Service;
use App\Entity\Customer;
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 customer object
$cust = $job_order->getCustomer();
// attach jo info
$data['jo_id'] = $job_order->getID();
$data['jo_status'] = $job_order->getStatus();
// send the event
return $this->sendEvent($cust, $title, $body, $data);
}
public function sendEvent(Customer $cust, $title, $body, $data = [])
{
// get all v2 devices
$devices = $this->getDevices($cust);
if (empty($devices)) {
return false;
}
// send fcm notification
$result = $this->send(array_keys($devices), $this->translator->trans($title), $this->translator->trans($body), $data);
return $result;
}
protected function getDevices(Customer $cust)
{
$sessions = [];
$device_ids = [];
$cust_user = $cust->getCustomerUser();
if (!empty($cust_user)) {
$sessions = $cust_user->getMobileSessions();
}
if (empty($sessions)) {
error_log("no sessions to send fcm notification to");
return false;
}
// send to every customer session
foreach ($sessions as $sess) {
$device_id = $sess->getDevicePushID();
if (!empty($device_id) && !isset($device_ids[$device_id])) {
// send to this device
$device_ids[$device_id] = true;
}
}
if (empty($device_ids)) {
error_log("no devices to send fcm notification to");
return false;
}
return $device_ids;
}
}