Completed
Push — master ( b93c78...0ed572 )
by Julián
02:22
created

GcmService::send()   C

Complexity

Conditions 9
Paths 23

Size

Total Lines 48
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 48
rs 5.5102
cc 9
eloc 30
nc 23
nop 1
1
<?php
2
/**
3
 * Push notification services abstraction (http://github.com/juliangut/tify)
4
 *
5
 * @link https://github.com/juliangut/tify for the canonical source repository
6
 *
7
 * @license https://github.com/juliangut/tify/blob/master/LICENSE
8
 */
9
10
namespace Jgut\Tify\Service;
11
12
use Jgut\Tify\Notification\AbstractNotification;
13
use Jgut\Tify\Notification\GcmNotification as GcmNotification;
14
use Jgut\Tify\Result;
15
use Jgut\Tify\Service\Client\GcmBuilder as ClientBuilder;
16
use Jgut\Tify\Service\Message\GcmBuilder as MessageBuilder;
17
use ZendService\Google\Exception\RuntimeException as ServiceRuntimeException;
18
19
class GcmService extends AbstractService implements SendInterface
20
{
21
    /**
22
     * Status codes translation.
23
     *
24
     * @see https://developers.google.com/cloud-messaging/http-server-ref
25
     *
26
     * @var array
27
     */
28
    private static $statusCodes = [
29
        'MissingRegistration' => 'Missing Registration Token',
30
        'InvalidRegistration' => 'Invalid Registration Token',
31
        'NotRegistered' => 'Unregistered Recipient',
32
        'InvalidPackageName' => 'Invalid Package Name',
33
        'MismatchSenderId' => 'Mismatched Sender',
34
        'MessageTooBig' => 'Message Too Big',
35
        'InvalidDataKey' => 'Invalid Data Key',
36
        'InvalidTtl' => 'Invalid Time to Live',
37
        'Unavailable' => 'Timeout',
38
        'InternalServerError' => 'Internal Server Error',
39
        'RecipientMessageRateExceeded' => 'Recipient Message Rate Exceeded',
40
        'TopicsMessageRateExceeded' => 'Topics Message Rate Exceeded',
41
        'UnknownError' => 'Unknown Error',
42
    ];
43
44
    /**
45
     * @var \ZendService\Google\Gcm\Client
46
     */
47
    protected $pushClient;
48
49
    /**
50
     * {@inheritdoc}
51
     *
52
     * @throws \InvalidArgumentException
53
     */
54
    public function send(AbstractNotification $notification)
55
    {
56
        if (!$notification instanceof GcmNotification) {
57
            throw new \InvalidArgumentException('Notification must be an accepted GCM notification');
58
        }
59
60
        $service = $this->getPushService($this->getParameter('api_key'));
61
62
        $results = [];
63
64
        foreach (array_chunk($notification->getTokens(), 100) as $tokensRange) {
65
            $message = MessageBuilder::build($tokensRange, $notification);
66
67
            $time = new \DateTime;
68
69
            try {
70
                $response = $service->send($message)->getResults();
71
72
                foreach ($tokensRange as $token) {
73
                    if (isset($response[$token]) && !isset($response[$token]['error'])) {
74
                        $result = new Result($token, $time);
75
                    } elseif (isset($response[$token])) {
76
                        $result = new Result(
77
                            $token,
78
                            $time,
79
                            Result::STATUS_ERROR,
80
                            self::$statusCodes[$response[$token]['error']]
81
                        );
82
                    } else {
83
                        $result = new Result(
84
                            $token,
85
                            $time,
86
                            Result::STATUS_ERROR,
87
                            self::$statusCodes['UnknownError']
88
                        );
89
                    }
90
91
                    $results[] = $result;
92
                }
93
            } catch (ServiceRuntimeException $exception) {
94
                foreach ($tokensRange as $token) {
95
                    $results[] = new Result($token, $time, Result::STATUS_ERROR, $exception->getMessage());
96
                }
97
            }
98
        }
99
100
        $notification->setSent($results);
101
    }
102
103
    /**
104
     * Get opened client.
105
     *
106
     * @param string $apiKey
107
     *
108
     * @return \ZendService\Google\Gcm\Client
109
     */
110
    protected function getPushService($apiKey)
111
    {
112
        if (!isset($this->pushClient)) {
113
            $this->pushClient = ClientBuilder::buildPush($apiKey);
114
        }
115
116
        return $this->pushClient;
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    protected function getDefinedParameters()
123
    {
124
        return ['api_key'];
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130
    protected function getDefaultParameters()
131
    {
132
        return [];
133
    }
134
135
    /**
136
     * {@inheritdoc}
137
     */
138
    protected function getRequiredParameters()
139
    {
140
        return ['api_key'];
141
    }
142
}
143