Passed
Push — master ( 90372d...e80252 )
by Nikolay
25:24
created

init_db()   B

Complexity

Conditions 11
Paths 1

Size

Total Lines 81
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 50
dl 0
loc 81
c 0
b 0
f 0
rs 7.3166
cc 11
nc 1
nop 2

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
 * Copyright © MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Alexey Portnov, 2 2020
7
 */
8
9
/*
10
	Различные глобальные переменные. 
11
*/
12
13
use Phalcon\Cache\Backend\File;
14
use Phalcon\Cache\Frontend\Data;
15
use Phalcon\Events\Manager;
16
use Phalcon\Loader;
17
use Phalcon\Logger;
18
use Phalcon\Logger\Adapter\File as FileLogger;
19
use Phalcon\Mvc\Model\MetaData\Memory;
20
use Phalcon\Mvc\Model\MetaData\Strategy\Annotations as StrategyAnnotations;
21
use Phalcon\Translate\Adapter\NativeArray;
22
23
$g = array(
24
	"cf_path" 			=> "/cf",
25
	"pt1c_db_path" 		=> "/cf/conf/mikopbx.db",
26
	"pt1c_pbx_name" 	=> "mikopbx",
27
	"pt1c_pbx_name_kind"=> "MIKO PBX",
28
	"pt1c_run_path" 	=> "/var/run",
29
	"pt1c_etc_path" 	=> "/etc",
30
	"pt1c_inc_path" 	=> "/etc/inc",
31
	"pt1c_cdr_db_path" 	=> "/tmp/cdr.db",
32
	"debug" 			=> FALSE,
33
	"varetc_path" 		=> "/var/etc",
34
	"vardb_path"  		=> "/var/db",
35
	"varlog_path" 		=> "/var/log",
36
	"tmp_path" 			=> "/tmp",
37
	"conf_path" 		=> "/conf",
38
	"www_path" 			=> "/usr/www",
39
	"platform" 			=> "Generic (x64)",
40
	"booting"			=> FALSE
41
);
42
43
// Подключаем дополнительные модули.
44
require_once("system.php");
45
require_once("util.php");
46
require_once("network.php");
47
require_once("verify.php");
48
require_once("storage.php");
49
require_once("config.php");
50
require_once("pbx.php");
51
require_once("firewall.php");
52
require_once("extensions.php");
53
require_once("cdr.php");
54
require_once("astdb.php");
55
require_once("notifications.php");
56
require_once("Backup.php");
57
require_once("SentryErrorLogger.php");
58
59
60
// Инициализация для консольного приложения.
61
if( 'cli' == php_sapi_name() || defined('ISPBXCORESERVICES')){
62
    /**
63
     * @param \Phalcon\Di\FactoryDefault $m_di
64
     * @param array $config
65
     */
66
    function init_db(&$m_di, $config){
67
        $m_di->remove('db');
68
        $m_di->remove('dbCDR');
69
        $m_di->remove('dbLog');
70
71
        $m_di->set('db', function() use ($config) {
72
            $db_class = '\Phalcon\Db\Adapter\Pdo\\'.$config['database']['adapter'];
73
            $connection= new $db_class(array("dbname" => $config['database']['dbfile']));
74
75
            if (is_file('/tmp/debug')) {
76
                $logpath = Cdr::getPathtoLog();
77
                $logger  = new FileLogger($logpath);
78
                $eventsManager = new Manager();
79
                // Слушаем все события базы данных
80
                $eventsManager->attach('db', function ($event, $connection) use ($logger) {
81
                    if ($event->getType() === 'beforeQuery') {
82
                        $statement = $connection->getSQLStatement();
83
                        $variables = $connection->getSqlVariables();
84
                        if (is_array($variables)) {
85
                            foreach ($variables as $variable => $value) {
86
                                if (is_array($value)){
87
                                    $value = '('.implode(', ',$value).')';
88
                                }
89
                                $variable = str_replace(':','',$variable);
90
                                $statement = str_replace(":$variable", "'$value'", $statement);
91
                            }
92
                        }
93
                        $logger->log($statement, Logger::SPECIAL);
94
                    }
95
                });
96
97
                // Назначаем EventsManager экземпляру адаптера базы данных
98
                $connection->setEventsManager($eventsManager);
99
            }
100
            return $connection;
101
        });
102
        // Asterisk CDR Database connection.
103
        $m_di->set('dbCDR', function() use ($config){
104
            $dbclass = 'Phalcon\Db\Adapter\Pdo\\'.$config['cdrdatabase']['adapter'];
105
106
            /** @var \Phalcon\Db\Adapter\Pdo\Sqlite $connection */
107
            $connection = new $dbclass(array(
108
                "dbname" => $config['cdrdatabase']['dbfile']
109
            ));
110
            if (is_file('/tmp/debug')) {
111
                $logpath = Cdr::getPathtoLog();
112
                $logger  = new FileLogger($logpath);
113
                $eventsManager = new Manager();
114
                // Слушаем все события базы данных
115
                $eventsManager->attach('db', function ($event, $connection) use ($logger) {
116
                    if ($event->getType() === 'beforeQuery') {
117
                        $statement = $connection->getSQLStatement();
118
                        $variables = $connection->getSqlVariables();
119
                        if (is_array($variables)) {
120
                            foreach ($variables as $variable => $value) {
121
                                if (is_array($value)){
122
                                    $value = '('.implode(', ',$value).')';
123
                                }
124
                                $variable = str_replace(':','',$variable);
125
                                $statement = str_replace(":$variable", "'$value'", $statement);
126
                            }
127
                        }
128
                        $logger->log($statement, Logger::SPECIAL);
129
                    }
130
                });
131
132
                // Назначаем EventsManager экземпляру адаптера базы данных
133
                $connection->setEventsManager($eventsManager);
134
            }
135
            return $connection;
136
        });
137
        $m_di->set('dbLog', function() use ($config){
138
            $dbclass = 'Phalcon\Db\Adapter\Pdo\\'.$config['logdatabase']['adapter'];
139
            $connection= new $dbclass(array(
140
                "dbname" => $config['logdatabase']['dbfile']
141
            ));
142
            return $connection;
143
        });
144
145
        // Подключаем db файлы модулей как севрисы в DI
146
        Modules\DiServicesInstall::Register($m_di);
147
    }
148
    function init_loader(&$g, $config){
149
        $dirScripts = [
150
            $config['application']['modelsDir'],    // Модели, для работы с настройками.
151
            $g['pt1c_inc_path'].'/std_modules',     // Генератор конфигов.
152
            // $g['pt1c_inc_path'].'/custom_modules',  // Генератор конфигов.
153
            $g['pt1c_inc_path'],
154
        ];
155
156
        $nameSpaces     = [
157
            'Models'  => $config['application']['modelsDir'],
158
            'Modules' => [
159
                $config['application']['modulesDir'],
160
                $config['application']['modulesBaseDir']
161
            ],
162
        ];
163
        $libraryFiles = [
164
            $config['application']['backendDir'].'modules/DiServicesInstall.php', // Подключаем db файлы модулей как севрисы в DI
165
            $config['application']['backendDir'].'library/vendor/autoload.php' // Sentry - cloud error logger
166
        ];
167
        $m_loader = new Loader();
168
        $m_loader->registerNamespaces($nameSpaces);
169
        $m_loader->registerDirs($dirScripts);
170
		$m_loader->registerFiles($libraryFiles);
171
        $m_loader->register();
172
        $g['m_loader'] = $m_loader;
173
    }
174
    /// ************************************************************************************
175
    // Параметры для. Phalcon. // Start
176
    /// ************
177
    // подключение файла phalcon_settings.php обнуляет $m_loader и $m_di
178
    $phalcon_settings     = include 'phalcon_settings.php';
179
    init_loader($g, $phalcon_settings);
180
181
    // Регистрируем автозагрузчик, и скажем ему, чтобы зарегистрировал каталог задач
182
    $m_di 	= new Phalcon\DI\FactoryDefault();
183
    $m_di->set('config', new \Phalcon\Config($phalcon_settings));
184
    // Настройки подключения к базе данных.
185
    init_db($m_di, $phalcon_settings);
186
187
    /**
188
     * Register the translation service
189
     */
190
    $m_di->setShared('translation', function() use ($phalcon_settings,$m_di){
0 ignored issues
show
Unused Code introduced by
The import $phalcon_settings is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
191
        return new NativeArray(
0 ignored issues
show
Bug introduced by
The call to Phalcon\Translate\Adapte...iveArray::__construct() has too few arguments starting with options. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

191
        return /** @scrutinizer ignore-call */ new NativeArray(

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
192
            array(
0 ignored issues
show
Bug introduced by
array('content' => $m_di->getMessages()) of type array is incompatible with the type Phalcon\Translate\InterpolatorFactory expected by parameter $interpolator of Phalcon\Translate\Adapte...iveArray::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

192
            /** @scrutinizer ignore-type */ array(
Loading history...
193
                'content' => $m_di->getMessages()
194
            )
195
        );
196
    });
197
198
    /**
199
     * Кеш для контроллеров.
200
     */
201
    $m_di->set('managedCache', function () use ($phalcon_settings) {
202
        $frontCache = new Data( ['lifetime' => 3600]);
203
        $cache = new File( $frontCache, [
204
                'cacheDir' => $phalcon_settings['application']['cacheDir'],
205
            ]
206
        );
207
        return $cache;
208
    }
209
    );
210
211
    /**
212
     * If the configuration specify the use of metadata adapter use it or use memory otherwise
213
     */
214
215
    $m_di->set('modelsMetadata', function () {
216
        $metaData = new Memory([
217
            'lifetime' => 86400,
218
            'prefix'   => 'metacache_key',
219
        ]);
220
        $metaData->setStrategy(
221
            new StrategyAnnotations()
222
        );
223
224
        return $metaData;
225
    });
226
227
228
    /**
229
     * Register the translation service
230
     */
231
    $m_di->setShared('messages', function() use ($g){
232
        $messages=[];
233
        $language='en-en';
234
        if(file_exists($g['pt1c_db_path'])){
235
            try{
236
                $conf = new Config();
237
                $language = $conf->get_general_settings('PBXLanguage');
238
            }catch (Exception $e){
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
239
            }
240
        }
241
242
        if (empty($_ENV['SSH_CLIENT']) && file_exists("/etc/inc/messages/{$language}.php")) {
243
            require "/etc/inc/messages/{$language}.php";
244
        } else {
245
            require '/etc/inc/messages/en-en.php';
246
        }
247
        return  $messages;
248
    });
249
250
    if(!defined('ISPBXCORESERVICES')){
251
        $cli_translation = $m_di->getTranslation();
252
        $g['cli_translation']    = $cli_translation;
253
        $g['pt1c_pbx_name_kind'] = Util::translate('MIKO_PBX');
254
    }
255
    $g['m_di'] = &$m_di;
256
    $g['phalcon_settings'] = &$phalcon_settings;
257
    /// ************
258
    // Параметры для. Phalcon. // End
259
    /// ************************************************************************************
260
261
    if(is_file('/etc/localtime')){
262
        System::php_timezone_configure();
263
    }
264
265
    /**
266
	 * Логирование ошибок в облако
267
	 */
268
	if(defined('ISPBXCORESERVICES')){
269
		$errorLogger = new SentryErrorLogger('pbx-core-api');
270
	} else {
271
		$errorLogger = new SentryErrorLogger('pbx-core-workers');
272
	}
273
	$errorLogger->init();
274
	$g['error_logger']=&$errorLogger;
275
276
}