Completed
Push — master ( 60b053...61ce86 )
by Marcus
02:08
created

HCSF::init()   F

Complexity

Conditions 11
Paths 512

Size

Total Lines 74
Code Lines 41

Duplication

Lines 12
Ratio 16.22 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 12
loc 74
rs 3.4177
c 2
b 0
f 0
cc 11
eloc 41
nc 512
nop 0

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
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
        $this->helper = $this->serviceManager->get('helper');
77
78 View Code Duplication
        if ($this->config->getCore('enable_module_customer')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
79
            $this->serviceManager->setFactory('helpercustomer', function (ServiceManager $serviceManager) {
80
                return new \HaaseIT\HCSF\Customer\Helper($serviceManager);
81
            });
82
            $this->helperCustomer = $this->serviceManager->get('helpercustomer');
83
        }
84
85 View Code Duplication
        if ($this->config->getCore('enable_module_shop')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

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