<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Notification;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Nyholm\Psr7\Factory\Psr17Factory;
use OneSignal\Config;
use OneSignal\OneSignal;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class NotificationSubscriber implements EventSubscriberInterface
{
private $entityManager;
private $config;
private $httpClient;
private $requestFactory;
private $oneSignal;
private $streamFactory;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
$this->config = new Config('26b2a12d-5cb9-4eea-a668-01f7e98ad9c2', 'MjNjZjcwNDItNzkyNC00MjBlLTg4NGMtZWZkNTNjNzkzMDU1');
$this->httpClient = new Psr18Client();
$this->requestFactory = $this->streamFactory = new Psr17Factory();
$this->oneSignal = new OneSignal($this->config, $this->httpClient, $this->requestFactory, $this->streamFactory);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['sendNotification', EventPriorities::PRE_WRITE],
];
}
public function sendNotification(ViewEvent $event): void
{
$notification = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$notification instanceof Notification || Request::METHOD_POST !== $method) {
return;
}
/*hashes_array = array();
$hashes_array[] = array(
"id" => "like-button",
"text" => "Like",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "https://yoursite.com"
);
$hashes_array[] = array(
"id" => "like-button-2",
"text" => "Like2",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "https://yoursite.com"
);*/
if(is_null($notification->getDeliverAt())){
$this->oneSignal->notifications()->add([
'contents' => [
$notification->getLocale() => $notification->getMessage()
],
'subtitle' => [
'en' => $notification->getSubtitle()
],
'included_segments' => ['Subscribed Users'],
'data' => ["target" => $notification->getTarget(),"id" => $notification->getIdobject()]
]);
} else {
$this->oneSignal->notifications()->add([
'contents' => [
$notification->getLocale() => $notification->getMessage()
],
'subtitle' => [
'en' => $notification->getSubtitle()
],
'included_segments' => ['Subscribed Users'],
'data' => ["target" => $notification->getTarget(),"id" => $notification->getIdobject()],
'send_after' => new \DateTimeImmutable($notification->getDeliverAt())
]);
}
}
}