Completed
Push — master ( ae86ae...26bb40 )
by Marcus
02:07
created

Helper   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 260
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 9

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 55
c 4
b 1
f 0
lcom 0
cbo 9
dl 0
loc 260
rs 6

11 Methods

Rating   Name   Duplication   Size   Complexity  
A redirectToPage() 0 9 2
A terminateScript() 0 4 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
C getLanguage() 0 31 15
C getPurifier() 0 34 7
A twigCallback() 0 13 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
25
/**
26
 * Class Helper
27
 * @package HaaseIT\HCSF
28
 */
29
class Helper
30
{
31
    /**
32
     * @param string $target
33
     * @param bool $replace
34
     * @param int $http_response_header
35
     * @return void|false
36
     */
37
    public static function redirectToPage($target = '', $replace = false, $http_response_header = 302)
38
    {
39
        if (empty($target)) {
40
            return false;
41
        }
42
43
        header('Location: '.$target, $replace, $http_response_header);
44
        self::terminateScript();
45
    }
46
47
    /**
48
     * @param string $message
49
     */
50
    public static function terminateScript($message = '')
51
    {
52
        die($message);
0 ignored issues
show
Coding Style Compatibility introduced by
The method terminateScript() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
53
    }
54
55
    /**
56
     * @param $file
57
     * @param int $width
58
     * @param int $height
59
     * @return bool|string
60
     */
61
    public static function getSignedGlideURL($file, $width = 0, $height = 0)
62
    {
63
        $urlBuilder = \League\Glide\Urls\UrlBuilderFactory::create('', HelperConfig::$secrets['glide_signkey']);
64
65
        $param = [];
66
        if ($width == 0 && $height == 0) {
67
            return false;
68
        }
69
        if ($width != 0) {
70
            $param['w'] = $width;
71
        }
72
        if ($height != 0) {
73
            $param['h'] = $height;
74
        }
75
        if ($width != 0 && $height != 0) {
76
            $param['fit'] = 'stretch';
77
        }
78
79
        return $urlBuilder->getUrl($file, $param);
80
    }
81
82
    /**
83
     * @param $to
84
     * @param string $subject
85
     * @param string $message
86
     * @param array $aImagesToEmbed
87
     * @param array $aFilesToAttach
88
     * @return bool
89
     */
90
    public static function mailWrapper($to, $subject = '(No subject)', $message = '', $aImagesToEmbed = [], $aFilesToAttach = []) {
91
        $mail = new \PHPMailer;
92
        $mail->CharSet = 'UTF-8';
93
94
        $mail->isMail();
95
        if (HelperConfig::$core['mail_method'] === 'sendmail') {
96
            $mail->isSendmail();
97
        } elseif (HelperConfig::$core['mail_method'] === 'smtp') {
98
            $mail->isSMTP();
99
            $mail->Host = HelperConfig::$secrets['mail_smtp_server'];
100
            $mail->Port = HelperConfig::$secrets['mail_smtp_port'];
101
            if (HelperConfig::$secrets['mail_smtp_auth'] === true) {
102
                $mail->SMTPAuth = true;
103
                $mail->Username = HelperConfig::$secrets['mail_smtp_auth_user'];
104
                $mail->Password = HelperConfig::$secrets['mail_smtp_auth_pwd'];
105
                if (HelperConfig::$secrets['mail_smtp_secure']) {
106
                    $mail->SMTPSecure = 'tls';
107
                    if (HelperConfig::$secrets['mail_smtp_secure_method'] === 'ssl') {
108
                        $mail->SMTPSecure = 'ssl';
109
                    }
110
                }
111
            }
112
        }
113
114
        $mail->From = HelperConfig::$core['email_sender'];
115
        $mail->FromName = HelperConfig::$core['email_sendername'];
116
        $mail->addAddress($to);
117
        $mail->isHTML(true);
118
        $mail->Subject = $subject;
119
        $mail->Body = $message;
120
121
        if (is_array($aImagesToEmbed) && count($aImagesToEmbed)) {
122
            foreach ($aImagesToEmbed as $sKey => $imgdata) {
123
                $imginfo = getimagesizefromstring($imgdata['binimg']);
124
                $mail->addStringEmbeddedImage($imgdata['binimg'], $sKey, $sKey, 'base64', $imginfo['mime']);
125
            }
126
        }
127
128
        if (is_array($aFilesToAttach) && count($aFilesToAttach)) {
129
            foreach ($aFilesToAttach as $sValue) {
130
                if (file_exists($sValue)) {
131
                    $mail->addAttachment($sValue);
132
                }
133
            }
134
        }
135
136
        return $mail->send();
137
    }
138
139
    // don't remove this, this is the fallback for unavailable twig functions
140
    /**
141
     * @param $string
142
     * @return mixed
143
     */
144
    public static function reachThrough($string) {
145
        return $string;
146
    }
147
    // don't remove this, this is the fallback for unavailable twig functions
148
    /**
149
     * @return string
150
     */
151
    public static function returnEmptyString() {
152
        return '';
153
    }
154
155
    /**
156
     * @param array $aP
157
     * @param Page $P
158
     */
159
    public static function getDebug($aP, $P)
0 ignored issues
show
Coding Style introduced by
getDebug uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
getDebug uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
getDebug uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
160
    {
161
        if (!empty($_POST)) {
162
            Tools::debug($_POST, '$_POST');
163
        } elseif (!empty($_REQUEST)) {
164
            Tools::debug($_REQUEST, '$_REQUEST');
165
        }
166
        if (!empty($_SESSION)) {
167
            Tools::debug($_SESSION, '$_SESSION');
168
        }
169
        Tools::debug($aP, '$aP');
170
        Tools::debug($P, '$P');
171
    }
172
173
    /**
174
     * @return int|mixed|string
175
     */
176
    public static function getLanguage()
0 ignored issues
show
Coding Style introduced by
getLanguage uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
getLanguage uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
getLanguage uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
177
    {
178
        $langavailable = HelperConfig::$core['lang_available'];
179
        if (
180
            HelperConfig::$core['lang_detection_method'] === 'domain'
181
            && isset(HelperConfig::$core['lang_by_domain'])
182
            && is_array(HelperConfig::$core['lang_by_domain'])
183
        ) { // domain based language detection
184
            foreach (HelperConfig::$core['lang_by_domain'] as $sKey => $sValue) {
185
                if ($_SERVER['SERVER_NAME'] == $sValue || $_SERVER['SERVER_NAME'] == 'www.'.$sValue) {
186
                    $sLang = $sKey;
187
                    break;
188
                }
189
            }
190
        } elseif (HelperConfig::$core['lang_detection_method'] === 'legacy') { // legacy language detection
191
            $sLang = key($langavailable);
192
            if (isset($_GET['language']) && array_key_exists($_GET['language'], $langavailable)) {
193
                $sLang = strtolower($_GET['language']);
194
                setcookie('language', strtolower($_GET['language']), 0, '/');
195
            } elseif (isset($_COOKIE['language']) && array_key_exists($_COOKIE['language'], $langavailable)) {
196
                $sLang = strtolower($_COOKIE['language']);
197
            } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && array_key_exists(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2), $langavailable)) {
198
                $sLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
199
            }
200
        }
201
        if (!isset($sLang)) {
202
            $sLang = key($langavailable);
203
        }
204
205
        return $sLang;
206
    }
207
208
    /**
209
     * @param string $purpose
210
     * @return bool|\HTMLPurifier
211
     */
212
    public static function getPurifier($purpose)
213
    {
214
        $purifier_config = \HTMLPurifier_Config::createDefault();
215
        $purifier_config->set('Core.Encoding', 'UTF-8');
216
        $purifier_config->set('Cache.SerializerPath', PATH_PURIFIERCACHE);
217
        $purifier_config->set('HTML.Doctype', HelperConfig::$core['purifier_doctype']);
218
219
        if ($purpose === 'textcat') {
220
            $configkey = 'textcat';
221
            $configsection = 'core';
222
        } elseif ($purpose === 'page') {
223
            $configkey = 'pagetext';
224
            $configsection = 'core';
225
        } elseif ($purpose === 'item') {
226
            $configkey = 'itemtext';
227
            $configsection = 'shop';
228
        } elseif ($purpose === 'itemgroup') {
229
            $configkey = 'itemgrouptext';
230
            $configsection = 'shop';
231
        } else {
232
            return false;
233
        }
234
235
        if (!empty(HelperConfig::${$configsection}[$configkey.'_unsafe_html_whitelist'])) {
236
            $purifier_config->set('HTML.Allowed', HelperConfig::${$configsection}[$configkey.'_unsafe_html_whitelist']);
237
        }
238
        if (!empty(HelperConfig::${$configsection}[$configkey.'_loose_filtering'])) {
239
            $purifier_config->set('HTML.Trusted', true);
240
            $purifier_config->set('Attr.EnableID', true);
241
            $purifier_config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']);
242
        }
243
244
        return new \HTMLPurifier($purifier_config);
245
    }
246
247
    /**
248
     * @param $callback
249
     * @param $parameters
250
     * @return bool|mixed
251
     */
252
    public static function twigCallback($callback, $parameters)
253
    {
254
        $callbacks = [
255
            'renderItemStatusIcon' => '\HaaseIT\HCSF\Shop\Helper::renderItemStatusIcon',
256
            'shopadminMakeCheckbox' => '\HaaseIT\HCSF\Shop\Helper::shopadminMakeCheckbox',
257
        ];
258
259
        if (!isset($callbacks[$callback])) {
260
            return false;
261
        }
262
        
263
        return call_user_func($callbacks[$callback], $parameters);
264
    }
265
266
    /**
267
     * @param \Doctrine\DBAL\Connection $dbal
268
     * @param string $table
269
     * @param array $data
270
     * @return string
271
     */
272
    public static function autoInsert(\Doctrine\DBAL\Connection $dbal, $table, array $data)
273
    {
274
        /** @var \Doctrine\DBAL\Query\QueryBuilder $querybuilder */
275
        $querybuilder = $dbal->createQueryBuilder();
276
        $querybuilder->insert($table);
277
278
        foreach ($data as $colname => $col) {
279
            $querybuilder
280
                ->setValue($colname, ':'.$colname)
281
                ->setParameter(':'.$colname, $col);
282
        }
283
284
        $querybuilder->execute();
285
286
        return $dbal->lastInsertId();
287
    }
288
}
289