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

HCSF::generatePage()   F

Complexity

Conditions 22
Paths 18432

Size

Total Lines 107
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 107
rs 2
cc 22
eloc 69
nc 18432
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace HaaseIT\HCSF;
4
5
use Zend\ServiceManager\ServiceManager;
6
use HaaseIT\HCSF\Shop\Helper as SHelper;
7
8
class HCSF
9
{
10
    /**
11
     * @var ServiceManager
12
     */
13
    protected $serviceManager;
14
15
    public function __construct()
16
    {
17
        define('HCSF_BASEDIR', dirname(__DIR__).DIRECTORY_SEPARATOR);
18
        define('DB_ADDRESSFIELDS', 'cust_id, cust_no, cust_email, cust_corp, cust_name, cust_street, cust_zip, cust_town, cust_phone, cust_cellphone, cust_fax, cust_country, cust_group, cust_active, cust_emailverified, cust_tosaccepted, cust_cancellationdisclaimeraccepted');
19
        define('DB_ITEMFIELDS', 'itm_no, itm_name, itm_price, itm_vatid, itm_rg, itm_img, itm_group, itm_data, itm_weight, itml_name_override, itml_text1, itml_text2, itm_index');
20
        define('DB_ITEMGROUPFIELDS', 'itmg_no, itmg_name, itmg_img, itmgt_shorttext, itmgt_details');
21
        define('FILE_PAYPALLOG', 'ipnlog.txt');
22
23
        // set scale for bcmath
24
        bcscale(6);
25
    }
26
27
    public function init()
28
    {
29
        $this->serviceManager = new ServiceManager();
30
31
        $this->setupRequest();
32
33
        HelperConfig::init();
34
        if (HelperConfig::$core['debug']) {
35
            \HaaseIT\Toolbox\Tools::$bEnableDebug = true;
36
        }
37
38
        $this->setupSession();
39
40
        date_default_timezone_set(HelperConfig::$core['defaulttimezone']);
41
42
        $this->setupHardcodedTextcats();
43
44
        $this->serviceManager->setFactory('db', function () {
45
            return null;
46
        });
47
48
        if (!HelperConfig::$core['maintenancemode']) {
49
            $this->setupDB();
50
            $this->setupTextcats();
51
            HelperConfig::loadNavigation($this->serviceManager);
52
        }
53
54
        $this->setupTwig();
55
56
        if (HelperConfig::$core['enable_module_shop']) {
57
            $this->serviceManager->setFactory('oItem', function (ServiceManager $serviceManager) {
58
                return new \HaaseIT\HCSF\Shop\Items($serviceManager);
59
            });
60
        }
61
62
        $router = new \HaaseIT\HCSF\Router($this->serviceManager);
63
        return $router->getPage();
64
    }
65
66
    protected function setupRequest()
0 ignored issues
show
Coding Style introduced by
setupRequest 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...
67
    {
68
        // PSR-7 Stuff
69
        // Init request object
70
        $this->serviceManager->setFactory('request', function () {
71
            $request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
72
73
            // cleanup request
74
            $requesturi = urldecode($request->getRequestTarget());
75
            $parsedrequesturi = substr($requesturi, strlen(dirname($_SERVER['PHP_SELF'])));
76
            if (substr($parsedrequesturi, 1, 1) !== '/') {
77
                $parsedrequesturi = '/'.$parsedrequesturi;
78
            }
79
            return $request->withRequestTarget($parsedrequesturi);
80
        });
81
    }
82
83
    protected function setupSession()
0 ignored issues
show
Coding Style introduced by
setupSession 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...
Coding Style introduced by
setupSession 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...
Coding Style introduced by
setupSession 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...
84
    {
85
        if (isset($_COOKIE['acceptscookies']) && HelperConfig::$core['enable_module_customer'] && $_COOKIE['acceptscookies'] === 'yes') {
86
            // Session handling
87
            // session.use_trans_sid wenn nötig aktivieren
88
            ini_set('session.use_only_cookies', 0);
89
            session_name('sid');
90
            if(ini_get('session.use_trans_sid') == 1) {
91
                ini_set('session.use_trans_sid', 0);
92
            }
93
            // Session wenn nötig starten
94
            if (session_id() == '') {
95
                session_start();
96
            }
97
98
            // check if the stored ip and ua equals the clients, if not, reset. if not set at all, reset
99
            if (!empty($_SESSION['hijackprevention'])) {
100
                if (
101
                    $_SESSION['hijackprevention']['remote_addr'] != $_SERVER['REMOTE_ADDR']
102
                    ||
103
                    $_SESSION['hijackprevention']['user_agent'] != $_SERVER['HTTP_USER_AGENT']
104
                ) {
105
                    \session_regenerate_id();
106
                    \session_unset();
107
                }
108
            } else {
109
                \session_regenerate_id();
110
                \session_unset();
111
                $_SESSION['hijackprevention']['remote_addr'] = $_SERVER['REMOTE_ADDR'];
112
                $_SESSION['hijackprevention']['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
113
            }
114
        }
115
    }
116
117
    protected function setupHardcodedTextcats()
118
    {
119
        if (file_exists(HCSF_BASEDIR.'src/hardcodedtextcats/'.HelperConfig::$lang.'.php')) {
120
            $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/'.HelperConfig::$lang.'.php';
121
        } else {
122
            if (file_exists(HCSF_BASEDIR.'src/hardcodedtextcats/'.key(HelperConfig::$core['lang_available']).'.php')) {
123
                $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/'.key(HelperConfig::$core['lang_available']).'.php';
124
            } else {
125
                $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/de.php';
126
            }
127
        }
128
129
        HardcodedText::init($HT);
130
    }
131
132
    protected function setupDB()
133
    {
134
        $this->serviceManager->setFactory('dbal', function () {
135
            $config = new \Doctrine\DBAL\Configuration();
136
137
            $connectionParams = [
138
                'url' =>
139
                    HelperConfig::$secrets['db_type'].'://'
140
                    .HelperConfig::$secrets['db_user'].':'
141
                    .HelperConfig::$secrets['db_password'].'@'
142
                    .HelperConfig::$secrets['db_server'].'/'
143
                    .HelperConfig::$secrets['db_name'],
144
                'charset' => 'UTF8',
145
                'driverOptions' => [
146
                    \PDO::ATTR_EMULATE_PREPARES => false,
147
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
148
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
149
                ],
150
            ];
151
152
            return \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
153
        });
154
155
        $this->serviceManager->setFactory('db', function (ServiceManager $serviceManager) {
156
            return $serviceManager->get('dbal')->getWrappedConnection();
157
        });
158
    }
159
160
    protected function setupTextcats()
161
    {
162
        $this->serviceManager->setFactory('textcats', function (ServiceManager $serviceManager) {
163
            $langavailable = HelperConfig::$core['lang_available'];
164
            $textcats = new \HaaseIT\Toolbox\Textcat(
165
                HelperConfig::$lang,
166
                $serviceManager->get('db'),
167
                key($langavailable),
168
                HelperConfig::$core['textcatsverbose'],
169
                PATH_LOGS
170
            );
171
            $textcats->loadTextcats();
172
173
            return $textcats;
174
        });
175
    }
176
177
    protected function setupTwig()
178
    {
179
        $this->serviceManager->setFactory('twig', function (ServiceManager $serviceManager) {
180
            $loader = new \Twig_Loader_Filesystem([PATH_BASEDIR.'customviews', HCSF_BASEDIR.'src/views/']);
181
182
            $twig_options = [
183
                'autoescape' => false,
184
                'debug' => HelperConfig::$core['debug'] ? true : false,
185
            ];
186
            if (HelperConfig::$core['templatecache_enable'] &&
187
                is_dir(PATH_TEMPLATECACHE) && is_writable(PATH_TEMPLATECACHE)) {
188
                $twig_options['cache'] = PATH_TEMPLATECACHE;
189
            }
190
            $twig = new \Twig_Environment($loader, $twig_options);
191
192
            if (HelperConfig::$core['allow_parsing_of_page_content']) {
193
                $twig->addExtension(new \Twig_Extension_StringLoader());
194
            } else { // make sure, template_from_string is callable
195
                $twig->addFunction(new \Twig_SimpleFunction('template_from_string', '\HaaseIT\HCSF\Helper::reachThrough'));
196
            }
197
198
            if (!HelperConfig::$core['maintenancemode']) {
199
                $twig->addFunction(new \Twig_SimpleFunction('T', [$serviceManager->get('textcats'), 'T']));
200
            } else {
201
                $twig->addFunction(new \Twig_SimpleFunction('T', '\HaaseIT\HCSF\Helper::returnEmptyString'));
202
            }
203
204
            $twig->addFunction(new \Twig_SimpleFunction('HT', '\HaaseIT\HCSF\HardcodedText::get'));
205
            $twig->addFunction(new \Twig_SimpleFunction('gFF', '\HaaseIT\Toolbox\Tools::getFormField'));
206
            $twig->addFunction(new \Twig_SimpleFunction('ImgURL', '\HaaseIT\HCSF\Helper::getSignedGlideURL'));
207
            $twig->addFunction(new \Twig_SimpleFunction('callback', 'HaaseIT\HCSF\Helper::twigCallback'));
208
            $twig->addFunction(new \Twig_SimpleFunction('makeLinkHRefWithAddedGetVars', '\HaaseIT\Toolbox\Tools::makeLinkHRefWithAddedGetVars'));
209
            $twig->addFilter(new \Twig_SimpleFilter('decodehtmlentity', 'html_entity_decode'));
210
211
            return $twig;
212
        });
213
    }
214
215
    /**
216
     * @return mixed
217
     */
218
    public function getServiceManager()
219
    {
220
        return $this->serviceManager;
221
    }
222
223
    /**
224
     * @param Page $P
225
     * @return array
226
     */
227
    public function generatePage(Page $P)
0 ignored issues
show
Coding Style introduced by
generatePage 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...
228
    {
229
        $requesturi = $this->serviceManager->get('request')->getRequestTarget();
230
231
        $aP = [
232
            'language' => HelperConfig::$lang,
233
            'pageconfig' => $P->cb_pageconfig,
234
            'pagetype' => $P->cb_pagetype,
235
            'subnavkey' => $P->cb_subnav,
236
            'requesturi' => $requesturi,
237
            'requesturiarray' => parse_url($requesturi),
238
            'locale_format_date' => HelperConfig::$core['locale_format_date'],
239
            'locale_format_date_time' => HelperConfig::$core['locale_format_date_time'],
240
            'maintenancemode' => HelperConfig::$core['maintenancemode'],
241
            'numberformat_decimals' => HelperConfig::$core['numberformat_decimals'],
242
            'numberformat_decimal_point' => HelperConfig::$core['numberformat_decimal_point'],
243
            'numberformat_thousands_seperator' => HelperConfig::$core['numberformat_thousands_seperator'],
244
            'customroottemplate' => $P->getCustomRootTemplate(),
245
            'headers' => $P->getHeaders(),
246
        ];
247
        if (HelperConfig::$core['enable_module_customer']) {
248
            $aP['isloggedin'] = \HaaseIT\HCSF\Customer\Helper::getUserData();
249
            $aP['enable_module_customer'] = true;
250
        }
251
        if (HelperConfig::$core['enable_module_shop']) {
252
            $aP['currency'] = HelperConfig::$shop['waehrungssymbol'];
253
            $aP['orderamounts'] = HelperConfig::$shop['orderamounts'];
254
            if (isset(HelperConfig::$shop['vat']['full'])) {
255
                $aP['vatfull'] = HelperConfig::$shop['vat']['full'];
256
            }
257
            if (isset(HelperConfig::$shop['vat']['reduced'])) {
258
                $aP['vatreduced'] = HelperConfig::$shop['vat']['reduced'];
259
            }
260
            if (isset(HelperConfig::$shop['custom_order_fields'])) {
261
                $aP['custom_order_fields'] = HelperConfig::$shop['custom_order_fields'];
262
            }
263
            $aP['enable_module_shop'] = true;
264
        }
265
        if (isset($P->cb_key)) {
266
            $aP['path'] = pathinfo($P->cb_key);
0 ignored issues
show
Bug introduced by
The property cb_key does not seem to exist in HaaseIT\HCSF\Page.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
267
        } else {
268
            $aP['path'] = pathinfo($aP['requesturi']);
269
        }
270
        if ($P->cb_customcontenttemplate != NULL) {
271
            $aP['customcontenttemplate'] = $P->cb_customcontenttemplate;
272
        }
273
        if ($P->cb_customdata != NULL) {
274
            $aP['customdata'] = $P->cb_customdata;
275
        }
276
        if (isset($_SERVER['HTTP_REFERER'])) {
277
            $aP['referer'] = $_SERVER['HTTP_REFERER'];
278
        }
279
280
        // if there is no subnav defined but there is a default subnav defined, use it
281
        // subnavkey can be used in the templates to find out, where we are
282
        if ((!isset($aP['subnavkey']) || $aP['subnavkey'] == '') && HelperConfig::$core['subnav_default'] != '') {
283
            $aP['subnavkey'] = HelperConfig::$core['subnav_default'];
284
            $P->cb_subnav = HelperConfig::$core['subnav_default'];
285
        }
286
        if ($P->cb_subnav != NULL && isset(HelperConfig::$navigation[$P->cb_subnav])) {
287
            $aP['subnav'] = HelperConfig::$navigation[$P->cb_subnav];
288
        }
289
290
        // Get page title, meta-keywords, meta-description
291
        $aP['pagetitle'] = $P->oPayload->getTitle();
292
        $aP['keywords'] = $P->oPayload->cl_keywords;
293
        $aP['description'] = $P->oPayload->cl_description;
294
295
        // TODO: Add head scripts to DB
296
        //if (isset($P["head_scripts"]) && $P["head_scripts"] != '') $aP["head_scripts"] = $P["head_scripts"];
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
297
298
        // Shopping cart infos
299
        if (HelperConfig::$core['enable_module_shop']) {
300
            $aP['cartinfo'] = SHelper::getShoppingcartData();
301
        }
302
303
        $aP['countrylist'][] = ' | ';
304
        foreach (HelperConfig::$countries['countries_' .HelperConfig::$lang] as $sKey => $sValue) {
305
            $aP['countrylist'][] = $sKey.'|'.$sValue;
306
        }
307
308
        if (
309
            HelperConfig::$core['enable_module_shop']
310
            && (
311
                $aP['pagetype'] === 'itemoverview'
312
                || $aP['pagetype'] === 'itemoverviewgrpd'
313
                || $aP['pagetype'] === 'itemdetail'
314
            )
315
        ) {
316
            $aP = SHelper::handleItemPage($this->serviceManager, $P, $aP);
317
        }
318
319
        $aP['content'] = $P->oPayload->cl_html;
320
321
        $aP['content'] = str_replace('@', '&#064;', $aP['content']); // Change @ to HTML Entity -> maybe less spam mails
322
323
        $aP['lang_available'] = HelperConfig::$core['lang_available'];
324
        $aP['lang_detection_method'] = HelperConfig::$core['lang_detection_method'];
325
        $aP['lang_by_domain'] = HelperConfig::$core['lang_by_domain'];
326
327
        if (HelperConfig::$core['debug']) {
328
            self::getDebug($aP, $P);
0 ignored issues
show
Bug introduced by
The method getDebug() does not seem to exist on object<HaaseIT\HCSF\HCSF>.

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...
329
            $aP['debugdata'] = \HaaseIT\Toolbox\Tools::$sDebug;
330
        }
331
332
        return $aP;
333
    }
334
}