├── test.sh
├── .gitignore
├── .travis.yml
├── phpunit.xml
├── tests
└── PHP_GCM
│ ├── SenderTest.php
│ ├── InvalidRequestExceptionTest.php
│ ├── ResultTest.php
│ ├── AggregateResultTest.php
│ ├── MulticastResultTest.php
│ ├── NotificationTest.php
│ └── MessageTest.php
├── CONTRIBUTING.md
├── composer.json
├── src
└── PHP_GCM
│ ├── InvalidRequestException.php
│ ├── Result.php
│ ├── Constants.php
│ ├── MulticastResult.php
│ ├── AggregateResult.php
│ ├── Notification.php
│ ├── Message.php
│ └── Sender.php
├── README.md
└── LICENSE
/test.sh:
--------------------------------------------------------------------------------
1 | vendor/bin/phpunit
2 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ./tests/
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/tests/PHP_GCM/SenderTest.php:
--------------------------------------------------------------------------------
1 | assertNotNull($sender);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/src/PHP_GCM/InvalidRequestException.php:
--------------------------------------------------------------------------------
1 |
8 | * This is equivalent to GCM posts that return an HTTP error different of 200.
9 | */
10 | class InvalidRequestException extends \Exception {
11 |
12 | private $status;
13 | private $description;
14 |
15 | public function __construct($status, $description = '') {
16 | $this->status = $status;
17 | $this->description = $description;
18 |
19 | parent::__construct($description, $status, null);
20 | }
21 |
22 | public function __toString() {
23 | return __CLASS__ . ': HTTP Status Code: ' . $this->status . ' (' . $this->description . ')';
24 | }
25 |
26 | /**
27 | * Gets the HTTP Status Code.
28 | *
29 | * @return int
30 | */
31 | public function getHttpStatusCode() {
32 | return $this->status;
33 | }
34 |
35 | /**
36 | * Gets the error description.
37 | *
38 | * @return string
39 | */
40 | public function getDescription() {
41 | return $this->description;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/src/PHP_GCM/Result.php:
--------------------------------------------------------------------------------
1 |
9 | * If the message is successfully created, the {@link #getMessageId()} returns
10 | * the message id and {@link #getErrorCodeName()} returns {@literal null};
11 | * otherwise, {@link #getMessageId()} returns {@literal null} and
12 | * {@link #getErrorCodeName()} returns the code of the error.
13 | *
14 | *
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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/src/PHP_GCM/Constants.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 |
--------------------------------------------------------------------------------
/src/PHP_GCM/MulticastResult.php:
--------------------------------------------------------------------------------
1 | success = $success;
26 | $this->failure = $failure;
27 | $this->canonicalIds = $canonicalIds;
28 | $this->multicastId = $multicastId;
29 | $this->retryMulticastIds = $retryMulticastIds;
30 |
31 | $this->results = array();
32 | }
33 |
34 | /**
35 | * Add a result to the result property
36 | *
37 | * @param Result $result
38 | */
39 | public function addResult(Result $result) {
40 | $this->results[] = $result;
41 | }
42 |
43 | /**
44 | * Gets the multicast id.
45 | *
46 | * @return string
47 | */
48 | public function getMulticastId() {
49 | return $this->multicastId;
50 | }
51 |
52 | /**
53 | * Gets the number of successful messages.
54 | *
55 | * @return int
56 | */
57 | public function getSuccess() {
58 | return $this->success;
59 | }
60 |
61 | /**
62 | * Gets the total number of messages sent, regardless of the status.
63 | *
64 | * @return int
65 | */
66 | public function getTotal() {
67 | return $this->success + $this->failure;
68 | }
69 |
70 | /**
71 | * Gets the number of failed messages.
72 | *
73 | * @return int
74 | */
75 | public function getFailure() {
76 | return $this->failure;
77 | }
78 |
79 | /**
80 | * Gets the number of successful messages that also returned a canonical
81 | * registration id.
82 | *
83 | * @return int
84 | */
85 | public function getCanonicalIds() {
86 | return $this->canonicalIds;
87 | }
88 |
89 | /**
90 | * Gets the results of each individual message
91 | *
92 | * @return array
93 | */
94 | public function getResults() {
95 | return $this->results;
96 | }
97 |
98 | /**
99 | * Gets additional ids if more than one multicast message was sent.
100 | *
101 | * @return array
102 | */
103 | public function getRetryMulticastIds() {
104 | return $this->retryMulticastIds;
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/PHP_GCM/AggregateResult.php:
--------------------------------------------------------------------------------
1 | multicastResults = $multicastResults;
22 |
23 | $this->results = [];
24 | $this->retryMulticastIds = [];
25 | $this->success = $this->failure = $this->canonicalIds = 0;
26 | foreach($multicastResults as $multicastResult) {
27 | $this->success += $multicastResult->getSuccess();
28 | $this->failure += $multicastResult->getFailure();
29 | $this->canonicalIds += $multicastResult->getCanonicalIds();
30 | array_splice($this->results, count($this->results), 0, $multicastResult->getResults());
31 | array_splice($this->retryMulticastIds, count($this->retryMulticastIds), 0, $multicastResult->getRetryMulticastIds());
32 | }
33 | }
34 |
35 | /**
36 | * Gets the number of successful messages.
37 | *
38 | * @return int
39 | */
40 | public function getSuccess() {
41 | return $this->success;
42 | }
43 |
44 | /**
45 | * Gets the total number of messages sent, regardless of the status.
46 | *
47 | * @return int
48 | */
49 | public function getTotal() {
50 | return $this->success + $this->failure;
51 | }
52 |
53 | /**
54 | * Gets the number of failed messages.
55 | *
56 | * @return int
57 | */
58 | public function getFailure() {
59 | return $this->failure;
60 | }
61 |
62 | /**
63 | * Gets the number of successful messages that also returned a canonical
64 | * registration id.
65 | *
66 | * @return int
67 | */
68 | public function getCanonicalIds() {
69 | return $this->canonicalIds;
70 | }
71 |
72 | /**
73 | * Gets the results of each individual message
74 | *
75 | * @return array
76 | */
77 | public function getResults() {
78 | return $this->results;
79 | }
80 |
81 | /**
82 | * Gets additional ids if more than one multicast message was sent.
83 | *
84 | * @return array
85 | */
86 | public function getMulticastResults() {
87 | return $this->multicastResults;
88 | }
89 |
90 | /**
91 | * Gets the multicast id of the first try.
92 | *
93 | * @return string
94 | */
95 | public function getMulticastId() {
96 | return !!count($this->multicastResults) ? $this->multicastResults[0]->getMulticastId() : 0;
97 | }
98 |
99 | /**
100 | * Gets additional ids if more than one multicast message was sent.
101 | *
102 | * @return array
103 | */
104 | public function getRetryMulticastIds() {
105 | return $this->retryMulticastIds;
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/src/PHP_GCM/Notification.php:
--------------------------------------------------------------------------------
1 | sound = 'default';
26 | }
27 |
28 | /**
29 | * Required, Android only.
30 | *
31 | * @param string Indicates notification icon. On Android: sets value to myicon for drawable resource myicon.
32 | * @return Notification Returns the instance of this Notification for method chaining.
33 | */
34 | public function icon($icon) {
35 | $this->icon = $icon;
36 | return $this;
37 | }
38 |
39 | public function getIcon() {
40 | return $this->icon;
41 | }
42 |
43 | /**
44 | * Optional, Android and iOS.
45 | *
46 | * Android sound files must reside in /res/raw/, while iOS sound files can be
47 | * in the main bundle of the client app or in the Library/Sounds folder of the
48 | * app’s data container. See the iOS Developer Library for more information.
49 | *
50 | * @param string Indicates a sound to play when the device receives the notification.
51 | * Supports default, or the filename of a sound resource bundled in the app.
52 | * @return Notification Returns the instance of this Notification for method chaining.
53 | */
54 | public function sound($sound) {
55 | $this->sound = $sound;
56 | return $this;
57 | }
58 |
59 | public function getSound() {
60 | return $this->sound;
61 | }
62 |
63 | /**
64 | * Required Android
65 | * Optional iOS
66 | *
67 | * @param string Indicates notification title. This field is not visible on iOS phones and tablets.
68 | * @return Notification Returns the instance of this Notification for method chaining.
69 | */
70 | public function title($title) {
71 | $this->title = $title;
72 | return $this;
73 | }
74 |
75 | public function getTitle() {
76 | return $this->title;
77 | }
78 |
79 | /**
80 | * Optional, Android and iOS.
81 | *
82 | * @param string Indicates notification body text.
83 | * @return Notification Returns the instance of this Notification for method chaining.
84 | */
85 | public function body($body) {
86 | $this->body = $body;
87 | return $this;
88 | }
89 |
90 | public function getBody() {
91 | return $this->body;
92 | }
93 |
94 | /**
95 | * Optional, iOS only.
96 | *
97 | * @param int Indicates the badge on client app home icon.
98 | * @return Notification Returns the instance of this Notification for method chaining.
99 | */
100 | public function badge($badge) {
101 | $this->badge = $badge;
102 | return $this;
103 | }
104 |
105 | public function getBadge() {
106 | return $this->badge;
107 | }
108 |
109 | /**
110 | * Optional, Android only.
111 | *
112 | * @param string Indicates whether each notification message results in a new entry
113 | * on the notification center on Android. If not set, each request creates a new notification.
114 | * If set, and a notification with the same tag is already being shown, the new notification
115 | * replaces the existing one in notification center.
116 | * @return Notification Returns the instance of this Notification for method chaining.
117 | */
118 | public function tag($tag) {
119 | $this->tag = $tag;
120 | return $this;
121 | }
122 |
123 | public function getTag() {
124 | return $this->tag;
125 | }
126 |
127 | /**
128 | * Optional, Android only.
129 | *
130 | * @param string Indicates color of the icon, expressed in #rrggbb format
131 | * @return Notification Returns the instance of this Notification for method chaining.
132 | */
133 | public function color($color) {
134 | $this->color = $color;
135 | return $this;
136 | }
137 |
138 | public function getColor() {
139 | return $this->color;
140 | }
141 |
142 | /**
143 | * Optional, Android and iOS.
144 | *
145 | * @param string The action associated with a user click on the notification.
146 | * On Android, if this is set, an activity with a matching intent filter is launched
147 | * when user clicks the notification. For example, if one of your Activities includes the intent filter:
148 | *
149 | *
150 | *
151 | *
152 | *
153 | *
154 | * Set click_action to OPEN_ACTIVITY_1 to open it.
155 | * If set, corresponds to category in APNS payload.
156 | * @return Notification Returns the instance of this Notification for method chaining.
157 | */
158 | public function clickAction($clickAction) {
159 | $this->clickAction = $clickAction;
160 | return $this;
161 | }
162 |
163 | public function getClickAction() {
164 | return $this->clickAction;
165 | }
166 |
167 | /**
168 | * Optional, Android and iOS.
169 | *
170 | * @param string Indicates the key to the body string for localization.
171 | * On iOS, this corresponds to "loc-key" in APNS payload.
172 | * On Android, use the key in the app's string resources when populating this value.
173 | * @return Notification Returns the instance of this Notification for method chaining.
174 | */
175 | public function bodyLocKey($bodyLocKey) {
176 | $this->bodyLocKey = $bodyLocKey;
177 | return $this;
178 | }
179 |
180 | public function getBodyLocKey() {
181 | return $this->bodyLocKey;
182 | }
183 |
184 | /**
185 | * Optional, Android and iOS.
186 | *
187 | * @param array Indicates the string value to replace format specifiers in body string for localization.
188 | * On iOS, this corresponds to "loc-args" in APNS payload.
189 | * On Android, these are the format arguments for the string resource. For more information, see Formatting strings.
190 | * @return Notification Returns the instance of this Notification for method chaining.
191 | */
192 | public function bodyLocArgs(array $bodyLocArgs) {
193 | $this->bodyLocArgs = $bodyLocArgs;
194 | return $this;
195 | }
196 |
197 | public function getBodyLocArgs() {
198 | return $this->bodyLocArgs;
199 | }
200 |
201 | /**
202 | * Optional, Android and iOS.
203 | *
204 | * @param string Indicates the key to the title string for localization.
205 | * On iOS, this corresponds to "title-loc-key" in APNS payload.
206 | * On Android, use the key in the app's string resources when populating this value.
207 | * @return Notification Returns the instance of this Notification for method chaining.
208 | */
209 | public function titleLocKey($titleLocKey) {
210 | $this->titleLocKey = $titleLocKey;
211 | return $this;
212 | }
213 |
214 | public function getTitleLocKey() {
215 | return $this->titleLocKey;
216 | }
217 |
218 | /**
219 | * Optional, Android and iOS.
220 | *
221 | * @param array Indicates the string value to replace format specifiers in title string for localization.
222 | * On iOS, this corresponds to "title-loc-args" in APNS payload.
223 | * On Android, these are the format arguments for the string resource. For more information, see Formatting strings.
224 | * @return Notification Returns the instance of this Notification for method chaining.
225 | */
226 | public function titleLocArgs(array $titleLocArgs) {
227 | $this->titleLocArgs = $titleLocArgs;
228 | return $this;
229 | }
230 |
231 | public function getTitleLocArgs() {
232 | return $this->titleLocArgs;
233 | }
234 | }
235 |
--------------------------------------------------------------------------------
/src/PHP_GCM/Message.php:
--------------------------------------------------------------------------------
1 | timeToLive = 2419200;
46 | $this->delayWhileIdle = false;
47 | $this->dryRun = false;
48 | }
49 |
50 | /**
51 | * Sets the collapseKey property.
52 | *
53 | * @param string $collapseKey
54 | * @return Message Returns the instance of this Message for method chaining.
55 | */
56 | public function collapseKey($collapseKey) {
57 | $this->collapseKey = $collapseKey;
58 | return $this;
59 | }
60 |
61 | public function getCollapseKey() {
62 | return $this->collapseKey;
63 | }
64 |
65 | /**
66 | * Sets the delayWhileIdle property (default value is {false}).
67 | *
68 | * @param bool $delayWhileIdle
69 | * @return Message Returns the instance of this Message for method chaining.
70 | */
71 | public function delayWhileIdle($delayWhileIdle) {
72 | $this->delayWhileIdle = $delayWhileIdle;
73 | return $this;
74 | }
75 |
76 | public function getDelayWhileIdle() {
77 | if(isset($this->delayWhileIdle))
78 | return $this->delayWhileIdle;
79 | return null;
80 | }
81 |
82 | /**
83 | * Sets the dryRun property (default value is {false}).
84 | *
85 | * @param bool $dryRun
86 | * @return Message Returns the instance of this Message for method chaining.
87 | */
88 | public function dryRun($dryRun) {
89 | $this->dryRun = $dryRun;
90 | return $this;
91 | }
92 |
93 | public function getDryRun() {
94 | return $this->dryRun;
95 | }
96 |
97 | /**
98 | * Sets the time to live, in seconds.
99 | *
100 | * @param int $timeToLive
101 | * @return Message Returns the instance of this Message for method chaining.
102 | */
103 | public function timeToLive($timeToLive) {
104 | $this->timeToLive = $timeToLive;
105 | return $this;
106 | }
107 |
108 | public function getTimeToLive() {
109 | return $this->timeToLive;
110 | }
111 |
112 | /**
113 | * Adds a key/value pair to the payload data.
114 | *
115 | * @param string $key
116 | * @param string $value
117 | * @return Message Returns the instance of this Message for method chaining.
118 | */
119 | public function addData($key, $value) {
120 | $this->data[$key] = $value;
121 | return $this;
122 | }
123 |
124 | /**
125 | * Sets the data property
126 | *
127 | * @param array $data
128 | * @return Message Returns the instance of this Message for method chaining.
129 | */
130 | public function data(array $data) {
131 | $this->data = $data;
132 | return $this;
133 | }
134 |
135 | public function getData() {
136 | return $this->data;
137 | }
138 |
139 | /**
140 | * Sets the restrictedPackageName property.
141 | *
142 | * @param string $restrictedPackageName
143 | * @return Message Returns the instance of this Message for method chaining.
144 | */
145 | public function restrictedPackageName($restrictedPackageName) {
146 | $this->restrictedPackageName = $restrictedPackageName;
147 | return $this;
148 | }
149 |
150 | public function getRestrictedPackageName() {
151 | return $this->restrictedPackageName;
152 | }
153 |
154 | /**
155 | * Sets the notification for the message. See the Notification class for more information.
156 | *
157 | * @param Notification $notification
158 | * @return Message Returns the instance of this Message for method chaining.
159 | */
160 | public function notification(Notification $notification) {
161 | $this->notification = $notification;
162 | return $this;
163 | }
164 |
165 | public function getNotification() {
166 | return $this->notification;
167 | }
168 |
169 | /**
170 | * Sets the contentAvailable property
171 | *
172 | * @param $contentAvailable
173 | * @return $this
174 | */
175 | public function contentAvailable($contentAvailable) {
176 | $this->contentAvailable = $contentAvailable;
177 | return $this;
178 | }
179 |
180 | public function getContentAvailable() {
181 | return $this->contentAvailable;
182 | }
183 |
184 | /**
185 | * Sets the priority property
186 | *
187 | * @param $priority
188 | * @return $this
189 | */
190 | public function priority($priority) {
191 | $this->priority = $priority;
192 | return $this;
193 | }
194 |
195 | public function getPriority() {
196 | return $this->priority;
197 | }
198 |
199 | public function build($recipients) {
200 | $message = array();
201 |
202 | if (!is_array($recipients)) {
203 | $message[self::TO] = $recipients;
204 | } else if (count($recipients) == 1) {
205 | $message[self::TO] = $recipients[0];
206 | } else {
207 | $message[self::REGISTRATION_IDS] = $recipients;
208 | }
209 |
210 | if (!empty($this->collapseKey)) {
211 | $message[self::COLLAPSE_KEY] = $this->collapseKey;
212 | }
213 |
214 | $message[self::DELAY_WHILE_IDLE] = $this->delayWhileIdle;
215 | $message[self::TIME_TO_LIVE] = $this->timeToLive;
216 | $message[self::DRY_RUN] = $this->dryRun;
217 |
218 | if (!empty($this->restrictedPackageName)) {
219 | $message[self::RESTRICTED_PACKAGE_NAME] = $this->restrictedPackageName;
220 | }
221 |
222 | if (!is_null($this->contentAvailable)) {
223 | $message[self::CONTENT_AVAILABLE] = $this->contentAvailable;
224 | }
225 |
226 | if ($this->priority) {
227 | $message[self::PRIORITY] = $this->priority;
228 | }
229 |
230 | if (!is_null($this->data) && count($this->data) > 0) {
231 | $message[self::DATA] = $this->data;
232 | }
233 |
234 | if ($this->notification != null) {
235 | $message[self::NOTIFICATION] = array();
236 |
237 | if ($this->notification->getBadge() != null) {
238 | $message[self::NOTIFICATION][self::NOTIFICATION_BADGE] = $this->notification->getBadge();
239 | }
240 |
241 | $message[self::NOTIFICATION][self::NOTIFICATION_BODY] = $this->notification->getBody();
242 | $message[self::NOTIFICATION][self::NOTIFICATION_BODY_LOC_ARGS] = $this->notification->getBodyLocArgs();
243 | $message[self::NOTIFICATION][self::NOTIFICATION_BODY_LOC_KEY] = $this->notification->getBodyLocKey();
244 | $message[self::NOTIFICATION][self::NOTIFICATION_CLICK_ACTION] = $this->notification->getClickAction();
245 | $message[self::NOTIFICATION][self::NOTIFICATION_COLOR] = $this->notification->getColor();
246 | $message[self::NOTIFICATION][self::NOTIFICATION_ICON] = $this->notification->getIcon();
247 | $message[self::NOTIFICATION][self::NOTIFICATION_SOUND] = $this->notification->getSound();
248 | $message[self::NOTIFICATION][self::NOTIFICATION_TAG] = $this->notification->getTag();
249 | $message[self::NOTIFICATION][self::NOTIFICATION_TITLE] = $this->notification->getTitle();
250 | $message[self::NOTIFICATION][self::NOTIFICATION_TITLE_LOC_ARGS] = $this->notification->getTitleLocArgs();
251 | $message[self::NOTIFICATION][self::NOTIFICATION_TITLE_LOC_KEY] = $this->notification->getTitleLocKey();
252 | }
253 |
254 | return json_encode($message);
255 | }
256 | }
257 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------