Completed
Push — master ( ab2cfb...4b8982 )
by Dominik
06:17 queued 04:34
created

AzineEmailTwigExtension   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 77.66%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 19
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 189
ccs 73
cts 94
cp 0.7766
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A textWrap() 0 4 1
A addCampaignParamsForTemplate() 0 4 1
B addCampaignParamsToAllUrls() 0 41 5
A stripAndConvertTags() 0 23 3
B urlEncodeText() 0 24 1
A __construct() 0 5 1
A getFilters() 0 9 1
A getName() 0 4 1
B printVars() 0 18 5
1
<?php
2
namespace Azine\EmailBundle\Services;
3
4
use Symfony\Component\Translation\TranslatorInterface;
5
6
class AzineEmailTwigExtension extends \Twig_Extension
7
{
8
    /**
9
     * @var TemplateProviderInterface
10
     */
11
    private $templateProvider;
12
13
    /**
14
     * @var TranslatorInterface		
15
     */		
16
    private $translator;
17
    
18
    /**
19
     * @var array
20
     */
21
    private $domainsToTrack;
22
23
    /**
24
     * @param TemplateProviderInterface $templateProvider
25
     * @param array of string $domainsToTrack
26
     */
27 12
    public function __construct(TemplateProviderInterface $templateProvider, TranslatorInterface $translator, array $domainsToTrack = array()){
28 12
        $this->templateProvider = $templateProvider;
29 12
        $this->translator = $translator;
30 12
        $this->domainsToTrack = $domainsToTrack;
31 12
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 1
    public function getFilters()
37
    {
38 1
        $filters[] = new \Twig_SimpleFilter('textWrap', array($this, 'textWrap'));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$filters was never initialized. Although not strictly required by PHP, it is generally a good practice to add $filters = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
39 1
        $filters[] = new \Twig_SimpleFilter('urlEncodeText', array($this, 'urlEncodeText'), array('is_safe' => array('html')));
40 1
        $filters[] = new \Twig_SimpleFilter('addCampaignParamsForTemplate', array($this, 'addCampaignParamsForTemplate'), array('is_safe' => array('html')));
41 1
        $filters[] = new \Twig_SimpleFilter('stripAndConvertTags', array($this, 'stripAndConvertTags'), array('is_safe' => array('html')));
42 1
        $filters[] = new \Twig_SimpleFilter('printVars', array($this, 'printVars'));
43 1
        return $filters;
44
    }
45
46 1
    public function urlEncodeText($text)
47
    {
48 1
        $text = str_replace("%","%25", $text);
49 1
        $text = str_replace(array(	"\n",
50 1
                                    " ",
51 1
                                    "&",
52 1
                                    "\\",
53 1
                                    "<",
54 1
                                    ">",
55 1
                                    '"',
56 1
                                    "	",
57 1
                                ),
58 1
                            array(	"%0D%0A",
59 1
                                    "%20",
60 1
                                    "%26",
61 1
                                    "%5C",
62 1
                                    "%3D",
63 1
                                    "%3E",
64 1
                                    "%23",
65 1
                                    "%09",
66 1
                                ), $text);
67
68 1
        return $text;
69
    }
70
71
    /**
72
     * Wrap the text to the lineLength is not exeeded.
73
     * @param  string  $text
74
     * @param  integer $lineLength default: 75
75
     * @return string  the wrapped string
76
     */
77 3
    public function textWrap($text, $lineLength = 75)
78
    {
79 3
        return wordwrap($text, $lineLength);
80
    }
81
82
    /**
83
     * Returns the name of the extension.
84
     *
85
     * @return string The extension name
86
     */
87
    public function getName()
88
    {
89
        return 'azine_email_bundle_twig_extension';
90
    }
91
92
    public function addCampaignParamsForTemplate($html, $templateId, $templateParams){
93
        $campaignParams = $this->templateProvider->getCampaignParamsFor($templateId, $templateParams);
94
        return $this->addCampaignParamsToAllUrls($html, $campaignParams);
95
    }
96
97
    /**
98
     * Add the campaign-parameters to all URLs in the html
99
     * @param  string $html
100
     * @param  array  $campaignParams
101
     * @return string
102
     */
103 4
    public function addCampaignParamsToAllUrls($html, $campaignParams)
104
    {
105
106 4
        $urlPattern = '/(href=[\'|"])(http[s]?\:\/\/\S*)([\'|"])/';
107
108
        $filteredHtml = preg_replace_callback($urlPattern, function ($matches) use ($campaignParams) {
109 4
                                                                    $start = $matches[1];
110 4
                                                                    $url = $matches[2];
111 4
                                                                    $end = $matches[3];
112 4
                                                                    $domain = parse_url($url, PHP_URL_HOST);
113
114
                                                                    // if the url is not in the list of domains to track then
115 4
                                                                    if(array_search($domain, $this->domainsToTrack) === false){
116
                                                                        // don't append tracking parameters to the url
117 3
                                                                        return $start.$url.$end;
118
                                                                    }
119
120
                                                                    // avoid duplicate params and don't replace existing params
121 1
                                                                    $params = array();
122 1
                                                                    foreach($campaignParams as $nextKey => $nextValue){
123 1
                                                                        if(strpos($url, $nextKey) === false){
124 1
                                                                            $params[$nextKey] = $nextValue;
125 1
                                                                        }
126 1
                                                                    }
127
128 1
                                                                    $urlParams = http_build_query($params);
129
130 1
                                                                    if (strpos($url,"?") === false) {
131 1
                                                                        $urlParams = "?".$urlParams;
132 1
                                                                    } else {
133 1
                                                                        $urlParams = "&".$urlParams;
134
                                                                    }
135
136 1
                                                                    $replacement = $start.$url.$urlParams.$end;
137
138 1
                                                                    return $replacement;
139
140 4
                                                                }, $html);
141
142 4
        return $filteredHtml;
143
    }
144
145
    /**
146
     * Convert:
147
     * - a-tags to show the link and if the link-text is not contained in the link, also the link-text
148
     * - remove double-whitespaces and whitespaces at line beginnings and ends.
149
     * - html-special chars to their original representation (php => htmlspecialchars_decode)
150
     * and then remove all html-tags (php => strip_tags)
151
     */
152
    public function stripAndConvertTags($html){
153
154 1
        $linkConvertedHtml = preg_replace_callback('/<a.*?href=[\'|"](.+?)[\'|"].*?>(.*?)<\/a>/s', function ($matches) {
155 1
            $url = $matches[1];
156 1
            $text = trim(strip_tags($matches[2]));
157
158 1
            if(strlen($text) == 0 || stripos($url, $text) !== false){
159 1
                $replacement = $url;
160 1
            } else {
161 1
                $replacement = $text . ": " . $url;
162
            }
163
164 1
            return $replacement;
165
166 1
        }, $html);
167
168 1
        $txt = strip_tags($linkConvertedHtml);
169 1
        $txt = preg_replace('/[[:blank:]]+/', ' ', $txt);
170 1
        $txt = preg_replace("/\n[[:blank:]]/", "\n", $txt);
171 1
        $txt = preg_replace("/[[:blank:]]\n/", "\n", $txt);
172 1
        $txt = html_entity_decode($txt);
173 1
        return $txt;
174
    }
175
176
    public function printVars(array $vars, $allDetails = false, $indent = ""){
177
        $output = "";
178
        $defaultIndent = "    ";
179
        ksort($vars);
180
        foreach ($vars as $key => $value){
181
            if($allDetails) {
182
                $value = "\n" . $this->printVars((array) $value, $allDetails, $indent.$defaultIndent);
183
            } else {
184
                if (is_array($value)){
185
                    $value = "array(".sizeof($value).")";
186
                } else if (is_object($value)) {
187
                    $value = "object(".get_class($value).")";
188
                }
189
            }
190
            $output .= "$indent $key: $value\n";
191
        }
192
        return $output;
193
    }
194
}
195