Completed
Push — development ( a150a5...f82eb6 )
by Andrij
17:01
created

Lib_init::__construct()   C

Complexity

Conditions 9
Paths 94

Size

Total Lines 66
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 9
eloc 27
c 2
b 1
f 0
nc 94
nop 0
dl 0
loc 66
rs 6.4099

How to fix   Long Method   

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
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
7
use Monolog\Handler\StreamHandler;
8
use Propel\Runtime\Propel;
9
use Propel\Runtime\Connection\ConnectionManagerSingle;
10
11
/**
12
 * Executing custom CMS initialization code
13
 */
14
class Lib_init
15
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
16
17
    /**
18
     *
19
     * @var MY_Controller
20
     */
21
    private $CI;
22
23
    /**
24
     * Lib_init constructor.
25
     */
26
    public function __construct() {
27
28
        /*
29
         * include composer autoloader
30
         */
31
        include_once APPPATH . 'third_party/autoload.php';
32
33
        /*
34
         * Define DS for Premmerce compatibility
35
         * TODO: Remove DS usage from all project
36
         *
37
         */
38
        defined('DS') or define('DS', '/');
39
40
        try {
41
42
            $this->CI = get_instance();
43
44
            if (function_exists('date_default_timezone_set')) {
45
                date_default_timezone_set(config_item('default_time_zone'));
46
            }
47
48
            // Sessions engine should run on cookies to minimize opportunities
49
            // of session fixation attack
50
            ini_set('session.use_only_cookies', 1);
51
52
            $this->CI->load->library('native_session', '', 'session');
53
54
            $this->CI->load->library('cache');
55
56
            if (!$this->checkIsInstalled()) { // if not installed then not all bootstrap needed
0 ignored issues
show
introduced by
There should be no white space after an opening "{"
Loading history...
57
                return;
58
            }
59
60
            $this->initDatabase();
61
62
            $this->initPropel();
63
64
            /**
65
             *  @todo
66
             *  1. Delete this line
67
             *  2. Kill all eval && hooks before delete this line
68
             */
69
            $this->CI->load->library('cms_hooks');
70
71
            $this->CI->load->library('lib_category'); // needs database
72
73
            // Redirect to url with out ending slash
74
            $uri = $this->_detect_uri();
75
76
            $first_segment = $this->CI->uri->segment(1);
77
            if (substr($uri, -1, 1) === '/' && $first_segment !== 'admin' && $uri !== '/') {
78
                $get_params = '';
79
                if ($this->CI->input->get()) {
80
                    $get_params = '?' . http_build_query($this->CI->input->get());
81
                }
82
                redirect(substr($uri, 0, -1) . $get_params, 'location', 301);
83
            }
84
85
            $this->initShop();
86
87
        } catch (Exception $ex) {
88
            log_message('error', $ex->getMessage());
89
            show_error('Init error', 500);
90
        }
91
    }
92
93
    private function checkIsInstalled() {
94
        $isNotInstalledInConfig = !config_item('is_installed');
95
        $installControllerExists = file_exists(getModulePath('install') . '/install.php');
96
97
        if (!$isNotInstalledInConfig && !$installControllerExists) {
98
            return true;
99
        }
100
101
        // Not installed
102
        if ($isNotInstalledInConfig && $installControllerExists) {
103
            if ($this->CI->uri->segment(1) != 'install') {
104
                redirect('/install');
105
            }
106
            return false;
107
        }
108
109
        // Something went bad during installation in past. Both of this variables
110
        // should be either true (not installed) or false (install was complete)
111
        if ($isNotInstalledInConfig && !$installControllerExists) {
112
            show_error('Something went wrong during installation... It could be repaired only manually.');
113
        }
114
    }
115
116
    /**
117
     * Load CI_DB_mysqli_driver
118
     *
119
     * @throws Exception
0 ignored issues
show
introduced by
Comment missing or not on the next line for @throws tag in function comment
Loading history...
120
     */
121
    private function initDatabase() {
122
123
        // Load DB
124
        $this->CI->load->database();
125
126
        $db = $this->CI->db;
127
128
        if ($db == null) {
129
            throw new \Exception('Database object not initialized');
130
        }
131
        $result = $this->CI->db->query("SHOW TABLES FROM `{$db->database}`");
132
133
        if (!$result) {
134
            throw new \Exception('Error on checking database');
135
        }
136
137
        if (!$result->num_rows > 0) {
138
            throw new \Exception('No tables in database');
139
        }
140
    }
141
142
    private function initPropel() {
143
        $serviceContainer = Propel::getServiceContainer();
144
        $serviceContainer->setAdapterClass('Shop', 'mysql');
145
        $manager = new ConnectionManagerSingle();
146
147
        $manager->setConfiguration(
148
            [
149
             'dsn'      => 'mysql:host=' . $this->CI->db->hostname . ';dbname=' . $this->CI->db->database,
150
             'user'     => $this->CI->db->username,
151
             'password' => $this->CI->db->password,
152
             'settings' => ['charset' => 'utf8'],
153
            ]
154
        );
155
156
        $serviceContainer->setConnectionManager('Shop', $manager);
157
158
        Propel::getConnection('Shop')->query('SET NAMES utf8 COLLATE utf8_unicode_ci');
159
160
        // log propel queries
161
        if (ENVIRONMENT == 'development') {
162
            $con = Propel::getWriteConnection('Shop');
163
            $con->useDebug(true);
164
            $logger = new Monolog\Logger('defaultLogger');
165
            $logger->pushHandler(new StreamHandler(APPPATH . 'logs/propel.log'));
166
            $serviceContainer->setLogger('defaultLogger', $logger);
167
        }
168
    }
169
170
    private function initShop() {
171
172
        if ($shopPath = getModulePath('shop')) {
173
174
            define('SHOP_DIR', $shopPath);
175
176
            ShopCore::init();
177
178
        }
179
    }
180
181
    public function _detect_uri() {
182
        if (!$this->CI->input->server('REQUEST_URI')) {
183
            return '';
184
        }
185
186
        $uri = $this->CI->input->server('REQUEST_URI');
187
        if (strpos($uri, $this->CI->input->server('SCRIPT_NAME')) === 0) {
188
            $uri = substr($uri, strlen($this->CI->input->server('SCRIPT_NAME')));
189
        } elseif (strpos($uri, dirname($this->CI->input->server('SCRIPT_NAME'))) === 0) {
190
            $uri = substr($uri, strlen(dirname($this->CI->input->server('SCRIPT_NAME'))));
191
        }
192
193
        // This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct
194
        // URI is found, and also fixes the QUERY_STRING server var and $_GET array.
195
        if (strncmp($uri, '?/', 2) === 0) {
196
            $uri = substr($uri, 2);
197
        }
198
        $parts = preg_split('#\?#i', $uri, 2);
199
        $uri = $parts[0];
200
        if (isset($parts[1])) {
201
            $_SERVER['QUERY_STRING'] = $parts[1];
202
            /*  !!!important directly $_GET array is required here to write query string */
203
            parse_str($this->CI->input->server('QUERY_STRING'), $_GET);
0 ignored issues
show
introduced by
The $_GET super global must not be accessed directly; use Security::getRequestData() instead
Loading history...
204
        } else {
205
            $_SERVER['QUERY_STRING'] = '';
206
            $_GET = [];
0 ignored issues
show
introduced by
The $_GET super global must not be accessed directly; use Security::getRequestData() instead
Loading history...
207
        }
208
209
        if ($uri == '/' || empty($uri)) {
210
            return '/';
211
        }
212
213
        $uri = parse_url($uri, PHP_URL_PATH);
214
        return $uri;
215
    }
216
217
}