Completed
Push — development ( 67765c...7029e6 )
by Andrij
18:12
created

Kernel   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 250
Duplicated Lines 2.4 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
dl 6
loc 250
rs 9.8
c 0
b 0
f 0
wmc 31
lcom 1
cbo 12

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 22 1
B run() 0 40 6
A registerErrorHandler() 6 8 2
A assignTemplateData() 0 13 3
A user_browser() 0 9 1
B initModules() 0 26 6
A checkOffline() 0 10 4
A setLanguage() 0 22 3
A redirectWithoutLocale() 0 8 2
A setLanguageConfiguration() 0 6 1
A loadFunctionsFile() 0 9 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php namespace core\src;
2
3
use CI;
4
use CMSFactory\Events;
5
use core\src\Exception\PageNotFoundException;
6
use Doctrine\Common\Cache\CacheProvider;
7
8
use Symfony\Component\Debug\Debug;
9
use Symfony\Component\Debug\DebugClassLoader;
10
use Symfony\Component\Debug\ErrorHandler;
11
use Symfony\Component\Debug\ExceptionHandler;
12
13
class Kernel
14
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
15
16
    /**
17
     * @var CI
18
     */
19
    private $ci;
20
21
    /**
22
     * @var CacheProvider
23
     */
24
    private $cache;
25
26
    /**
27
     * @var array
28
     */
29
    private $modules;
30
31
    /**
32
     * @var array
33
     */
34
    private $templateData;
35
36
    /**
37
     * @var CoreModel
38
     */
39
    private $codeModel;
40
41
    /**
42
     * @var CoreConfiguration
43
     */
44
    private $configuration;
45
46
    /**
47
     * @var UrlParser
48
     */
49
    private $urlParser;
50
51
    /**
52
     * @var \Core
53
     */
54
    private $core;
55
56
    /**
57
     * Kernel constructor.
58
     * @param \Core $core
59
     * @param CI $ci
60
     */
61
    public function __construct($core, CI $ci) {
62
63
        $this->ci = $ci;
64
        $this->core = $core;
65
        $this->configuration = CoreFactory::getConfiguration();
66
        $this->cache = CoreFactory::getCache();
0 ignored issues
show
Documentation Bug introduced by
It seems like \core\src\CoreFactory::getCache() can also be of type object<Doctrine\Common\Cache\Cache>. However, the property $cache is declared as type object<Doctrine\Common\Cache\CacheProvider>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
67
        $this->codeModel = CoreFactory::getModel();
68
        $this->urlParser = CoreFactory::getUrlParser();
69
70
        $this->configuration->setLanguages($this->codeModel->getLanguages());
71
        $this->configuration->setDefaultLanguage($this->codeModel->getDefaultLanguage());
72
73
        $this->ci->config->set_item('template', $this->configuration->getSettings()['site_template']);
74
75
        $this->ci->load->module('cfcm');
76
        $this->ci->load->library('template');
77
        $this->ci->load->library('lib_seo');
78
        $this->ci->load->library('DX_Auth');
79
80
        $this->ci->lib_seo->init($core->settings);
81
82
    }
83
84
    public function run() {
85
86
        try {
87
88
            $this->registerErrorHandler();
89
90
            $url = $this->ci->input->server('REQUEST_URI');
91
92
            if(!$url && $this->ci->input->is_cli_request()) {
0 ignored issues
show
introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
93
                $url = $this->ci->uri->uri_string();
94
            }
95
96
            $this->urlParser->parse($url);
97
98
            $this->setLanguage();
99
100
            $this->loadFunctionsFile();
101
102
            $this->checkOffline();
103
104
            SHOP_INSTALLED && class_exists('\ShopCore') && \ShopCore::initEnviroment();
105
106
            $this->initModules();
107
108
            $this->assignTemplateData();
109
110
            Events::create()->registerEvent(NULL, 'Core:pageLoaded');
111
112
            CoreFactory::getRouter()->setModules($this->modules);
113
            $this->configuration->setModules($this->modules);
114
            $this->ci->template->add_array($this->templateData);
115
116
            CoreFactory::getFrontController()->display($this->urlParser->getUrl());
117
        } catch (PageNotFoundException $e) {
118
            $this->core->core_data['data_type'] = '404';
119
            $this->core->core_data['id'] = null;
120
            $this->core->error_404();
121
        }
122
123
    }
124
125
    private function registerErrorHandler() {
126 View Code Duplication
        if (ENVIRONMENT === 'development') {
127
            Debug::enable(E_ERROR | E_PARSE);
0 ignored issues
show
introduced by
Call to debug function Debug::enable() must be removed
Loading history...
128
            ErrorHandler::register();
129
            ExceptionHandler::register();
130
            DebugClassLoader::enable();
131
        }
132
    }
133
134
    private function assignTemplateData() {
135
        if ($this->ci->dx_auth->is_logged_in() == TRUE) {
136
            $this->templateData['is_logged_in'] = TRUE;
137
            $this->templateData['username'] = $this->ci->dx_auth->get_username();
138
        }
139
        $this->ci->template->add_array(['agent' => $this->user_browser()]);
140
141
        if ($this->dx_auth->use_recaptcha) {
0 ignored issues
show
Bug introduced by
The property dx_auth does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
142
            $this->templateData['captcha_type'] = 'recaptcha';
143
        } else {
144
            $this->templateData['captcha_type'] = 'captcha';
145
        }
146
    }
147
148
    private function user_browser() {
149
150
        $agent = $this->ci->load->library('user_agent');
151
        $browserIn = [
152
                      '0' => $agent->browser(),
153
                      '1' => $agent->version(),
154
                     ];
155
        return $browserIn;
156
    }
157
158
    private function initModules() {
159
160
        $query = $this->ci->cms_base->get_modules();
161
162
        if ($query->num_rows() > 0) {
163
            $this->modules = $query->result_array();
164
165
            foreach ($this->modules as $module) {
166
                $moduleLinks[$module['name']] = '/' . $module['identif'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$moduleLinks was never initialized. Although not strictly required by PHP, it is generally a good practice to add $moduleLinks = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
167
            }
168
169
            $this->templateData['modules'] = $moduleLinks;
170
        }
171
172
        foreach ($this->modules as $module) {
173
            if ($module['autoload'] == 1) {
174
                $mod_name = $module['name'];
175
176
                $module = $this->ci->load->module($mod_name);
177
                if (method_exists($module, 'autoload') === TRUE) {
178
                    $this->core_data['module'] = $mod_name;
0 ignored issues
show
Bug introduced by
The property core_data does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
179
                    $module->autoload();
180
                }
181
            }
182
        }
183
    }
184
185
    /**
186
     * Show offline page if site in offline mode
187
     */
188
    private function checkOffline() {
189
        $isMainSaasRequest = 0 === strpos($this->ci->input->server('PATH_INFO'), '/mainsaas');
190
        $siteIsOffline = $this->configuration->getSettings()['site_offline'] == 'yes';
191
        $isAdmin = $this->ci->session->userdata('DX_role_id') == 1;
192
        if ($siteIsOffline && !$isMainSaasRequest && !$isAdmin) {
193
            header('HTTP/1.1 503 Service Unavailable');
194
            $this->ci->template->display('offline');
195
            exit;
196
        }
197
    }
198
199
    /**
200
     * Reset template path
201
     * and configurations
202
     * @return string|null
0 ignored issues
show
introduced by
@return doc comment specified, but function has no return statement
Loading history...
203
     */
204
    private function setLanguage() {
205
206
        if ($locale = $this->urlParser->getLocale()) {
207
            $defaultLanguage = $this->configuration->getDefaultLanguage();
208
209
            if ($locale == $defaultLanguage['identif']) {
210
                $this->redirectWithoutLocale();
211
            }
212
213
            $this->setLanguageConfiguration($this->configuration->getLanguages()[$locale]);
214
215
            // Reload template settings
216
            $this->ci->template->set_config_value('tpl_path', TEMPLATES_PATH . $this->configuration->getSettings()['site_template'] . '/');
217
            $this->ci->template->load();
218
            // Add language identifier to base_url
219
            $this->ci->config->set_item('base_url', base_url() . $locale);
220
221
        } else {
222
            $this->setLanguageConfiguration($this->configuration->getDefaultLanguage());
223
        }
224
225
    }
226
227
    /**
228
     * redirect to url without default lang segment
229
     */
230
    private function redirectWithoutLocale() {
231
232
        $get = $this->ci->input->server('QUERY_STRING') ? '?' . $this->ci->input->server('QUERY_STRING') : '';
233
        $url = implode('/', array_slice($this->ci->uri->segment_array(), 1));
234
        header('Location:/' . $url . $get);
235
        exit;
236
237
    }
238
239
    /**
240
     * @param array $language
241
     */
242
    private function setLanguageConfiguration(array $language) {
243
        $this->configuration->setCurrentLanguage($language);
244
        $this->ci->config->set_item('language', $language['folder']);
245
        $this->ci->config->set_item('cur_lang', $language['id']);
246
        $this->ci->lang->load('main', $language['folder']);
247
    }
248
249
    /**
250
     * Include functions from template
251
     */
252
    private function loadFunctionsFile() {
253
254
        $settings = $this->configuration->getSettings();
255
        $full_path = './templates/' . $settings['site_template'] . '/functions.php';
256
257
        if (file_exists($full_path)) {
258
            include_once $full_path;
259
        }
260
    }
261
262
}