Completed
Push — master ( 9d94a6...b1baeb )
by Marcus
01:53
created

HCSF   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 410
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 21

Importance

Changes 0
Metric Value
wmc 58
lcom 1
cbo 21
dl 0
loc 410
rs 4.5599
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 1
F init() 0 78 11
A setupRequest() 0 16 2
B setupSession() 0 37 8
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
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
            // cleanup request
147
            $requesturi = urldecode($request->getRequestTarget());
148
            $parsedrequesturi = substr($requesturi, strlen(dirname(filter_input(INPUT_SERVER, 'PHP_SELF'))));
149
            if (substr($parsedrequesturi, 1, 1) !== '/') {
150
                $parsedrequesturi = '/'.$parsedrequesturi;
151
            }
152
            return $request->withRequestTarget($parsedrequesturi);
153
        });
154
    }
155
156
    protected function setupSession()
157
    {
158
        if (
159
            (
160
                $this->config->getCore('enable_module_customer')
161
                || $this->config->getCore('override_enable_session')
162
            )
163
            && filter_input(INPUT_COOKIE, 'acceptscookies') === 'yes'
164
        ) {
165
            // Session handling
166
            // session.use_trans_sid wenn nötig aktivieren
167
            session_name('sid');
168
            // Session wenn nötig starten
169
            if (empty(session_id())) {
170
                session_start();
171
            }
172
173
            $serverremoteaddr = filter_input(INPUT_SERVER, 'REMOTE_ADDR');
174
            $serveruseragent = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT');
175
            // check if the stored ip and ua equals the clients, if not, reset. if not set at all, reset
176
            if (!empty($_SESSION['hijackprevention'])) {
177
                if (
178
                    $_SESSION['hijackprevention']['remote_addr'] != $serverremoteaddr
179
                    ||
180
                    $_SESSION['hijackprevention']['user_agent'] != $serveruseragent
181
                ) {
182
                    session_regenerate_id();
183
                    session_unset();
184
                }
185
            } else {
186
                session_regenerate_id();
187
                session_unset();
188
                $_SESSION['hijackprevention']['remote_addr'] = $serverremoteaddr;
189
                $_SESSION['hijackprevention']['user_agent'] = $serveruseragent;
190
            }
191
        }
192
    }
193
194
    protected function setupHardcodedTextcats()
195
    {
196
        $lang = $this->config->getLang();
197
        $langavailable = $this->config->getCore('lang_available');
198
        if (file_exists(HCSF_BASEDIR.'src/config/hardcodedtextcats/'.$lang.'.php')) {
199
            $HT = require HCSF_BASEDIR.'src/config/hardcodedtextcats/'.$lang.'.php';
200
        } else {
201
            if (file_exists(HCSF_BASEDIR.'src/config/hardcodedtextcats/'.key($langavailable).'.php')) {
202
                $HT = require HCSF_BASEDIR.'src/config/hardcodedtextcats/'.key($langavailable).'.php';
203
            } else {
204
                $HT = require HCSF_BASEDIR.'src/config/hardcodedtextcats/de.php';
205
            }
206
        }
207
208
        return new HardcodedText($HT);
209
    }
210
211
    protected function setupDB()
212
    {
213
        $this->serviceManager->setFactory('dbal', function () {
214
            $config = new \Doctrine\DBAL\Configuration();
215
216
            $connectionParams = [
217
                'url' =>
218
                    $this->config->getSecret('db_type').'://'
219
                    .$this->config->getSecret('db_user').':'
220
                    .$this->config->getSecret('db_password').'@'
221
                    .$this->config->getSecret('db_server').'/'
222
                    .$this->config->getSecret('db_name'),
223
                'charset' => 'UTF8',
224
                'driverOptions' => [
225
                    \PDO::ATTR_EMULATE_PREPARES => false,
226
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
227
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
228
                ],
229
            ];
230
231
            return \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
232
        });
233
234
        $this->serviceManager->setFactory('db', function (ServiceManager $serviceManager) {
235
            return $serviceManager->get('dbal')->getWrappedConnection();
236
        });
237
    }
238
239
    protected function setupTextcats()
240
    {
241
        $this->serviceManager->setFactory('textcats', function (ServiceManager $serviceManager) {
242
            $langavailable = $this->config->getCore('lang_available');
243
            $textcats = new \HaaseIT\Toolbox\Textcat(
244
                $this->config->getLang(),
245
                $serviceManager->get('db'),
246
                key($langavailable),
247
                $this->config->getCore('textcatsverbose'),
248
                PATH_LOGS
249
            );
250
            $textcats->loadTextcats();
251
252
            return $textcats;
253
        });
254
    }
255
256
    protected function setupTwig()
257
    {
258
        $this->serviceManager->setFactory('twig', function (ServiceManager $serviceManager) {
259
            $loader = new \Twig_Loader_Filesystem([PATH_BASEDIR.'customization/views', HCSF_BASEDIR.'src/views/']);
260
261
            $twig_options = [
262
                'autoescape' => false,
263
                'debug' => $this->config->getCore('debug') ? true : false,
264
            ];
265
            if ($this->config->getCore('templatecache_enable') &&
266
                is_dir(PATH_TEMPLATECACHE) && is_writable(PATH_TEMPLATECACHE)) {
267
                $twig_options['cache'] = PATH_TEMPLATECACHE;
268
            }
269
            $twig = new \Twig_Environment($loader, $twig_options);
270
271
            if ($this->config->getCore('allow_parsing_of_page_content')) {
272
                $twig->addExtension(new \Twig_Extension_StringLoader());
273
            } else { // make sure, template_from_string is callable
274
                $twig->addFunction(new \Twig_SimpleFunction('template_from_string', [$this->helper, 'reachThrough']));
275
            }
276
277
            if (!$this->config->getCore('maintenancemode')) {
278
                $twig->addFunction(new \Twig_SimpleFunction('T', [$serviceManager->get('textcats'), 'T']));
279
            } else {
280
                $twig->addFunction(new \Twig_SimpleFunction('T', [$this->helper, 'returnEmptyString']));
281
            }
282
283
            $twig->addFunction(new \Twig_SimpleFunction('HT', [$serviceManager->get('hardcodedtextcats'), 'get']));
284
            $twig->addFunction(new \Twig_SimpleFunction('gFF', '\HaaseIT\Toolbox\Tools::getFormField'));
285
            $twig->addFunction(new \Twig_SimpleFunction('ImgURL', [$this->helper, 'getSignedGlideURL']));
286
            $twig->addFunction(new \Twig_SimpleFunction('callback', [$this->helper, 'twigCallback']));
287
            $twig->addFunction(new \Twig_SimpleFunction('makeLinkHRefWithAddedGetVars', '\HaaseIT\Toolbox\Tools::makeLinkHRefWithAddedGetVars'));
288
            $twig->addFilter(new \Twig_SimpleFilter('decodehtmlentity', 'html_entity_decode'));
289
290
            return $twig;
291
        });
292
    }
293
294
    /**
295
     * @return ServiceManager
296
     */
297
    public function getServiceManager()
298
    {
299
        return $this->serviceManager;
300
    }
301
302
    /**
303
     * @param Page $P
304
     * @return array
305
     */
306
    public function generatePage(Page $P)
307
    {
308
        $requesturi = $this->serviceManager->get('request')->getRequestTarget();
309
310
        $aP = [
311
            'language' => $this->config->getLang(),
312
            'pageconfig' => $P->cb_pageconfig,
313
            'pagetype' => $P->cb_pagetype,
314
            'subnavkey' => $P->cb_subnav,
315
            'requesturi' => $requesturi,
316
            'requesturiarray' => parse_url($requesturi),
317
            'locale_format_date' => $this->config->getCore('locale_format_date'),
318
            'locale_format_date_time' => $this->config->getCore('locale_format_date_time'),
319
            'maintenancemode' => $this->config->getCore('maintenancemode'),
320
            'numberformat_decimals' => $this->config->getCore('numberformat_decimals'),
321
            'numberformat_decimal_point' => $this->config->getCore('numberformat_decimal_point'),
322
            'numberformat_thousands_seperator' => $this->config->getCore('numberformat_thousands_seperator'),
323
            'customroottemplate' => $P->getCustomRootTemplate(),
324
            'headers' => $P->getHeaders(),
325
        ];
326
        if ($this->config->getCore('enable_module_customer')) {
327
            $aP['isloggedin'] = $this->helperCustomer->getUserData();
328
            $aP['enable_module_customer'] = true;
329
        }
330
        if ($this->config->getCore('enable_module_shop')) {
331
            $aP['currency'] = $this->config->getShop('waehrungssymbol');
332
            $aP['orderamounts'] = $this->config->getShop('orderamounts');
333
            if (!empty($this->config->getShop('vat')['full'])) {
334
                $aP['vatfull'] = $this->config->getShop('vat')['full'];
335
            }
336
            if (!empty($this->config->getShop('vat')['reduced'])) {
337
                $aP['vatreduced'] = $this->config->getShop('vat')['reduced'];
338
            }
339
            if (!empty($this->config->getShop('custom_order_fields'))) {
340
                $aP['custom_order_fields'] = $this->config->getShop('custom_order_fields');
341
            }
342
            $aP['enable_module_shop'] = true;
343
        }
344
        if (isset($P->cb_key)) {
345
            $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...
346
        } else {
347
            $aP['path'] = pathinfo($aP['requesturi']);
348
        }
349
        if ($P->cb_customcontenttemplate != null) {
350
            $aP['customcontenttemplate'] = $P->cb_customcontenttemplate;
351
        }
352
        if ($P->cb_customdata != null) {
353
            $aP['customdata'] = $P->cb_customdata;
354
        }
355
        $serverhttpreferer = filter_input(INPUT_SERVER, 'HTTP_REFERER');
356
        if ($serverhttpreferer !== null) {
357
            $aP['referer'] = $serverhttpreferer;
358
        }
359
360
        // if there is no subnav defined but there is a default subnav defined, use it
361
        // subnavkey can be used in the templates to find out, where we are
362
        if (empty($aP['subnavkey']) && !empty($this->config->getCore('subnav_default'))) {
363
            $aP['subnavkey'] = $this->config->getCore('subnav_default');
364
            $P->cb_subnav = $this->config->getCore('subnav_default');
365
        }
366
        if ($P->cb_subnav != null && !empty($this->config->getNavigation($P->cb_subnav))) {
367
            $aP['subnav'] = $this->config->getNavigation($P->cb_subnav);
368
        }
369
370
        // Get page title, meta-keywords, meta-description
371
        $aP['pagetitle'] = '';
372
        if (method_exists($P->oPayload, 'getTitle')) {
373
            $aP['pagetitle'] = $P->oPayload->getTitle();
374
        }
375
        $aP['keywords'] = $P->oPayload->cl_keywords;
376
        $aP['description'] = $P->oPayload->cl_description;
377
378
        // Shopping cart infos
379
        if ($this->config->getCore('enable_module_shop')) {
380
            $aP['cartinfo'] = $this->helperShop->getShoppingcartData();
381
        }
382
383
        $aP['countrylist'][] = ' | ';
384
        $configcountries = $this->config->getCountries('countries_' .$this->config->getLang());
385
        foreach ($configcountries as $sKey => $sValue) {
386
            $aP['countrylist'][] = $sKey.'|'.$sValue;
387
        }
388
389
        if ($this->config->getCore('enable_module_shop')) {
390
            if (
391
                $aP['pagetype'] === 'itemoverview'
392
                || $aP['pagetype'] === 'itemoverviewgrpd'
393
                || $aP['pagetype'] === 'itemdetail'
394
            ) {
395
                $aP = $this->helperShop->handleItemPage($this->serviceManager, $P, $aP);
396
            } elseif ($aP['pagetype'] === 'itemoverviewjson') {
397
                // todo
398
            }
399
        }
400
401
        $aP['content'] = $P->oPayload->cl_html;
402
403
        $aP['content'] = str_replace('@', '&#064;', $aP['content']); // Change @ to HTML Entity -> maybe less spam mails
404
405
        $aP['lang_available'] = $this->config->getCore('lang_available');
406
        $aP['lang_detection_method'] = $this->config->getCore('lang_detection_method');
407
        $aP['lang_by_domain'] = $this->config->getCore('lang_by_domain');
408
409
        if ($this->config->getCore('debug')) {
410
            $this->helper->getDebug($aP, $P);
411
            $aP['debugdata'] = \HaaseIT\Toolbox\Tools::$sDebug;
412
        }
413
414
        return $aP;
415
    }
416
}
417