GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 1dc585...abcc73 )
by Alexander
02:30
created

Dispatcher::createFeedbackConnection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
/*
4
 * (c) Alexander Zhukov <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Zbox\UnifiedPush;
11
12
use Zbox\UnifiedPush\Message\MessageInterface,
13
    Zbox\UnifiedPush\Notification\NotificationBuilder;
14
use Zbox\UnifiedPush\NotificationService\NotificationServices,
15
    Zbox\UnifiedPush\NotificationService\ServiceClientInterface,
16
    Zbox\UnifiedPush\NotificationService\ServiceClientFactory;
17
use Zbox\UnifiedPush\Exception\InvalidRecipientException,
18
    Zbox\UnifiedPush\Exception\DispatchMessageException,
19
    Zbox\UnifiedPush\Exception\MalformedNotificationException,
20
    Zbox\UnifiedPush\Exception\ClientException,
21
    Zbox\UnifiedPush\Exception\RuntimeException;
22
use Psr\Log\LoggerAwareInterface,
23
    Psr\Log\LoggerInterface,
24
    Psr\Log\NullLogger;
25
26
/**
27
 * Class Dispatcher
28
 * @package Zbox\UnifiedPush
29
 */
30
class Dispatcher implements LoggerAwareInterface
31
{
32
    /**
33
     * @var Application
34
     */
35
    private $application;
36
37
    /**
38
     * @var NotificationBuilder
39
     */
40
    private $notificationBuilder;
41
42
    /**
43
     * @var array
44
     */
45
    private $connectionPool;
46
47
    /**
48
     * @var ServiceClientFactory
49
     */
50
    private $clientFactory;
51
52
    /**
53
     * @var LoggerInterface
54
     */
55
    private $logger;
56
57
    /**
58
     * @param Application $application
59
     * @param ServiceClientFactory $clientFactory
60
     * @param NotificationBuilder $notificationBuilder
61
     */
62
    public function __construct(
63
        Application $application,
64
        ServiceClientFactory $clientFactory,
65
        NotificationBuilder $notificationBuilder
66
    ){
67
        $this->application    = $application;
68
        $this->clientFactory  = $clientFactory;
69
        $this->notificationBuilder = $notificationBuilder;
70
71
        $this->setLogger(new NullLogger());
72
    }
73
74
    /**
75
     * @param LoggerInterface $logger
76
     * @return $this
77
     */
78
    public function setLogger(LoggerInterface $logger)
79
    {
80
        $this->logger = $logger;
81
        return $this;
82
    }
83
84
    /**
85
     * @param bool $isDevelopment
86
     * @return $this
87
     */
88
    public function setDevelopmentMode($isDevelopment)
89
    {
90
        $this->clientFactory->setDevelopmentMode($isDevelopment);
91
        return $this;
92
    }
93
94
    /**
95
     * Returns credentials for notification service
96
     *
97
     * @param string $serviceName
98
     * @return array
99
     */
100
    private function getServiceCredentials($serviceName)
101
    {
102
        return $this->application->getCredentialsByService($serviceName);
103
    }
104
105
    /**
106
     * Gets a service client connection by service name
107
     *
108
     * @param string $serviceName
109
     * @return ServiceClientInterface
110
     */
111
    public function getConnection($serviceName)
112
    {
113
        if (empty($this->connectionPool[$serviceName])) {
114
            $this->initConnection($serviceName);
115
        }
116
117
        return $this->connectionPool[$serviceName];
118
    }
119
120
    /**
121
     * Initialize service client connection by service name
122
     *
123
     * @param string $serviceName
124
     * @return $this
125
     */
126
    public function initConnection($serviceName)
127
    {
128
        $credentials  = $this->getServiceCredentials($serviceName);
129
        $connection   = $this->clientFactory->createServiceClient($serviceName, $credentials);
130
        $this->connectionPool[$serviceName] = $connection;
131
132
        return $this;
133
    }
134
135
    /**
136
     * Creates a feedback service connection
137
     *
138
     * @param string $serviceName
139
     * @return ServiceClientInterface
140
     */
141
    private function createFeedbackConnection($serviceName)
142
    {
143
        $credentials  = $this->getServiceCredentials($serviceName);
144
        return $this->clientFactory->createServiceClient($serviceName, $credentials, true);
145
    }
146
147
    /**
148
     * Tries to connect and send a message to notification service
149
     *
150
     * @return bool
151
     * @throws Zbox\UnifiedPush\Exception\InvalidRecipientException
152
     * @throws Zbox\UnifiedPush\Exception\DispatchMessageException
153
     * @throws Zbox\UnifiedPush\Exception\MalformedNotificationException
154
     */
155
    private function sendNotifications()
156
    {
157
        while ($notification = $this->notificationBuilder->getNotification()) {
158
            try {
159
                $connection = $this->getConnection($notification->getType());
160
                $connection->setNotification($notification);
161
                $connection->sendRequest();
162
163
            } catch (InvalidRecipientException $e) {
164
                while ($recipient = $e->getRecipientDevice()) {
165
                    $this->application->addInvalidRecipient($notification->getType(), $recipient);
166
                }
167
168
            } catch (DispatchMessageException $e) {
169
                $this->logger->warning(
170
                    sprintf("Dispatch message warning with code %d  '%s'", $e->getCode(), $e->getMessage())
171
                );
172
173
            } catch (MalformedNotificationException $e) {
174
                $this->logger->error(
175
                    sprintf("Malformed Notification error: %s", $e->getMessage())
176
                );
177
                return false;
178
            }
179
        }
180
        return true;
181
    }
182
183
    /**
184
     * Tries to dispatch all messages to notification service
185
     *
186
     * @return bool
187
     * @throws Zbox\UnifiedPush\Exception\ClientException
188
     * @throws Zbox\UnifiedPush\Exception\RuntimeException
189
     * @throws \Exception
190
     */
191
    public function dispatch()
192
    {
193
        $messages = $this->application->getMessagesIterator();
194
195
        try {
196
            while ($messages->valid()) {
197
                $message = $messages->current();
198
                if ($this->notificationBuilder->buildNotifications($message)) {
199
                    $messages->offsetUnset($message->getMessageIdentifier());
200
                }
201
                $messages->next();
202
            }
203
204
            $this->sendNotifications();
205
206
        } catch (ClientException $e) {
207
            $this->logger->error(
208
                sprintf("Client connection error: %s", $e->getMessage())
209
            );
210
            return;
211
212
        } catch (RuntimeException $e) {
213
            $this->logger->error(
214
                sprintf("Runtime error: %s", $e->getMessage())
215
            );
216
            return;
217
218
        } catch (\Exception $e) {
219
            $this->logger->error(
220
                sprintf("Error occurs: %s", $e->getMessage())
221
            );
222
            return;
223
        }
224
    }
225
226
    /**
227
     * Tries to connect and load feedback data
228
     *
229
     * @return $this
230
     * @throws RuntimeException
231
     * @throws \Exception
232
     */
233
    public function loadFeedback()
234
    {
235
        $serviceName = NotificationServices::APPLE_PUSH_NOTIFICATIONS_SERVICE;
236
237
        try {
238
            $this->logger->info(sprintf("Querying the feedback service '%s'", $serviceName));
239
240
            $connection = $this->createFeedbackConnection($serviceName);
241
            $invalidRecipients = $connection->sendRequest();
242
243
            while ($invalidRecipients->valid()) {
244
                $recipient = $invalidRecipients->current();
245
                $this->application->addInvalidRecipient($serviceName, $recipient);
246
                $invalidRecipients->next();
247
            }
248
249
        } catch (RuntimeException $e) {
250
            $this->logger->error(
251
                sprintf("Runtime error while acquiring feedback: %s", $e->getMessage())
252
            );
253
254
        } catch (\Exception $e) {
255
            $this->logger->error(
256
                sprintf("Error occurs while acquiring feedback: %s", $e->getMessage())
257
            );
258
        }
259
260
        return $this;
261
    }
262
}
263