Completed
Push — master ( 0ba7dd...4699e0 )
by Dominik
11s
created

AzineTemplateProvider   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 532
Duplicated Lines 8.27 %

Coupling/Cohesion

Components 4
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 53
lcom 4
cbo 4
dl 44
loc 532
ccs 173
cts 173
cp 1
rs 6.96
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
B getParamArrayFor() 0 90 6
A getSnippetArrayFor() 0 37 5
B getCampaignParamsFor() 0 21 6
A addCustomHeaders() 10 22 4
A saveWebViewFor() 0 8 2
A getTemplatesToStoreForWebView() 0 7 1
A getWebViewTokenId() 0 4 1
A __construct() 0 22 4
A getTemplateImageDir() 0 4 1
A addTemplateVariablesFor() 17 29 4
A addTemplateSnippetsWithImagesFor() 17 32 5
A getRouter() 0 4 1
A getTranslator() 0 8 2
B makeImagePathsWebRelative() 0 20 6
A isFileAllowed() 0 11 3
A getFolderFrom() 0 8 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AzineTemplateProvider 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 AzineTemplateProvider, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Azine\EmailBundle\Services;
4
5
/*
6
 * This Service provides the templates and template-variables to be used for emails
7
 * @author Dominik Businger
8
 */
9
use Azine\EmailBundle\DependencyInjection\AzineEmailExtension;
10
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
11
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
12
use Symfony\Component\Translation\TranslatorInterface;
13
14
class AzineTemplateProvider implements TemplateProviderInterface
15
{
16
    const BASE_TEMPLATE = 'AzineEmailBundle::baseEmailLayout';
17
    const NEWSLETTER_TEMPLATE = 'AzineEmailBundle::newsletterEmailLayout';
18
    const NOTIFICATIONS_TEMPLATE = 'AzineEmailBundle::notificationsEmailLayout';
19
    const CONTENT_ITEM_MESSAGE_TEMPLATE = 'AzineEmailBundle:contentItem:message';
20
    const FOS_USER_PWD_RESETTING_TEMPLATE = '@FOSUser/Resetting/email';
21
    const FOS_USER_REGISTRATION_TEMPLATE = '@FOSUser/Registration/email';
22
    const FOS_USER_CONFIRM_EMAIL_UPDATE = '@FOSUser/Profile/email_update_confirmation';
23
    const SEND_IMMEDIATELY_FLAG = 'AzineEmailBundle_SendThisEmailImmediately';
24
25
    /**
26
     * Override this function for your template(s)!
27
     *
28
     * For each template you like to render, you need to supply the array with variables that can be passed to the twig renderer.
29
     * Those variables can then be used in the twig-template => {{ logo_png }}
30
     *
31
     * In this function you should fill a set of variables for each template.
32
     *
33
     * @param string $template the template id in standard-notation, without the ending ( .txt.twig) => "AcmeFooBundle:bar:default"
34
     *
35
     * @return array
36
     */
37 11
    protected function getParamArrayFor($template)
38
    {
39
        // this implementation uses the same array for all templates.
40
        // override this function with a more sophisticated logic
41
        // if you need different styles for different templates.
42
43 11
        $newVars = array();
44
45
        // add template-specific stuff.
46 11
        if (self::NOTIFICATIONS_TEMPLATE == $template) {
47 1
            $newVars['subject'] = 'Your notifications sent by AzineEmailBundle';
48
        }
49
50 11
        if (self::NEWSLETTER_TEMPLATE == $template) {
51 5
            $newVars['subject'] = 'Newsletter sent by AzineEmailBundle';
52
        }
53
54
        // send some mails immediately instead of spooled
55 11
        if (self::FOS_USER_PWD_RESETTING_TEMPLATE == $template
56 10
            || self::FOS_USER_REGISTRATION_TEMPLATE == $template
57 11
            || self::FOS_USER_CONFIRM_EMAIL_UPDATE == $template
58
        ) {
59 3
            $newVars[self::SEND_IMMEDIATELY_FLAG] = true;
60
        }
61
62
        // add generic stuff needed for all templates
63
64
        // add images to be encoded and attached to the email
65
        // the absolute file-path will be replaced with the CID of
66
        // the attached image, so it will be rendered in the html-email.
67
        // => to render the logo inside your twig-template you can write:
68
        // <html><body> ... <img src="{{ logo_png }}" alt="logo"> ... </body></html>
69 11
        $imagesDir = $this->getTemplateImageDir();
70 11
        $newVars['logo_png'] = $imagesDir.'logo.png';
71 11
        $newVars['bottom_shadow_png'] = $imagesDir.'bottomshadow.png';
72 11
        $newVars['top_shadow_png'] = $imagesDir.'topshadow.png';
73 11
        $newVars['left_shadow_png'] = $imagesDir.'left-shadow.png';
74 11
        $newVars['right_shadow_png'] = $imagesDir.'right-shadow.png';
75 11
        $newVars['placeholder_png'] = $imagesDir.'placeholder.png';
76
77
        // define some colors to be reused in the following style-definitions
78 11
        $azGreen = 'green';
79 11
        $azBlue = 'blue';
80 11
        $blackColor = 'black';
81 11
        $lightGray = '#EEEEEE';
82
83
        // add html-styles for your html-emails
84
        // css does not work in html-emails, so all styles need to be
85
        // embeded directly into the html-elements
86 11
        $newVars['azGreen'] = $azGreen;
87 11
        $newVars['azBlue'] = $azBlue;
88 11
        $newVars['blackColor'] = $blackColor;
89 11
        $newVars['lightGray'] = $lightGray;
90 11
        $newVars['bodyBackgroundColor'] = '#fdfbfa';
91 11
        $newVars['contentBackgroundColor'] = '#f2f1f0';
92 11
        $fontFamily = 'Arial, Helvetica, sans-serif';
93 11
        $newVars['fontFamily'] = $fontFamily;
94 11
        $newVars['emailWidth'] = 640; // width for the whole email-body
95 11
        $newVars['shadowWidth'] = 10; // width for the shadows left and right of the content
96 11
        $newVars['contentWidth'] = 620; // width for the mail content
97 11
        $newVars['mediaQueryWidth'] = 479; // width for the media-query for mobile devices
98 11
        $newVars['mobileEmailWidth'] = 459; // width for the whole email-body for mobile devices
99 11
        $newVars['mobileContentWidth'] = 439; // width for the mail content for mobile devices
100 11
        $newVars['footerBackgroundColor'] = '#434343';
101
102 11
        $newVars['h1Style'] = "style='padding:0; margin:0; font:bold 30px $fontFamily; color:$azBlue; text-decoration:none;'";
103 11
        $newVars['h2Style'] = "style='padding:0; margin:0; font:bold 24px $fontFamily; color:$azBlue; text-decoration:none;'";
104 11
        $newVars['h3Style'] = "style='margin:12px 0 5px 0; font:bold 18px $fontFamily; padding:0; color:$azGreen; text-decoration:none;'";
105 11
        $newVars['h4Style'] = "style='padding:0; margin:0 0 20px 0; color:$blackColor; font-size:14px; text-decoration:none;'";
106 11
        $newVars['smallGreyStyle'] = "style='color: grey; font: $fontFamily 11px;'";
107 11
        $newVars['salutationStyle'] = "style='color:$azBlue; font:bold 16px $fontFamily;'";
108 11
        $newVars['smallerTextStyle'] = "style='font: normal 13px/18px $fontFamily;'";
109 11
        $newVars['dateStyle'] = "style='padding:0; margin:5px 0; color:$blackColor; font-weight:bold; font-size:12px;'";
110 11
        $newVars['readMoreLinkStyle'] = "style='color:$azGreen; text-decoration:none; font-size:13px;'";
111 11
        $newVars['titleLinkStyle'] = "style='text-decoration:none;'";
112 11
        $newVars['salutationStyle'] = "style='color:$azBlue; font:bold 16px Arial;'";
113 11
        $newVars['dateStyle'] = "style='padding:0; margin:5px 0; color:$blackColor; font-weight:bold; font-size:12px;'";
114 11
        $newVars['smallerTextStyle'] = "style='font: normal 13px/18px Arial, Helvetica, sans-serif;'";
115 11
        $newVars['actionButtonStyle'] = "style='font-weight: bold; background: none repeat scroll 0 0 #DF940B; border: 1px solid orange; border-radius: 5px; box-shadow: 0 1px 0 #DF940B inset; color: white; padding: 10px;'";
116 11
        $newVars['sloganStyle'] = "style='font-size: 16px; color:$blackColor; margin: 0px; padding: 0px;'";
117
118
        // some simple txt styling elements
119 11
        $newVars['txtH1Style'] = '////////////////////////////////////////////////////////////////////////////////';
120 11
        $newVars['txtH2Style'] = '================================================================================';
121 11
        $newVars['txtH3Style'] = '--------------------------------------------------------------------------------';
122 11
        $newVars['txtH4Style'] = "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''";
123 11
        $newVars['txtHR'] = '________________________________________________________________________________';
124
125 11
        return $newVars;
126
    }
127
128
    /**
129
     * Override this function for your template(s) if you use other "snippets" with embedded images.
130
     *
131
     * This function adds more complex elements to the array of variables that are passed
132
     * to the twig-renderer, just before sending the mail.
133
     *
134
     * In this implementation for example some reusable "snippets" are added to render
135
     * a nice shadow around content parts and add a "link to top" at the top of each part.
136
     *
137
     * As these "snippets" contain references to images that first had to be embedded into the
138
     * Message, these "snippets" are added after embedding/adding the attachments.
139
     *
140
     * This means, that here the variable "bottom_shadow_png" defined in AzineTemplateProvider.fillParamArrayFor()
141
     * does not contain the path to the image-file anymore but now contains the CID of the embedded image.
142
     *
143
     * @param string $template    the template id in standard-notation, without the ending ( .txt.twig) => "AcmeFooBundle:bar:default"
144
     * @param array  $vars
145
     * @param string $emailLocale
146
     *
147
     * @throws \Exception
148
     *
149
     * @return array of strings
150
     */
151 11
    protected function getSnippetArrayFor($template, array $vars, $emailLocale)
152
    {
153
        // this implementation uses the same snippets for all templates.
154
        // override this function with a more sophisticated logic
155
        // if you need different snippets for different templates.
156
157
        // the snippets added in this implementation depend on the
158
        // following images, so they must be present in the $vars-array
159
        if (
160 11
                !array_key_exists('bottom_shadow_png', $vars) ||
161 10
                !array_key_exists('top_shadow_png', $vars) ||
162 10
                !array_key_exists('left_shadow_png', $vars) ||
163 11
                !array_key_exists('right_shadow_png', $vars)
164
        ) {
165 1
            throw new \Exception('some required images are not yet added to the template-vars array.');
166
        }
167
168 10
        $snippets = array();
169
170
        // define some vars that are used several times
171 10
        $lightGray = $vars['lightGray'];
172 10
        $blackColor = $vars['blackColor'];
173 10
        $upLinkTitle = $this->getTranslator($emailLocale)->trans('html.email.go.to.top.link.label', array(), 'messages', $emailLocale);
174 9
        $fontFamily = $vars['fontFamily'];
175
176
        // create and add html-elements for easy reuse in the twig-templates
177 9
        $snippets['linkToTop'] = "<a href='#top' style='text-decoration:none;color:$blackColor' title='$upLinkTitle'>Λ</a>";
178 9
        $snippets['tableOpen'] = "<table summary='box with shadows' class='emailWidth' width='".$vars['emailWidth']."' border='0' align='center' cellpadding='0' cellspacing='0'  style='font: normal 14px/18px $fontFamily;'>";
179 9
        $snippets['topShadow'] = $snippets['tableOpen']."<tr><td class='emailWidth'  colspan='3' width='".$vars['emailWidth']."'><img class='emailWidth' width='".$vars['emailWidth']."' height='10' src='".$vars['top_shadow_png']."' alt='' style='vertical-align: bottom;'/></td></tr>";
180 9
        $snippets['leftShadow'] = "<tr><td width='10' style='border-right: 1px solid $lightGray; background-image: url(\"".$vars['left_shadow_png']."\");'>&nbsp;</td>";
181 9
        $snippets['rightShadow'] = "<td width='10' style='border-left: 1px solid $lightGray; background-image: url(\"".$vars['right_shadow_png']."\");'>&nbsp;</td></tr>";
182 9
        $snippets['bottomShadow'] = "	<tr><td colspan='3' class='emailWidth' width='".$vars['emailWidth']."'><img src='".$vars['bottom_shadow_png']."' class='emailWidth' width='".$vars['emailWidth']."' height='10' alt='' style='vertical-align: top;'/></td></tr></table>";
183 9
        $snippets['linkToTopRow'] = $snippets['leftShadow']."<td width='610' bgcolor='white' style='text-align: right; padding: 5px 5px 0; border-top: 1px solid $lightGray;'>".$snippets['linkToTop'].'</td>'.$snippets['rightShadow'];
184 9
        $snippets['cellSeparator'] = '</td>'.$snippets['rightShadow'].$snippets['bottomShadow'].$snippets['topShadow'].$snippets['linkToTopRow'].$snippets['leftShadow']."<td bgcolor='white' width='580' align='left' valign='top' style='padding:10px 20px 20px 20px;'>";
185
186 9
        return $snippets;
187
    }
188
189
    /**
190
     * Override this function to define your own campaign-parameters
191
     * (non-PHPdoc).
192
     *
193
     * @see Azine\EmailBundle\Services\TemplateProviderInterface::getCampaignParamsFor()
194
     */
195 8
    public function getCampaignParamsFor($templateId, array $params = null)
196
    {
197
        $campaignParams = array(
198 8
            $this->tracking_params_campaign_medium => 'email',
199 8
            $this->tracking_params_campaign_name => date('y-m-d'),
200
        );
201
202 8
        if (self::NEWSLETTER_TEMPLATE == $templateId) {
203 5
            $campaignParams[$this->tracking_params_campaign_source] = 'newsletter';
204 4
        } elseif (self::NOTIFICATIONS_TEMPLATE == $templateId) {
205 1
            $campaignParams[$this->tracking_params_campaign_source] = 'mailnotify';
206 4
        } elseif (self::CONTENT_ITEM_MESSAGE_TEMPLATE == $templateId) {
207 1
            $campaignParams[$this->tracking_params_campaign_content] = 'message';
208
209
        // don't track password-reset emails
210 3
        } elseif (self::FOS_USER_PWD_RESETTING_TEMPLATE == $templateId || self::FOS_USER_REGISTRATION_TEMPLATE == $templateId) {
211 2
            $campaignParams = array();
212
        }
213
214 8
        return $campaignParams;
215
    }
216
217
    /**
218
     * Override this function if you want to add extra headers to the messages sent.
219
     * (non-PHPdoc).
220
     *
221
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::addCustomHeaders()
222
     */
223 6
    public function addCustomHeaders($template, \Swift_Message $message, array $params)
224
    {
225
        //$headerSet = $message->getHeaders();
226
        //$headerSet->addTextHeader($name, $vale);
227 6
        if (array_key_exists($this->getWebViewTokenId(), $params)) {
228
229
            $headerSet = $message->getHeaders();
230
            $headerSet->addTextHeader('x-azine-webview-token', $params[$this->getWebViewTokenId()]);
231
        }
232
233 View Code Duplication
        if (array_key_exists(AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_NAME, $params)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
234 8
235
            $headerSet = $message->getHeaders();
236 8
            $headerSet->addTextHeader('x-utm_campaign', $params[AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_NAME]);
237 5
        }
238
239 View Code Duplication
        if (array_key_exists(AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_SOURCE, $params)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
240 4
241
            $headerSet = $message->getHeaders();
242
            $headerSet->addTextHeader('x-utm_source', $params[AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_SOURCE]);
243
        }
244
    }
245
246
    /**
247
     * (non-PHPdoc).
248 8
     *
249
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::saveWebViewFor()
250 8
     */
251 8
    public function saveWebViewFor($template)
252
    {
253 8
        if (false !== array_search($template, $this->getTemplatesToStoreForWebView())) {
254
            return true;
255
        }
256
257
        return false;
258
    }
259
260
    /**
261
     * Override this function to define which emails you want to make the web-view available and for which not.
262 8
     *
263
     * @return array of string => the template id in standard-notation, without the ending ( .txt.twig) => "AcmeFooBundle:bar:default"
264 8
     */
265
    protected function getTemplatesToStoreForWebView()
266
    {
267
        $include = array();
268
        $include[] = self::NEWSLETTER_TEMPLATE;
269
270
        return $include;
271
    }
272
273
    /**
274
     * Only override this method if you want to change the ID used in the twig-template for the web-view-link from 'azineEmailWebViewToken' to something else.
275
     * (non-PHPdoc).
276
     *
277
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::getWebViewTokenId()
278
     */
279
    public function getWebViewTokenId()
280
    {
281
        return self::EMAIL_WEB_VIEW_TOKEN;
282
    }
283
284
    //////////////////////////////////////////////////////////////////////////
285
    /* You probably don't need to change or override any of the stuff below */
286
    //////////////////////////////////////////////////////////////////////////
287
288
    const CONTENT_ITEMS = 'contentItems';
289
    const EMAIL_WEB_VIEW_TOKEN = 'azineEmailWebViewToken';
290
291
    /**
292
     * Full filesystem-path to the directory where you store your email-template images.
293
     *
294
     * @var string
295
     */
296
    private $templateImageDir;
297
298
    /**
299
     * List of directories from which images are allowed to be embeded into emails.
300
     *
301
     * @var array of string
302
     */
303
    private $allowedImageFolders = array();
304
305
    /**
306
     * @var UrlGeneratorInterface
307
     */
308
    private $router;
309
310
    /**
311
     * @var TranslatorInterface
312
     */
313
    private $translator;
314
315
    /**
316
     * Array to store all the arrays for the variables/parameters for all the different templates.
317
     *
318
     * @var array of array
319
     */
320
    protected $paramArrays = array();
321
322
    /**
323
     * @var string
324
     */
325
    protected $tracking_params_campaign_source;
326
327
    /**
328
     * @var string
329
     */
330
    protected $tracking_params_campaign_medium;
331
332
    /**
333
     * @var string
334
     */
335
    protected $tracking_params_campaign_content;
336
337 16
    /**
338
     * @var string
339 16
     */
340 16
    protected $tracking_params_campaign_name;
341 16
342 16
    /**
343 16
     * @var string
344
     */
345
    protected $tracking_params_campaign_term;
346 16
347 16
    /**
348 16
     * Array to store all the arrays for the code snippets for all the different temlpates.
349 16
     *
350
     * @var unknown_type
351
     */
352 16
    protected $snippetArrays = array();
353 16
354 16
    public function __construct(UrlGeneratorInterface $router, TranslatorInterface $translator, array $parameters)
355 16
    {
356 16
        $this->router = $router;
357 16
        $this->translator = $translator;
358 16
        $templateImageDir = realpath($parameters[AzineEmailExtension::TEMPLATE_IMAGE_DIR]);
359
        if (false !== $this->templateImageDir) {
360
            $this->templateImageDir = $templateImageDir.'/';
361
        }
362
363
        foreach ($parameters[AzineEmailExtension::ALLOWED_IMAGES_FOLDERS] as $nextFolder) {
364
            $imageFolder = realpath($nextFolder);
365 11
            if (false !== $imageFolder) {
366
                $this->allowedImageFolders[md5($imageFolder)] = $imageFolder.'/';
367 11
            }
368
        }
369
        $this->allowedImageFolders[md5($this->templateImageDir)] = $this->templateImageDir;
370
        $this->tracking_params_campaign_content = $parameters[AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_CONTENT];
371
        $this->tracking_params_campaign_medium = $parameters[AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_MEDIUM];
372
        $this->tracking_params_campaign_name = $parameters[AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_NAME];
373
        $this->tracking_params_campaign_source = $parameters[AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_SOURCE];
374
        $this->tracking_params_campaign_term = $parameters[AzineEmailExtension::TRACKING_PARAM_CAMPAIGN_TERM];
375 11
    }
376
377 11
    /**
378 11
     * (non-PHPdoc).
379
     *
380
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::getTemplateImageDir()
381
     */
382 11
    public function getTemplateImageDir()
383
    {
384
        return $this->templateImageDir;
385 11
    }
386 6
387
    /**
388 6
     * (non-PHPdoc).
389 6
     *
390
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::addTemplateVariablesFor()
391
     */
392 6
    public function addTemplateVariablesFor($template, array $contentVariables)
393
    {
394
        if (!array_key_exists($template, $this->paramArrays)) {
395 6
            $this->paramArrays[$template] = $this->getParamArrayFor($template);
396
        }
397
398 6
        // add vars for main template
399
        $contentVariables = array_merge($this->paramArrays[$template], $contentVariables);
400
401
        // add the template-variables to the contentItem-params-arrays
402 11 View Code Duplication
        if (array_key_exists(self::CONTENT_ITEMS, $contentVariables)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
403
            foreach ($contentVariables[self::CONTENT_ITEMS] as $key => $contentItem) {
404
                // get the key (=> template)
405
                reset($contentItem);
406
                $itemTemplate = key($contentItem);
407
408
                // get the params
409
                $itemParams = $contentItem[$itemTemplate];
410 11
411
                // add params for this template
412 11
                $contentItem[$itemTemplate] = $this->addTemplateVariablesFor($itemTemplate, $itemParams);
413 11
414
                // store back into the main array
415 11
                $contentVariables[self::CONTENT_ITEMS][$key] = $contentItem;
416 11
            }
417
        }
418
419
        return $contentVariables;
420 9
    }
421
422
    /**
423 9
     * (non-PHPdoc).
424 4
     *
425
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::addTemplateSnippetsWithImagesFor()
426 4
     */
427 4
    public function addTemplateSnippetsWithImagesFor($template, array $vars, $emailLocale, $forWebView = false)
428
    {
429
        $channel = $forWebView ? 'webView' : 'email';
430 4
        $templateKey = $channel.$template.$emailLocale;
431
432
        if (!array_key_exists($templateKey, $this->snippetArrays)) {
433 4
            $this->snippetArrays[$templateKey] = $this->getSnippetArrayFor($template, $vars, $emailLocale);
434
        }
435
436 4
        // add vars for main template
437
        $vars = array_merge($this->snippetArrays[$templateKey], $vars);
438
439
        // add the template-code-snippets to the contentItem-params-arrays
440 9 View Code Duplication
        if (array_key_exists(self::CONTENT_ITEMS, $vars)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
441
            foreach ($vars[self::CONTENT_ITEMS] as $key => $contentItem) {
442
                // get the key (=> template)
443
                reset($contentItem);
444
                $itemTemplate = key($contentItem);
445
446 3
                // get the params
447
                $itemParams = $contentItem[$itemTemplate];
448 3
449
                // add params for this template
450
                $contentItem[$itemTemplate] = $this->addTemplateSnippetsWithImagesFor($itemTemplate, $itemParams, $emailLocale, $forWebView);
451
452
                // store back into the main array
453
                $vars[self::CONTENT_ITEMS][$key] = $contentItem;
454
            }
455
        }
456
457
        return $vars;
458
    }
459
460 10
    /**
461
     * @return UrlGeneratorInterface
462 10
     */
463 1
    protected function getRouter()
464
    {
465
        return $this->router;
466 9
    }
467
468
    /**
469
     * Only use the translator here when you already know in which language the user should get the email.
470
     *
471
     * @param string $emailLocale
472
     *
473
     * @throws \Exception
474
     *
475
     * @return Translator
476
     */
477 3
    protected function getTranslator($emailLocale)
478
    {
479 3
        if (null === $emailLocale) {
480 3
            throw new \Exception('Only use the translator here when you already know in which language the user should get the email.');
481
        }
482 3
483 3
        return $this->translator;
484
    }
485 3
486 3
    /**
487 3
     * Recursively replace all absolute image-file-paths with relative web-paths.
488
     *
489 3
     * @param array  $emailVars
490 3
     * @param string $locale
491
     *
492
     * @return array
493
     */
494 3
    public function makeImagePathsWebRelative(array $emailVars, $locale)
495
    {
496
        foreach ($emailVars as $key => $value) {
497
            if (is_string($value) && is_file($value)) {
498
                // check if the file is in an allowed_images_folder
499
                $folderKey = $this->isFileAllowed($value);
500
                if (false !== $folderKey) {
501
                    // replace the fs-path with the web-path
502 9
                    $fsPathToReplace = $this->getFolderFrom($folderKey);
503
                    $filename = substr($value, strlen($fsPathToReplace));
504 9
                    $newValue = $this->getRouter()->generate('azine_email_serve_template_image', array('folderKey' => $folderKey, 'filename' => urlencode($filename), '_locale' => $locale));
505 9
                    $emailVars[$key] = $newValue;
506 9
                }
507 9
            } elseif (is_array($value)) {
508
                $emailVars[$key] = $this->makeImagePathsWebRelative($value, $locale);
509
            }
510
        }
511 2
512
        return $emailVars;
513
    }
514
515
    /**
516
     * (non-PHPdoc).
517
     *
518
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::isFileAllowed()
519 1
     */
520
    public function isFileAllowed($filePath)
521 1
    {
522 1
        $filePath = realpath($filePath);
523
        foreach ($this->allowedImageFolders as $key => $nextFolder) {
524
            if (0 === strpos($filePath, $nextFolder)) {
525 1
                return $key;
526
            }
527
        }
528
529
        return false;
530
    }
531
532
    /**
533
     * (non-PHPdoc).
534
     *
535
     * @see Azine\EmailBundle\Services.TemplateProviderInterface::getFolderFrom()
536
     */
537
    public function getFolderFrom($key)
538
    {
539
        if (array_key_exists($key, $this->allowedImageFolders)) {
540
            return $this->allowedImageFolders[$key];
541
        }
542
543
        return false;
544
    }
545
}
546