Completed
Push — master ( ce178a...31732a )
by Marcus
02:32
created

Helper   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 7

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 50
c 3
b 0
f 0
lcom 0
cbo 7
dl 0
loc 214
rs 8.6206

8 Methods

Rating   Name   Duplication   Size   Complexity  
B getSignedGlideURL() 0 20 7
C mailWrapper() 0 49 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

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 $file
33
     * @param int $width
34
     * @param int $height
35
     * @return bool|string
36
     */
37
    public static function getSignedGlideURL($file, $width = 0, $height = 0)
38
    {
39
        $urlBuilder = \League\Glide\Urls\UrlBuilderFactory::create('', HelperConfig::$secrets['glide_signkey']);
40
41
        $param = [];
42
        if ($width == 0 && $height == 0) {
43
            return false;
44
        }
45
        if ($width != 0) {
46
            $param['w'] = $width;
47
        }
48
        if ($height != 0) {
49
            $param['h'] = $height;
50
        }
51
        if ($width != 0 && $height != 0) {
52
            $param['fit'] = 'stretch';
53
        }
54
55
        return $urlBuilder->getUrl($file, $param);
56
    }
57
58
    /**
59
     * @param $to
60
     * @param string $subject
61
     * @param string $message
62
     * @param array $aImagesToEmbed
63
     * @param array $aFilesToAttach
64
     * @return bool
65
     */
66
    public static function mailWrapper($to, $subject = '(No subject)', $message = '', $aImagesToEmbed = [], $aFilesToAttach = []) {
67
        $mail = new \PHPMailer;
68
        $mail->CharSet = 'UTF-8';
69
70
        $mail->isMail();
71
        if (HelperConfig::$core['mail_method'] === 'sendmail') {
72
            $mail->isSendmail();
73
        } elseif (HelperConfig::$core['mail_method'] === 'smtp') {
74
            $mail->isSMTP();
75
            $mail->Host = HelperConfig::$secrets['mail_smtp_server'];
76
            $mail->Port = HelperConfig::$secrets['mail_smtp_port'];
77
            if (HelperConfig::$secrets['mail_smtp_auth'] === true) {
78
                $mail->SMTPAuth = true;
79
                $mail->Username = HelperConfig::$secrets['mail_smtp_auth_user'];
80
                $mail->Password = HelperConfig::$secrets['mail_smtp_auth_pwd'];
81
                if (HelperConfig::$secrets['mail_smtp_secure']) {
82
                    $mail->SMTPSecure = 'tls';
83
                    if (HelperConfig::$secrets['mail_smtp_secure_method'] === 'ssl') {
84
                        $mail->SMTPSecure = 'ssl';
85
                    }
86
                }
87
            }
88
        }
89
90
        $mail->From = HelperConfig::$core['email_sender'];
91
        $mail->FromName = HelperConfig::$core['email_sendername'];
92
        $mail->addAddress($to);
93
        $mail->isHTML(true);
94
        $mail->Subject = $subject;
95
        $mail->Body = $message;
96
97
        if (is_array($aImagesToEmbed) && count($aImagesToEmbed)) {
98
            foreach ($aImagesToEmbed as $sKey => $imgdata) {
99
                $imginfo = getimagesizefromstring($imgdata['binimg']);
100
                $mail->addStringEmbeddedImage($imgdata['binimg'], $sKey, $sKey, 'base64', $imginfo['mime']);
101
            }
102
        }
103
104
        if (is_array($aFilesToAttach) && count($aFilesToAttach)) {
105
            foreach ($aFilesToAttach as $sValue) {
106
                if (file_exists($sValue)) {
107
                    $mail->addAttachment($sValue);
108
                }
109
            }
110
        }
111
112
        //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
113
        return $mail->send();
114
    }
115
116
    // don't remove this, this is the fallback for unavailable twig functions
117
    /**
118
     * @param $string
119
     * @return mixed
120
     */
121
    public static function reachThrough($string) {
122
        return $string;
123
    }
124
    // don't remove this, this is the fallback for unavailable twig functions
125
    /**
126
     * @return string
127
     */
128
    public static function returnEmptyString() {
129
        return '';
130
    }
131
132
    /**
133
     * @param array $aP
134
     * @param Page $P
135
     */
136
    private static function getDebug($aP, $P)
0 ignored issues
show
Unused Code introduced by
The parameter $P is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
137
    {
138
        if (!empty($_POST)) {
139
            Tools::debug($_POST, '$_POST');
140
        } elseif (!empty($_REQUEST)) {
141
            Tools::debug($_REQUEST, '$_REQUEST');
142
        }
143
        if (!empty($_SESSION)) {
144
            Tools::debug($_SESSION, '$_SESSION');
145
        }
146
        Tools::debug($aP, '$aP');
147
        //Tools::debug($P, '$P');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
148
    }
149
150
    /**
151
     * @return int|mixed|string
152
     */
153
    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...
154
    {
155
        $langavailable = HelperConfig::$core['lang_available'];
156
        if (
157
            HelperConfig::$core['lang_detection_method'] === 'domain'
158
            && isset(HelperConfig::$core['lang_by_domain'])
159
            && is_array(HelperConfig::$core['lang_by_domain'])
160
        ) { // domain based language detection
161
            foreach (HelperConfig::$core['lang_by_domain'] as $sKey => $sValue) {
162
                if ($_SERVER['SERVER_NAME'] == $sValue || $_SERVER['SERVER_NAME'] == 'www.'.$sValue) {
163
                    $sLang = $sKey;
164
                    break;
165
                }
166
            }
167
        } elseif (HelperConfig::$core['lang_detection_method'] === 'legacy') { // legacy language detection
168
            $sLang = key($langavailable);
169
            if (isset($_GET['language']) && array_key_exists($_GET['language'], $langavailable)) {
170
                $sLang = strtolower($_GET['language']);
171
                setcookie('language', strtolower($_GET['language']), 0, '/');
172
            } elseif (isset($_COOKIE['language']) && array_key_exists($_COOKIE['language'], $langavailable)) {
173
                $sLang = strtolower($_COOKIE['language']);
174
            } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && array_key_exists(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2), $langavailable)) {
175
                $sLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
176
            }
177
        }
178
        if (!isset($sLang)) {
179
            $sLang = key($langavailable);
180
        }
181
182
        return $sLang;
183
    }
184
185
    /**
186
     * @param string $purpose
187
     * @return bool|\HTMLPurifier
188
     */
189
    public static function getPurifier($purpose)
190
    {
191
        $purifier_config = \HTMLPurifier_Config::createDefault();
192
        $purifier_config->set('Core.Encoding', 'UTF-8');
193
        $purifier_config->set('Cache.SerializerPath', PATH_PURIFIERCACHE);
194
        $purifier_config->set('HTML.Doctype', HelperConfig::$core['purifier_doctype']);
195
196
        if ($purpose === 'textcat') {
197
            $configkey = 'textcat';
198
            $configsection = 'core';
199
        } elseif ($purpose === 'page') {
200
            $configkey = 'pagetext';
201
            $configsection = 'core';
202
        } elseif ($purpose === 'item') {
203
            $configkey = 'itemtext';
204
            $configsection = 'shop';
205
        } elseif ($purpose === 'itemgroup') {
206
            $configkey = 'itemgrouptext';
207
            $configsection = 'shop';
208
        } else {
209
            return false;
210
        }
211
212
        if (!empty(HelperConfig::${$configsection}[$configkey.'_unsafe_html_whitelist'])) {
213
            $purifier_config->set('HTML.Allowed', HelperConfig::${$configsection}[$configkey.'_unsafe_html_whitelist']);
214
        }
215
        if (!empty(HelperConfig::${$configsection}[$configkey.'_loose_filtering'])) {
216
            $purifier_config->set('HTML.Trusted', true);
217
            $purifier_config->set('Attr.EnableID', true);
218
            $purifier_config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']);
219
        }
220
221
        return new \HTMLPurifier($purifier_config);
222
    }
223
224
    /**
225
     * @param $callback
226
     * @param $parameters
227
     * @return bool|mixed
228
     */
229
    public static function twigCallback($callback, $parameters)
230
    {
231
        $callbacks = [
232
            'renderItemStatusIcon' => '\HaaseIT\HCSF\Shop\Helper::renderItemStatusIcon',
233
            'shopadminMakeCheckbox' => '\HaaseIT\HCSF\Shop\Helper::shopadminMakeCheckbox',
234
        ];
235
236
        if (!isset($callbacks[$callback])) {
237
            return false;
238
        }
239
        
240
        return call_user_func($callbacks[$callback], $parameters);
241
    }
242
}