├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── composer.json
├── phpunit.xml
├── src
└── PHP_GCM
│ ├── AggregateResult.php
│ ├── Constants.php
│ ├── InvalidRequestException.php
│ ├── Message.php
│ ├── MulticastResult.php
│ ├── Notification.php
│ ├── Result.php
│ └── Sender.php
├── test.sh
└── tests
└── PHP_GCM
├── AggregateResultTest.php
├── InvalidRequestExceptionTest.php
├── MessageTest.php
├── MulticastResultTest.php
├── NotificationTest.php
├── ResultTest.php
└── SenderTest.php
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | vendor/
3 | composer.lock
4 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: php
3 | php:
4 | - '5.6'
5 | - '7.0'
6 | - hhvm
7 | - nightly
8 | install:
9 | - composer install
10 | - chmod +x test.sh
11 | script: ./test.sh
12 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Thank you for considering contributing to this project. Below are a few guidelines to keep in mind when contributing.
4 |
5 | ## Tests
6 |
7 | All tests should be passing and all new code should have accompanying tests.
8 |
9 | ## Commits
10 |
11 | * Commits should be small, self-contained, atomic and do one thing.
12 | * Commit messages should use the imperative present tense and be concise and descriptive.
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # php-gcm
2 |
3 | [](https://travis-ci.org/lkorth/php-gcm)
4 | [](https://packagist.org/packages/php-gcm/php-gcm)
5 |
6 | Why
7 | --------
8 | [Google Cloud Messaging for Android](http://developer.android.com/google/gcm/index.html) is very powerful,
9 | but there are a lot of details to handle. This library takes care of the details and makes GCM very easy
10 | to use with PHP.
11 |
12 | Support
13 | -------
14 | php-gcm supports the [HTTP server protocol](https://developers.google.com/cloud-messaging/server) for GCM.
15 | There is not currently support for XMPP, but implementations and pull requests for XMPP are welcome.
16 | See [#3](https://github.com/lkorth/php-gcm/issues/3) for more details.
17 |
18 | php-gcm supports PHP versions >= 5.3.10. php-gcm may work on older versions of PHP, but has not been
19 | tested on them.
20 |
21 | Install
22 | ---------
23 | Composer is the easiest way to manage dependencies in your project. Create a file named composer.json with the following:
24 |
25 | ```json
26 | {
27 | "require": {
28 | "php-gcm/php-gcm": "^1.1.1"
29 | }
30 | }
31 | ```
32 |
33 | And run Composer to install php-gcm:
34 |
35 | ```bash
36 | $ curl -s http://getcomposer.org/installer | php
37 | $ composer.phar install
38 | ```
39 |
40 | ### Latest
41 |
42 | php-gcm follows [SEMVER](http://semver.org/). If you would like to try out the latest, possibly unstable or incorrect
43 | code, the dependency can be pointed to `dev-master`.
44 |
45 | ```json
46 | {
47 | "require": {
48 | "php-gcm/php-gcm": "dev-master"
49 | }
50 | }
51 | ```
52 |
53 | Usage
54 | -------
55 | ```php
56 | $sender = new Sender($gcmApiKey);
57 | $message = new Message($collapseKey, $payloadData);
58 |
59 | try {
60 | $result = $sender->send($message, $deviceRegistrationId, $numberOfRetryAttempts);
61 | } catch (\InvalidArgumentException $e) {
62 | // $deviceRegistrationId was null
63 | } catch (PHP_GCM\InvalidRequestException $e) {
64 | // server returned HTTP code other than 200 or 503
65 | } catch (\Exception $e) {
66 | // message could not be sent
67 | }
68 | ```
69 |
70 | License
71 | --------
72 | php-gcm is licensed under the Apache 2.0 License. See the [LICENSE](LICENSE) file for more details.
73 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "php-gcm/php-gcm",
3 | "description": "A PHP library for sending GCM messages",
4 | "keywords": ["library", "gcm", "php", "android"],
5 | "homepage": "https://github.com/lkorth/php-gcm",
6 | "license": "Apache-2.0",
7 | "authors": [
8 | {
9 | "name": "Luke Korth",
10 | "email": "luke@lukekorth.com"
11 | }
12 | ],
13 | "support": {
14 | "issues": "https://github.com/lkorth/php-gcm/issues",
15 | "source": "https://github.com/lkorth/php-gcm"
16 | },
17 | "autoload": {
18 | "psr-0": { "PHP_GCM": "src/" }
19 | },
20 | "require": {
21 | "php": ">=5.3.10",
22 | "ext-curl": "*"
23 | },
24 | "require-dev": {
25 | "phpunit/phpunit": "5.1"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
15 | * There are cases when a request is accept and the message successfully 16 | * created, but GCM has a canonical registration id for that device. In this 17 | * case, the server should update the registration id to avoid rejected requests 18 | * in the future. 19 | * 20 | *
21 | * In a nutshell, the workflow to handle a result is: 22 | *
23 | * - Call {@link #getMessageId()}: 24 | * - {@literal null} means error, call {@link #getErrorCodeName()} 25 | * - non-{@literal null} means the message was created: 26 | * - Call {@link #getCanonicalRegistrationId()} 27 | * - if it returns {@literal null}, do nothing. 28 | * - otherwise, update the server datastore with the new id. 29 | *30 | */ 31 | class Result { 32 | 33 | private $messageId; 34 | private $canonicalRegistrationId; 35 | private $errorCode; 36 | 37 | /** 38 | * Sets the message id 39 | * 40 | * @param string $messageId 41 | */ 42 | public function setMessageId($messageId) { 43 | $this->messageId = $messageId; 44 | } 45 | 46 | /** 47 | * Gets the message id, if any 48 | * 49 | * @return string 50 | */ 51 | public function getMessageId() { 52 | return $this->messageId; 53 | } 54 | 55 | /** 56 | * Sets the canonical registration id 57 | * 58 | * @param string $canonicalRegistrationId 59 | */ 60 | public function setCanonicalRegistrationId($canonicalRegistrationId) { 61 | $this->canonicalRegistrationId = $canonicalRegistrationId; 62 | } 63 | 64 | /** 65 | * Gets the canonical registration id, if any 66 | * 67 | * @return string 68 | */ 69 | public function getCanonicalRegistrationId() { 70 | return $this->canonicalRegistrationId; 71 | } 72 | 73 | /** 74 | * Sets the error code 75 | * 76 | * @param string $errorCode 77 | */ 78 | public function setErrorCode($errorCode) { 79 | $this->errorCode = $errorCode; 80 | } 81 | 82 | /** 83 | * Gets the error code, if any 84 | * 85 | * @return string 86 | */ 87 | public function getErrorCode() { 88 | return $this->errorCode; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/PHP_GCM/Sender.php: -------------------------------------------------------------------------------- 1 | key = $key; 40 | $this->retries = 3; 41 | $this->certificatePath = null; 42 | } 43 | 44 | /** 45 | * Allows a non-default certificate chain to be used when communicating 46 | * with Google APIs. 47 | * 48 | * @param string $certificatePath full qualified path to a certificate store. 49 | * @return Sender Returns the instance of this Sender for method chaining. 50 | */ 51 | public function certificatePath($certificatePath) { 52 | $this->certificatePath = $certificatePath; 53 | return $this; 54 | } 55 | 56 | /** 57 | * Set the number of retries to attempt in the case of service unavailability. Defaults to 3 retries. 58 | * 59 | * Note: Retries use exponential back-off in the case of service unavailability and 60 | * could block the calling thread for many seconds. 61 | * 62 | * @param int $retries number of retries in case of service unavailability errors. 63 | * @return Sender Returns the instance of this Sender for method chaining. 64 | */ 65 | public function retries($retries) { 66 | $this->retries = $retries; 67 | return $this; 68 | } 69 | 70 | /** 71 | * Sends a GCM message to one or more devices, retrying up to the specified 72 | * number of retries in case of unavailability. 73 | * 74 | * Note: Retries use exponential back-off in the case of service unavailability and 75 | * could block the calling thread for many seconds. 76 | * 77 | * @param Message $message to be sent 78 | * @param string|array $registrationIds String registration id or an array of registration ids of the devices where the message will be sent. 79 | * @return AggregateResult combined result of all requests made. 80 | * @throws \InvalidArgumentException If registrationIds is empty 81 | * @throws InvalidRequestException If GCM did not return a 200 after the specified number of retries. 82 | */ 83 | public function send(Message $message, $registrationIds) { 84 | if (empty($registrationIds)) { 85 | throw new \InvalidArgumentException('registrationIds cannot be empty'); 86 | } 87 | 88 | if (!is_array($registrationIds)) { 89 | $registrationIds = array($registrationIds); 90 | } 91 | 92 | $chunks = array_chunk($registrationIds, 1000); 93 | 94 | $multicastResults = array(); 95 | foreach($chunks as $chunk) { 96 | $attempt = 0; 97 | $backoff = self::BACKOFF_INITIAL_DELAY; 98 | $results = array(); 99 | $unsentRegistrationIds = array_values($chunk); 100 | $multicastIds = array(); 101 | do { 102 | $attempt++; 103 | 104 | try { 105 | $multicastResult = $this->makeRequest($message, $unsentRegistrationIds); 106 | $multicastIds[] = $multicastResult->getMulticastId(); 107 | $unsentRegistrationIds = $this->updateStatus($unsentRegistrationIds, $results, $multicastResult); 108 | } catch (InvalidRequestException $e) { 109 | if ($attempt >= $this->retries) { 110 | throw $e; 111 | } 112 | } 113 | 114 | $tryAgain = count($unsentRegistrationIds) > 0 && $attempt <= $this->retries; 115 | if ($tryAgain) { 116 | $sleepTime = $backoff / 2 + rand(0, $backoff); 117 | sleep($sleepTime / 1000); 118 | if (2 * $backoff < self::MAX_BACKOFF_DELAY) { 119 | $backoff *= 2; 120 | } 121 | } 122 | } while ($tryAgain); 123 | 124 | $success = $failure = $canonicalIds = 0; 125 | foreach ($results as $result) { 126 | if (!is_null($result->getMessageId())) { 127 | $success++; 128 | 129 | if (!is_null($result->getCanonicalRegistrationId())) { 130 | $canonicalIds++; 131 | } 132 | } else { 133 | $failure++; 134 | } 135 | } 136 | 137 | $result = new MulticastResult($success, $failure, $canonicalIds, $multicastIds[0], $multicastIds); 138 | foreach ($registrationIds as $registrationId) { 139 | $result->addResult($results[$registrationId]); 140 | } 141 | 142 | $multicastResults[] = $result; 143 | } 144 | 145 | return new AggregateResult($multicastResults); 146 | } 147 | 148 | /** 149 | * Creates a device group under the specified senderId with the specificed notificationKeyName and adds all 150 | * devices in registrationIds to the group. 151 | * 152 | * @param $senderId A unique numerical value created when you configure your API project 153 | * (given as "Project Number" in the Google Developers Console). The sender ID is used in the registration 154 | * process to identify an app server that is permitted to send messages to the client app. 155 | * @param $notificationKeyName a name or identifier (e.g., it can be a username) that is unique to a given group. 156 | * The notificationKeyName and notificationKey are unique to a group of registration tokens. It is important 157 | * that notificationKeyName is unique per client app if you have multiple client apps for the same sender ID. 158 | * This ensures that messages only go to the intended target app. 159 | * @param string|array $registrationIds String registration id or an array of registration ids of the devices to add to the group. 160 | * @return string notificationKey used to send a notification to all the devices in the group. 161 | * @throws \InvalidArgumentException If senderId, notificationKeyName or registrationIds are empty. 162 | * @throws InvalidRequestException If GCM did not return a 200. 163 | */ 164 | public function createDeviceGroup($senderId, $notificationKeyName, array $registrationIds) { 165 | return $this->performDeviceGroupOperation($senderId, $notificationKeyName, null, $registrationIds, self::DEVICE_GROUP_CREATE); 166 | } 167 | 168 | /** 169 | * Adds devices to an existing device group. 170 | * 171 | * @param $senderId A unique numerical value created when you configure your API project 172 | * (given as "Project Number" in the Google Developers Console). The sender ID is used in the registration 173 | * process to identify an app server that is permitted to send messages to the client app. 174 | * @param $notificationKeyName a name or identifier (e.g., it can be a username) that is unique to a given group. 175 | * The notificationKeyName and notificationKey are unique to a group of registration tokens. It is important 176 | * that notificationKeyName is unique per client app if you have multiple client apps for the same sender ID. 177 | * This ensures that messages only go to the intended target app. 178 | * @param $notificationKey the notificationKey returned from Sender#createDeviceGroup. 179 | * @param string|array $registrationIds String registration id or an array of registration ids of the devices to add to the group. 180 | * @return string notificationKey used to send a notification to all the devices in the group. 181 | * @throws \InvalidArgumentException If senderId, notificationKeyName, notificationKey or registrationIds are empty. 182 | * @throws InvalidRequestException If GCM did not return a 200. 183 | */ 184 | public function addDeviceToGroup($senderId, $notificationKeyName, $notificationKey, array $registrationIds) { 185 | if (empty($notificationKey)) { 186 | throw new \InvalidArgumentException('notificationKey cannot be empty'); 187 | } 188 | 189 | return $this->performDeviceGroupOperation($senderId, $notificationKeyName, $notificationKey, $registrationIds, self::DEVICE_GROUP_ADD); 190 | } 191 | 192 | /** 193 | * Removes devices from an existing device group. 194 | * 195 | * @param $senderId A unique numerical value created when you configure your API project 196 | * (given as "Project Number" in the Google Developers Console). The sender ID is used in the registration 197 | * process to identify an app server that is permitted to send messages to the client app. 198 | * @param $notificationKeyName a name or identifier (e.g., it can be a username) that is unique to a given group. 199 | * The notificationKeyName and notificationKey are unique to a group of registration tokens. It is important 200 | * that notificationKeyName is unique per client app if you have multiple client apps for the same sender ID. 201 | * This ensures that messages only go to the intended target app. 202 | * @param $notificationKey the notificationKey returned from Sender#createDeviceGroup. 203 | * @param string|array $registrationIds String registration id or an array of registration ids of the devices to add to the group. 204 | * @return string notificationKey used to send a notification to all the devices in the group. 205 | * @throws \InvalidArgumentException If senderId, notificationKeyName, notificationKey or registrationIds are empty. 206 | * @throws InvalidRequestException If GCM did not return a 200. 207 | */ 208 | public function removeDeviceFromGroup($senderId, $notificationKeyName, $notificationKey, array $registrationIds) { 209 | if (empty($notificationKey)) { 210 | throw new \InvalidArgumentException('notificationKey cannot be empty'); 211 | } 212 | 213 | return $this->performDeviceGroupOperation($senderId, $notificationKeyName, $notificationKey, $registrationIds, self::DEVICE_GROUP_REMOVE); 214 | } 215 | 216 | private function performDeviceGroupOperation($senderId, $notificationKeyName, $notificationKey, array $registrationIds, $operation) { 217 | if (empty($senderId)) { 218 | throw new \InvalidArgumentException('senderId cannot be empty'); 219 | } 220 | 221 | if (empty($notificationKeyName)) { 222 | throw new \InvalidArgumentException('notificationKeyName cannot be empty'); 223 | } 224 | 225 | if (empty($registrationIds)) { 226 | throw new \InvalidArgumentException('registrationIds cannot be empty'); 227 | } 228 | 229 | if (!is_array($registrationIds)) { 230 | $registrationIds = array($registrationIds); 231 | } 232 | 233 | $request = array(); 234 | $request[self::DEVICE_GROUP_OPERATION] = $operation; 235 | $request[self::DEVICE_GROUP_NOTIFICATION_KEY_NAME] = $notificationKeyName; 236 | $request[self::DEVICE_GROUP_REGISTRATION_IDS] = $registrationIds; 237 | 238 | if ($notificationKey != null) { 239 | $request[self::DEVICE_GROUP_NOTIFICATION_KEY] = $notificationKey; 240 | } 241 | 242 | $ch = $this->getCurlRequest(); 243 | curl_setopt($ch, CURLOPT_URL, self::DEVICE_GROUP_ENDPOINT); 244 | curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: key=' . $this->key, self::DEVICE_GROUP_PROJET_ID_HEADER . ': ' . $senderId)); 245 | curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request)); 246 | $response = curl_exec($ch); 247 | $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 248 | curl_close($ch); 249 | 250 | if ($status != 200) { 251 | $response = json_decode($response, true); 252 | throw new InvalidRequestException($status, $response[self::ERROR]); 253 | } 254 | 255 | $response = json_decode($response, true); 256 | return $response[self::DEVICE_GROUP_NOTIFICATION_KEY]; 257 | } 258 | 259 | private function makeRequest(Message $message, array $registrationIds) { 260 | $ch = $this->getCurlRequest(); 261 | curl_setopt($ch, CURLOPT_URL, self::SEND_ENDPOINT); 262 | curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: key=' . $this->key)); 263 | curl_setopt($ch, CURLOPT_POSTFIELDS, $message->build($registrationIds)); 264 | $response = curl_exec($ch); 265 | $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 266 | curl_close($ch); 267 | 268 | if ($status == 400) { 269 | throw new InvalidRequestException($status, 'Check that the JSON message is properly formatted and contains valid fields.'); 270 | } else if ($status == 401) { 271 | throw new InvalidRequestException($status, 'The sender account used to send a message could not be authenticated.'); 272 | } else if ($status == 500) { 273 | throw new InvalidRequestException($status, 'The server encountered an error while trying to process the request.'); 274 | } else if ($status == 503) { 275 | throw new InvalidRequestException($status, 'The server could not process the request in time.'); 276 | } else if ($status != 200) { 277 | throw new InvalidRequestException($status, $response); 278 | } 279 | 280 | $response = json_decode($response, true); 281 | $success = $response[self::SUCCESS]; 282 | $failure = $response[self::FAILURE]; 283 | $canonicalIds = $response[self::CANONICAL_IDS]; 284 | $multicastId = $response[self::MULTICAST_ID]; 285 | 286 | $multicastResult = new MulticastResult($success, $failure, $canonicalIds, $multicastId); 287 | 288 | if(isset($response[self::RESULTS])){ 289 | $individualResults = $response[self::RESULTS]; 290 | 291 | foreach($individualResults as $singleResult) { 292 | $messageId = isset($singleResult[self::MESSAGE_ID]) ? $singleResult[self::MESSAGE_ID] : null; 293 | $canonicalRegId = isset($singleResult[self::REGISTRATION_ID]) ? $singleResult[self::REGISTRATION_ID] : null; 294 | $error = isset($singleResult[self::ERROR]) ? $singleResult[self::ERROR] : null; 295 | 296 | $result = new Result(); 297 | $result->setMessageId($messageId); 298 | $result->setCanonicalRegistrationId($canonicalRegId); 299 | $result->setErrorCode($error); 300 | 301 | $multicastResult->addResult($result); 302 | } 303 | } 304 | 305 | return $multicastResult; 306 | } 307 | 308 | /** 309 | * Updates the status of the messages sent to devices and the list of devices 310 | * that should be retried. 311 | * 312 | * @param array $unsentRegIds list of devices that are still pending an update. 313 | * @param array $allResults map of status that will be updated. 314 | * @param MulticastResult multicastResult result of the last multicast sent. 315 | * 316 | * @return array updated version of devices that should be retried. 317 | */ 318 | private function updateStatus($unsentRegIds, &$allResults, MulticastResult $multicastResult) { 319 | $results = $multicastResult->getResults(); 320 | if(count($results) != count($unsentRegIds)) { 321 | // should never happen, unless there is a flaw in the algorithm 322 | throw new \RuntimeException('Internal error: sizes do not match. currentResults: ' . $results . 323 | '; unsentRegIds: ' . $unsentRegIds); 324 | } 325 | 326 | $newUnsentRegIds = array(); 327 | for ($i = 0; $i < count($unsentRegIds); $i++) { 328 | $regId = $unsentRegIds[$i]; 329 | $result = $results[$i]; 330 | $allResults[$regId] = $result; 331 | $error = $result->getErrorCode(); 332 | 333 | if(!is_null($error) && $error == Constants::$ERROR_UNAVAILABLE) 334 | $newUnsentRegIds[] = $regId; 335 | } 336 | 337 | return $newUnsentRegIds; 338 | } 339 | 340 | private function getCurlRequest() { 341 | $ch = curl_init(); 342 | 343 | if ($this->certificatePath != null) { 344 | curl_setopt($ch, CURLOPT_CAINFO, $this->certificatePath); 345 | } 346 | 347 | curl_setopt($ch, CURLOPT_POST, true); 348 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 349 | 350 | return $ch; 351 | } 352 | } 353 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | vendor/bin/phpunit 2 | -------------------------------------------------------------------------------- /tests/PHP_GCM/AggregateResultTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('multicast-id1', $aggregateResult->getMulticastId()); 16 | $this->assertEquals(3, $aggregateResult->getSuccess()); 17 | $this->assertEquals(9, $aggregateResult->getTotal()); 18 | $this->assertEquals(6, $aggregateResult->getFailure()); 19 | $this->assertEquals(3, $aggregateResult->getCanonicalIds()); 20 | $this->assertTrue(is_array($aggregateResult->getResults()) && empty($aggregateResult->getResults())); 21 | $this->assertTrue(is_array($aggregateResult->getRetryMulticastIds()) && empty($aggregateResult->getRetryMulticastIds())); 22 | } 23 | 24 | public function testGetMulticastId() { 25 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 26 | 27 | $this->assertEquals('multicast-id', $result->getMulticastId()); 28 | } 29 | 30 | public function testGetSuccess() { 31 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 32 | 33 | $this->assertEquals(1, $result->getSuccess()); 34 | } 35 | 36 | public function testGetTotal() { 37 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 38 | 39 | $this->assertEquals(3, $result->getTotal()); 40 | } 41 | 42 | public function testGetFailure() { 43 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 44 | 45 | $this->assertEquals(2, $result->getFailure()); 46 | } 47 | 48 | public function testGetCanonicalIds() { 49 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 50 | 51 | $this->assertEquals(1, $result->getCanonicalIds()); 52 | } 53 | 54 | public function testGetResults() { 55 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 56 | $result->addResult(new Result()); 57 | 58 | $this->assertTrue(is_array($result->getResults())); 59 | $this->assertEquals(array(new Result()), $result->getResults()); 60 | } 61 | 62 | public function testGetRetryMulticastIds() { 63 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array(1)); 64 | 65 | $this->assertEquals(array(1), $result->getRetryMulticastIds()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /tests/PHP_GCM/InvalidRequestExceptionTest.php: -------------------------------------------------------------------------------- 1 | assertEquals(422, $exception->getHttpStatusCode()); 11 | $this->assertEquals('', $exception->getDescription()); 12 | $this->assertEquals('PHP_GCM\InvalidRequestException: HTTP Status Code: 422 ()', (string) $exception); 13 | } 14 | 15 | public function testConstructsCorrectlyWithDescription() { 16 | $exception = new InvalidRequestException(422, 'there was an error'); 17 | 18 | $this->assertEquals(422, $exception->getHttpStatusCode()); 19 | $this->assertEquals('there was an error', $exception->getDescription()); 20 | $this->assertEquals('PHP_GCM\InvalidRequestException: HTTP Status Code: 422 (there was an error)', (string) $exception); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /tests/PHP_GCM/MessageTest.php: -------------------------------------------------------------------------------- 1 | assertEquals(2419200, $message->getTimeToLive()); 11 | $this->assertEquals(false, $message->getDelayWhileIdle()); 12 | $this->assertFalse($message->getDryRun()); 13 | } 14 | 15 | public function testSetsCollapseKey() { 16 | $message = new Message(); 17 | 18 | $message->collapseKey('collapse_key'); 19 | 20 | $this->assertEquals('collapse_key', $message->getCollapseKey()); 21 | } 22 | 23 | public function testSetsDelayWhileIdle() { 24 | $message = new Message(); 25 | 26 | $message->delayWhileIdle(true); 27 | 28 | $this->assertTrue($message->getDelayWhileIdle()); 29 | } 30 | 31 | public function testSetsDryRun() { 32 | $message = new Message(); 33 | 34 | $message->dryRun(true); 35 | 36 | $this->assertTrue($message->getDryRun()); 37 | } 38 | 39 | public function testSetsTimeToLive() { 40 | $message = new Message(); 41 | 42 | $message->timeToLive(100); 43 | 44 | $this->assertEquals(100, $message->getTimeToLive()); 45 | } 46 | 47 | public function testAddsData() { 48 | $message = new Message(); 49 | 50 | $message->addData('key1', 'value1'); 51 | 52 | $this->assertEquals(array('key1' => 'value1'), $message->getData()); 53 | } 54 | 55 | public function testAddsDataWhenDataAlreadyExists() { 56 | $message = new Message(); 57 | $message->data(array('key1' => 'value1', 'key2' => 'value2')); 58 | 59 | $message->addData('key3', 'value3'); 60 | 61 | $this->assertEquals(array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'), $message->getData()); 62 | } 63 | 64 | public function testSetsData() { 65 | $message = new Message(); 66 | 67 | $message->data(array('key1' => 'value1', 'key2' => 'value2')); 68 | 69 | $this->assertEquals(array('key1' => 'value1', 'key2' => 'value2'), $message->getData()); 70 | } 71 | 72 | public function testSetsRestrictedPackageName() { 73 | $message = new Message(); 74 | 75 | $message->restrictedPackageName('com.lukekorth.android'); 76 | 77 | $this->assertEquals('com.lukekorth.android', $message->getRestrictedPackageName()); 78 | } 79 | 80 | public function testSetsNotification() { 81 | $message = new Message(); 82 | $notification = new Notification(); 83 | 84 | $message->notification($notification); 85 | 86 | $this->assertEquals($notification, $message->getNotification()); 87 | } 88 | 89 | public function testSetsContentAvailable() { 90 | $message = new Message(); 91 | 92 | $message->contentAvailable(true); 93 | 94 | $this->assertTrue($message->getContentAvailable()); 95 | } 96 | 97 | public function testSetsPriority() { 98 | $message = new Message(); 99 | 100 | $message->priority("high"); 101 | 102 | $this->assertEquals("high", $message->getPriority()); 103 | } 104 | 105 | public function testSettersAreChainable() { 106 | $message = new Message(); 107 | $message->collapseKey('collapse-key') 108 | ->delayWhileIdle(true) 109 | ->dryRun(true) 110 | ->timeToLive(100) 111 | ->data(array('key1' => 'value1')) 112 | ->addData('key2', 'value2') 113 | ->restrictedPackageName('com.lukekorth.android') 114 | ->contentAvailable(true) 115 | ->priority("high"); 116 | 117 | $this->assertEquals('collapse-key', $message->getCollapseKey()); 118 | $this->assertEquals(true, $message->getDelayWhileIdle()); 119 | $this->assertEquals(true, $message->getDryRun()); 120 | $this->assertEquals(100, $message->getTimeToLive()); 121 | $this->assertEquals(array('key1' => 'value1', 'key2' => 'value2'), $message->getData()); 122 | $this->assertEquals('com.lukekorth.android', $message->getRestrictedPackageName()); 123 | $this->assertTrue($message->getContentAvailable()); 124 | $this->assertEquals("high", $message->getPriority()); 125 | } 126 | 127 | public function testBuildAcceptsSingleRecipient() { 128 | $message = new Message(); 129 | 130 | $builtMessage = json_decode($message->build('recipient'), true); 131 | 132 | $this->assertEquals('recipient', $builtMessage[Message::TO]); 133 | } 134 | 135 | public function testBuildAcceptsArrayWithSingleRecipient() { 136 | $message = new Message(); 137 | 138 | $builtMessage = json_decode($message->build(array('recipient')), true); 139 | 140 | $this->assertEquals('recipient', $builtMessage[Message::TO]); 141 | } 142 | 143 | public function testBuildAcceptsArrayWithMultipleRecipients() { 144 | $message = new Message(); 145 | 146 | $builtMessage = json_decode($message->build(array('recipient', 'other-recipient')), true); 147 | 148 | $this->assertEquals(2, count($builtMessage[Message::REGISTRATION_IDS])); 149 | } 150 | 151 | public function testBuildDoesNotSetCollapseKeyWhenAbsent() { 152 | $message = new Message(); 153 | 154 | $builtMessage = json_decode($message->build(array('recipient')), true); 155 | 156 | $this->assertFalse(array_key_exists(Message::COLLAPSE_KEY, $builtMessage)); 157 | } 158 | 159 | public function testBuildSetsCollapseKey() { 160 | $message = new Message(); 161 | $message->collapseKey('collapse-key'); 162 | 163 | $builtMessage = json_decode($message->build(array('recipient')), true); 164 | 165 | $this->assertEquals('collapse-key', $builtMessage[Message::COLLAPSE_KEY]); 166 | } 167 | 168 | public function testBuildSetsDelayWhileIdle() { 169 | $message = new Message(); 170 | $message->delayWhileIdle(true); 171 | 172 | $builtMessage = json_decode($message->build(array('recipient')), true); 173 | 174 | $this->assertTrue($builtMessage[Message::DELAY_WHILE_IDLE]); 175 | } 176 | 177 | public function testBuildSetsTimeToLive() { 178 | $message = new Message(); 179 | $message->timeToLive(100); 180 | 181 | $builtMessage = json_decode($message->build(array('recipient')), true); 182 | 183 | $this->assertEquals(100, $builtMessage[Message::TIME_TO_LIVE]); 184 | } 185 | 186 | public function testBuildSetsDryRun() { 187 | $message = new Message(); 188 | $message->dryRun(true); 189 | 190 | $builtMessage = json_decode($message->build(array('recipient')), true); 191 | 192 | $this->assertTrue($builtMessage[Message::DRY_RUN]); 193 | } 194 | 195 | public function testBuildDoesNotSetRestrictedPackageNameWhenAbsent() { 196 | $message = new Message(); 197 | 198 | $builtMessage = json_decode($message->build(array('recipient')), true); 199 | 200 | $this->assertFalse(array_key_exists(Message::RESTRICTED_PACKAGE_NAME, $builtMessage)); 201 | } 202 | 203 | public function testBuildSetsRestrictedPackageName() { 204 | $message = new Message(); 205 | $message->restrictedPackageName('package-name'); 206 | 207 | $builtMessage = json_decode($message->build(array('recipient')), true); 208 | 209 | $this->assertEquals('package-name', $builtMessage[Message::RESTRICTED_PACKAGE_NAME]); 210 | } 211 | 212 | public function testBuildSetsContentAvailableWhenTrue() { 213 | $message = new Message(); 214 | $message->contentAvailable(true); 215 | 216 | $builtMessage = json_decode($message->build(array('recipient')), true); 217 | 218 | $this->assertTrue($builtMessage[Message::CONTENT_AVAILABLE]); 219 | } 220 | 221 | public function testBuildSetsContentAvailableWhenFalse() { 222 | $message = new Message(); 223 | $message->contentAvailable(false); 224 | 225 | $builtMessage = json_decode($message->build(array('recipient')), true); 226 | 227 | $this->assertFalse($builtMessage[Message::CONTENT_AVAILABLE]); 228 | } 229 | 230 | public function testBuildDoesNotSetContentAvailableWhenAbsent() { 231 | $message = new Message(); 232 | 233 | $builtMessage = json_decode($message->build(array('recipient')), true); 234 | 235 | $this->assertFalse(array_key_exists(Message::CONTENT_AVAILABLE, $builtMessage)); 236 | } 237 | 238 | public function testBuildSetsPriority() { 239 | $message = new Message(); 240 | $message->priority("high"); 241 | 242 | $builtMessage = json_decode($message->build(array('recipient')), true); 243 | 244 | $this->assertEquals("high", $builtMessage[Message::PRIORITY]); 245 | } 246 | 247 | public function testBuildDoesNotSetPriorityWhenAbsent() { 248 | $message = new Message(); 249 | 250 | $builtMessage = json_decode($message->build(array('recipient')), true); 251 | 252 | $this->assertFalse(array_key_exists(Message::PRIORITY, $builtMessage)); 253 | } 254 | 255 | public function testBuildDoesNotSetDataWhenDataIsAbsent() { 256 | $message = new Message(); 257 | 258 | $builtMessage = json_decode($message->build(array('recipient')), true); 259 | 260 | $this->assertFalse(array_key_exists(Message::DATA, $builtMessage)); 261 | } 262 | 263 | public function testBuildDoesNotSetDataWhenDataIsEmpty() { 264 | $message = new Message(); 265 | $message->data(array()); 266 | 267 | $builtMessage = json_decode($message->build(array('recipient')), true); 268 | 269 | $this->assertFalse(array_key_exists(Message::DATA, $builtMessage)); 270 | } 271 | 272 | public function testBuildSetsData() { 273 | $message = new Message(); 274 | $message->data(array('key' => 'value')); 275 | 276 | $builtMessage = json_decode($message->build(array('recipient')), true); 277 | 278 | $this->assertEquals('value', $builtMessage[Message::DATA]['key']); 279 | } 280 | 281 | public function testBuildHandlesMultiDimentionalArraysForData() { 282 | $message = new Message(); 283 | $message->data(array('foo' => array('bar' => 'baz'))); 284 | 285 | $builtMessage = json_decode($message->build(array('recipient')), true); 286 | 287 | $this->assertEquals('baz', $builtMessage[Message::DATA]['foo']['bar']); 288 | } 289 | 290 | public function testBuildDoesNotIncludeNotificationWhenNotSet() { 291 | $message = new Message(); 292 | 293 | $builtMessage = json_decode($message->build('recipient'), true); 294 | 295 | $this->assertFalse(array_key_exists(Message::NOTIFICATION, $builtMessage)); 296 | } 297 | 298 | public function testBuildIncludesNotificationWhenSet() { 299 | $message = new Message(); 300 | $message->notification(new Notification()); 301 | 302 | $builtMessage = json_decode($message->build('recipient'), true); 303 | 304 | $this->assertTrue(array_key_exists(Message::NOTIFICATION, $builtMessage)); 305 | } 306 | 307 | public function testBuildSetsNotification() { 308 | $notification = new Notification(); 309 | $notification->icon('icon') 310 | ->sound('sound') 311 | ->title('title') 312 | ->body('body') 313 | ->badge(1) 314 | ->tag('tag') 315 | ->color('color') 316 | ->clickAction('click-action') 317 | ->bodyLocKey('bodyLocKey') 318 | ->bodyLocArgs(array('key' => 'value')) 319 | ->titleLocKey('titleLocKey') 320 | ->titleLocArgs(array('key' => 'value')); 321 | $message = new Message(); 322 | $message->notification($notification); 323 | 324 | $builtMessage = json_decode($message->build('recipient'), true); 325 | $builtNotification = $builtMessage[Message::NOTIFICATION]; 326 | 327 | $this->assertEquals('icon', $builtNotification[Message::NOTIFICATION_ICON]); 328 | $this->assertEquals('sound', $builtNotification[Message::NOTIFICATION_SOUND]); 329 | $this->assertEquals('title', $builtNotification[Message::NOTIFICATION_TITLE]); 330 | $this->assertEquals('body', $builtNotification[Message::NOTIFICATION_BODY]); 331 | $this->assertEquals(1, $builtNotification[Message::NOTIFICATION_BADGE]); 332 | $this->assertEquals('tag', $builtNotification[Message::NOTIFICATION_TAG]); 333 | $this->assertEquals('color', $builtNotification[Message::NOTIFICATION_COLOR]); 334 | $this->assertEquals('click-action', $builtNotification[Message::NOTIFICATION_CLICK_ACTION]); 335 | $this->assertEquals('bodyLocKey', $builtNotification[Message::NOTIFICATION_BODY_LOC_KEY]); 336 | $this->assertEquals(array('key' => 'value'), $builtNotification[Message::NOTIFICATION_BODY_LOC_ARGS]); 337 | $this->assertEquals('titleLocKey', $builtNotification[Message::NOTIFICATION_TITLE_LOC_KEY]); 338 | $this->assertEquals(array('key' => 'value'), $builtNotification[Message::NOTIFICATION_TITLE_LOC_ARGS]); 339 | } 340 | } 341 | -------------------------------------------------------------------------------- /tests/PHP_GCM/MulticastResultTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('multicast-id', $result->getMulticastId()); 11 | $this->assertEquals(1, $result->getSuccess()); 12 | $this->assertEquals(3, $result->getTotal()); 13 | $this->assertEquals(2, $result->getFailure()); 14 | $this->assertEquals(1, $result->getCanonicalIds()); 15 | $this->assertTrue(is_array($result->getResults()) && empty($result->getResults())); 16 | $this->assertTrue(is_array($result->getRetryMulticastIds()) && empty($result->getRetryMulticastIds())); 17 | } 18 | 19 | public function testAddResult() { 20 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 21 | $this->assertTrue(is_array($result->getResults()) && empty($result->getResults())); 22 | 23 | $result->addResult(new Result()); 24 | 25 | $this->assertTrue(is_array($result->getResults()) && count($result->getResults()) == 1); 26 | } 27 | 28 | public function testGetMulticastId() { 29 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 30 | 31 | $this->assertEquals('multicast-id', $result->getMulticastId()); 32 | } 33 | 34 | public function testGetSuccess() { 35 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 36 | 37 | $this->assertEquals(1, $result->getSuccess()); 38 | } 39 | 40 | public function testGetTotal() { 41 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 42 | 43 | $this->assertEquals(3, $result->getTotal()); 44 | } 45 | 46 | public function testGetFailure() { 47 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 48 | 49 | $this->assertEquals(2, $result->getFailure()); 50 | } 51 | 52 | public function testGetCanonicalIds() { 53 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 54 | 55 | $this->assertEquals(1, $result->getCanonicalIds()); 56 | } 57 | 58 | public function testGetResults() { 59 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array()); 60 | $result->addResult(new Result()); 61 | 62 | $this->assertTrue(is_array($result->getResults())); 63 | $this->assertEquals(array(new Result()), $result->getResults()); 64 | } 65 | 66 | public function testGetRetryMulticastIds() { 67 | $result = new MulticastResult(1, 2, 1, 'multicast-id', array(1)); 68 | 69 | $this->assertEquals(array(1), $result->getRetryMulticastIds()); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /tests/PHP_GCM/NotificationTest.php: -------------------------------------------------------------------------------- 1 | notification = new Notification(); 11 | } 12 | 13 | public function testConstructsCorrectly() { 14 | $this->assertEquals('default', $this->notification->getSound()); 15 | } 16 | 17 | public function testSetsIcon() { 18 | $this->notification->icon('icon'); 19 | 20 | $this->assertEquals('icon', $this->notification->getIcon()); 21 | } 22 | 23 | public function testSetsSound() { 24 | $this->notification->sound('sound'); 25 | 26 | $this->assertEquals('sound', $this->notification->getSound()); 27 | } 28 | 29 | public function testSetsTitle() { 30 | $this->notification->title('title'); 31 | 32 | $this->assertEquals('title', $this->notification->getTitle()); 33 | } 34 | 35 | public function testSetsBody() { 36 | $this->notification->body('body'); 37 | 38 | $this->assertEquals('body', $this->notification->getBody()); 39 | } 40 | 41 | public function testSetsBadge() { 42 | $this->notification->badge(1); 43 | 44 | $this->assertEquals(1, $this->notification->getBadge()); 45 | } 46 | 47 | public function testSetsTag() { 48 | $this->notification->tag('tag'); 49 | 50 | $this->assertEquals('tag', $this->notification->getTag()); 51 | } 52 | 53 | public function testSetsColor() { 54 | $this->notification->color('color'); 55 | 56 | $this->assertEquals('color', $this->notification->getColor()); 57 | } 58 | 59 | public function testSetsClickAction() { 60 | $this->notification->clickAction('click-action'); 61 | 62 | $this->assertEquals('click-action', $this->notification->getClickAction()); 63 | } 64 | 65 | public function testSetsBodyLocKey() { 66 | $this->notification->bodyLocKey('bodyLocKey'); 67 | 68 | $this->assertEquals('bodyLocKey', $this->notification->getBodyLocKey()); 69 | } 70 | 71 | public function testSetsBodyLocArgs() { 72 | $this->notification->bodyLocArgs(array('key' => 'value')); 73 | 74 | $this->assertEquals(array('key' => 'value'), $this->notification->getBodyLocArgs()); 75 | } 76 | 77 | public function testSetsTitleLocKey() { 78 | $this->notification->titleLocKey('titleLocKey'); 79 | 80 | $this->assertEquals('titleLocKey', $this->notification->getTitleLocKey()); 81 | } 82 | 83 | public function testSetsTitleLocArgs() { 84 | $this->notification->titleLocArgs(array('key' => 'value')); 85 | 86 | $this->assertEquals(array('key' => 'value'), $this->notification->getTitleLocArgs()); 87 | } 88 | 89 | public function testSettersAreChainable() { 90 | $this->notification->icon('icon') 91 | ->sound('sound') 92 | ->title('title') 93 | ->body('body') 94 | ->badge(1) 95 | ->tag('tag') 96 | ->color('color') 97 | ->clickAction('click-action') 98 | ->bodyLocKey('bodyLocKey') 99 | ->bodyLocArgs(array('key' => 'value')) 100 | ->titleLocKey('titleLocKey') 101 | ->titleLocArgs(array('key' => 'value')); 102 | 103 | $this->assertEquals('icon', $this->notification->getIcon()); 104 | $this->assertEquals('sound', $this->notification->getSound()); 105 | $this->assertEquals('title', $this->notification->getTitle()); 106 | $this->assertEquals('body', $this->notification->getBody()); 107 | $this->assertEquals(1, $this->notification->getBadge()); 108 | $this->assertEquals('tag', $this->notification->getTag()); 109 | $this->assertEquals('color', $this->notification->getColor()); 110 | $this->assertEquals('click-action', $this->notification->getClickAction()); 111 | $this->assertEquals('bodyLocKey', $this->notification->getBodyLocKey()); 112 | $this->assertEquals(array('key' => 'value'), $this->notification->getBodyLocArgs()); 113 | $this->assertEquals('titleLocKey', $this->notification->getTitleLocKey()); 114 | $this->assertEquals(array('key' => 'value'), $this->notification->getTitleLocArgs()); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /tests/PHP_GCM/ResultTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('', $result->getMessageId()); 11 | $this->assertEquals('', $result->getCanonicalRegistrationId()); 12 | $this->assertEquals('', $result->getErrorCode()); 13 | } 14 | 15 | public function testSetsMessageId() { 16 | $result = new Result(); 17 | 18 | $result->setMessageId('message-id'); 19 | 20 | $this->assertEquals('message-id', $result->getMessageId()); 21 | } 22 | 23 | public function testSetsCanonicalRegistrationId() { 24 | $result = new Result(); 25 | 26 | $result->setCanonicalRegistrationId('canonical-registration-id'); 27 | 28 | $this->assertEquals('canonical-registration-id', $result->getCanonicalRegistrationId()); 29 | } 30 | 31 | public function testSetsErrorCode() { 32 | $result = new Result(); 33 | 34 | $result->setErrorCode(422); 35 | 36 | $this->assertEquals(422, $result->getErrorCode()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tests/PHP_GCM/SenderTest.php: -------------------------------------------------------------------------------- 1 | assertNotNull($sender); 11 | } 12 | } 13 | --------------------------------------------------------------------------------