Total Complexity | 52 |
Total Lines | 351 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 1 | Features | 0 |
Complex classes like SparkPostController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SparkPostController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class SparkPostController extends Controller |
||
20 | { |
||
21 | protected $eventsCount = 0; |
||
22 | protected $skipCount = 0; |
||
23 | private static $allowed_actions = [ |
||
|
|||
24 | 'incoming', |
||
25 | 'test', |
||
26 | 'configure_inbound_emails' |
||
27 | ]; |
||
28 | |||
29 | /** |
||
30 | * Inject public dependencies into the controller |
||
31 | * |
||
32 | * @var array |
||
33 | */ |
||
34 | private static $dependencies = [ |
||
35 | 'logger' => '%$Psr\Log\LoggerInterface', |
||
36 | ]; |
||
37 | |||
38 | /** |
||
39 | * @var Psr\Log\LoggerInterface |
||
40 | */ |
||
41 | public $logger; |
||
42 | |||
43 | public function index(HTTPRequest $req) |
||
48 | ]); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * You can also see /resources/sample.json |
||
53 | * |
||
54 | * @param HTTPRequest $req |
||
55 | */ |
||
56 | public function test(HTTPRequest $req) |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * @link https://support.sparkpost.com/customer/portal/articles/2039614-enabling-inbound-email-relaying-relay-webhooks |
||
79 | * @param HTTPRequest $req |
||
80 | * @return string |
||
81 | */ |
||
82 | public function configure_inbound_emails(HTTPRequest $req) |
||
198 | } |
||
199 | } |
||
200 | |||
201 | /** |
||
202 | * Handle incoming webhook |
||
203 | * |
||
204 | * @link https://developers.sparkpost.com/api/#/reference/webhooks/create-a-webhook |
||
205 | * @link https://www.sparkpost.com/blog/webhooks-beyond-the-basics/ |
||
206 | * @link https://support.sparkpost.com/customer/portal/articles/1976204-webhook-event-reference |
||
207 | * @param HTTPRequest $req |
||
208 | */ |
||
209 | public function incoming(HTTPRequest $req) |
||
210 | { |
||
211 | // Each webhook batch contains the header X-Messagesystems-Batch-Id, |
||
212 | // which is useful for auditing and prevention of processing duplicate batches. |
||
213 | $batchId = $req->getHeader('X-Messagesystems-Batch-Id'); |
||
214 | if (!$batchId) { |
||
215 | $batchId = uniqid(); |
||
216 | } |
||
217 | |||
218 | $json = file_get_contents('php://input'); |
||
219 | |||
220 | // By default, return a valid response |
||
221 | $response = $this->getResponse(); |
||
222 | $response->setStatusCode(200); |
||
223 | $response->setBody('NO DATA'); |
||
224 | |||
225 | if (!$json) { |
||
226 | return $response; |
||
227 | } |
||
228 | |||
229 | $payload = json_decode($json, JSON_OBJECT_AS_ARRAY); |
||
230 | |||
231 | // Check credentials if defined |
||
232 | $isAuthenticated = true; |
||
233 | $authError = null; |
||
234 | if (SparkPostHelper::getWebhookUsername()) { |
||
235 | $requestUser = $req->getHeader('php_auth_user'); |
||
236 | $requestPassword = $req->getHeader('php_auth_pw'); |
||
237 | if (!$requestUser) { |
||
238 | $requestUser = $_SERVER['PHP_AUTH_USER']; |
||
239 | } |
||
240 | if (!$requestPassword) { |
||
241 | $requestPassword = $_SERVER['PHP_AUTH_PW']; |
||
242 | } |
||
243 | |||
244 | $hasSuppliedCredentials = $requestUser && $requestPassword; |
||
245 | if ($hasSuppliedCredentials) { |
||
246 | $user = SparkPostHelper::getWebhookUsername(); |
||
247 | $password = SparkPostHelper::getWebhookPassword(); |
||
248 | $isAuthenticated = ($requestUser == $user && $requestPassword == $password); |
||
249 | if ($user != $requestUser) { |
||
250 | $authError = "User $requestUser doesn't match"; |
||
251 | } elseif ($password != $requestPassword) { |
||
252 | $authError = "Password $requestPassword don't match"; |
||
253 | } |
||
254 | } else { |
||
255 | $isAuthenticated = false; |
||
256 | $authError = "No credentials"; |
||
257 | } |
||
258 | } |
||
259 | |||
260 | $webhookLogDir = Environment::getEnv('SPARKPOST_WEBHOOK_LOG_DIR'); |
||
261 | if ($webhookLogDir) { |
||
262 | $dir = rtrim(Director::baseFolder(), '/') . '/' . rtrim($webhookLogDir, '/'); |
||
263 | |||
264 | if (!is_dir($dir) && Director::isDev()) { |
||
265 | mkdir($dir, 0755, true); |
||
266 | } |
||
267 | |||
268 | if (is_dir($dir)) { |
||
269 | $payload['@headers'] = $req->getHeaders(); |
||
270 | $payload['@isAuthenticated'] = $isAuthenticated; |
||
271 | $payload['@authError'] = $authError; |
||
272 | $prettyPayload = json_encode($payload, JSON_PRETTY_PRINT); |
||
273 | $time = date('Ymd-His'); |
||
274 | file_put_contents($dir . '/' . $time . '_' . $batchId . '.json', $prettyPayload); |
||
275 | } else { |
||
276 | $this->getLogger()->debug("Directory $dir does not exist"); |
||
277 | } |
||
278 | } |
||
279 | |||
280 | if (!$isAuthenticated) { |
||
281 | return $response; |
||
282 | } |
||
283 | |||
284 | try { |
||
285 | $this->processPayload($payload, $batchId); |
||
286 | } catch (Exception $ex) { |
||
287 | // Maybe processing payload will create exceptions, but we |
||
288 | // catch them to send a proper response to the API |
||
289 | $logLevel = self::config()->log_level ? self::config()->log_level : 7; |
||
290 | $this->getLogger()->log($ex->getMessage(), $logLevel); |
||
291 | } |
||
292 | |||
293 | $response->setBody('OK'); |
||
294 | |||
295 | return $response; |
||
296 | } |
||
297 | |||
298 | /** |
||
299 | * Process data |
||
300 | * |
||
301 | * @param array $payload |
||
302 | * @param string $batchId |
||
303 | */ |
||
304 | protected function processPayload(array $payload, $batchId = null) |
||
305 | { |
||
306 | $this->extend('beforeProcessPayload', $payload, $batchId); |
||
307 | |||
308 | $subaccount = SparkPostHelper::getClient()->getSubaccount(); |
||
309 | |||
310 | foreach ($payload as $r) { |
||
311 | $ev = $r['msys']; |
||
312 | |||
313 | // This is a test payload |
||
314 | if (empty($ev)) { |
||
315 | continue; |
||
316 | } |
||
317 | |||
318 | $type = key($ev); |
||
319 | if (!isset($ev[$type])) { |
||
320 | $this->getLogger()->warn("Invalid type $type in SparkPost payload"); |
||
321 | continue; |
||
322 | } |
||
323 | $data = $ev[$type]; |
||
324 | |||
325 | // Ignore events not related to the subaccount we are managing |
||
326 | if (!empty($data['subaccount_id']) && $subaccount && $subaccount != $data['subaccount_id']) { |
||
327 | $this->skipCount++; |
||
328 | continue; |
||
329 | } |
||
330 | |||
331 | $this->eventsCount++; |
||
332 | $this->extend('onAnyEvent', $data, $type); |
||
333 | |||
334 | switch ($type) { |
||
335 | //Click, Open |
||
336 | case SparkPostApiClient::TYPE_ENGAGEMENT: |
||
337 | $this->extend('onEngagementEvent', $data, $type); |
||
338 | break; |
||
339 | //Generation Failure, Generation Rejection |
||
340 | case SparkPostApiClient::TYPE_GENERATION: |
||
341 | $this->extend('onGenerationEvent', $data, $type); |
||
342 | break; |
||
343 | //Bounce, Delivery, Injection, SMS Status, Spam Complaint, Out of Band, Policy Rejection, Delay |
||
344 | case SparkPostApiClient::TYPE_MESSAGE: |
||
345 | $this->extend('onMessageEvent', $data, $type); |
||
346 | break; |
||
347 | //Relay Injection, Relay Rejection, Relay Delivery, Relay Temporary Failure, Relay Permanent Failure |
||
348 | case SparkPostApiClient::TYPE_RELAY: |
||
349 | $this->extend('onRelayEvent', $data, $type); |
||
350 | break; |
||
351 | //List Unsubscribe, Link Unsubscribe |
||
352 | case SparkPostApiClient::TYPE_UNSUBSCRIBE: |
||
353 | $this->extend('onUnsubscribeEvent', $data, $type); |
||
354 | break; |
||
355 | } |
||
356 | } |
||
357 | |||
358 | $this->extend('afterProcessPayload', $payload, $batchId); |
||
359 | } |
||
360 | |||
361 | |||
362 | /** |
||
363 | * Get logger |
||
364 | * |
||
365 | * @return Psr\SimpleCache\CacheInterface |
||
366 | */ |
||
367 | public function getLogger() |
||
370 | } |
||
371 | } |
||
372 |