Skip to content

Instantly share code, notes, and snippets.

@jenky
Last active August 16, 2016 04:07
Show Gist options
  • Save jenky/ad36b32fd2ecbcd0ce2b238272bd3de9 to your computer and use it in GitHub Desktop.
Save jenky/ad36b32fd2ecbcd0ce2b238272bd3de9 to your computer and use it in GitHub Desktop.
Laravel push notification job based on modified version of https://github.com/davibennun/laravel-push-notification package
<?php
namespace App\Jobs;
use App\Contracts\PushNotification as Pusher;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Sly\NotificationPusher\Collection\DeviceCollection;
use Sly\NotificationPusher\Model\Device;
use Sly\NotificationPusher\Model\Message;
class PushNotification extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
* @var string
*/
protected $type;
/**
* @var mixed
*/
protected $devices;
/**
* @var mixed
*/
protected $message;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($type, $devices, $message)
{
$this->type = $type;
$this->devices = $devices;
$this->message = $message;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Pusher $pushNotification)
{
$pushNotification->make($this->type)
->to($this->getDevices())
->send($this->getMessage());
return $pushNotification;
}
/**
* Get all devices need to send the push notification.
*
* @return mixed
*/
protected function getDevices()
{
if ($this->devices instanceof Device || $this->devices instanceof DeviceCollection) {
return $this->devices;
}
if (is_array($this->devices)) {
$devices = [];
foreach ($this->devices as $key => $value) {
if (is_array($value)) {
$devices[] = new Device($key, $value);
} else {
$devices[] = new Device(strval($value));
}
}
return new DeviceCollection($devices);
}
return strval($this->devices);
}
/**
* Get the push notification message.
*
* @return string|\Sly\NotificationPusher\Model\Message
*/
protected function getMessage()
{
if ($this->message instanceof Message) {
return $this->message;
}
if (is_array($this->message)) {
list($message, $data) = $this->message;
return new Message($message, $data);
}
return strval($this->message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment