initial commit
[namibia] / module / Utility / src / Utility / Comms / Gcm.php
1 <?php
2 namespace Utility\Comms;
3
4
5 /**
6  * Facilitates chatting to android devices via GCM.
7  * @author andre.fourie
8  */
9 class Gcm
10 {
11
12
13         /**
14          * Send message via GCM.
15          * @param string|array $registrationIds
16          * @param array        $messageData
17          * @param array        $collapse
18          * @return array
19          */
20         static public function send($registrationIds, array $messageData, array $collapse = array())
21         {
22                 //-- Preparation work.
23                 if (!is_array($registrationIds))
24                 {
25                         $registrationIds = array($registrationIds);
26                 }
27                 if (0 == count($registrationIds))
28                 {
29                         return array(
30                                 'Success' => 0,
31                                 'Failed'  => 0
32                         );
33                 }
34
35                 //-- GCM client.
36                 $client = new \ZendService\Google\Gcm\Client();
37                 $client->setApiKey('AIzaSyCrg16ZpPKm0QU2NhhCanH0O-MaxwoO8LU');
38                 $httpClient = new \Zend\Http\Client(null, array(
39                         'adapter'       => 'Zend\Http\Client\Adapter\Socket',
40                         'sslverifypeer' => false
41                 ));
42                 $client->setHttpClient($httpClient);
43
44                 //-- GCM message.
45                 $message = new \ZendService\Google\Gcm\Message();
46                 $message->setRegistrationIds($registrationIds);
47                 $message->setData($messageData);
48                 foreach ($collapse as $collapseKey)
49                 {
50                         $message->setCollapseKey($collapseKey);
51                 }
52                 $message->setRestrictedPackageName('com.nirph.bid4cars');
53                 $message->setDelayWhileIdle(false);
54                 $message->setTimeToLive(600);
55                 $message->setDryRun(false);
56
57                 //-- Send the message.
58                 try
59                 {
60                         $response = $client->send($message);
61                 }
62                 catch (\Exception $e)
63                 {
64                         \Utility\Debug::errorLog(__METHOD__ . ':ERROR', $e->getMessage());
65                         return array(
66                                 'Success' => 0,
67                                 'Failed'  => count($registrationIds)
68                         );
69                 }
70                 return array(
71                         'Success' => $response->getSuccessCount(),
72                         'Failed'  => $response->getFailureCount()
73                 );
74         }
75
76
77 }
78