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 ( 4b1995...c0ae65 )
by Alexander
02:14
created

Dispatcher::addConnection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
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\Message\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 array
39
     */
40
    private $connectionPool;
41
42
    /**
43
     * @var ServiceClientFactory
44
     */
45
    private $clientFactory;
46
47
    /**
48
     * @var LoggerInterface
49
     */
50
    private $logger;
51
52
    /**
53
     * @param Application $application
54
     */
55
    public function __construct(Application $application)
56
    {
57
        $this->setLogger(new NullLogger());
58
        $this->application    = $application;
59
        $this->clientFactory  = new ServiceClientFactory();
60
    }
61
62
    /**
63
     * @param LoggerInterface $logger
64
     * @return $this
65
     */
66
    public function setLogger(LoggerInterface $logger)
67
    {
68
        $this->logger = $logger;
69
        return $this;
70
    }
71
72
    /**
73
     * @param bool $isDevelopment
74
     * @return $this
75
     */
76
    public function setDevelopmentMode($isDevelopment)
77
    {
78
        $this->clientFactory->setDevelopmentMode($isDevelopment);
79
        return $this;
80
    }
81
82
    /**
83
     * Returns credentials for notification service
84
     *
85
     * @param string $serviceName
86
     * @return array
87
     */
88
    private function getServiceCredentials($serviceName)
89
    {
90
        return $this->application->getCredentialsByService($serviceName);
91
    }
92
93
    /**
94
     * Gets a service client connection by service name
95
     *
96
     * @param string $serviceName
97
     * @return ServiceClientInterface
98
     */
99
    public function getConnection($serviceName)
100
    {
101
        if (empty($this->connectionPool[$serviceName])) {
102
            $this->initConnection($serviceName);
103
        }
104
105
        return $this->connectionPool[$serviceName];
106
    }
107
108
    /**
109
     * Initialize service client connection by service name
110
     *
111
     * @param string $serviceName
112
     * @return $this
113
     */
114
    public function initConnection($serviceName)
115
    {
116
        $credentials  = $this->getServiceCredentials($serviceName);
117
        $connection   = $this->clientFactory->createServiceClient($serviceName, $credentials);
118
        $this->connectionPool[$serviceName] = $connection;
119
120
        return $this;
121
    }
122
123
    /**
124
     * Creates a feedback service connection
125
     *
126
     * @param string $serviceName
127
     * @return ServiceClientInterface
128
     */
129
    private function createFeedbackConnection($serviceName)
130
    {
131
        $credentials  = $this->getServiceCredentials($serviceName);
132
        return $this->clientFactory->createServiceClient($serviceName, $credentials, true);
133
    }
134
135
    /**
136
     * Tries to connect and send a message to notification service
137
     *
138
     * @param MessageInterface $message
139
     * @return bool
140
     * @throws Zbox\UnifiedPush\Exception\InvalidRecipientException
141
     * @throws Zbox\UnifiedPush\Exception\DispatchMessageException
142
     * @throws Zbox\UnifiedPush\Exception\MalformedNotificationException
143
     */
144
    private function sendMessage(MessageInterface $message)
145
    {
146
        $this->logger->info(
147
            sprintf("Sending message id '%s'", $message->getMessageIdentifier())
148
        );
149
        $builder = new NotificationBuilder($message);
150
151
        while ($notification = $builder->getNotification()) {
152
            try {
153
                $connection = $this->getConnection($message->getMessageType());
154
                $connection->sendNotification($notification);
155
156
            } catch (InvalidRecipientException $e) {
157
                while ($recipient = $e->getRecipient()) {
158
                    $this->application->addInvalidRecipient($message->getMessageType(), $recipient);
159
                }
160
161
            } catch (DispatchMessageException $e) {
162
                $this->logger->warning(
163
                    sprintf("Dispatch message warning with code %d  '%s'", $e->getCode(), $e->getMessage())
164
                );
165
166
            } catch (MalformedNotificationException $e) {
167
                $this->logger->error(
168
                    sprintf("Malformed Notification error: %s", $e->getMessage())
169
                );
170
                return false;
171
            }
172
        }
173
        return true;
174
    }
175
176
    /**
177
     * Tries to dispatch all messages to notification service
178
     *
179
     * @return bool
180
     * @throws Zbox\UnifiedPush\Exception\ClientException
181
     * @throws Zbox\UnifiedPush\Exception\RuntimeException
182
     * @throws \Exception
183
     */
184
    public function dispatch()
185
    {
186
        $messages = $this->application->getMessagesIterator();
187
188
        try {
189
            while ($messages->valid()) {
190
                $message = $messages->current();
191
                if ($this->sendMessage($message)) {
192
                    $messages->offsetUnset($message->getMessageIdentifier());
193
                }
194
                $messages->next();
195
            }
196
        } catch (ClientException $e) {
197
            $this->logger->error(
198
                sprintf("Client connection error: %s", $e->getMessage())
199
            );
200
            return;
201
202
        } catch (RuntimeException $e) {
203
            $this->logger->error(
204
                sprintf("Runtime error: %s", $e->getMessage())
205
            );
206
            return;
207
208
        } catch (\Exception $e) {
209
            $this->logger->error(
210
                sprintf("Error occurs: %s", $e->getMessage())
211
            );
212
            return;
213
        }
214
    }
215
216
    /**
217
     * Tries to connect and load feedback data
218
     *
219
     * @return $this
220
     * @throws RuntimeException
221
     * @throws \Exception
222
     */
223
    public function loadFeedback()
224
    {
225
        $serviceName = NotificationServices::APPLE_PUSH_NOTIFICATIONS_SERVICE;
226
227
        try {
228
            $this->logger->info(sprintf("Querying the feedback service '%s'", $serviceName));
229
230
            $connection = $this->createFeedbackConnection($serviceName);
231
            $invalidRecipients = $connection->readFeedback();
232
233
            while ($invalidRecipients->valid()) {
234
                $recipient = $invalidRecipients->current();
235
                $this->application->addInvalidRecipient($serviceName, $recipient);
236
                $invalidRecipients->next();
237
            }
238
239
        } catch (RuntimeException $e) {
240
            $this->logger->error(
241
                sprintf("Runtime error while acquiring feedback: %s", $e->getMessage())
242
            );
243
244
        } catch (\Exception $e) {
245
            $this->logger->error(
246
                sprintf("Error occurs while acquiring feedback: %s", $e->getMessage())
247
            );
248
        }
249
250
        return $this;
251
    }
252
}
253