Bootstrap::initEventManager()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 9.28
c 0
b 0
f 0
cc 4
nc 2
nop 1
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());
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,
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);
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());
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
        $response = $this->dispatch($di);
96
        $response->send();
97
98
    }
99
100
    private function initRouting($application, $di)
101
    {
102
        $router = new \Application\Mvc\Router\DefaultRouter();
103
        $router->setDi($di);
104
        foreach ($application->getModules() as $module) {
105
            $routesClassName = str_replace('Module', 'Routes', $module['className']);
106
            if (class_exists($routesClassName)) {
107
                $routesClass = new $routesClassName();
108
                $router = $routesClass->init($router);
109
            }
110
            $initClassName = str_replace('Module', 'Init', $module['className']);
111
            if (class_exists($initClassName)) {
112
                new $initClassName();
113
            }
114
        }
115
        $di->set('router', $router);
116
    }
117
118
    private function initAssetsManager($di)
119
    {
120
        $config = $di->get('config');
121
        $assetsManager = new \Application\Assets\Manager();
122
        $js_collection = $assetsManager->collection('js')
0 ignored issues
show
Bug introduced by
The method setLocal cannot be called on $assetsManager->collection('js') (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
123
            ->setLocal(true)
124
            ->addFilter(new \Phalcon\Assets\Filters\Jsmin())
125
            ->setTargetPath(ROOT . '/assets/js.js')
126
            ->setTargetUri('assets/js.js')
127
            ->join(true);
128
        if ($config->assets->js) {
129
            foreach ($config->assets->js as $js) {
130
                $js_collection->addJs(ROOT . '/' . $js);
131
            }
132
        }
133
134
        // Admin JS Assets
135
        $assetsManager->collection('modules-admin-js')
0 ignored issues
show
Bug introduced by
The method setLocal cannot be called on $assetsManager->collection('modules-admin-js') (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
136
            ->setLocal(true)
137
            ->addFilter(new \Phalcon\Assets\Filters\Jsmin())
138
            ->setTargetPath(ROOT . '/assets/modules-admin.js')
139
            ->setTargetUri('assets/modules-admin.js')
140
            ->join(true);
141
142
        // Admin LESS Assets
143
        $assetsManager->collection('modules-admin-less')
0 ignored issues
show
Bug introduced by
The method setLocal cannot be called on $assetsManager->collection('modules-admin-less') (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
144
            ->setLocal(true)
145
            ->addFilter(new \Application\Assets\Filter\Less())
146
            ->setTargetPath(ROOT . '/assets/modules-admin.less')
147
            ->setTargetUri('assets/modules-admin.less')
148
            ->join(true)
149
            ->addCss(APPLICATION_PATH . '/modules/Admin/assets/admin.less');
150
151
        $di->set('assets', $assetsManager);
152
    }
153
154
    private function initEventManager($di)
155
    {
156
        $eventsManager = new \Phalcon\Events\Manager();
157
        $dispatcher = new \Phalcon\Mvc\Dispatcher();
158
159
        $eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher) use ($di) {
160
            new \YonaCMS\Plugin\CheckPoint($di->get('request'));
161
            new \YonaCMS\Plugin\Localization($dispatcher);
162
            new \YonaCMS\Plugin\AdminLocalization($di->get('config'));
163
            new \YonaCMS\Plugin\Acl($di->get('acl'), $dispatcher, $di->get('view'));
164
            new \YonaCMS\Plugin\MobileDetect($di->get('session'), $di->get('view'), $di->get('request'));
165
        });
166
167
        $eventsManager->attach("dispatch:afterDispatchLoop", function ($event, $dispatcher) use ($di) {
168
            new \Seo\Plugin\SeoManager($dispatcher, $di->get('request'), $di->get('router'), $di->get('view'));
169
            new \YonaCMS\Plugin\Title($di);
170
        });
171
172
        // Profiler
173
        $registry = $di->get('registry');
174
        if ($registry->cms['PROFILER']) {
175
            $profiler = new \Phalcon\Db\Profiler();
176
            $di->set('profiler', $profiler);
177
178
            $eventsManager->attach('db', function ($event, $db) use ($profiler) {
179
                if ($event->getType() == 'beforeQuery') {
180
                    $profiler->startProfile($db->getSQLStatement());
181
                }
182
                if ($event->getType() == 'afterQuery') {
183
                    $profiler->stopProfile();
184
                }
185
            });
186
        }
187
188
        $db = $di->get('db');
189
        $db->setEventsManager($eventsManager);
190
191
        $dispatcher->setEventsManager($eventsManager);
192
        $di->set('dispatcher', $dispatcher);
193
    }
194
195
    private function initView($di)
196
    {
197
        $view = new \Phalcon\Mvc\View();
198
199
        define('MAIN_VIEW_PATH', '../../../views/');
200
        $view->setMainView(MAIN_VIEW_PATH . 'main');
201
        $view->setLayoutsDir(MAIN_VIEW_PATH . '/layouts/');
202
        $view->setLayout('main');
203
        $view->setPartialsDir(MAIN_VIEW_PATH . '/partials/');
204
205
        // Volt
206
        $volt = new \Application\Mvc\View\Engine\Volt($view, $di);
207
        $volt->setOptions(['compiledPath' => APPLICATION_PATH . '/../data/cache/volt/']);
208
        $volt->initCompiler();
209
210
211
        $phtml = new \Phalcon\Mvc\View\Engine\Php($view, $di);
212
        $viewEngines = [
213
            ".volt"  => $volt,
214
            ".phtml" => $phtml,
215
        ];
216
217
        $view->registerEngines($viewEngines);
218
219
        $ajax = $di->get('request')->getQuery('_ajax');
220
        if ($ajax) {
221
            $view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_LAYOUT);
222
        }
223
224
        $di->set('view', $view);
225
226
        return $view;
227
    }
228
229
    private function initCache($di)
230
    {
231
        $config = $di->get('config');
232
233
        $cacheFrontend = new \Phalcon\Cache\Frontend\Data([
234
            "lifetime" => 60,
235
            "prefix"   => HOST_HASH,
236
        ]);
237
238
        $cache = null;
239
        switch ($config->cache) {
240
            case 'file':
241
                $cache = new \Phalcon\Cache\Backend\File($cacheFrontend, [
242
                    "cacheDir" => APPLICATION_PATH . "/../data/cache/backend/"
243
                ]);
244
                break;
245
            case 'memcache':
246
                $cache = new \Phalcon\Cache\Backend\Memcache(
247
                    $cacheFrontend, [
248
                    "host" => $config->memcache->host,
249
                    "port" => $config->memcache->port,
250
                ]);
251
                break;
252
            case 'memcached':
253
                $cache = new \Phalcon\Cache\Backend\Libmemcached(
254
                    $cacheFrontend, [
255
                    "host" => $config->memcached->host,
256
                    "port" => $config->memcached->port,
257
                ]);
258
                break;
259
        }
260
        $di->set('cache', $cache, true);
261
        $di->set('modelsCache', $cache, true);
262
263
        \Application\Widget\Proxy::$cache = $cache; // Modules Widget System
264
265
        $modelsMetadata = new \Phalcon\Mvc\Model\Metadata\Memory();
266
        $di->set('modelsMetadata', $modelsMetadata);
267
268
        $di->set('cacheManager', new CacheManager());
269
    }
270
271
    private function dispatch($di)
272
    {
273
        $router = $di['router'];
274
275
        $router->handle();
276
277
        $view = $di['view'];
278
279
        $dispatcher = $di['dispatcher'];
280
281
        $response = $di['response'];
282
283
        $dispatcher->setModuleName($router->getModuleName());
284
        $dispatcher->setControllerName($router->getControllerName());
285
        $dispatcher->setActionName($router->getActionName());
286
        $dispatcher->setParams($router->getParams());
287
288
        $moduleName = \Application\Utils\ModuleName::camelize($router->getModuleName());
289
290
        $ModuleClassName = $moduleName . '\Module';
291
        if (class_exists($ModuleClassName)) {
292
            $module = new $ModuleClassName;
293
            $module->registerAutoloaders();
294
            $module->registerServices($di);
295
        }
296
297
        $view->start();
298
299
        $registry = $di['registry'];
300
        if ($registry->cms['DEBUG_MODE']) {
301
            $debug = new \Phalcon\Debug();
302
            $debug->listen();
303
304
            $dispatcher->dispatch();
305
        } else {
306
            try {
307
                $dispatcher->dispatch();
308
            } catch (\Phalcon\Exception $e) {
309
                // Errors catching
310
311
                $view->setViewsDir(__DIR__ . '/modules/Index/views/');
312
                $view->setPartialsDir('');
313
                $view->e = $e;
314
315
                if ($e instanceof \Phalcon\Mvc\Dispatcher\Exception) {
316
                    $response->setStatusCode(404, 'Not Found');
317
                    $view->partial('error/error404');
318
                } else {
319
                    $response->setStatusCode(503, 'Service Unavailable');
320
                    $view->partial('error/error503');
321
                }
322
323
                return $response;
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
        return $response;
361
    }
362
363
}
364