Complex classes like AzineEmailTemplateController 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 AzineEmailTemplateController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
30 | class AzineEmailTemplateController extends Controller |
||
31 | { |
||
32 | |||
33 | 1 | /** |
|
34 | * Show a set of options to view html- and text-versions of email in the browser and send them as emails to test-accounts |
||
35 | 1 | */ |
|
36 | 1 | public function indexAction(Request $request) |
|
37 | 1 | { |
|
38 | $customEmail = $request->get('customEmail', '[email protected]'); |
||
39 | 1 | $templates = $this->get('azine_email_web_view_service')->getTemplatesForWebPreView(); |
|
40 | 1 | $emails = $this->get('azine_email_web_view_service')->getTestMailAccounts(); |
|
41 | 1 | ||
42 | 1 | return $this->get('templating') |
|
43 | 1 | ->renderResponse("AzineEmailBundle:Webview:index.html.twig", |
|
44 | array( |
||
45 | 'customEmail' => $customEmail, |
||
46 | 'templates' => $templates, |
||
47 | 'emails' => $emails, |
||
48 | )); |
||
49 | } |
||
50 | |||
51 | 1 | /** |
|
52 | * Show a web-preview-version of an email-template, filled with dummy-content |
||
53 | 1 | * @param string $format |
|
54 | 1 | * @return Response |
|
55 | 1 | */ |
|
56 | public function webPreViewAction(Request $request, $template, $format = null) |
||
57 | 1 | { |
|
58 | 1 | ||
59 | if ($format !== "txt") { |
||
60 | $format = "html"; |
||
61 | 1 | } |
|
62 | 1 | ||
63 | 1 | $locale = $request->getLocale(); |
|
64 | |||
65 | // merge request vars with dummyVars, but make sure request vars remain as they are. |
||
66 | 1 | $emailVars = array_merge(array(), $request->query->all()); |
|
67 | $emailVars = $this->get('azine_email_web_view_service')->getDummyVarsFor($template, $locale, $emailVars); |
||
68 | $emailVars = array_merge($emailVars, $request->query->all()); |
||
69 | 1 | ||
70 | 1 | // add the styles |
|
71 | 1 | $emailVars = $this->getTemplateProviderService()->addTemplateVariablesFor($template, $emailVars); |
|
72 | 1 | ||
73 | 1 | // add the from-email for the footer-text |
|
74 | if (!array_key_exists('fromEmail', $emailVars)) { |
||
75 | $noReply = $this->getParameter('azine_email_no_reply'); |
||
76 | 1 | $emailVars['fromEmail'] = $noReply['email']; |
|
77 | $emailVars['fromName'] = $noReply['name']; |
||
78 | } |
||
79 | 1 | ||
80 | // set the emailLocale for the templates |
||
81 | $emailVars['emailLocale'] = $locale; |
||
82 | 1 | ||
83 | // replace absolute image-paths with relative ones. |
||
84 | $emailVars = $this->getTemplateProviderService()->makeImagePathsWebRelative($emailVars, $locale); |
||
85 | 1 | ||
86 | // add code-snippets |
||
87 | $emailVars = $this->getTemplateProviderService()->addTemplateSnippetsWithImagesFor($template, $emailVars, $locale); |
||
88 | 1 | ||
89 | 1 | // render & return email |
|
90 | 1 | $response = $this->renderResponse("$template.$format.twig", $emailVars); |
|
91 | 1 | ||
92 | 1 | // add campaign tracking params |
|
93 | $campaignParams = $this->getTemplateProviderService()->getCampaignParamsFor($template, $emailVars); |
||
94 | 1 | $campaignParams['utm_medium'] = 'webPreview'; |
|
95 | 1 | if(sizeof($campaignParams) > 0) { |
|
96 | $htmlBody = $response->getContent(); |
||
97 | 1 | $htmlBody = $this->get("azine.email.bundle.twig.filters")->addCampaignParamsToAllUrls($htmlBody, $campaignParams); |
|
98 | 1 | ||
99 | $emailOpenTrackingCodeBuilder = $this->get('azine_email_email_open_tracking_code_builder'); |
||
100 | 1 | if ($emailOpenTrackingCodeBuilder) { |
|
101 | 1 | // add an image at the end of the html tag with the tracking-params to track email-opens |
|
102 | 1 | $imgTrackingCode = $emailOpenTrackingCodeBuilder->getTrackingImgCode($template, $campaignParams, $emailVars, "dummy", "[email protected]", null, null); |
|
103 | 1 | if ($imgTrackingCode && strlen($imgTrackingCode) > 0) { |
|
104 | 1 | // replace the tracking url, so no request is made to the real tracking system. |
|
105 | 1 | $imgTrackingCode = str_replace("://", "://webview-dummy-domain.", $imgTrackingCode); |
|
106 | 1 | $htmlCloseTagPosition = strpos($htmlBody, "</html>"); |
|
107 | $htmlBody = substr_replace($htmlBody, $imgTrackingCode, $htmlCloseTagPosition, 0); |
||
108 | } |
||
109 | 1 | } |
|
110 | $response->setContent($htmlBody); |
||
111 | 1 | } |
|
112 | |||
113 | // if the requested format is txt, remove the html-part |
||
114 | 1 | if ($format == "txt") { |
|
115 | 1 | // set the correct content-type |
|
116 | 1 | $response->headers->set("Content-Type","text/plain"); |
|
117 | 1 | ||
118 | // cut away the html-part |
||
119 | 1 | $content = $response->getContent(); |
|
120 | $textEnd = stripos($content, "<!doctype"); |
||
121 | $response->setContent(substr($content, 0, $textEnd)); |
||
122 | } |
||
123 | |||
124 | return $response; |
||
125 | } |
||
126 | 6 | ||
127 | /** |
||
128 | * Show a web-version of an email that has been sent to recipients and has been stored in the database. |
||
129 | 6 | * @param string $token |
|
130 | */ |
||
131 | public function webViewAction ($token) |
||
132 | 6 | { |
|
133 | // find email recipients, template & params |
||
134 | $sentEmail = $this->getSentEmailForToken($token); |
||
135 | 5 | ||
136 | // check if the sent email is available |
||
137 | 3 | if ($sentEmail != null) { |
|
138 | 3 | ||
139 | // check if the current user is allowed to see the email |
||
140 | if ($this->userIsAllowedToSeeThisMail($sentEmail)) { |
||
141 | 3 | ||
142 | $template = $sentEmail->getTemplate(); |
||
143 | $emailVars = $sentEmail->getVariables(); |
||
144 | 3 | ||
145 | 3 | // re-attach all entities to the EntityManager. |
|
146 | $this->reAttachAllEntities($emailVars); |
||
147 | |||
148 | 3 | // remove the web-view-token from the param-array |
|
149 | $templateProvider = $this->getTemplateProviderService(); |
||
150 | 3 | unset($emailVars[$templateProvider->getWebViewTokenId()]); |
|
151 | |||
152 | 3 | // render & return email |
|
153 | 1 | $response = $this->renderResponse("$template.html.twig", $emailVars); |
|
154 | 1 | ||
155 | $campaignParams = $templateProvider->getCampaignParamsFor($template, $emailVars); |
||
156 | 3 | ||
157 | if (sizeof($campaignParams) > 0) { |
||
158 | $response->setContent($this->get("azine.email.bundle.twig.filters")->addCampaignParamsToAllUrls($response->getContent(), $campaignParams)); |
||
159 | } |
||
160 | 2 | ||
161 | 2 | return $response; |
|
162 | |||
163 | // if the user is not allowed to see this mail |
||
164 | } else { |
||
165 | $msg = $this->get('translator')->trans('web.pre.view.test.mail.access.denied'); |
||
166 | 1 | throw new AccessDeniedException($msg); |
|
167 | 1 | } |
|
168 | 1 | } |
|
169 | |||
170 | 1 | // the parameters-array is null => the email is not available in webView |
|
171 | $days = $this->getParameter("azine_email_web_view_retention"); |
||
172 | $response = $this->renderResponse("AzineEmailBundle:Webview:mail.not.available.html.twig", array('days' => $days)); |
||
173 | $response->setStatusCode(404); |
||
174 | |||
175 | return $response; |
||
176 | } |
||
177 | |||
178 | /** |
||
179 | * Check if the user is allowed to see the email. |
||
180 | 5 | * => the mail is public or the user is among the recipients or the user is an admin. |
|
181 | * |
||
182 | 5 | * @param SentEmail $mail |
|
183 | * @return boolean |
||
184 | */ |
||
185 | 5 | private function userIsAllowedToSeeThisMail(SentEmail $mail) |
|
186 | 1 | { |
|
187 | $recipients = $mail->getRecipients(); |
||
188 | |||
189 | // it is a public email |
||
190 | 4 | if ($recipients == null) { |
|
191 | 4 | return true; |
|
192 | } |
||
193 | |||
194 | // get the current user |
||
195 | $currentUser = null; |
||
196 | if (!$this->has('security.token_storage')) { |
||
197 | 4 | // @codeCoverageIgnoreStart |
|
198 | throw new \LogicException('The SecurityBundle is not registered in your application.'); |
||
199 | // @codeCoverageIgnoreEnd |
||
200 | 4 | ||
201 | 3 | } else { |
|
202 | 3 | $token = $this->get('security.token_storage')->getToken(); |
|
203 | |||
204 | // check if the token is not null and the user in the token an object |
||
205 | if ($token instanceof TokenInterface && is_object($token->getUser())) { |
||
206 | 4 | $currentUser = $token->getUser(); |
|
207 | } |
||
208 | } |
||
209 | 3 | ||
210 | // it is not a public email, and a user is logged in |
||
211 | 3 | if ($currentUser != null) { |
|
212 | |||
213 | // the user is among the recipients |
||
214 | 2 | if(array_search($currentUser->getEmail(), $recipients) !== false) |
|
215 | |||
216 | 2 | return true; |
|
217 | 1 | ||
218 | // the user is admin |
||
219 | if($currentUser->hasRole("ROLE_ADMIN")) |
||
220 | |||
221 | return true; |
||
222 | } |
||
223 | 2 | ||
224 | // not public email, but |
||
225 | // - there is no user, or |
||
226 | // - the user is not among the recipients and |
||
227 | // - the user not an admin-user either |
||
228 | return false; |
||
229 | } |
||
230 | |||
231 | /** |
||
232 | * Replace all unmanaged Objects in the array (recursively) |
||
233 | * by managed Entities fetched via Doctrine EntityManager. |
||
234 | * |
||
235 | * It is assumed that managed objects can be identified |
||
236 | 3 | * by their id and implement the function getId() to get that id. |
|
237 | * |
||
238 | 3 | * @param array $vars passed by reference & manipulated but not returned. |
|
239 | 3 | * @return null |
|
240 | */ |
||
241 | private function reAttachAllEntities(array &$vars) |
||
242 | { |
||
243 | $em = $this->get('doctrine')->getManager(); |
||
244 | foreach ($vars as $key => $next) { |
||
245 | if (is_object($next) && method_exists($next, 'getId')) { |
||
246 | $className = get_class($next); |
||
247 | $managedEntity = $em->find($className, $next->getId()); |
||
248 | if ($managedEntity) { |
||
249 | $vars[$key] = $managedEntity; |
||
250 | } |
||
251 | 3 | continue; |
|
252 | } elseif (is_array($next)) { |
||
253 | 3 | $this->reAttachAllEntities($next); |
|
254 | continue; |
||
255 | } |
||
256 | } |
||
257 | |||
258 | } |
||
259 | |||
260 | /** |
||
261 | 2 | * Serve the image from the templates-folder |
|
262 | * @param string $filename |
||
263 | 2 | * @param string $folderKey |
|
264 | 2 | * @return \Symfony\Component\HttpFoundation\BinaryFileResponse |
|
265 | 1 | */ |
|
266 | 1 | public function serveImageAction($folderKey, $filename) |
|
267 | 1 | { |
|
268 | 1 | $folder = $this->getTemplateProviderService()->getFolderFrom($folderKey); |
|
269 | if ($folder !== false) { |
||
270 | 1 | $fullPath = $folder.$filename; |
|
271 | $response = BinaryFileResponse::create($fullPath); |
||
272 | $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE); |
||
273 | 1 | $response->headers->set("Content-Type", "image"); |
|
274 | |||
275 | return $response; |
||
276 | } |
||
277 | |||
278 | throw new FileNotFoundException($filename); |
||
279 | 6 | } |
|
280 | |||
281 | 6 | /** |
|
282 | * @return TemplateProviderInterface |
||
283 | */ |
||
284 | protected function getTemplateProviderService() |
||
285 | { |
||
286 | return $this->get('azine_email_template_provider'); |
||
287 | } |
||
288 | |||
289 | /** |
||
290 | 5 | * @param string $view |
|
291 | * @param array $parameters |
||
292 | 5 | * @param Response $response |
|
293 | * @return Response |
||
294 | */ |
||
295 | protected function renderResponse($view, array $parameters = array(), Response $response = null) |
||
296 | { |
||
297 | return $this->get('templating')->renderResponse($view, $parameters, $response); |
||
298 | } |
||
299 | |||
300 | 6 | /** |
|
301 | * Get the sent email from the database |
||
302 | 6 | * @param string $token the token identifying the sent email |
|
303 | * @return SentEmail |
||
304 | 6 | */ |
|
305 | protected function getSentEmailForToken($token) |
||
306 | { |
||
307 | $sentEmail = $this->get('doctrine')->getRepository('AzineEmailBundle:SentEmail')->findOneByToken($token); |
||
308 | |||
309 | return $sentEmail; |
||
310 | } |
||
311 | |||
312 | /** |
||
313 | * Send a test-mail for the template to the given email-address |
||
314 | * @param string $template templateId without ending => AzineEmailBundle::baseEmailLayout (without .txt.twig) |
||
315 | * @param string $email |
||
316 | * @return \Symfony\Component\HttpFoundation\RedirectResponse |
||
317 | */ |
||
318 | public function sendTestEmailAction(Request $request, $template, $email) |
||
319 | { |
||
320 | $locale = $request->getLocale(); |
||
321 | |||
322 | // get the email-vars for email-sending => absolute fs-paths to images |
||
323 | $emailVars = $this->get('azine_email_web_view_service')->getDummyVarsFor($template, $locale); |
||
324 | |||
325 | // send the mail |
||
326 | $message = \Swift_Message::newInstance(); |
||
327 | $mailer = $this->get("azine_email_template_twig_swift_mailer"); |
||
328 | $sent = $mailer->sendSingleEmail($email, "Test Recipient", $emailVars['subject'], $emailVars, $template.".txt.twig", $locale, $emailVars['sendMailAccountAddress'], $emailVars['sendMailAccountName']." (Test)", $message); |
||
329 | |||
330 | $spamReport = $this->getSpamIndexReportForSwiftMessage($message); |
||
331 | if (is_array($spamReport)) { |
||
332 | if ($spamReport['curlHttpCode'] == 200 && $spamReport['success']) { |
||
333 | $spamScore = $spamReport['score']; |
||
334 | $spamInfo = "SpamScore: $spamScore! \n".$spamReport['report']; |
||
335 | } else { |
||
336 | //@codeCoverageIgnoreStart |
||
337 | // this only happens if the spam-check-server has a problem / is not responding |
||
338 | $spamScore = 10; |
||
339 | $spamInfo = "Getting the spam-info failed. |
||
340 | HttpCode: ".$spamReport['curlHttpCode']." |
||
341 | SpamReportMsg: ".$spamReport['message']; |
||
342 | if(array_key_exists('curlError', $spamReport)) { |
||
343 | $spamInfo .= " |
||
344 | cURL-Error: " . $spamReport['curlError']; |
||
345 | } |
||
346 | //@codeCoverageIgnoreEnd |
||
347 | } |
||
348 | |||
349 | if ($spamScore <= 2) { |
||
350 | $request->getSession()->getFlashBag()->add('info', $spamInfo); |
||
351 | } elseif ($spamScore > 2 && $spamScore < 5) { |
||
352 | $request->getSession()->getFlashBag()->add('warn', $spamInfo); |
||
353 | } else { |
||
354 | $request->getSession()->getFlashBag()->add('error', $spamInfo); |
||
355 | } |
||
356 | |||
357 | } |
||
358 | |||
359 | // inform about sent/failed emails |
||
360 | if ($sent) { |
||
361 | $msg = $this->get('translator')->trans('web.pre.view.test.mail.sent.for.%template%.to.%email%', array('%template%' => $template, '%email%' => $email)); |
||
362 | $this->getSession()->getFlashBag()->add('info', $msg); |
||
|
|||
363 | |||
364 | //@codeCoverageIgnoreStart |
||
365 | } else { |
||
366 | // this only happens if the mail-server has a problem |
||
367 | $msg = $this->get('translator')->trans('web.pre.view.test.mail.failed.for.%template%.to.%email%', array('%template%' => $template, '%email%' => $email)); |
||
368 | $this->getSession()->getFlashBag()->add('warn', $msg); |
||
369 | //@codeCoverageIgnoreStart |
||
370 | } |
||
371 | |||
372 | // show the index page again. |
||
373 | return new RedirectResponse($this->get('router')->generate('azine_email_template_index', array('customEmail' => $email))); |
||
374 | } |
||
375 | |||
376 | /** |
||
377 | * Make an RESTful call to http://spamcheck.postmarkapp.com/filter to test the emails-spam-index. |
||
378 | * See http://spamcheck.postmarkapp.com/doc |
||
379 | * @return array TestResult array('success', 'message', 'curlHttpCode', 'curlError', ['score', 'report']) |
||
380 | */ |
||
381 | public function getSpamIndexReportForSwiftMessage(\Swift_Message $message, $report = 'long') |
||
385 | |||
386 | 2 | /** |
|
387 | * @param $msgString |
||
388 | * @param string $report |
||
389 | * @return mixed |
||
390 | */ |
||
391 | private function getSpamIndexReport($msgString, $report = 'long') |
||
436 | |||
437 | 1 | /** |
|
438 | 1 | * Ajax action to check the spam-score for the pasted email-source |
|
439 | 1 | */ |
|
440 | 1 | public function checkSpamScoreOfSentEmailAction(Request $request) |
|
441 | 1 | { |
|
442 | 1 | $msgString = $request->get('emailSource'); |
|
443 | 1 | $spamReport = $this->getSpamIndexReport($msgString); |
|
444 | $spamInfo = ""; |
||
445 | if (is_array($spamReport)) { |
||
446 | if (array_key_exists('curlHttpCode', $spamReport) && $spamReport['curlHttpCode'] == 200 && $spamReport['success'] && array_key_exists('score', $spamReport)) { |
||
470 | } |
||
471 |
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.