Helper   B
last analyzed

Complexity

Total Complexity 44

Size/Duplication

Total Lines 292
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 44
lcom 1
cbo 10
dl 0
loc 292
rs 8.8798
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A getCleanRequestTarget() 0 12 2
A redirectToPage() 0 9 2
A terminateScript() 0 4 1
A formatNumber() 0 9 1
B getSignedGlideURL() 0 20 7
C mailWrapper() 0 48 13
A reachThrough() 0 3 1
A returnEmptyString() 0 3 1
A getDebug() 0 13 4
B getPurifier() 0 34 7
A twigCallback() 0 15 2
A autoInsert() 0 16 2

How to fix   Complexity   

Complex Class

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

1
<?php
2
3
/*
4
    HCSF - A multilingual CMS and Shopsystem
5
    Copyright (C) 2014  Marcus Haase - [email protected]
6
7
    This program is free software: you can redistribute it and/or modify
8
    it under the terms of the GNU General Public License as published by
9
    the Free Software Foundation, either version 3 of the License, or
10
    (at your option) any later version.
11
12
    This program is distributed in the hope that it will be useful,
13
    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
    GNU General Public License for more details.
16
17
    You should have received a copy of the GNU General Public License
18
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
namespace HaaseIT\HCSF;
22
23
use HaaseIT\Toolbox\Tools;
24
use Zend\ServiceManager\ServiceManager;
25
26
/**
27
 * Class Helper
28
 * @package HaaseIT\HCSF
29
 */
30
class Helper
31
{
32
    /**
33
     * @var ServiceManager
34
     */
35
    protected $serviceManager;
36
37
    /**
38
     * @var \HaaseIT\HCSF\HelperConfig
39
     */
40
    protected $config;
41
42
    /**
43
     * @var array
44
     */
45
    protected $core = [];
46
47
    /**
48
     * @var array
49
     */
50
    protected $secrets = [];
51
52
    /**
53
     * @var array
54
     */
55
    protected $shop = [];
56
57
    /**
58
     * Helper constructor.
59
     * @param ServiceManager $serviceManager
60
     */
61
    public function __construct(ServiceManager $serviceManager)
62
    {
63
        $this->serviceManager = $serviceManager;
64
        $this->config = $serviceManager->get('config');
65
        $this->secrets = $this->config->getSecret();
66
        $this->core = $this->config->getCore();
67
        $this->shop = $this->config->getShop();
68
    }
69
70
    public function getCleanRequestTarget() {
71
        $request = $this->serviceManager->get('request');
72
73
        // cleanup request
74
        $requesturi = urldecode($request->getRequestTarget());
75
        $parsedrequesturi = substr($requesturi, strlen(dirname(filter_input(INPUT_SERVER, 'PHP_SELF'))));
76
        if (substr($parsedrequesturi, 1, 1) !== '/') {
77
            $parsedrequesturi = '/'.$parsedrequesturi;
78
        }
79
80
        return $parsedrequesturi;
81
    }
82
83
    /**
84
     * @param string $target
85
     * @param bool $replace
86
     * @param int $http_response_header
87
     * @return void|false
88
     */
89
    public function redirectToPage($target = '', $replace = false, $http_response_header = 302)
90
    {
91
        if (empty($target)) {
92
            return false;
93
        }
94
95
        header('Location: '.$target, $replace, $http_response_header);
96
        $this->terminateScript();
97
    }
98
99
    /**
100
     * @param string $message
101
     */
102
    public function terminateScript($message = '')
103
    {
104
        die($message);
105
    }
106
107
    /**
108
     * @param $number
109
     * @return string
110
     */
111
    public function formatNumber($number)
112
    {
113
        return number_format(
114
            $number,
115
            $this->config->getCore('numberformat_decimals'),
116
            $this->config->getCore('numberformat_decimal_point'),
117
            $this->config->getCore('numberformat_thousands_seperator')
118
        );
119
    }
120
121
    /**
122
     * @param $file
123
     * @param int $width
124
     * @param int $height
125
     * @return bool|string
126
     */
127
    public function getSignedGlideURL($file, $width = 0, $height = 0)
128
    {
129
        $urlBuilder = \League\Glide\Urls\UrlBuilderFactory::create('', $this->secrets['glide_signkey']);
130
131
        $param = [];
132
        if ($width == 0 && $height == 0) {
133
            return false;
134
        }
135
        if ($width != 0) {
136
            $param['w'] = $width;
137
        }
138
        if ($height != 0) {
139
            $param['h'] = $height;
140
        }
141
        if ($width != 0 && $height != 0) {
142
            $param['fit'] = 'stretch';
143
        }
144
145
        return $urlBuilder->getUrl($file, $param);
146
    }
147
148
    /**
149
     * @param $to
150
     * @param string $subject
151
     * @param string $message
152
     * @param array $aImagesToEmbed
153
     * @param array $aFilesToAttach
154
     * @return bool
155
     */
156
    public function mailWrapper($to, $subject = '(No subject)', $message = '', $aImagesToEmbed = [], $aFilesToAttach = []) {
157
        $mail = new \PHPMailer;
158
        $mail->CharSet = 'UTF-8';
159
160
        $mail->isMail();
161
        if ($this->core['mail_method'] === 'sendmail') {
162
            $mail->isSendmail();
163
        } elseif ($this->core['mail_method'] === 'smtp') {
164
            $mail->isSMTP();
165
            $mail->Host = $this->secrets['mail_smtp_server'];
166
            $mail->Port = $this->secrets['mail_smtp_port'];
167
            if ($this->secrets['mail_smtp_auth'] === true) {
168
                $mail->SMTPAuth = true;
169
                $mail->Username = $this->secrets['mail_smtp_auth_user'];
170
                $mail->Password = $this->secrets['mail_smtp_auth_pwd'];
171
                if ($this->secrets['mail_smtp_secure']) {
172
                    $mail->SMTPSecure = 'tls';
173
                    if ($this->secrets['mail_smtp_secure_method'] === 'ssl') {
174
                        $mail->SMTPSecure = 'ssl';
175
                    }
176
                }
177
            }
178
        }
179
180
        $mail->From = $this->core['email_sender'];
181
        $mail->FromName = $this->core['email_sendername'];
182
        $mail->addAddress($to);
183
        $mail->isHTML(true);
184
        $mail->Subject = $subject;
185
        $mail->Body = $message;
186
187
        if (is_array($aImagesToEmbed) && count($aImagesToEmbed)) {
188
            foreach ($aImagesToEmbed as $sKey => $imgdata) {
189
                $imginfo = getimagesizefromstring($imgdata['binimg']);
190
                $mail->addStringEmbeddedImage($imgdata['binimg'], $sKey, $sKey, 'base64', $imginfo['mime']);
191
            }
192
        }
193
194
        if (is_array($aFilesToAttach) && count($aFilesToAttach)) {
195
            foreach ($aFilesToAttach as $sValue) {
196
                if (file_exists($sValue)) {
197
                    $mail->addAttachment($sValue);
198
                }
199
            }
200
        }
201
202
        return $mail->send();
203
    }
204
205
    // don't remove this, this is the fallback for unavailable twig functions
206
    /**
207
     * @param $string
208
     * @return mixed
209
     */
210
    public function reachThrough($string) {
211
        return $string;
212
    }
213
    // don't remove this, this is the fallback for unavailable twig functions
214
    /**
215
     * @return string
216
     */
217
    public function returnEmptyString() {
218
        return '';
219
    }
220
221
    /**
222
     * @param array $aP
223
     * @param Page $P
224
     */
225
    public function getDebug($aP, $P)
226
    {
227
        if (!empty($_POST)) {
228
            Tools::debug($_POST, '$_POST');
229
        } elseif (!empty($_REQUEST)) {
230
            Tools::debug($_REQUEST, '$_REQUEST');
231
        }
232
        if (!empty($_SESSION)) {
233
            Tools::debug($_SESSION, '$_SESSION');
234
        }
235
        Tools::debug($aP, '$aP');
236
        Tools::debug($P, '$P');
237
    }
238
239
    /**
240
     * @param string $purpose
241
     * @return bool|\HTMLPurifier
242
     */
243
    public function getPurifier($purpose)
244
    {
245
        $purifier_config = \HTMLPurifier_Config::createDefault();
246
        $purifier_config->set('Core.Encoding', 'UTF-8');
247
        $purifier_config->set('Cache.SerializerPath', PATH_PURIFIERCACHE);
248
        $purifier_config->set('HTML.Doctype', $this->core['purifier_doctype']);
249
250
        if ($purpose === 'textcat') {
251
            $configkey = 'textcat';
252
            $configsection = 'core';
253
        } elseif ($purpose === 'page') {
254
            $configkey = 'pagetext';
255
            $configsection = 'core';
256
        } elseif ($purpose === 'item') {
257
            $configkey = 'itemtext';
258
            $configsection = 'shop';
259
        } elseif ($purpose === 'itemgroup') {
260
            $configkey = 'itemgrouptext';
261
            $configsection = 'shop';
262
        } else {
263
            return false;
264
        }
265
266
        if (!empty($this->{$configsection}[$configkey.'_unsafe_html_whitelist'])) {
267
            $purifier_config->set('HTML.Allowed', $this->{$configsection}[$configkey.'_unsafe_html_whitelist']);
268
        }
269
        if (!empty($this->{$configsection}[$configkey.'_loose_filtering'])) {
270
            $purifier_config->set('HTML.Trusted', true);
271
            $purifier_config->set('Attr.EnableID', true);
272
            $purifier_config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']);
273
        }
274
275
        return new \HTMLPurifier($purifier_config);
276
    }
277
278
    /**
279
     * @param $callback
280
     * @param $parameters
281
     * @return bool|mixed
282
     */
283
    public function twigCallback($callback, $parameters)
284
    {
285
        $helperShop = $this->serviceManager->get('helpershop');
286
287
        $callbacks = [
288
            'renderItemStatusIcon' => [$helperShop, 'renderItemStatusIcon'],
289
            'shopadminMakeCheckbox' => [$helperShop, 'shopadminMakeCheckbox'],
290
        ];
291
292
        if (!isset($callbacks[$callback])) {
293
            return false;
294
        }
295
296
        return call_user_func($callbacks[$callback], $parameters);
297
    }
298
299
    /**
300
     * @param \Doctrine\DBAL\Connection $dbal
301
     * @param string $table
302
     * @param array $data
303
     * @return string
304
     */
305
    public function autoInsert(\Doctrine\DBAL\Connection $dbal, $table, array $data)
306
    {
307
        /** @var \Doctrine\DBAL\Query\QueryBuilder $querybuilder */
308
        $querybuilder = $dbal->createQueryBuilder();
309
        $querybuilder->insert($table);
310
311
        foreach ($data as $colname => $col) {
312
            $querybuilder
313
                ->setValue($colname, ':'.$colname)
314
                ->setParameter(':'.$colname, $col);
315
        }
316
317
        $querybuilder->execute();
318
319
        return $dbal->lastInsertId();
320
    }
321
}
322