Total Complexity | 48 |
Total Lines | 334 |
Duplicated Lines | 0 % |
Changes | 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 | if (SparkPostHelper::getWebhookUsername()) { |
||
234 | $hasSuppliedCredentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW'])); |
||
235 | if ($hasSuppliedCredentials) { |
||
236 | $user = SparkPostHelper::getWebhookUsername(); |
||
237 | $password = SparkPostHelper::getWebhookPassword(); |
||
238 | $isAuthenticated = ($_SERVER['PHP_AUTH_USER'] == $user || $_SERVER['PHP_AUTH_PW'] == $password); |
||
239 | } else { |
||
240 | $isAuthenticated = false; |
||
241 | } |
||
242 | } |
||
243 | |||
244 | $webhookLogDir = Environment::getEnv('SPARKPOST_WEBHOOK_LOG_DIR'); |
||
245 | if ($webhookLogDir) { |
||
246 | $dir = rtrim(Director::baseFolder(), '/') . '/' . rtrim($webhookLogDir, '/'); |
||
247 | |||
248 | if (!is_dir($dir) && Director::isDev()) { |
||
249 | mkdir($dir, 0755, true); |
||
250 | } |
||
251 | |||
252 | if (is_dir($dir)) { |
||
253 | $payload['@headers'] = $req->getHeaders(); |
||
254 | $payload['@isAuthenticated'] = $isAuthenticated; |
||
255 | $prettyPayload = json_encode($payload, JSON_PRETTY_PRINT); |
||
256 | $time = date('Ymd-His'); |
||
257 | file_put_contents($dir . '/' . $time . '_' . $batchId . '.json', $prettyPayload); |
||
258 | } else { |
||
259 | $this->getLogger()->debug("Directory $dir does not exist"); |
||
260 | } |
||
261 | } |
||
262 | |||
263 | if (!$isAuthenticated) { |
||
264 | return $response; |
||
265 | } |
||
266 | |||
267 | try { |
||
268 | $this->processPayload($payload, $batchId); |
||
269 | } catch (Exception $ex) { |
||
270 | // Maybe processing payload will create exceptions, but we |
||
271 | // catch them to send a proper response to the API |
||
272 | $logLevel = self::config()->log_level ? self::config()->log_level : 7; |
||
273 | $this->getLogger()->log($ex->getMessage(), $logLevel); |
||
274 | } |
||
275 | |||
276 | $response->setBody('OK'); |
||
277 | |||
278 | return $response; |
||
279 | } |
||
280 | |||
281 | /** |
||
282 | * Process data |
||
283 | * |
||
284 | * @param array $payload |
||
285 | * @param string $batchId |
||
286 | */ |
||
287 | protected function processPayload(array $payload, $batchId = null) |
||
288 | { |
||
289 | $this->extend('beforeProcessPayload', $payload, $batchId); |
||
290 | |||
291 | $subaccount = SparkPostHelper::getClient()->getSubaccount(); |
||
292 | |||
293 | foreach ($payload as $r) { |
||
294 | $ev = $r['msys']; |
||
295 | |||
296 | // This is a test payload |
||
297 | if (empty($ev)) { |
||
298 | continue; |
||
299 | } |
||
300 | |||
301 | $type = key($ev); |
||
302 | if (!isset($ev[$type])) { |
||
303 | $this->getLogger()->warn("Invalid type $type in SparkPost payload"); |
||
304 | continue; |
||
305 | } |
||
306 | $data = $ev[$type]; |
||
307 | |||
308 | // Ignore events not related to the subaccount we are managing |
||
309 | if (!empty($data['subaccount_id']) && $subaccount && $subaccount != $data['subaccount_id']) { |
||
310 | $this->skipCount++; |
||
311 | continue; |
||
312 | } |
||
313 | |||
314 | $this->eventsCount++; |
||
315 | $this->extend('onAnyEvent', $data, $type); |
||
316 | |||
317 | switch ($type) { |
||
318 | //Click, Open |
||
319 | case SparkPostApiClient::TYPE_ENGAGEMENT: |
||
320 | $this->extend('onEngagementEvent', $data, $type); |
||
321 | break; |
||
322 | //Generation Failure, Generation Rejection |
||
323 | case SparkPostApiClient::TYPE_GENERATION: |
||
324 | $this->extend('onGenerationEvent', $data, $type); |
||
325 | break; |
||
326 | //Bounce, Delivery, Injection, SMS Status, Spam Complaint, Out of Band, Policy Rejection, Delay |
||
327 | case SparkPostApiClient::TYPE_MESSAGE: |
||
328 | $this->extend('onMessageEvent', $data, $type); |
||
329 | break; |
||
330 | //Relay Injection, Relay Rejection, Relay Delivery, Relay Temporary Failure, Relay Permanent Failure |
||
331 | case SparkPostApiClient::TYPE_RELAY: |
||
332 | $this->extend('onRelayEvent', $data, $type); |
||
333 | break; |
||
334 | //List Unsubscribe, Link Unsubscribe |
||
335 | case SparkPostApiClient::TYPE_UNSUBSCRIBE: |
||
336 | $this->extend('onUnsubscribeEvent', $data, $type); |
||
337 | break; |
||
338 | } |
||
339 | } |
||
340 | |||
341 | $this->extend('afterProcessPayload', $payload, $batchId); |
||
342 | } |
||
343 | |||
344 | |||
345 | /** |
||
346 | * Get logger |
||
347 | * |
||
348 | * @return Psr\SimpleCache\CacheInterface |
||
349 | */ |
||
350 | public function getLogger() |
||
353 | } |
||
354 | } |
||
355 |