1 | <?php |
||
2 | |||
3 | namespace LeKoala\SsPwa; |
||
4 | |||
5 | use SilverStripe\Control\Controller; |
||
6 | use SilverStripe\Control\HTTPResponse; |
||
7 | use SilverStripe\Security\Security; |
||
8 | |||
9 | class PushController extends Controller |
||
10 | { |
||
11 | /** |
||
12 | * @config |
||
13 | * @var boolean |
||
14 | */ |
||
15 | private static $enabled = true; |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
16 | |||
17 | /** |
||
18 | * @var array<string> |
||
19 | */ |
||
20 | private static $allowed_actions = [ |
||
0 ignored issues
–
show
|
|||
21 | 'index', |
||
22 | 'addPushSubscription', |
||
23 | 'removePushSubscription', |
||
24 | ]; |
||
25 | |||
26 | /** |
||
27 | * @return string |
||
28 | */ |
||
29 | public function index() |
||
30 | { |
||
31 | return ''; |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * @return array<string,mixed> |
||
36 | */ |
||
37 | protected function getJsonData(): array |
||
38 | { |
||
39 | $json = $this->getRequest()->getBody(); |
||
40 | $data = json_decode($json, true); |
||
41 | if (!$data) { |
||
42 | return []; |
||
43 | } |
||
44 | return $data; |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * @return string|HTTPResponse |
||
49 | */ |
||
50 | public function addPushSubscription() |
||
51 | { |
||
52 | if (!self::config()->get('enabled')) { |
||
53 | return ''; |
||
54 | } |
||
55 | $data = $this->getJsonData(); |
||
56 | $success = false; |
||
57 | if (!empty($data['endpoint'])) { |
||
58 | $success = PushSubscription::createNew($data, Security::getCurrentUser(), PushSubscription::WEBPUSH); |
||
59 | } |
||
60 | |||
61 | $results = [ |
||
62 | 'success' => $success |
||
63 | ]; |
||
64 | $body = json_encode($results); |
||
65 | $body = $body ? $body : ''; |
||
66 | $resp = $this->getResponse(); |
||
67 | $resp->addHeader('Content-Type', 'application/json'); |
||
68 | $resp->setBody($body); |
||
69 | return $resp; |
||
70 | } |
||
71 | |||
72 | /** |
||
73 | * @return string|HTTPResponse |
||
74 | */ |
||
75 | public function removePushSubscription() |
||
76 | { |
||
77 | if (!self::config()->get('enabled')) { |
||
78 | return ''; |
||
79 | } |
||
80 | $data = $this->getJsonData(); |
||
81 | $success = false; |
||
82 | if (!empty($data['endpoint'])) { |
||
83 | $success = PushSubscription::deleteEndpoint($data['endpoint']); |
||
84 | } |
||
85 | |||
86 | $results = [ |
||
87 | 'success' => $success |
||
88 | ]; |
||
89 | $body = json_encode($results); |
||
90 | $body = $body ? $body : ''; |
||
91 | $resp = $this->getResponse(); |
||
92 | $resp->addHeader('Content-Type', 'application/json'); |
||
93 | $resp->setBody($body); |
||
94 | return $resp; |
||
95 | } |
||
96 | } |
||
97 |