Passed
Branch master (c73d10)
by Stefan
02:51 queued 55s
created

PNSubscriber.php (1 issue)

Severity
1
<?php
2
require_once 'autoloader.php';
3
require_once 'PNSendWelcome.php';
4
5
use SKien\PNServer\PNDataProviderSQLite;
6
use SKien\PNServer\PNSubscription;
7
8
/**
9
 * Example to handle the HTTP-Request send from the ServiceWorker to 
10
 * subscribe our notification service.
11
 * 
12
 * For easy setup we use the SQLite dataprovider and set the database file
13
 * located in the same directory as this script.
14
 * You may use the MySQL dataprovider, just locate the database in a differnet
15
 * directory or write your own dataprovider for your project.
16
 * 
17
 * Remember to adjust the path and name of the script in the service worker
18
 * (PNServiceWorker.js) when implementing the requesthandler in your own project.
19
 * 
20
 * Set $bSendWelcome=true, to send a welcome notification to each user 
21
 * newly subscribed our service, after the subscription was saved in 
22
 * the database.
23
 *
24
 * THIS CODE IS INTENDED ONLY AS EXAMPLE - DONT USE IT DIRECT IN YOU PROJECT
25
 *
26
 * @author Stefanius <[email protected]>
27
 * @copyright MIT License - see the LICENSE file for details
28
 */
29
30
// set to true, if you will send songle welcome notification to each new subscription
31
$bSendWelcome = true;
32
33
$result = array();
34
// only serve POST request containing valid json data
35
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
36
	if (isset($_SERVER['CONTENT_TYPE'])	&& trim(strtolower($_SERVER['CONTENT_TYPE']) == 'application/json')) {
37
		// get posted json data
38
		if (($strJSON = trim(file_get_contents('php://input'))) === false) {
39
			$result['msg'] = 'invalid JSON data!';
40
		} else {
41
			$oDP = new PNDataProviderSQLite();
42
			if ($oDP->saveSubscription($strJSON) !== false) {
43
				$result['msg'] = 'subscription saved on server!';
44
				if ($bSendWelcome) {
0 ignored issues
show
The condition $bSendWelcome is always true.
Loading history...
45
				    sendWelcome(PNSubscription::fromJSON($strJSON));
46
				}
47
			} else {
48
				$result['msg'] = 'error saving subscription!';
49
			}
50
		}
51
	} else {
52
		$result['msg'] = 'invalid content type!';
53
	}
54
} else {
55
	$result['msg'] = 'no post request!';
56
}
57
// let the service-worker know the result
58
echo json_encode($result);
59