Completed
Pull Request — master (#84)
by
unknown
03:43 queued 01:14
created

Bootstrap::dispatch()   C

Complexity

Conditions 9
Paths 24

Size

Total Lines 92
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 92
rs 5.1048
cc 9
eloc 60
nc 24
nop 1

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
namespace YonaCMS;
4
use Application\Cache\Manager as CacheManager;
5
6
/**
7
 * Bootstrap
8
 * @copyright Copyright (c) 2011 - 2014 Aleksandr Torosh (http://wezoom.com.ua)
9
 * @author Aleksandr Torosh <[email protected]>
10
 */
11
class Bootstrap
12
{
13
14
    public function run()
15
    {
16
        $di = new \Phalcon\DI\FactoryDefault();
17
18
        // Config
19
        require_once APPLICATION_PATH . '/modules/Cms/Config.php';
20
        $config = \Cms\Config::get();
21
        $di->set('config', $config);
22
23
        // Registry
24
        $registry = new \Phalcon\Registry();
25
        $di->set('registry', $registry);
26
27
        // Loader
28
        $loader = new \Phalcon\Loader();
29
        $loader->registerNamespaces($config->loader->namespaces->toArray());
0 ignored issues
show
Bug introduced by
The property loader does not seem to exist in Phalcon\Config.

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...
30
        $loader->registerDirs([APPLICATION_PATH . "/plugins/"]);
31
        $loader->registerFiles([APPLICATION_PATH . '/../vendor/autoload.php']);
32
        $loader->register();
33
34
        // Database
35
        $db = new \Phalcon\Db\Adapter\Pdo\Mysql([
36
            "host"     => $config->database->host,
0 ignored issues
show
Bug introduced by
The property database does not seem to exist in Phalcon\Config.

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...
37
            "username" => $config->database->username,
38
            "password" => $config->database->password,
39
            "dbname"   => $config->database->dbname,
40
            "charset"  => $config->database->charset,
41
        ]);
42
        $di->set('db', $db);
43
44
        // View
45
        $this->initView($di);
46
47
        // URL
48
        $url = new \Phalcon\Mvc\Url();
49
        $url->setBasePath($config->base_path);
0 ignored issues
show
Bug introduced by
The property base_path does not seem to exist in Phalcon\Config.

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...
50
        $url->setBaseUri($config->base_path);
51
        $di->set('url', $url);
52
53
        // Cache
54
        $this->initCache($di);
55
56
        // CMS
57
        $cmsModel = new \Cms\Model\Configuration();
58
        $registry->cms = $cmsModel->getConfig(); // Отправляем в Registry
59
60
        // Application
61
        $application = new \Phalcon\Mvc\Application();
62
        $application->registerModules($config->modules->toArray());
0 ignored issues
show
Bug introduced by
The property modules does not seem to exist in Phalcon\Config.

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...
63
64
        // Events Manager, Dispatcher
65
        $this->initEventManager($di);
66
67
        // Session
68
        $session = new \Phalcon\Session\Adapter\Files();
69
        $session->start();
70
        $di->set('session', $session);
71
72
        $acl = new \Application\Acl\DefaultAcl();
73
        $di->set('acl', $acl);
74
75
        // JS Assets
76
        $this->initAssetsManager($di);
77
78
        // Flash helper
79
        $flash = new \Phalcon\Flash\Session([
80
            'error'   => 'ui red inverted segment',
81
            'success' => 'ui green inverted segment',
82
            'notice'  => 'ui blue inverted segment',
83
            'warning' => 'ui orange inverted segment',
84
        ]);
85
        $di->set('flash', $flash);
86
87
        $di->set('helper', new \Application\Mvc\Helper());
88
89
        // Routing
90
        $this->initRouting($application, $di);
91
92
        $application->setDI($di);
93
94
        // Main dispatching process
95
        $this->dispatch($di);
96
97
    }
98
99
    private function initRouting($application, $di)
100
    {
101
        $router = new \Application\Mvc\Router\DefaultRouter();
102
        $router->setDi($di);
103
        foreach ($application->getModules() as $module) {
104
            $routesClassName = str_replace('Module', 'Routes', $module['className']);
105
            if (class_exists($routesClassName)) {
106
                $routesClass = new $routesClassName();
107
                $router = $routesClass->init($router);
108
            }
109
            $initClassName = str_replace('Module', 'Init', $module['className']);
110
            if (class_exists($initClassName)) {
111
                new $initClassName();
112
            }
113
        }
114
        $di->set('router', $router);
115
    }
116
117
    private function initAssetsManager($di)
118
    {
119
        $config = $di->get('config');
120
        $assetsManager = new \Application\Assets\Manager();
121
        $js_collection = $assetsManager->collection('js')
122
            ->setLocal(true)
123
            ->addFilter(new \Phalcon\Assets\Filters\Jsmin())
124
            ->setTargetPath(ROOT . '/assets/js.js')
125
            ->setTargetUri('assets/js.js')
126
            ->join(true);
127
        if ($config->assets->js) {
128
            foreach ($config->assets->js as $js) {
129
                $js_collection->addJs(ROOT . '/' . $js);
130
            }
131
        }
132
133
        // Admin JS Assets
134
        $assetsManager->collection('modules-admin-js')
135
            ->setLocal(true)
136
            ->addFilter(new \Phalcon\Assets\Filters\Jsmin())
137
            ->setTargetPath(ROOT . '/assets/modules-admin.js')
138
            ->setTargetUri('assets/modules-admin.js')
139
            ->join(true);
140
141
        // Admin LESS Assets
142
        $assetsManager->collection('modules-admin-less')
143
            ->setLocal(true)
144
            ->addFilter(new \Application\Assets\Filter\Less())
145
            ->setTargetPath(ROOT . '/assets/modules-admin.less')
146
            ->setTargetUri('assets/modules-admin.less')
147
            ->join(true)
148
            ->addCss(APPLICATION_PATH . '/modules/Admin/assets/admin.less');
149
150
        $di->set('assets', $assetsManager);
151
    }
152
153
    private function initEventManager($di)
154
    {
155
        $eventsManager = new \Phalcon\Events\Manager();
156
        $dispatcher = new \Phalcon\Mvc\Dispatcher();
157
158
        $eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher) use ($di) {
159
            new \YonaCMS\Plugin\CheckPoint($di->get('request'));
160
            new \YonaCMS\Plugin\Localization($dispatcher);
161
            new \YonaCMS\Plugin\AdminLocalization($di->get('config'));
162
            new \YonaCMS\Plugin\Acl($di->get('acl'), $dispatcher, $di->get('view'));
163
            new \YonaCMS\Plugin\MobileDetect($di->get('session'), $di->get('view'), $di->get('request'));
164
        });
165
166
        $eventsManager->attach("dispatch:afterDispatchLoop", function ($event, $dispatcher) use ($di) {
167
            new \Seo\Plugin\SeoManager($dispatcher, $di->get('request'), $di->get('router'), $di->get('view'));
168
            new \YonaCMS\Plugin\Title($di);
169
        });
170
171
        // Profiler
172
        $registry = $di->get('registry');
173
        if ($registry->cms['PROFILER']) {
174
            $profiler = new \Phalcon\Db\Profiler();
175
            $di->set('profiler', $profiler);
176
177
            $eventsManager->attach('db', function ($event, $db) use ($profiler) {
178
                if ($event->getType() == 'beforeQuery') {
179
                    $profiler->startProfile($db->getSQLStatement());
180
                }
181
                if ($event->getType() == 'afterQuery') {
182
                    $profiler->stopProfile();
183
                }
184
            });
185
        }
186
187
        $db = $di->get('db');
188
        $db->setEventsManager($eventsManager);
189
190
        $dispatcher->setEventsManager($eventsManager);
191
        $di->set('dispatcher', $dispatcher);
192
    }
193
194
    private function initView($di)
195
    {
196
        $view = new \Phalcon\Mvc\View();
197
198
        define('MAIN_VIEW_PATH', '../../../views/');
199
        $view->setMainView(MAIN_VIEW_PATH . 'main');
200
        $view->setLayoutsDir(MAIN_VIEW_PATH . '/layouts/');
201
        $view->setLayout('main');
202
        $view->setPartialsDir(MAIN_VIEW_PATH . '/partials/');
203
204
        // Volt
205
        $volt = new \Application\Mvc\View\Engine\Volt($view, $di);
206
        $volt->setOptions(['compiledPath' => APPLICATION_PATH . '/../data/cache/volt/']);
207
        $volt->initCompiler();
208
209
210
        $phtml = new \Phalcon\Mvc\View\Engine\Php($view, $di);
211
        $viewEngines = [
212
            ".volt"  => $volt,
213
            ".phtml" => $phtml,
214
        ];
215
216
        $view->registerEngines($viewEngines);
217
218
        $ajax = $di->get('request')->getQuery('_ajax');
219
        if ($ajax) {
220
            $view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_LAYOUT);
221
        }
222
223
        $di->set('view', $view);
224
225
        return $view;
226
    }
227
228
    private function initCache($di)
229
    {
230
        $config = $di->get('config');
231
232
        $cacheFrontend = new \Phalcon\Cache\Frontend\Data([
233
            "lifetime" => 60,
234
            "prefix"   => HOST_HASH,
235
        ]);
236
237
        $cache = null;
238
        switch ($config->cache) {
239
            case 'file':
240
                $cache = new \Phalcon\Cache\Backend\File($cacheFrontend, [
241
                    "cacheDir" => APPLICATION_PATH . "/../data/cache/backend/"
242
                ]);
243
                break;
244
            case 'memcache':
245
                $cache = new \Phalcon\Cache\Backend\Memcache(
246
                    $cacheFrontend, [
247
                    "host" => $config->memcache->host,
248
                    "port" => $config->memcache->port,
249
                ]);
250
                break;
251
            case 'memcached':
252
                $cache = new \Phalcon\Cache\Backend\Libmemcached(
253
                    $cacheFrontend, [
254
                    "host" => $config->memcached->host,
255
                    "port" => $config->memcached->port,
256
                ]);
257
                break;
258
        }
259
        $di->set('cache', $cache, true);
260
        $di->set('modelsCache', $cache, true);
261
262
        \Application\Widget\Proxy::$cache = $cache; // Modules Widget System
263
264
        $modelsMetadata = new \Phalcon\Mvc\Model\Metadata\Memory();
265
        $di->set('modelsMetadata', $modelsMetadata);
266
267
        $di->set('cacheManager', new CacheManager());
268
    }
269
270
    private function dispatch($di)
271
    {
272
        $router = $di['router'];
273
274
        $router->handle();
275
276
        $view = $di['view'];
277
278
        $dispatcher = $di['dispatcher'];
279
280
        $response = $di['response'];
281
282
        $dispatcher->setModuleName($router->getModuleName());
283
        $dispatcher->setControllerName($router->getControllerName());
284
        $dispatcher->setActionName($router->getActionName());
285
        $dispatcher->setParams($router->getParams());
286
287
        $moduleName = \Application\Utils\ModuleName::camelize($router->getModuleName());
288
289
        $ModuleClassName = $moduleName . '\Module';
290
        if (class_exists($ModuleClassName)) {
291
            $module = new $ModuleClassName;
292
            $module->registerAutoloaders();
293
            $module->registerServices($di);
294
        }
295
296
        $view->start();
297
298
        $registry = $di['registry'];
299
        if ($registry->cms['DEBUG_MODE']) {
300
            $debug = new \Phalcon\Debug();
301
            $debug->listen();
302
303
            $dispatcher->dispatch();
304
        } else {
305
            try {
306
                $dispatcher->dispatch();
307
            } catch (\Phalcon\Exception $e) {
308
                // Errors catching
309
310
                $view->setViewsDir(__DIR__ . '/modules/Index/views/');
311
                $view->setPartialsDir('');
312
                $view->e = $e;
313
314
                if ($e instanceof \Phalcon\Mvc\Dispatcher\Exception) {
315
                    $response->setStatusCode(404, 'Not Found');
316
                    $view->partial('error/error404');
317
                } else {
318
                    $response->setStatusCode(503, 'Service Unavailable');
319
                    $view->partial('error/error503');
320
                }
321
322
                $response->send();
323
                return;
324
            }
325
        }
326
327
        $view->render(
328
            $dispatcher->getControllerName(),
329
            $dispatcher->getActionName(),
330
            $dispatcher->getParams()
331
        );
332
333
        $view->finish();
334
335
        // AJAX
336
        $request = $di['request'];
337
        $_ajax = $request->getQuery('_ajax');
338
        if ($_ajax) {
339
            $contents = $view->getContent();
340
341
            $return = new \stdClass();
342
            $return->html = $contents;
343
            $return->title = $di->get('helper')->title()->get();
344
            $return->success = true;
345
346
            if ($view->bodyClass) {
347
                $return->bodyClass = $view->bodyClass;
348
            }
349
350
            $headers = $response->getHeaders()->toArray();
351
            if (isset($headers[404]) || isset($headers[503])) {
352
                $return->success = false;
353
            }
354
            $response->setContentType('application/json', 'UTF-8');
355
            $response->setContent(json_encode($return));
356
        } else {
357
            $response->setContent($view->getContent());
358
        }
359
360
        $response->send();
361
    }
362
363
}
364