Skip to content

Instantly share code, notes, and snippets.

@ChristopherDosin
Created May 8, 2016 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChristopherDosin/7ebed345d4bfd5accbe6a8a9be3eb32e to your computer and use it in GitHub Desktop.
Save ChristopherDosin/7ebed345d4bfd5accbe6a8a9be3eb32e to your computer and use it in GitHub Desktop.
PHP - WebPush Manager
<?php
namespace GSS\Component\Push;
use Symfony\Component\DependencyInjection\Container;
class Manager
{
const GCM_URL = 'https://android.googleapis.com/gcm/send/';
const MOZ_URL = 'https://updates.push.services.mozilla.com/push/v1/';
private $db;
private $key;
public function __construct(Container $container)
{
$this->db = $container->get('database');
$this->key = $container->getParameter('gcm.key');
}
public function sendMessage($userId, $title, $message)
{
$services = [
'gcm' => [],
'moz' => []
];
$ids = $this->db->fetchCol('SELECT gcm FROM users_to_gcm WHERE userID = ?', [$userId]);
if (empty($ids)) {
return false;
}
$this->db->query('UPDATE users SET GCMMessage = ? WHERE id = ?', [
json_encode(['title' => $title, 'message' => $message]),
$userId
]);
/**
* Splitt Services
*/
foreach ($ids as $id) {
if (strstr($id, self::GCM_URL)) {
if (empty($services['gcm'][0])) {
$services['gcm'][0]['headers'] = [
'Authorization: key=' . $this->key,
'Content-Type: application/json'
];
$services['gcm'][0]['body'] = [];
$services['gcm'][0]['method'] = 'POST';
}
$services['gcm'][0]['body']['registration_ids'][] = str_replace(self::GCM_URL, '', $id);
$services['gcm'][0]['url'] = substr(self::GCM_URL, 0, -1);
} else {
$services['moz'][] = [
'headers' => [],
'body' => [],
'method' => 'PUT',
'url' => $id
];
}
}
/**
* Process WebPushes
*/
foreach ($services as $service) {
foreach ($service as $request) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request['url']);
if ($request['method'] == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request['body']));
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request['method']);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $request['headers']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment