-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirebaseService.php
More file actions
60 lines (55 loc) · 1.61 KB
/
Copy pathFirebaseService.php
File metadata and controls
60 lines (55 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
namespace ADT\FancyAdmin\Model\Services;
use ADT\DoctrineComponents\EntityManager;
use ADT\FancyAdmin\Model\Queries\Factories\IdentityQueryFactory;
use Doctrine\ORM\NonUniqueResultException;
use Kreait\Firebase\Exception\FirebaseException;
use Kreait\Firebase\Exception\Messaging\NotFound;
use Kreait\Firebase\Exception\MessagingException;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Nette\Localization\Translator;
use Tracy\Debugger;
abstract class FirebaseService
{
public function __construct(
protected string $serviceAccount,
readonly protected EntityManager $entityManager,
readonly protected IdentityQueryFactory $identityQueryFactory,
readonly protected Translator $translator,
) {
}
/**
* @throws MessagingException
* @throws FirebaseException
* @throws \ReflectionException
* @throws NonUniqueResultException
*/
public function sendMessage(string $token, array $body): void
{
try {
(new Factory())
->withServiceAccount($this->serviceAccount)
->createMessaging()
->send(
CloudMessage::new()
->withToken($token)
->withData($body)
->withHighestPossiblePriority()
);
} catch (NotFound) {
$validTokens = [];
foreach ($this->identityQueryFactory->create()->byFirebaseToken($token)->fetch() as $_user) {
Debugger::log($_user->getId() . ' ' . $token, 'firebase-not-found');
foreach ($_user->getFirebaseTokens() as $userToken) {
if ($userToken === $token) {
continue;
}
$validTokens[] = $userToken;
}
$_user->setFirebaseTokens($validTokens);
}
$this->entityManager->flush();
}
}
}