shyim
5/8/2016 - 5:51 PM

PHP - WebPush Manager

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);
            }
        }
    }
}