HCSF   C
last analyzed

Complexity

Total Complexity 57

Size/Duplication

Total Lines 404
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 20

Importance

Changes 0
Metric Value
wmc 57
lcom 1
cbo 20
dl 0
loc 404
rs 5.04
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 1
F init() 0 78 11
A setupHardcodedTextcats() 0 16 3
A setupDB() 0 27 1
A setupTextcats() 0 16 1
B setupTwig() 0 37 7
A getServiceManager() 0 4 1
A setupRequest() 0 10 1
B setupSession() 0 37 8
F generatePage() 0 110 23

How to fix   Complexity   

Complex Class

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

1
<?php
2
3
namespace HaaseIT\HCSF;
4
5
use Zend\ServiceManager\ServiceManager;
6
7
class HCSF
8
{
9
    /**
10
     * @var ServiceManager
11
     */
12
    protected $serviceManager;
13
14
    /**
15
     * @var HelperConfig
16
     */
17
    protected $config;
18
19
    /**
20
     * @var \HaaseIT\HCSF\Helper
21
     */
22
    protected $helper;
23
24
    /**
25
     * @var \HaaseIT\HCSF\Customer\Helper
26
     */
27
    protected $helperCustomer;
28
29
    /**
30
     * @var \HaaseIT\HCSF\Shop\Helper
31
     */
32
    protected $helperShop;
33
34
    /**
35
     * HCSF constructor.
36
     * @param string $basedir
37
     */
38
    public function __construct($basedir)
39
    {
40
        define('HCSF_BASEDIR', dirname(__DIR__).DIRECTORY_SEPARATOR);
41
        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');
42
        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');
43
        define('DB_ITEMGROUPFIELDS', 'itmg_no, itmg_name, itmg_img, itmgt_shorttext, itmgt_details');
44
        define('FILE_PAYPALLOG', 'ipnlog.txt');
45
        define('CLI', php_sapi_name() === 'cli');
46
47
        define("PATH_BASEDIR", $basedir.DIRECTORY_SEPARATOR);
48
        define("PATH_LOGS", PATH_BASEDIR.'hcsflogs/');
49
        define("PATH_CACHE", PATH_BASEDIR.'cache/');
50
        define("DIRNAME_TEMPLATECACHE", 'templates');
51
        define("PATH_TEMPLATECACHE", PATH_CACHE.DIRNAME_TEMPLATECACHE);
52
        define("PATH_PURIFIERCACHE", PATH_CACHE.'htmlpurifier/');
53
        define("DIRNAME_GLIDECACHE", 'glide');
54
        define("PATH_GLIDECACHE", PATH_CACHE.DIRNAME_GLIDECACHE);
55
56
        // set scale for bcmath
57
        bcscale(6);
58
    }
59
60
    public function init()
61
    {
62
        $this->serviceManager = new ServiceManager();
63
64
        if (!CLI) {
65
            $this->setupRequest();
66
        }
67
68
        $this->serviceManager->setFactory('config', function () {
69
            return new HelperConfig();
70
        });
71
        $this->config = $this->serviceManager->get('config');
72
73
        $this->serviceManager->setFactory('helper', function (ServiceManager $serviceManager) {
74
            return new \HaaseIT\HCSF\Helper($serviceManager);
75
        });
76
77
        $this->serviceManager->setFactory('helpercustomer', function (ServiceManager $serviceManager) {
78
            return new \HaaseIT\HCSF\Customer\Helper($serviceManager);
79
        });
80
81
        $this->serviceManager->setFactory('helpershop', function (ServiceManager $serviceManager) {
82
            return new \HaaseIT\HCSF\Shop\Helper($serviceManager);
83
        });
84
85
        $this->helper = $this->serviceManager->get('helper');
86
87
        if ($this->config->getCore('enable_module_customer')) {
88
            $this->helperCustomer = $this->serviceManager->get('helpercustomer');
89
        }
90
91
        if ($this->config->getCore('enable_module_shop')) {
92
            $this->helperShop = $this->serviceManager->get('helpershop');
93
        }
94
95
96
        define("PATH_DOCROOT", PATH_BASEDIR.$this->config->getCore('dirname_docroot'));
97
        if ($this->config->getCore('debug')) {
98
            \HaaseIT\Toolbox\Tools::$bEnableDebug = true;
99
        }
100
101
        if (!CLI) {
102
            $this->setupSession();
103
        }
104
105
        date_default_timezone_set($this->config->getCore('defaulttimezone'));
106
107
        $this->serviceManager->setFactory('hardcodedtextcats', function () {
108
            return $this->setupHardcodedTextcats();
109
        });
110
111
        $this->serviceManager->setFactory('db', function () {
112
            return null;
113
        });
114
115
        if (!$this->config->getCore('maintenancemode') || CLI) {
116
            $this->setupDB();
117
            $this->setupTextcats();
118
            $this->config->loadNavigation($this->serviceManager);
119
        }
120
121
        if (!CLI) {
122
            $this->setupTwig();
123
        }
124
125
        if ($this->config->getCore('enable_module_shop')) {
126
            $this->serviceManager->setFactory('oItem', function (ServiceManager $serviceManager) {
127
                return new \HaaseIT\HCSF\Shop\Items($serviceManager);
128
            });
129
        }
130
131
        if (!CLI) {
132
            $router = new \HaaseIT\HCSF\Router($this->serviceManager);
133
            return $router->getPage();
134
        }
135
136
        return true;
137
    }
138
139
    protected function setupRequest()
140
    {
141
        // PSR-7 Stuff
142
        // Init request object
143
        $this->serviceManager->setFactory('request', function () {
144
            $request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
145
146
            return $request;
147
        });
148
    }
149
150
    protected function setupSession()
151
    {
152
        if (
153
            (
154
                $this->config->getCore('enable_module_customer')
155
                || $this->config->getCore('override_enable_session')
156
            )
157
            && filter_input(INPUT_COOKIE, 'acceptscookies') === 'yes'
158
        ) {
159
            // Session handling
160
            // session.use_trans_sid wenn nötig aktivieren
161
            session_name('sid');
162
            // Session wenn nötig starten
163
            if (empty(session_id())) {
164
                session_start();
165
            }
166
167
            $serverremoteaddr = filter_input(INPUT_SERVER, 'REMOTE_ADDR');
168
            $serveruseragent = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT');
169
            // check if the stored ip and ua equals the clients, if not, reset. if not set at all, reset
170
            if (!empty($_SESSION['hijackprevention'])) {
171
                if (
172
                    $_SESSION['hijackprevention']['remote_addr'] != $serverremoteaddr
173
                    ||
174
                    $_SESSION['hijackprevention']['user_agent'] != $serveruseragent
175
                ) {
176
                    session_regenerate_id();
177
                    session_unset();
178
                }
179
            } else {
180
                session_regenerate_id();
181
                session_unset();
182
                $_SESSION['hijackprevention']['remote_addr'] = $serverremoteaddr;
183
                $_SESSION['hijackprevention']['user_agent'] = $serveruseragent;
184
            }
185
        }
186
    }
187
188
    protected function setupHardcodedTextcats()
189
    {
190
        $lang = $this->config->getLang();
191
        $langavailable = $this->config->getCore('lang_available');
192
        if (file_exists(HCSF_BASEDIR.'src/config/hardcodedtextcats/'.$lang.'.php')) {
193
            $HT = require HCSF_BASEDIR.'src/config/hardcodedtextcats/'.$lang.'.php';
194
        } else {
195
            if (file_exists(HCSF_BASEDIR.'src/config/hardcodedtextcats/'.key($langavailable).'.php')) {
196
                $HT = require HCSF_BASEDIR.'src/config/hardcodedtextcats/'.key($langavailable).'.php';
197
            } else {
198
                $HT = require HCSF_BASEDIR.'src/config/hardcodedtextcats/de.php';
199
            }
200
        }
201
202
        return new HardcodedText($HT);
203
    }
204
205
    protected function setupDB()
206
    {
207
        $this->serviceManager->setFactory('dbal', function () {
208
            $config = new \Doctrine\DBAL\Configuration();
209
210
            $connectionParams = [
211
                'url' =>
212
                    $this->config->getSecret('db_type').'://'
213
                    .$this->config->getSecret('db_user').':'
214
                    .$this->config->getSecret('db_password').'@'
215
                    .$this->config->getSecret('db_server').'/'
216
                    .$this->config->getSecret('db_name'),
217
                'charset' => 'UTF8',
218
                'driverOptions' => [
219
                    \PDO::ATTR_EMULATE_PREPARES => false,
220
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
221
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
222
                ],
223
            ];
224
225
            return \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
226
        });
227
228
        $this->serviceManager->setFactory('db', function (ServiceManager $serviceManager) {
229
            return $serviceManager->get('dbal')->getWrappedConnection();
230
        });
231
    }
232
233
    protected function setupTextcats()
234
    {
235
        $this->serviceManager->setFactory('textcats', function (ServiceManager $serviceManager) {
236
            $langavailable = $this->config->getCore('lang_available');
237
            $textcats = new \HaaseIT\Toolbox\Textcat(
238
                $this->config->getLang(),
239
                $serviceManager->get('db'),
240
                key($langavailable),
241
                $this->config->getCore('textcatsverbose'),
242
                PATH_LOGS
243
            );
244
            $textcats->loadTextcats();
245
246
            return $textcats;
247
        });
248
    }
249
250
    protected function setupTwig()
251
    {
252
        $this->serviceManager->setFactory('twig', function (ServiceManager $serviceManager) {
253
            $loader = new \Twig_Loader_Filesystem([PATH_BASEDIR.'customization/views', HCSF_BASEDIR.'src/views/']);
254
255
            $twig_options = [
256
                'autoescape' => false,
257
                'debug' => $this->config->getCore('debug') ? true : false,
258
            ];
259
            if ($this->config->getCore('templatecache_enable') &&
260
                is_dir(PATH_TEMPLATECACHE) && is_writable(PATH_TEMPLATECACHE)) {
261
                $twig_options['cache'] = PATH_TEMPLATECACHE;
262
            }
263
            $twig = new \Twig_Environment($loader, $twig_options);
264
265
            if ($this->config->getCore('allow_parsing_of_page_content')) {
266
                $twig->addExtension(new \Twig_Extension_StringLoader());
267
            } else { // make sure, template_from_string is callable
268
                $twig->addFunction(new \Twig_SimpleFunction('template_from_string', [$this->helper, 'reachThrough']));
269
            }
270
271
            if (!$this->config->getCore('maintenancemode')) {
272
                $twig->addFunction(new \Twig_SimpleFunction('T', [$serviceManager->get('textcats'), 'T']));
273
            } else {
274
                $twig->addFunction(new \Twig_SimpleFunction('T', [$this->helper, 'returnEmptyString']));
275
            }
276
277
            $twig->addFunction(new \Twig_SimpleFunction('HT', [$serviceManager->get('hardcodedtextcats'), 'get']));
278
            $twig->addFunction(new \Twig_SimpleFunction('gFF', '\HaaseIT\Toolbox\Tools::getFormField'));
279
            $twig->addFunction(new \Twig_SimpleFunction('ImgURL', [$this->helper, 'getSignedGlideURL']));
280
            $twig->addFunction(new \Twig_SimpleFunction('callback', [$this->helper, 'twigCallback']));
281
            $twig->addFunction(new \Twig_SimpleFunction('makeLinkHRefWithAddedGetVars', '\HaaseIT\Toolbox\Tools::makeLinkHRefWithAddedGetVars'));
282
            $twig->addFilter(new \Twig_SimpleFilter('decodehtmlentity', 'html_entity_decode'));
283
284
            return $twig;
285
        });
286
    }
287
288
    /**
289
     * @return ServiceManager
290
     */
291
    public function getServiceManager()
292
    {
293
        return $this->serviceManager;
294
    }
295
296
    /**
297
     * @param Page $P
298
     * @return array
299
     */
300
    public function generatePage(Page $P)
301
    {
302
        $requesturi = $this->helper->getCleanRequestTarget();
303
304
        $aP = [
305
            'language' => $this->config->getLang(),
306
            'pageconfig' => $P->cb_pageconfig,
307
            'pagetype' => $P->cb_pagetype,
308
            'subnavkey' => $P->cb_subnav,
309
            'requesturi' => $requesturi,
310
            'requesturiarray' => parse_url($requesturi),
311
            'locale_format_date' => $this->config->getCore('locale_format_date'),
312
            'locale_format_date_time' => $this->config->getCore('locale_format_date_time'),
313
            'maintenancemode' => $this->config->getCore('maintenancemode'),
314
            'numberformat_decimals' => $this->config->getCore('numberformat_decimals'),
315
            'numberformat_decimal_point' => $this->config->getCore('numberformat_decimal_point'),
316
            'numberformat_thousands_seperator' => $this->config->getCore('numberformat_thousands_seperator'),
317
            'customroottemplate' => $P->getCustomRootTemplate(),
318
            'headers' => $P->getHeaders(),
319
        ];
320
        if ($this->config->getCore('enable_module_customer')) {
321
            $aP['isloggedin'] = $this->helperCustomer->getUserData();
322
            $aP['enable_module_customer'] = true;
323
        }
324
        if ($this->config->getCore('enable_module_shop')) {
325
            $aP['currency'] = $this->config->getShop('waehrungssymbol');
326
            $aP['orderamounts'] = $this->config->getShop('orderamounts');
327
            if (!empty($this->config->getShop('vat')['full'])) {
328
                $aP['vatfull'] = $this->config->getShop('vat')['full'];
329
            }
330
            if (!empty($this->config->getShop('vat')['reduced'])) {
331
                $aP['vatreduced'] = $this->config->getShop('vat')['reduced'];
332
            }
333
            if (!empty($this->config->getShop('custom_order_fields'))) {
334
                $aP['custom_order_fields'] = $this->config->getShop('custom_order_fields');
335
            }
336
            $aP['enable_module_shop'] = true;
337
        }
338
        if (isset($P->cb_key)) {
339
            $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...
340
        } else {
341
            $aP['path'] = pathinfo($aP['requesturi']);
342
        }
343
        if ($P->cb_customcontenttemplate != null) {
344
            $aP['customcontenttemplate'] = $P->cb_customcontenttemplate;
345
        }
346
        if ($P->cb_customdata != null) {
347
            $aP['customdata'] = $P->cb_customdata;
348
        }
349
        $serverhttpreferer = filter_input(INPUT_SERVER, 'HTTP_REFERER');
350
        if ($serverhttpreferer !== null) {
351
            $aP['referer'] = $serverhttpreferer;
352
        }
353
354
        // if there is no subnav defined but there is a default subnav defined, use it
355
        // subnavkey can be used in the templates to find out, where we are
356
        if (empty($aP['subnavkey']) && !empty($this->config->getCore('subnav_default'))) {
357
            $aP['subnavkey'] = $this->config->getCore('subnav_default');
358
            $P->cb_subnav = $this->config->getCore('subnav_default');
359
        }
360
        if ($P->cb_subnav != null && !empty($this->config->getNavigation($P->cb_subnav))) {
361
            $aP['subnav'] = $this->config->getNavigation($P->cb_subnav);
362
        }
363
364
        // Get page title, meta-keywords, meta-description
365
        $aP['pagetitle'] = '';
366
        if (method_exists($P->oPayload, 'getTitle')) {
367
            $aP['pagetitle'] = $P->oPayload->getTitle();
368
        }
369
        $aP['keywords'] = $P->oPayload->cl_keywords;
370
        $aP['description'] = $P->oPayload->cl_description;
371
372
        // Shopping cart infos
373
        if ($this->config->getCore('enable_module_shop')) {
374
            $aP['cartinfo'] = $this->helperShop->getShoppingcartData();
375
        }
376
377
        $aP['countrylist'][] = ' | ';
378
        $configcountries = $this->config->getCountries('countries_' .$this->config->getLang());
379
        foreach ($configcountries as $sKey => $sValue) {
380
            $aP['countrylist'][] = $sKey.'|'.$sValue;
381
        }
382
383
        if ($this->config->getCore('enable_module_shop')) {
384
            if (
385
                $aP['pagetype'] === 'itemoverview'
386
                || $aP['pagetype'] === 'itemoverviewgrpd'
387
                || $aP['pagetype'] === 'itemdetail'
388
            ) {
389
                $aP = $this->helperShop->handleItemPage($this->serviceManager, $P, $aP);
390
            } elseif ($aP['pagetype'] === 'itemoverviewjson') {
391
                // todo
392
            }
393
        }
394
395
        $aP['content'] = $P->oPayload->cl_html;
396
397
        $aP['content'] = str_replace('@', '&#064;', $aP['content']); // Change @ to HTML Entity -> maybe less spam mails
398
399
        $aP['lang_available'] = $this->config->getCore('lang_available');
400
        $aP['lang_detection_method'] = $this->config->getCore('lang_detection_method');
401
        $aP['lang_by_domain'] = $this->config->getCore('lang_by_domain');
402
403
        if ($this->config->getCore('debug')) {
404
            $this->helper->getDebug($aP, $P);
405
            $aP['debugdata'] = \HaaseIT\Toolbox\Tools::$sDebug;
406
        }
407
408
        return $aP;
409
    }
410
}
411