BuilderSubscriber   F
last analyzed

Complexity

Total Complexity 62

Size/Duplication

Total Lines 681
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 393
dl 0
loc 681
rs 3.44
c 0
b 0
f 0
wmc 62

15 Methods

Rating   Name   Duplication   Size   Complexity  
A renderPreferredChannel() 0 11 2
A getAttributeForFirtSlot() 0 3 1
A renderChannelFrequency() 0 11 2
A renderSegmentList() 0 11 2
A renderCategoryList() 0 11 2
A renderSavePrefs() 0 11 2
A renderSuccessMessage() 0 11 2
B renderLanguageBar() 0 63 10
A renderSocialShareButtons() 0 18 3
F onPageDisplay() 0 139 23
A getSubscribedEvents() 0 8 1
A onEmailBuild() 0 5 2
A onEmailGenerate() 0 8 2
A __construct() 0 18 1
B onPageBuild() 0 221 7

How to fix   Complexity   

Complex Class

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

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\PageBundle\EventListener;
13
14
use Doctrine\DBAL\Connection;
15
use DOMDocument;
16
use DOMXPath;
17
use Mautic\CoreBundle\Form\Type\GatedVideoType;
18
use Mautic\CoreBundle\Form\Type\SlotButtonType;
19
use Mautic\CoreBundle\Form\Type\SlotCategoryListType;
20
use Mautic\CoreBundle\Form\Type\SlotChannelFrequencyType;
21
use Mautic\CoreBundle\Form\Type\SlotCodeModeType;
22
use Mautic\CoreBundle\Form\Type\SlotDwcType;
23
use Mautic\CoreBundle\Form\Type\SlotImageCaptionType;
24
use Mautic\CoreBundle\Form\Type\SlotImageCardType;
25
use Mautic\CoreBundle\Form\Type\SlotImageType;
26
use Mautic\CoreBundle\Form\Type\SlotPreferredChannelType;
27
use Mautic\CoreBundle\Form\Type\SlotSavePrefsButtonType;
28
use Mautic\CoreBundle\Form\Type\SlotSegmentListType;
29
use Mautic\CoreBundle\Form\Type\SlotSeparatorType;
30
use Mautic\CoreBundle\Form\Type\SlotSocialFollowType;
31
use Mautic\CoreBundle\Form\Type\SlotSocialShareType;
32
use Mautic\CoreBundle\Form\Type\SlotSuccessMessageType;
33
use Mautic\CoreBundle\Form\Type\SlotTextType;
34
use Mautic\CoreBundle\Helper\BuilderTokenHelperFactory;
35
use Mautic\CoreBundle\Helper\TemplatingHelper;
36
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
37
use Mautic\EmailBundle\EmailEvents;
38
use Mautic\EmailBundle\Event\EmailBuilderEvent;
39
use Mautic\EmailBundle\Event\EmailSendEvent;
40
use Mautic\PageBundle\Event as Events;
41
use Mautic\PageBundle\Helper\TokenHelper;
42
use Mautic\PageBundle\Model\PageModel;
43
use Mautic\PageBundle\PageEvents;
44
use Mautic\PluginBundle\Helper\IntegrationHelper;
45
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
46
use Symfony\Component\Translation\TranslatorInterface;
47
48
class BuilderSubscriber implements EventSubscriberInterface
49
{
50
    /**
51
     * @var TokenHelper
52
     */
53
    private $tokenHelper;
54
55
    /**
56
     * @var IntegrationHelper
57
     */
58
    private $integrationHelper;
59
60
    /**
61
     * @var TranslatorInterface
62
     */
63
    private $translator;
64
65
    /**
66
     * @var Connection
67
     */
68
    private $connection;
69
70
    /**
71
     * @var CorePermissions
72
     */
73
    private $security;
74
75
    /**
76
     * @var TemplatingHelper
77
     */
78
    private $templating;
79
80
    /**
81
     * @var BuilderTokenHelperFactory
82
     */
83
    private $builderTokenHelperFactory;
84
85
    /**
86
     * @var PageModel
87
     */
88
    private $pageModel;
89
    private $pageTokenRegex      = '{pagelink=(.*?)}';
90
    private $dwcTokenRegex       = '{dwc=(.*?)}';
91
    private $langBarRegex        = '{langbar}';
92
    private $shareButtonsRegex   = '{sharebuttons}';
93
    private $titleRegex          = '{pagetitle}';
94
    private $descriptionRegex    = '{pagemetadescription}';
95
96
    const segmentListRegex  = '{segmentlist}';
97
    const categoryListRegex = '{categorylist}';
98
    const channelfrequency  = '{channelfrequency}';
99
    const preferredchannel  = '{preferredchannel}';
100
    const saveprefsRegex    = '{saveprefsbutton}';
101
    const successmessage    = '{successmessage}';
102
    const identifierToken   = '{leadidentifier}';
103
104
    /**
105
     * BuilderSubscriber constructor.
106
     */
107
    public function __construct(
108
        CorePermissions $security,
109
        TokenHelper $tokenHelper,
110
        IntegrationHelper $integrationHelper,
111
        PageModel $pageModel,
112
        BuilderTokenHelperFactory $builderTokenHelperFactory,
113
        TranslatorInterface $translator,
114
        Connection $connection,
115
        TemplatingHelper $templating
116
    ) {
117
        $this->security                  = $security;
118
        $this->tokenHelper               = $tokenHelper;
119
        $this->integrationHelper         = $integrationHelper;
120
        $this->pageModel                 = $pageModel;
121
        $this->builderTokenHelperFactory = $builderTokenHelperFactory;
122
        $this->translator                = $translator;
123
        $this->connection                = $connection;
124
        $this->templating                = $templating;
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130
    public static function getSubscribedEvents()
131
    {
132
        return [
133
            PageEvents::PAGE_ON_DISPLAY   => ['onPageDisplay', 0],
134
            PageEvents::PAGE_ON_BUILD     => ['onPageBuild', 0],
135
            EmailEvents::EMAIL_ON_BUILD   => ['onEmailBuild', 0],
136
            EmailEvents::EMAIL_ON_SEND    => ['onEmailGenerate', 0],
137
            EmailEvents::EMAIL_ON_DISPLAY => ['onEmailGenerate', 0],
138
        ];
139
    }
140
141
    /**
142
     * Add forms to available page tokens.
143
     */
144
    public function onPageBuild(Events\PageBuilderEvent $event)
145
    {
146
        $tokenHelper = $this->builderTokenHelperFactory->getBuilderTokenHelper('page');
147
148
        if ($event->abTestWinnerCriteriaRequested()) {
149
            //add AB Test Winner Criteria
150
            $bounceRate = [
151
                'group'    => 'mautic.page.abtest.criteria',
152
                'label'    => 'mautic.page.abtest.criteria.bounce',
153
                'event'    => PageEvents::ON_DETERMINE_BOUNCE_RATE_WINNER,
154
            ];
155
            $event->addAbTestWinnerCriteria('page.bouncerate', $bounceRate);
156
157
            $dwellTime = [
158
                'group'    => 'mautic.page.abtest.criteria',
159
                'label'    => 'mautic.page.abtest.criteria.dwelltime',
160
                'event'    => PageEvents::ON_DETERMINE_DWELL_TIME_WINNER,
161
            ];
162
            $event->addAbTestWinnerCriteria('page.dwelltime', $dwellTime);
163
        }
164
165
        if ($event->tokensRequested([$this->pageTokenRegex, $this->dwcTokenRegex])) {
166
            $event->addTokensFromHelper($tokenHelper, $this->pageTokenRegex, 'title', 'id', true);
167
168
            // add only filter based dwc tokens
169
            $dwcTokenHelper = $this->builderTokenHelperFactory->getBuilderTokenHelper('dynamicContent', 'dynamiccontent:dynamiccontents');
170
            $expr           = $this->connection->getExpressionBuilder()->andX('e.is_campaign_based <> 1 and e.slot_name is not null');
171
            $tokens         = $dwcTokenHelper->getTokens(
172
                $this->dwcTokenRegex,
173
                '',
174
                'name',
175
                'slot_name',
176
                $expr
177
            );
178
            $event->addTokens(is_array($tokens) ? $tokens : []);
0 ignored issues
show
introduced by
The condition is_array($tokens) is always true.
Loading history...
179
180
            $event->addTokens(
181
                $event->filterTokens(
182
                    [
183
                        $this->langBarRegex      => $this->translator->trans('mautic.page.token.lang'),
184
                        $this->shareButtonsRegex => $this->translator->trans('mautic.page.token.share'),
185
                        $this->titleRegex        => $this->translator->trans('mautic.core.title'),
186
                        $this->descriptionRegex  => $this->translator->trans('mautic.page.form.metadescription'),
187
                        self::segmentListRegex   => $this->translator->trans('mautic.page.form.segmentlist'),
188
                        self::categoryListRegex  => $this->translator->trans('mautic.page.form.categorylist'),
189
                        self::preferredchannel   => $this->translator->trans('mautic.page.form.preferredchannel'),
190
                        self::channelfrequency   => $this->translator->trans('mautic.page.form.channelfrequency'),
191
                        self::saveprefsRegex     => $this->translator->trans('mautic.page.form.saveprefs'),
192
                        self::successmessage     => $this->translator->trans('mautic.page.form.successmessage'),
193
                        self::identifierToken    => $this->translator->trans('mautic.page.form.leadidentifier'),
194
                    ]
195
                )
196
            );
197
        }
198
199
        if ($event->slotTypesRequested()) {
200
            $event->addSlotType(
201
                'text',
202
                $this->translator->trans('mautic.core.slot.label.text'),
203
                'font',
204
                'MauticCoreBundle:Slots:text.html.php',
205
                SlotTextType::class,
206
                1000
207
            );
208
            $event->addSlotType(
209
                'image',
210
                $this->translator->trans('mautic.core.slot.label.image'),
211
                'image',
212
                'MauticCoreBundle:Slots:image.html.php',
213
                SlotImageType::class,
214
                900
215
            );
216
            $event->addSlotType(
217
                'imagecard',
218
                $this->translator->trans('mautic.core.slot.label.imagecard'),
219
                'id-card-o',
220
                'MauticCoreBundle:Slots:imagecard.html.php',
221
                SlotImageCardType::class,
222
                870
223
            );
224
            $event->addSlotType(
225
                'imagecaption',
226
                $this->translator->trans('mautic.core.slot.label.imagecaption'),
227
                'image',
228
                'MauticCoreBundle:Slots:imagecaption.html.php',
229
                SlotImageCaptionType::class,
230
                850
231
            );
232
            $event->addSlotType(
233
                'button',
234
                $this->translator->trans('mautic.core.slot.label.button'),
235
                'external-link',
236
                'MauticCoreBundle:Slots:button.html.php',
237
                SlotButtonType::class,
238
                800
239
            );
240
            $event->addSlotType(
241
                'socialshare',
242
                $this->translator->trans('mautic.core.slot.label.socialshare'),
243
                'share-alt',
244
                'MauticCoreBundle:Slots:socialshare.html.php',
245
                SlotSocialShareType::class,
246
                700
247
            );
248
            $event->addSlotType(
249
                'socialfollow',
250
                $this->translator->trans('mautic.core.slot.label.socialfollow'),
251
                'twitter',
252
                'MauticCoreBundle:Slots:socialfollow.html.php',
253
                SlotSocialFollowType::class,
254
                600
255
            );
256
            if ($this->security->isGranted(['page:preference_center:editown', 'page:preference_center:editother'], 'MATCH_ONE')) {
257
                $event->addSlotType(
258
                    'segmentlist',
259
                    $this->translator->trans('mautic.core.slot.label.segmentlist'),
260
                    'list-alt',
261
                    'MauticCoreBundle:Slots:segmentlist.html.php',
262
                    SlotSegmentListType::class,
263
                    590
264
                );
265
                $event->addSlotType(
266
                    'categorylist',
267
                    $this->translator->trans('mautic.core.slot.label.categorylist'),
268
                    'bookmark-o',
269
                    'MauticCoreBundle:Slots:categorylist.html.php',
270
                    SlotCategoryListType::class,
271
                    580
272
                );
273
                $event->addSlotType(
274
                    'preferredchannel',
275
                    $this->translator->trans('mautic.core.slot.label.preferredchannel'),
276
                    'envelope-o',
277
                    'MauticCoreBundle:Slots:preferredchannel.html.php',
278
                    SlotPreferredChannelType::class,
279
                    570
280
                );
281
                $event->addSlotType(
282
                    'channelfrequency',
283
                    $this->translator->trans('mautic.core.slot.label.channelfrequency'),
284
                    'calendar',
285
                    'MauticCoreBundle:Slots:channelfrequency.html.php',
286
                    SlotChannelFrequencyType::class,
287
                    560
288
                );
289
                $event->addSlotType(
290
                    'saveprefsbutton',
291
                    $this->translator->trans('mautic.core.slot.label.saveprefsbutton'),
292
                    'floppy-o',
293
                    'MauticCoreBundle:Slots:saveprefsbutton.html.php',
294
                    SlotSavePrefsButtonType::class,
295
                    540
296
                );
297
298
                $event->addSlotType(
299
                    'successmessage',
300
                    $this->translator->trans('mautic.core.slot.label.successmessage'),
301
                    'check',
302
                    'MauticCoreBundle:Slots:successmessage.html.php',
303
                    SlotSuccessMessageType::class,
304
                    540
305
                );
306
            }
307
            $event->addSlotType(
308
                'codemode',
309
                $this->translator->trans('mautic.core.slot.label.codemode'),
310
                'code',
311
                'MauticCoreBundle:Slots:codemode.html.php',
312
                SlotCodeModeType::class,
313
                500
314
            );
315
            $event->addSlotType(
316
                'separator',
317
                $this->translator->trans('mautic.core.slot.label.separator'),
318
                'minus',
319
                'MauticCoreBundle:Slots:separator.html.php',
320
                SlotSeparatorType::class,
321
                400
322
            );
323
            $event->addSlotType(
324
                'gatedvideo',
325
                $this->translator->trans('mautic.core.slot.label.gatedvideo'),
326
                'video-camera',
327
                'MauticCoreBundle:Slots:gatedvideo.html.php',
328
                GatedVideoType::class,
329
                300
330
            );
331
            $event->addSlotType(
332
                'dwc',
333
                $this->translator->trans('mautic.core.slot.label.dynamiccontent'),
334
                'sticky-note-o',
335
                'MauticCoreBundle:Slots:dwc.html.php',
336
                SlotDwcType::class,
337
                200
338
            );
339
        }
340
341
        if ($event->sectionsRequested()) {
342
            $event->addSection(
343
                'one-column',
344
                $this->translator->trans('mautic.core.slot.label.onecolumn'),
345
                'file-text-o',
346
                'MauticCoreBundle:Sections:one-column.html.php',
347
                null,
348
                1000
349
            );
350
            $event->addSection(
351
                'two-column',
352
                $this->translator->trans('mautic.core.slot.label.twocolumns'),
353
                'columns',
354
                'MauticCoreBundle:Sections:two-column.html.php',
355
                null,
356
                900
357
            );
358
            $event->addSection(
359
                'three-column',
360
                $this->translator->trans('mautic.core.slot.label.threecolumns'),
361
                'th',
362
                'MauticCoreBundle:Sections:three-column.html.php',
363
                null,
364
                800
365
            );
366
        }
367
    }
368
369
    public function onPageDisplay(Events\PageDisplayEvent $event)
370
    {
371
        $content = $event->getContent();
372
        $page    = $event->getPage();
373
        $params  = $event->getParams();
374
375
        if (false !== strpos($content, $this->langBarRegex)) {
376
            $langbar = $this->renderLanguageBar($page);
377
            $content = str_ireplace($this->langBarRegex, $langbar, $content);
378
        }
379
380
        if (false !== strpos($content, $this->shareButtonsRegex)) {
0 ignored issues
show
Bug introduced by
It seems like $content can also be of type array; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

380
        if (false !== strpos(/** @scrutinizer ignore-type */ $content, $this->shareButtonsRegex)) {
Loading history...
381
            $buttons = $this->renderSocialShareButtons();
382
            $content = str_ireplace($this->shareButtonsRegex, $buttons, $content);
383
        }
384
385
        if (false !== strpos($content, $this->titleRegex)) {
386
            $content = str_ireplace($this->titleRegex, $page->getTitle(), $content);
387
        }
388
389
        if (false !== strpos($content, $this->descriptionRegex)) {
390
            $content = str_ireplace($this->descriptionRegex, $page->getMetaDescription(), $content);
391
        }
392
393
        if ($page->getIsPreferenceCenter()) {
394
            // replace slots
395
            if (count($params)) {
396
                $dom = new DOMDocument('1.0', 'utf-8');
397
                $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_NOERROR);
0 ignored issues
show
Bug introduced by
It seems like mb_convert_encoding($con...TML-ENTITIES', 'UTF-8') can also be of type array; however, parameter $source of DOMDocument::loadHTML() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

397
                $dom->loadHTML(/** @scrutinizer ignore-type */ mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_NOERROR);
Loading history...
398
                $xpath = new DOMXPath($dom);
399
400
                $divContent = $xpath->query('//*[@data-slot="segmentlist"]');
401
                for ($i = 0; $i < $divContent->length; ++$i) {
402
                    $slot            = $divContent->item($i);
403
                    $slot->nodeValue = self::segmentListRegex;
404
                    $slot->setAttribute('data-prefs-center', '1');
405
                    $content         = $dom->saveHTML();
406
                }
407
408
                $divContent = $xpath->query('//*[@data-slot="categorylist"]');
409
                for ($i = 0; $i < $divContent->length; ++$i) {
410
                    $slot            = $divContent->item($i);
411
                    $slot->nodeValue = self::categoryListRegex;
412
                    $slot->setAttribute('data-prefs-center', '1');
413
                    $content         = $dom->saveHTML();
414
                }
415
416
                $divContent = $xpath->query('//*[@data-slot="preferredchannel"]');
417
                for ($i = 0; $i < $divContent->length; ++$i) {
418
                    $slot            = $divContent->item($i);
419
                    $slot->nodeValue = self::preferredchannel;
420
                    $slot->setAttribute('data-prefs-center', '1');
421
                    $content         = $dom->saveHTML();
422
                }
423
424
                $divContent = $xpath->query('//*[@data-slot="channelfrequency"]');
425
                for ($i = 0; $i < $divContent->length; ++$i) {
426
                    $slot            = $divContent->item($i);
427
                    $slot->nodeValue = self::channelfrequency;
428
                    $slot->setAttribute('data-prefs-center', '1');
429
                    $content         = $dom->saveHTML();
430
                }
431
432
                $divContent = $xpath->query('//*[@data-slot="saveprefsbutton"]');
433
                for ($i = 0; $i < $divContent->length; ++$i) {
434
                    $slot            = $divContent->item($i);
435
                    $saveButton      = $xpath->query('//*[@data-slot="saveprefsbutton"]//a')->item(0);
436
                    $slot->nodeValue = self::saveprefsRegex;
437
                    $slot->setAttribute('data-prefs-center', '1');
438
                    $content         = $dom->saveHTML();
439
440
                    $params['saveprefsbutton'] = [
441
                        'style'      => $saveButton->getAttribute('style'),
442
                        'background' => $saveButton->getAttribute('background'),
443
                    ];
444
                }
445
446
                unset($slot, $xpath, $dom);
447
            }
448
            // replace tokens
449
            if (false !== strpos($content, self::segmentListRegex)) {
450
                $segmentList = $this->renderSegmentList($params);
451
                $content     = str_ireplace(self::segmentListRegex, $segmentList, $content);
452
            }
453
454
            if (false !== strpos($content, self::categoryListRegex)) {
455
                $categoryList = $this->renderCategoryList($params);
456
                $content      = str_ireplace(self::categoryListRegex, $categoryList, $content);
457
            }
458
459
            if (false !== strpos($content, self::preferredchannel)) {
460
                $preferredChannel = $this->renderPreferredChannel($params);
461
                $content          = str_ireplace(self::preferredchannel, $preferredChannel, $content);
462
            }
463
464
            if (false !== strpos($content, self::channelfrequency)) {
465
                $channelfrequency = $this->renderChannelFrequency($params);
466
                $content          = str_ireplace(self::channelfrequency, $channelfrequency, $content);
467
            }
468
469
            if (false !== strpos($content, self::saveprefsRegex)) {
470
                $savePrefs = $this->renderSavePrefs($params);
471
                $content   = str_ireplace(self::saveprefsRegex, $savePrefs, $content);
472
            }
473
            // add form before first block of prefs center
474
            if (isset($params['startform']) && false !== strpos($content, 'data-prefs-center')) {
475
                $dom = new DOMDocument('1.0', 'utf-8');
476
                $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_NOERROR);
477
                $xpath      = new DOMXPath($dom);
478
                // If use slots
479
                $divContent = $xpath->query('//*[@data-prefs-center="1"]');
480
                if (!$divContent->length) {
481
                    // If use tokens
482
                    $divContent = $xpath->query('//*[@data-prefs-center-first="1"]');
483
                }
484
485
                if ($divContent->length) {
486
                    $slot    = $divContent->item(0);
487
                    $newnode = $dom->createElement('startform');
488
                    $slot->parentNode->insertBefore($newnode, $slot);
0 ignored issues
show
Bug introduced by
The method insertBefore() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

488
                    $slot->parentNode->/** @scrutinizer ignore-call */ 
489
                                       insertBefore($newnode, $slot);

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.

Loading history...
489
                    $content = $dom->saveHTML();
490
                    $content = str_replace('<startform></startform>', $params['startform'], $content);
491
                }
492
            }
493
494
            if (false !== strpos($content, self::successmessage)) {
495
                $successMessage = $this->renderSuccessMessage($params);
496
                $content        = str_ireplace(self::successmessage, $successMessage, $content);
497
            }
498
        }
499
500
        $clickThrough = ['source' => ['page', $page->getId()]];
501
        $tokens       = $this->tokenHelper->findPageTokens($content, $clickThrough);
502
503
        if (count($tokens)) {
504
            $content = str_ireplace(array_keys($tokens), $tokens, $content);
505
        }
506
507
        $event->setContent($content);
0 ignored issues
show
Bug introduced by
It seems like $content can also be of type array; however, parameter $content of Mautic\PageBundle\Event\...playEvent::setContent() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

507
        $event->setContent(/** @scrutinizer ignore-type */ $content);
Loading history...
508
    }
509
510
    /**
511
     * Renders the HTML for the social share buttons.
512
     *
513
     * @return string
514
     */
515
    private function renderSocialShareButtons()
516
    {
517
        static $content = '';
518
519
        if (empty($content)) {
520
            $shareButtons = $this->integrationHelper->getShareButtons();
521
522
            $content = "<div class='share-buttons'>\n";
523
            foreach ($shareButtons as $button) {
524
                $content .= $button;
525
            }
526
            $content .= "</div>\n";
527
528
            //load the css into the header by calling the sharebtn_css view
529
            $this->templating->getTemplating()->render('MauticPageBundle:SubscribedEvents\PageToken:sharebtn_css.html.php');
530
        }
531
532
        return $content;
533
    }
534
535
    /**
536
     * @return string
537
     */
538
    private function getAttributeForFirtSlot()
539
    {
540
        return 'data-prefs-center-first="1"';
541
    }
542
543
    /**
544
     * Renders the HTML for the segment list.
545
     *
546
     * @return string
547
     */
548
    private function renderSegmentList(array $params = [])
549
    {
550
        static $content = '';
551
552
        if (empty($content)) {
553
            $content = "<div class='pref-segmentlist' ".$this->getAttributeForFirtSlot().">\n";
554
            $content .= $this->templating->getTemplating()->render('MauticCoreBundle:Slots:segmentlist.html.php', $params);
555
            $content .= "</div>\n";
556
        }
557
558
        return $content;
559
    }
560
561
    /**
562
     * @return string
563
     */
564
    private function renderCategoryList(array $params = [])
565
    {
566
        static $content = '';
567
568
        if (empty($content)) {
569
            $content = "<div class='pref-categorylist ' ".$this->getAttributeForFirtSlot().">\n";
570
            $content .= $this->templating->getTemplating()->render('MauticCoreBundle:Slots:categorylist.html.php', $params);
571
            $content .= "</div>\n";
572
        }
573
574
        return $content;
575
    }
576
577
    /**
578
     * @return string
579
     */
580
    private function renderPreferredChannel(array $params = [])
581
    {
582
        static $content = '';
583
584
        if (empty($content)) {
585
            $content = "<div class='pref-preferredchannel'>\n";
586
            $content .= $this->templating->getTemplating()->render('MauticCoreBundle:Slots:preferredchannel.html.php', $params);
587
            $content .= "</div>\n";
588
        }
589
590
        return $content;
591
    }
592
593
    /**
594
     * @return string
595
     */
596
    private function renderChannelFrequency(array $params = [])
597
    {
598
        static $content = '';
599
600
        if (empty($content)) {
601
            $content = "<div class='pref-channelfrequency'>\n";
602
            $content .= $this->templating->getTemplating()->render('MauticCoreBundle:Slots:channelfrequency.html.php', $params);
603
            $content .= "</div>\n";
604
        }
605
606
        return $content;
607
    }
608
609
    /**
610
     * @return string
611
     */
612
    private function renderSavePrefs(array $params = [])
613
    {
614
        static $content = '';
615
616
        if (empty($content)) {
617
            $content = "<div class='pref-saveprefs ' ".$this->getAttributeForFirtSlot().">\n";
618
            $content .= $this->templating->getTemplating()->render('MauticCoreBundle:Slots:saveprefsbutton.html.php', $params);
619
            $content .= "</div>\n";
620
        }
621
622
        return $content;
623
    }
624
625
    /**
626
     * @return string
627
     */
628
    private function renderSuccessMessage(array $params = [])
629
    {
630
        static $content = '';
631
632
        if (empty($content)) {
633
            $content = "<div class=\"pref-successmessage\">\n";
634
            $content .= $this->templating->getTemplating()->render('MauticCoreBundle:Slots:successmessage.html.php', $params);
635
            $content .= "</div>\n";
636
        }
637
638
        return $content;
639
    }
640
641
    /**
642
     * Renders the HTML for the language bar for a given page.
643
     *
644
     * @param $page
645
     *
646
     * @return string
647
     */
648
    private function renderLanguageBar($page)
649
    {
650
        static $langbar = '';
651
652
        if (empty($langbar)) {
653
            $parent   = $page->getTranslationParent();
654
            $children = $page->getTranslationChildren();
655
656
            //check to see if this page is grouped with another
657
            if (empty($parent) && empty($children)) {
658
                return;
659
            }
660
661
            $related = [];
662
663
            //get a list of associated pages/languages
664
            if (!empty($parent)) {
665
                $children = $parent->getTranslationChildren();
666
            } else {
667
                $parent = $page; //parent is self
668
            }
669
670
            if (!empty($children)) {
671
                $lang  = $parent->getLanguage();
672
                $trans = $this->translator->trans('mautic.page.lang.'.$lang);
673
                if ($trans == 'mautic.page.lang.'.$lang) {
674
                    $trans = $lang;
675
                }
676
                $related[$parent->getId()] = [
677
                    'lang' => $trans,
678
                    // Add ntrd to not auto redirect to another language
679
                    'url'  => $this->pageModel->generateUrl($parent, false).'?ntrd=1',
680
                ];
681
                foreach ($children as $c) {
682
                    $lang  = $c->getLanguage();
683
                    $trans = $this->translator->trans('mautic.page.lang.'.$lang);
684
                    if ($trans == 'mautic.page.lang.'.$lang) {
685
                        $trans = $lang;
686
                    }
687
                    $related[$c->getId()] = [
688
                        'lang' => $trans,
689
                        // Add ntrd to not auto redirect to another language
690
                        'url'  => $this->pageModel->generateUrl($c, false).'?ntrd=1',
691
                    ];
692
                }
693
            }
694
695
            //sort by language
696
            uasort(
697
                $related,
698
                function ($a, $b) {
699
                    return strnatcasecmp($a['lang'], $b['lang']);
700
                }
701
            );
702
703
            if (empty($related)) {
704
                return;
705
            }
706
707
            $langbar = $this->templating->getTemplating()->render('MauticPageBundle:SubscribedEvents\PageToken:langbar.html.php', ['pages' => $related]);
708
        }
709
710
        return $langbar;
711
    }
712
713
    public function onEmailBuild(EmailBuilderEvent $event)
714
    {
715
        if ($event->tokensRequested([$this->pageTokenRegex])) {
716
            $tokenHelper = $this->builderTokenHelperFactory->getBuilderTokenHelper('page');
717
            $event->addTokensFromHelper($tokenHelper, $this->pageTokenRegex, 'title', 'id', true);
718
        }
719
    }
720
721
    public function onEmailGenerate(EmailSendEvent $event)
722
    {
723
        $content      = $event->getContent();
724
        $plainText    = $event->getPlainText();
725
        $clickthrough = $event->shouldAppendClickthrough() ? $event->generateClickthrough() : [];
726
        $tokens       = $this->tokenHelper->findPageTokens($content.$plainText, $clickthrough);
0 ignored issues
show
Bug introduced by
Are you sure $plainText of type array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

726
        $tokens       = $this->tokenHelper->findPageTokens($content./** @scrutinizer ignore-type */ $plainText, $clickthrough);
Loading history...
727
728
        $event->addTokens($tokens);
729
    }
730
}
731