Failed Conditions
Pull Request — master (#1697)
by Ryo
169:53 queued 160:14
created

Application::initialize()   D

Complexity

Conditions 10
Paths 3

Size

Total Lines 99
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 12.1438

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 99
ccs 39
cts 54
cp 0.7221
rs 4.8514
cc 10
eloc 57
nc 3
nop 0
crap 12.1438

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
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
namespace Eccube;
25
26
use Eccube\Application\ApplicationTrait;
27
use Eccube\Common\Constant;
28
use Eccube\EventListener\TransactionListener;
29
use Monolog\Logger;
30
use Symfony\Component\EventDispatcher\EventDispatcher;
31
use Symfony\Component\Finder\Finder;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\Response;
34
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
35
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
36
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
37
use Symfony\Component\HttpKernel\KernelEvents;
38
use Symfony\Component\Yaml\Yaml;
39
class Application extends ApplicationTrait
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
40
{
41
    protected static $instance;
42
43
    protected $initialized = false;
44
    protected $initializedPlugin = false;
45
    protected $testMode = false;
46
47 1000
    public static function getInstance(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
48
    {
49 1000
        if (!is_object(self::$instance)) {
50 934
            self::$instance = new Application($values);
51
        }
52
53 1000
        return self::$instance;
54
    }
55
56 935
    public static function clearInstance()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
57
    {
58 935
        self::$instance = null;
59
    }
60
61
    final public function __clone()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
62
    {
63
        throw new \Exception('Clone is not allowed against '.get_class($this));
64
    }
65
66 948
    public function __construct(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
67
    {
68 948
        parent::__construct($values);
69
70 948
        if (is_null(self::$instance)) {
71 935
            self::$instance = $this;
72
        }
73
74
        // load config
75 948
        $this->initConfig();
76
77
        // init monolog
78 948
        $this->initLogger();
79
    }
80
81 948
    public function initConfig()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
82
    {
83
        // load config
84
        $this['config'] = $this->share(function() {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
85 941
            $ymlPath = __DIR__.'/../../app/config/eccube';
86 941
            $distPath = __DIR__.'/../../src/Eccube/Resource/config';
87
88 941
            $config = array();
89 941
            $config_yml = $ymlPath.'/config.yml';
90 941
            if (file_exists($config_yml)) {
91 941
                $config = Yaml::parse(file_get_contents($config_yml));
92
            }
93
94 941
            $config_dist = array();
95 941
            $config_yml_dist = $distPath.'/config.yml.dist';
96 941
            if (file_exists($config_yml_dist)) {
97 941
                $config_dist = Yaml::parse(file_get_contents($config_yml_dist));
98
            }
99
100 941
            $config_path = array();
101 941
            $path_yml = $ymlPath.'/path.yml';
102 941
            if (file_exists($path_yml)) {
103 941
                $config_path = Yaml::parse(file_get_contents($path_yml));
104
            }
105
106 941
            $config_constant = array();
107 941
            $constant_yml = $ymlPath.'/constant.yml';
108 941
            if (file_exists($constant_yml)) {
109
                $config_constant = Yaml::parse(file_get_contents($constant_yml));
110
                $config_constant = empty($config_constant) ? array() : $config_constant;
111
            }
112
113 941
            $config_constant_dist = array();
114 941
            $constant_yml_dist = $distPath.'/constant.yml.dist';
115 941
            if (file_exists($constant_yml_dist)) {
116 941
                $config_constant_dist = Yaml::parse(file_get_contents($constant_yml_dist));
117
            }
118
119 941
            $configAll = array_replace_recursive($config_constant_dist, $config_dist, $config_constant, $config_path, $config);
120
121 941
            $database = array();
122 941
            $yml = $ymlPath.'/database.yml';
123 941
            if (file_exists($yml)) {
124 941
                $database = Yaml::parse(file_get_contents($yml));
125
            }
126
127 941
            $mail = array();
128 941
            $yml = $ymlPath.'/mail.yml';
129 941
            if (file_exists($yml)) {
130 941
                $mail = Yaml::parse(file_get_contents($yml));
131
            }
132 941
            $configAll = array_replace_recursive($configAll, $database, $mail);
133
134 941
            $config_log = array();
135 941
            $yml = $ymlPath.'/log.yml';
136 941
            if (file_exists($yml)) {
137
                $config_log = Yaml::parse(file_get_contents($yml));
138
            }
139 941
            $config_log_dist = array();
140 941
            $log_yml_dist = $distPath.'/log.yml.dist';
141 941
            if (file_exists($log_yml_dist)) {
142 941
                $config_log_dist = Yaml::parse(file_get_contents($log_yml_dist));
143
            }
144
145 941
            $configAll = array_replace_recursive($configAll, $config_log_dist, $config_log);
146
147 941
            $config_nav = array();
148 941
            $yml = $ymlPath.'/nav.yml';
149 941
            if (file_exists($yml)) {
150
                $config_nav = array('nav' => Yaml::parse(file_get_contents($yml)));
151
            }
152 941
            $config_nav_dist = array();
153 941
            $nav_yml_dist = $distPath.'/nav.yml.dist';
154 941
            if (file_exists($nav_yml_dist)) {
155 941
                $config_nav_dist = array('nav' => Yaml::parse(file_get_contents($nav_yml_dist)));
156
            }
157
158 941
            $configAll = array_replace_recursive($configAll, $config_nav_dist, $config_nav);
159
160 941
            $config_doctrine_cache = array();
161 941
            $yml = $ymlPath.'/doctrine_cache.yml';
162 941
            if (file_exists($yml)) {
163
                $config_doctrine_cache = Yaml::parse(file_get_contents($yml));
164
            }
165 941
            $config_doctrine_cache_dist = array();
166 941
            $doctrine_cache_yml_dist = $distPath.'/doctrine_cache.yml.dist';
167 941
            if (file_exists($doctrine_cache_yml_dist)) {
168 941
                $config_doctrine_cache_dist = Yaml::parse(file_get_contents($doctrine_cache_yml_dist));
169
            }
170
171 941
            $configAll = array_replace_recursive($configAll, $config_doctrine_cache_dist, $config_doctrine_cache);
172
173 941
            return $configAll;
174 948
        });
175
    }
176
177 948
    public function initLogger()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
178
    {
179 948
        $app = $this;
180 948
        $this->register(new ServiceProvider\EccubeMonologServiceProvider($app));
0 ignored issues
show
Unused Code introduced by
The call to EccubeMonologServiceProvider::__construct() has too many arguments starting with $app.

This check compares calls to functions or methods with their respective definitions. If the call has more 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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
181 948
        $this['monolog.logfile'] = __DIR__.'/../../app/log/site.log';
182 948
        $this['monolog.name'] = 'eccube';
183
    }
184
185 938
    public function initialize()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
186
    {
187 938
        if ($this->initialized) {
188
            return;
189
        }
190
191
        // init locale
192 938
        $this->initLocale();
193
194
        // init session
195 938
        if (!$this->isSessionStarted()) {
196 938
            $this->initSession();
197
        }
198
199
        // init twig
200 938
        $this->initRendering();
201
202
        // init provider
203 938
        $this->register(new \Silex\Provider\HttpFragmentServiceProvider());
204 938
        $this->register(new \Silex\Provider\UrlGeneratorServiceProvider());
205 938
        $this->register(new \Silex\Provider\FormServiceProvider());
206 938
        $this->register(new \Silex\Provider\SerializerServiceProvider());
207 938
        $this->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
208
209 938
        $app = $this;
210
        $this->error(function(\Exception $e, $code) use ($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
211 12
            if ($app['debug']) {
212 10
                return;
213
            }
214
            switch ($code) {
215 2
                case 403:
216
                    $title = 'アクセスできません。';
217
                    $message = 'お探しのページはアクセスができない状況にあるか、移動もしくは削除された可能性があります。';
218
                    break;
219 2
                case 404:
220
                    // 404ページを表示する
221
                    // 問題が発生した場合は、他エラーと同じ汎用エラーページを表示する
222
                    try {
223 2
                        if ($app['twig']->getLoader()->exists('404.twig')) {
224 2
                            $globals = $app['twig']->getGlobals();
225 2
                            if (is_null($globals['PageLayout'])) {
226 1
                                $DeviceType = $app['eccube.repository.master.device_type']->find(\Eccube\Entity\Master\DeviceType::DEVICE_TYPE_PC);
227 1
                                $PageLayout = $app['eccube.repository.page_layout']->getByUrl($DeviceType, '404');
228 1
                                $app['twig']->addGlobal('PageLayout', $PageLayout);
229 1
                                $app['twig']->addGlobal('title', $PageLayout->getName());
230
                            }
231 2
                            if (is_null($globals['BaseInfo'])) {
232 1
                                $BaseInfo = $app['eccube.repository.base_info']->get();
233 1
                                $app['twig']->addGlobal('BaseInfo', $BaseInfo);
234
                            }
235
236 2
                            return $app->render('404.twig');
237
                        }
238
                    } catch (\Exception $e) {
239
                        // 問題があった場合は汎用のエラーページを表示するので、例外は無視する
240
                        $this['monolog']->error('Failure rendering "404 page".', array('message' => $e->getMessage()));
241
                    }
242
                    
0 ignored issues
show
introduced by
Please trim any trailing whitespace
Loading history...
243
                    $title = 'ページがみつかりません。';
244
                    $message = 'URLに間違いがないかご確認ください。';
245
                    break;
246
                default:
247
                    $title = 'システムエラーが発生しました。';
248
                    $message = '大変お手数ですが、サイト管理者までご連絡ください。';
249
                    break;
250
            }
251
252
            return $app->render('error.twig', array(
253
                'error_title' => $title,
254
                'error_message' => $message,
255
            ));
256 938
        });
257
258
        // init mailer
259 938
        $this->initMailer();
260
261
        // init doctrine orm
262 938
        $this->initDoctrine();
263
264
        // Set up the DBAL connection now to check for a proper connection to the database.
265 938
        $this->checkDatabaseConnection();
266
267
        // init security
268 938
        $this->initSecurity();
269
270
        // init ec-cube service provider
271 938
        $this->register(new ServiceProvider\EccubeServiceProvider());
272
273
        // mount controllers
274 938
        $this->register(new \Silex\Provider\ServiceControllerServiceProvider());
275 938
        $this->mount('', new ControllerProvider\FrontControllerProvider());
276 938
        $this->mount('/'.trim($this['config']['admin_route'], '/').'/', new ControllerProvider\AdminControllerProvider());
277 938
        Request::enableHttpMethodParameterOverride(); // PUTやDELETEできるようにする
278
279
        // add transaction listener
280 938
        $this['dispatcher']->addSubscriber(new TransactionListener($this));
281
282 938
        $this->initialized = true;
283
    }
284
285 938
    public function initLocale()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
286
    {
287
288
        // timezone
289 938
        if (!empty($this['config']['timezone'])) {
290 938
            date_default_timezone_set($this['config']['timezone']);
291
        }
292
293 938
        $this->register(new \Silex\Provider\TranslationServiceProvider(), array(
294 938
            'locale' => $this['config']['locale'],
295
        ));
296
        $this['translator'] = $this->share($this->extend('translator', function($translator, \Silex\Application $app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
297 607
            $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());
298
299 607
            $r = new \ReflectionClass('Symfony\Component\Validator\Validator');
300 607
            $file = dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf';
301 607
            if (file_exists($file)) {
302 607
                $translator->addResource('xliff', $file, $app['locale'], 'validators');
303
            }
304
305 607
            $file = __DIR__.'/Resource/locale/validator.'.$app['locale'].'.yml';
306 607
            if (file_exists($file)) {
307 607
                $translator->addResource('yaml', $file, $app['locale'], 'validators');
308
            }
309
310 607
            $file = __DIR__.'/Resource/locale/message.'.$app['locale'].'.yml';
311 607
            if (file_exists($file)) {
312 607
                $translator->addResource('yaml', $file, $app['locale']);
313
            }
314
315 607
            return $translator;
316 938
        }));
317
    }
318
319 938
    public function initSession()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
320
    {
321 938
        $this->register(new \Silex\Provider\SessionServiceProvider(), array(
322 938
            'session.storage.save_path' => $this['config']['root_dir'].'/app/cache/eccube/session',
323
            'session.storage.options' => array(
324 938
                'name' => 'eccube',
325 938
                'cookie_path' => $this['config']['root_urlpath'] ?: '/',
326 938
                'cookie_secure' => $this['config']['force_ssl'],
327 938
                'cookie_lifetime' => $this['config']['cookie_lifetime'],
328
                'cookie_httponly' => true,
329
                // cookie_domainは指定しない
330
                // http://blog.tokumaru.org/2011/10/cookiedomain.html
331
            ),
332
        ));
333
    }
334
335 938
    public function initRendering()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
336
    {
337 938
        $this->register(new \Silex\Provider\TwigServiceProvider(), array(
338 938
            'twig.form.templates' => array('Form/form_layout.twig'),
339
        ));
340
        $this['twig'] = $this->share($this->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
341 366
            $twig->addExtension(new \Eccube\Twig\Extension\EccubeExtension($app));
342 366
            $twig->addExtension(new \Twig_Extension_StringLoader());
343
344 366
            return $twig;
345 938
        }));
346
347
        $this->before(function(Request $request, \Silex\Application $app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
348
            // フロント or 管理画面ごとにtwigの探索パスを切り替える.
349
            $app['twig'] = $app->share($app->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
350 353
                $paths = array();
351
352
                // 互換性がないのでprofiler とproduction 時のcacheを分離する
353
354 353
                $app['admin'] = false;
355 353
                $app['front'] = false;
356
357 353
                if (isset($app['profiler'])) {
358
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/profiler/';
359
                } else {
360 353
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/production/';
361
                }
362 353
                $pathinfo = rawurldecode($app['request']->getPathInfo());
363 353
                if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/').'/') === 0) {
364 187
                    if (file_exists(__DIR__.'/../../app/template/admin')) {
365 187
                        $paths[] = __DIR__.'/../../app/template/admin';
366
                    }
367 187
                    $paths[] = $app['config']['template_admin_realdir'];
368 187
                    $paths[] = __DIR__.'/../../app/Plugin';
369 187
                    $cache = $cacheBaseDir.'admin';
370 187
                    $app['admin'] = true;
371
                } else {
372 167
                    if (file_exists($app['config']['template_realdir'])) {
373 167
                        $paths[] = $app['config']['template_realdir'];
374
                    }
375 167
                    $paths[] = $app['config']['template_default_realdir'];
376 167
                    $paths[] = __DIR__.'/../../app/Plugin';
377 167
                    $cache = $cacheBaseDir.$app['config']['template_code'];
378 167
                    $app['front'] = true;
379
                }
380 353
                $twig->setCache($cache);
381 353
                $app['twig.loader']->addLoader(new \Twig_Loader_Filesystem($paths));
382
383 353
                return $twig;
384 355
            }));
385
386
            // 管理画面のIP制限チェック.
387 355
            $pathinfo = rawurldecode($app['request']->getPathInfo());
388 355
            if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/').'/') === 0) {
389
                // IP制限チェック
390 187
                $allowHost = $app['config']['admin_allow_host'];
391 187
                if (count($allowHost) > 0) {
392
                    if (array_search($app['request']->getClientIp(), $allowHost) === false) {
393
                        throw new \Exception();
394
                    }
395
                }
396
            }
397 938
        }, self::EARLY_EVENT);
398
399
        // twigのグローバル変数を定義.
400 938
        $app = $this;
401
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
402
            // ショップ基本情報
403 353
            $BaseInfo = $app['eccube.repository.base_info']->get();
404 353
            $app['twig']->addGlobal('BaseInfo', $BaseInfo);
405
406 353
            $pathinfo = rawurldecode($app['request']->getPathInfo());
407 353
            if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/').'/') === 0) {
408
                // 管理画面
409
                // 管理画面メニュー
410 187
                $menus = array('', '', '');
411 187
                $app['twig']->addGlobal('menus', $menus);
412
413 187
                $Member = $app->user();
414 187
                if (is_object($Member)) {
415
                    // ログインしていれば管理者のロールを取得
416 181
                    $AuthorityRoles = $app['eccube.repository.authority_role']->findBy(array('Authority' => $Member->getAuthority()));
417
418 181
                    $roles = array();
419 181
                    foreach ($AuthorityRoles as $AuthorityRole) {
420
                        // 管理画面でメニュー制御するため相対パス全てをセット
421 181
                        $roles[] = $app['request']->getBaseUrl().'/'.$app['config']['admin_route'].$AuthorityRole->getDenyUrl();
422
                    }
423
424 187
                    $app['twig']->addGlobal('AuthorityRoles', $roles);
425
                }
426
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
427
            } else {
428
                // フロント画面
429 167
                $request = $event->getRequest();
430 167
                $route = $request->attributes->get('_route');
431
432
                // ユーザ作成画面
433 167
                if ($route === trim($app['config']['user_data_route'])) {
434 2
                    $params = $request->attributes->get('_route_params');
435 2
                    $route = $params['route'];
436
                    // プレビュー画面
437 165
                } elseif ($request->get('preview')) {
438
                    $route = 'preview';
439
                }
440
441
                try {
442 167
                    $DeviceType = $app['eccube.repository.master.device_type']
443 167
                        ->find(\Eccube\Entity\Master\DeviceType::DEVICE_TYPE_PC);
444 167
                    $PageLayout = $app['eccube.repository.page_layout']->getByUrl($DeviceType, $route);
445 137
                } catch (\Doctrine\ORM\NoResultException $e) {
446 137
                    $PageLayout = $app['eccube.repository.page_layout']->newPageLayout($DeviceType);
447
                }
448
449 167
                $app['twig']->addGlobal('PageLayout', $PageLayout);
450 167
                $app['twig']->addGlobal('title', $PageLayout->getName());
451
            }
452 938
        });
453
    }
454
455 938
    public function initMailer()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
456
    {
457
458
        // メール送信時の文字エンコード指定(デフォルトはUTF-8)
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
459 938
        if (isset($this['config']['mail']['charset_iso_2022_jp']) && is_bool($this['config']['mail']['charset_iso_2022_jp'])) {
460 938
            if ($this['config']['mail']['charset_iso_2022_jp'] === true) {
461
                \Swift::init(function() {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
462
                    \Swift_DependencyContainer::getInstance()
463
                        ->register('mime.qpheaderencoder')
464
                        ->asAliasOf('mime.base64headerencoder');
465
                    \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
466
                });
467
            }
468
        }
469
470 938
        $this->register(new \Silex\Provider\SwiftmailerServiceProvider());
471 938
        $this['swiftmailer.options'] = $this['config']['mail'];
472
473 938
        if (isset($this['config']['mail']['spool']) && is_bool($this['config']['mail']['spool'])) {
474
            $this['swiftmailer.use_spool'] = $this['config']['mail']['spool'];
475
        }
476
        // デフォルトはsmtpを使用
477 938
        $transport = $this['config']['mail']['transport'];
478 938
        if ($transport == 'sendmail') {
479
            $this['swiftmailer.transport'] = \Swift_SendmailTransport::newInstance();
480 938
        } elseif ($transport == 'mail') {
481
            $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance();
482
        }
483
    }
484
485 938
    public function initDoctrine()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
486
    {
487 938
        $this->register(new \Silex\Provider\DoctrineServiceProvider(), array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
488
            'dbs.options' => array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
489 938
                'default' => $this['config']['database']
490
        )));
491 938
        $this->register(new \Saxulum\DoctrineOrmManagerRegistry\Silex\Provider\DoctrineOrmManagerRegistryProvider());
492
493
        // プラグインのmetadata定義を合わせて行う.
494 938
        $pluginBasePath = __DIR__.'/../../app/Plugin';
495 938
        $finder = Finder::create()
496 938
            ->in($pluginBasePath)
497 938
            ->directories()
498 938
            ->depth(0);
499
500 938
        $ormMappings = array();
501 938
        $ormMappings[] = array(
502
            'type' => 'yml',
503
            'namespace' => 'Eccube\Entity',
504
            'path' => array(
505
                __DIR__.'/Resource/doctrine',
506
                __DIR__.'/Resource/doctrine/master',
507
            ),
508
        );
509
510 938
        foreach ($finder as $dir) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
511
512 139
            $file = $dir->getRealPath().'/config.yml';
513
514 139
            if (file_exists($file)) {
515 139
                $config = Yaml::parse(file_get_contents($file));
516
            } else {
517
                $code = $dir->getBaseName();
518
                $this['monolog']->warning("skip {$code} orm.path loading. config.yml not found.", array('path' => $file));
519
                continue;
520
            }
521
522
            // Doctrine Extend
523 139
            if (isset($config['orm.path']) && is_array($config['orm.path'])) {
524
                $paths = array();
525
                foreach ($config['orm.path'] as $path) {
526
                    $paths[] = $pluginBasePath.'/'.$config['code'].$path;
527
                }
528
                $ormMappings[] = array(
529
                    'type' => 'yml',
530
                    'namespace' => 'Plugin\\'.$config['code'].'\\Entity',
531 938
                    'path' => $paths,
532
                );
533
            }
534
        }
535
536
        $options = array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
537 938
            'mappings' => $ormMappings
538
        );
539
540 938
        if (!$this['debug']) {
541 3
            $cacheDrivers = array();
542 3
            if (array_key_exists('doctrine_cache', $this['config'])) {
543
                $cacheDrivers = $this['config']['doctrine_cache'];
544
            }
545 3
            if (array_key_exists('metadata_cache', $cacheDrivers)) {
546
                $options['metadata_cache'] = $cacheDrivers['metadata_cache'];
547
            }
548 3
            if (array_key_exists('query_cache', $cacheDrivers)) {
549
                $options['query_cache'] = $cacheDrivers['query_cache'];
550
            }
551 3
            if (array_key_exists('result_cache', $cacheDrivers)) {
552
                $options['result_cache'] = $cacheDrivers['result_cache'];
553
            }
554 3
            if (array_key_exists('hydration_cache', $cacheDrivers)) {
555
                $options['hydration_cache'] = $cacheDrivers['hydration_cache'];
556
            }
557
        }
558
559 938
        $this->register(new \Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
560 938
            'orm.proxies_dir' => __DIR__.'/../../app/cache/doctrine/proxies',
561 938
            'orm.em.options' => $options
562
        ));
563
    }
564
565 938
    public function initSecurity()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
566
    {
567 938
        $this->register(new \Silex\Provider\SecurityServiceProvider());
568 938
        $this->register(new \Silex\Provider\RememberMeServiceProvider());
569
570 938
        $this['security.firewalls'] = array(
571
            'admin' => array(
572 938
                'pattern' => "^/{$this['config']['admin_route']}/",
573
                'form' => array(
574 938
                    'login_path' => "/{$this['config']['admin_route']}/login",
575 938
                    'check_path' => "/{$this['config']['admin_route']}/login_check",
576 938
                    'username_parameter' => 'login_id',
577 938
                    'password_parameter' => 'password',
578
                    'with_csrf' => true,
579
                    'use_forward' => true,
580
                ),
581
                'logout' => array(
582 938
                    'logout_path' => "/{$this['config']['admin_route']}/logout",
583 938
                    'target_url' => "/{$this['config']['admin_route']}/",
584
                ),
585 938
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Member'),
586
                'anonymous' => true,
587 938
            ),
588
            'customer' => array(
589 938
                'pattern' => '^/',
590
                'form' => array(
591
                    'login_path' => '/mypage/login',
592
                    'check_path' => '/login_check',
593
                    'username_parameter' => 'login_email',
594
                    'password_parameter' => 'login_pass',
595
                    'with_csrf' => true,
596
                    'use_forward' => true,
597
                ),
598
                'logout' => array(
599
                    'logout_path' => '/logout',
600
                    'target_url' => '/',
601
                ),
602
                'remember_me' => array(
603 938
                    'key' => sha1($this['config']['auth_magic']),
604 938
                    'name' => 'eccube_rememberme',
605
                    // lifetimeはデフォルトの1年間にする
606
                    // 'lifetime' => $this['config']['cookie_lifetime'],
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
607 938
                    'path' => $this['config']['root_urlpath'] ?: '/',
608 938
                    'secure' => $this['config']['force_ssl'],
609
                    'httponly' => true,
610
                    'always_remember_me' => false,
611 938
                    'remember_me_parameter' => 'login_memory',
612
                ),
613 938
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Customer'),
614
                'anonymous' => true,
615
            ),
616
        );
617
618 938
        $this['security.access_rules'] = array(
619 938
            array("^/{$this['config']['admin_route']}/login", 'IS_AUTHENTICATED_ANONYMOUSLY'),
620 938
            array("^/{$this['config']['admin_route']}/", 'ROLE_ADMIN'),
621
            array('^/mypage/login', 'IS_AUTHENTICATED_ANONYMOUSLY'),
622
            array('^/mypage/withdraw_complete', 'IS_AUTHENTICATED_ANONYMOUSLY'),
623
            array('^/mypage/change', 'IS_AUTHENTICATED_FULLY'),
624
            array('^/mypage', 'ROLE_USER'),
625
        );
626
627
        $this['eccube.password_encoder'] = $this->share(function($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
628 938
            return new \Eccube\Security\Core\Encoder\PasswordEncoder($app['config']);
629 938
        });
630
        $this['security.encoder_factory'] = $this->share(function($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
631 938
            return new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array(
632 938
                'Eccube\Entity\Customer' => $app['eccube.password_encoder'],
633 938
                'Eccube\Entity\Member' => $app['eccube.password_encoder'],
634
            ));
635 938
        });
636
        $this['eccube.event_listner.security'] = $this->share(function($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
637 938
            return new \Eccube\EventListener\SecurityEventListener($app['orm.em']);
638 938
        });
639
        $this['user'] = function($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
640 256
            $token = $app['security']->getToken();
641
642 256
            return ($token !== null) ? $token->getUser() : null;
643
        };
644
645
        // ログイン時のイベントを設定.
646 938
        $this['dispatcher']->addListener(\Symfony\Component\Security\Http\SecurityEvents::INTERACTIVE_LOGIN, array($this['eccube.event_listner.security'], 'onInteractiveLogin'));
647
648
        // Voterの設定
649 938
        $app = $this;
650
        $this['authority_voter'] = $this->share(function($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
651 938
            return new \Eccube\Security\Voter\AuthorityVoter($app);
652 938
        });
653
654
        $app['security.voters'] = $app->extend('security.voters', function($voters) use ($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
655 938
            $voters[] = $app['authority_voter'];
656
657 938
            return $voters;
658 938
        });
659
660
        $this['security.access_manager'] = $this->share(function($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
661 938
            return new \Symfony\Component\Security\Core\Authorization\AccessDecisionManager($app['security.voters'], 'unanimous');
662 938
        });
663
664
    }
665
666 938
    public function initializePlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
667
    {
668 938
        if ($this->initializedPlugin) {
669
            return;
670
        }
671
672
        // setup event dispatcher
673 938
        $this->initPluginEventDispatcher();
674
675
        // load plugin
676 938
        $this->loadPlugin();
677
678 938
        $this->initializedPlugin = true;
679
    }
680
681 938
    public function initPluginEventDispatcher()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
682
    {
683
        // EventDispatcher
684
        $this['eccube.event.dispatcher'] = $this->share(function() {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
685 368
            return new EventDispatcher();
686 938
        });
687
688 938
        $app = $this;
689
690
        // hook point
691
        $this->on(KernelEvents::REQUEST, function (GetResponseEvent $event) use ($app) {
692 355
            if (!$event->isMasterRequest()) {
693 100
                return;
694
            }
695 355
            $hookpoint = 'eccube.event.app.before';
696 355
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
697 938
        }, self::EARLY_EVENT);
698
699 View Code Duplication
        $this->on(KernelEvents::REQUEST, function (GetResponseEvent $event) use ($app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
700 354
            if (!$event->isMasterRequest()) {
701 100
                return;
702
            }
703 351
            $route = $event->getRequest()->attributes->get('_route');
704 351
            $hookpoint = "eccube.event.controller.$route.before";
705 351
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
706 938
        });
707
708 View Code Duplication
        $this->on(KernelEvents::RESPONSE, function (FilterResponseEvent $event) use ($app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
709 349
            if (!$event->isMasterRequest()) {
710 100
                return;
711
            }
712 349
            $route = $event->getRequest()->attributes->get('_route');
713 349
            $hookpoint = "eccube.event.controller.$route.after";
714 349
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
715 938
        });
716
717
        $this->on(KernelEvents::RESPONSE, function (FilterResponseEvent $event) use ($app) {
718 349
            if (!$event->isMasterRequest()) {
719 100
                return;
720
            }
721 349
            $hookpoint = 'eccube.event.app.after';
722 349
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
723 938
        }, self::LATE_EVENT);
724
725
        $this->on(KernelEvents::TERMINATE, function (PostResponseEvent $event) use ($app) {
726 349
            $route = $event->getRequest()->attributes->get('_route');
727 349
            $hookpoint = "eccube.event.controller.$route.finish";
728 349
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
729 938
        });
730
731
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
732 349
            $route = $event->getRequest()->attributes->get('_route');
733 349
            $app['eccube.event.dispatcher']->dispatch('eccube.event.render.'.$route.'.before', $event);
734 938
        });
735
736
        // Request Event
737 View Code Duplication
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::REQUEST, function(\Symfony\Component\HttpKernel\Event\GetResponseEvent $event) use ($app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
738
739 354
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
740 100
                return;
741
            }
742
743 353
            $route = $event->getRequest()->attributes->get('_route');
744
745 353
            if (is_null($route)) {
746
                return;
747
            }
748
749 353
            $app['monolog']->debug('KernelEvents::REQUEST '.$route);
750
751
            // 全体
752 353
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.request', $event);
753
754 353
            if (strpos($route, 'admin') === 0) {
755
                // 管理画面
756 187
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.request', $event);
757
            } else {
758
                // フロント画面
759 167
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.request', $event);
760
            }
761
762
            // ルーティング単位
763 353
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.request", $event);
764
765 938
        }, 30); // Routing(32)が解決しし, 認証判定(8)が実行される前のタイミング.
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
766
767
        // Controller Event
768 View Code Duplication
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
769
770 353
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
771 100
                return;
772
            }
773
774
775 350
            $route = $event->getRequest()->attributes->get('_route');
776
777 350
            if (is_null($route)) {
778
                return;
779
            }
780
781 350
            $app['monolog']->debug('KernelEvents::CONTROLLER '.$route);
782
783
            // 全体
784 350
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.controller', $event);
785
786 350
            if (strpos($route, 'admin') === 0) {
787
                // 管理画面
788 185
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.controller', $event);
789
            } else {
790
                // フロント画面
791 166
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.controller', $event);
792
            }
793
794
            // ルーティング単位
795 350
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.controller", $event);
796 938
        });
797
798
        // Response Event
799 View Code Duplication
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
800
801 349
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
802 100
                return;
803
            }
804
805 349
            $route = $event->getRequest()->attributes->get('_route');
806
807 349
            if (is_null($route)) {
808 2
                return;
809
            }
810
811 347
            $app['monolog']->debug('KernelEvents::RESPONSE '.$route);
812
813
            // ルーティング単位
814 347
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.response", $event);
815
816 347
            if (strpos($route, 'admin') === 0) {
817
                // 管理画面
818 187
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.response', $event);
819
            } else {
820
                // フロント画面
821 161
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.response', $event);
822
            }
823
824
            // 全体
825 347
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.response', $event);
826 938
        });
827
828
        // Exception Event
829 View Code Duplication
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::EXCEPTION, function(\Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event) use ($app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
830
831 14
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
832
                return;
833
            }
834
835 14
            $route = $event->getRequest()->attributes->get('_route');
836
837 14
            if (is_null($route)) {
838 1
                return;
839
            }
840
841 13
            $app['monolog']->debug('KernelEvents::EXCEPTION '.$route);
842
843
            // ルーティング単位
844 13
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.exception", $event);
845
846 13
            if (strpos($route, 'admin') === 0) {
847
                // 管理画面
848 2
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.exception', $event);
849
            } else {
850
                // フロント画面
851 11
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.exception', $event);
852
            }
853
854
            // 全体
855 13
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.exception', $event);
856 938
        });
857
858
        // Terminate Event
859 View Code Duplication
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::TERMINATE, function(\Symfony\Component\HttpKernel\Event\PostResponseEvent $event) use ($app) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
860
861 349
            $route = $event->getRequest()->attributes->get('_route');
862
863 349
            if (is_null($route)) {
864 2
                return;
865
            }
866
867 347
            $app['monolog']->debug('KernelEvents::TERMINATE '.$route);
868
869
            // ルーティング単位
870 347
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.terminate", $event);
871
872 347
            if (strpos($route, 'admin') === 0) {
873
                // 管理画面
874 187
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.terminate', $event);
875
            } else {
876
                // フロント画面
877 161
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.terminate', $event);
878
            }
879
880
            // 全体
881 347
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.terminate', $event);
882 938
        });
883
    }
884
885 938
    public function loadPlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
886
    {
887
        // プラグインディレクトリを探索.
888 938
        $basePath = __DIR__.'/../../app/Plugin';
889 938
        $finder = Finder::create()
890 938
            ->in($basePath)
891 938
            ->directories()
892 938
            ->depth(0);
893
894 938
        $finder->sortByName();
895
896
        // ハンドラ優先順位をdbから持ってきてハッシュテーブルを作成
897 938
        $priorities = array();
898 938
        $handlers = $this['orm.em']
899 938
            ->getRepository('Eccube\Entity\PluginEventHandler')
900 938
            ->getHandlers();
901 938
        foreach ($handlers as $handler) {
902
            if ($handler->getPlugin()->getEnable() && !$handler->getPlugin()->getDelFlg()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
903
904
                $priority = $handler->getPriority();
905
            } else {
906
                // Pluginがdisable、削除済みの場合、EventHandlerのPriorityを全て0とみなす
907
                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED;
908
            }
909 938
            $priorities[$handler->getPlugin()->getClassName()][$handler->getEvent()][$handler->getHandler()] = $priority;
910
        }
911
912
        // プラグインをロードする.
913
        // config.yml/event.ymlの定義に沿ってインスタンスの生成を行い, イベント設定を行う.
914 938
        foreach ($finder as $dir) {
915
            //config.ymlのないディレクトリは無視する
916 140
            $path = $dir->getRealPath();
917 140
            $code = $dir->getBaseName();
918
            try {
919 140
                $this['eccube.service.plugin']->checkPluginArchiveContent($path);
920
            } catch (\Eccube\Exception\PluginException $e) {
921
                $this['monolog']->warning("skip {$code} config loading. config.yml not foud or invalid.", array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
922
                    'path' =>  $path,
923
                    'original-message' => $e->getMessage()
924
                ));
925
                continue;
926
            }
927 140
            $config = $this['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');
928
929 140
            $plugin = $this['orm.em']
930 140
                ->getRepository('Eccube\Entity\Plugin')
931 140
                ->findOneBy(array('code' => $config['code']));
932
933
            // const
934 140
            if (isset($config['const'])) {
935 1
                $this['config'] = $this->share($this->extend('config', function($eccubeConfig) use ($config) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
936 1
                    $eccubeConfig[$config['code']] = array(
937 1
                        'const' => $config['const'],
938
                    );
939
940 1
                    return $eccubeConfig;
941 1
                }));
942
            }
943
944 140
            if ($plugin && $plugin->getEnable() == Constant::DISABLED) {
945
                // プラグインが無効化されていれば読み込まない
946 1
                continue;
947
            }
948
949
            // Type: Event
950 139
            if (isset($config['event'])) {
951 139
                $class = '\\Plugin\\'.$config['code'].'\\'.$config['event'];
952 139
                $eventExists = true;
953
954 139 View Code Duplication
                if (!class_exists($class)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
955
                    $this['monolog']->warning("skip {$code} loading. event class not foud.", array(
956
                        'class' =>  $class,
957
                    ));
958
                    $eventExists = false;
959
                }
960
961 139
                if ($eventExists && file_exists($dir->getRealPath().'/event.yml')) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
962
963 139
                    $subscriber = new $class($this);
964
965 139
                    foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {
966 139
                        foreach ($handlers as $handler) {
967 139
                            if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする
968 139
                                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;
969
                            } else {
970
                                $priority = $priorities[$config['event']][$event][$handler[0]];
971
                            }
972
                            // 優先度が0のプラグインは登録しない
973 139
                            if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {
974 139
                                $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);
975
                            }
976
                        }
977
                    }
978
                }
979
            }
980
            // Type: ServiceProvider
981 139
            if (isset($config['service'])) {
982
                foreach ($config['service'] as $service) {
983
                    $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;
984 View Code Duplication
                    if (!class_exists($class)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
985
                        $this['monolog']->warning("skip {$code} loading. service provider class not foud.", array(
986
                            'class' =>  $class,
987
                        ));
988
                        continue;
989
                    }
990 938
                    $this->register(new $class($this));
991
                }
992
            }
993
        }
994
    }
995
996
    /**
997
     * PHPUnit を実行中かどうかを設定する.
998
     *
999
     * @param boolean $testMode PHPUnit を実行中の場合 true
1000
     */
1001 925
    public function setTestMode($testMode) {
1002 925
        $this->testMode = $testMode;
1003
    }
1004
1005
    /**
1006
     * PHPUnit を実行中かどうか.
1007
     *
1008
     * @return boolean PHPUnit を実行中の場合 true
1009
     */
1010 355
    public function isTestMode()
1011
    {
1012 355
        return $this->testMode;
1013
    }
1014
1015
    /**
1016
     *
1017
     * データベースの接続を確認
1018
     * 成功 : trueを返却
1019
     * 失敗 : \Doctrine\DBAL\DBALExceptionエラーが発生( 接続に失敗した場合 )、エラー画面を表示しdie()
1020
     * 備考 : app['debug']がtrueの際は処理を行わない
1021
     * @return boolean true
1022
     *
1023
     */
1024 938
    protected function checkDatabaseConnection()
1025
    {
1026 938
        if ($this['debug']) {
1027 935
            return;
1028
        }
1029
        try {
1030 3
            $this['db']->connect();
1031
        } catch (\Doctrine\DBAL\DBALException $e) {
1032
            $this['monolog']->error($e->getMessage());
1033
            $this['twig.path'] = array(__DIR__.'/Resource/template/exception');
1034
            $html = $this['twig']->render('error.twig', array(
1035
                'error_title' => 'データーベース接続エラー',
1036
                'error_message' => 'データーベースを確認してください',
1037
            ));
1038
            $response = new Response();
1039
            $response->setContent($html);
1040
            $response->setStatusCode('500');
1041
            $response->headers->set('Content-Type', 'text/html');
1042
            $response->send();
1043
            die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method checkDatabaseConnection() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
1044
        }
1045 3
        return true;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1046
    }
1047
1048
    /**
1049
     * セッションが開始されているかどうか.
1050
     *
1051
     * @return boolean セッションが開始済みの場合 true
1052
     * @link http://php.net/manual/ja/function.session-status.php#113468
1053
     */
1054 938
    protected function isSessionStarted()
1055
    {
1056 938
        if (php_sapi_name() !== 'cli') {
1057 938
            if (version_compare(phpversion(), '5.4.0', '>=')) {
1058 938
                return session_status() === PHP_SESSION_ACTIVE ? true : false;
1059
            } else {
1060
                return session_id() === '' ? false : true;
1061
            }
1062
        }
1063
        return false;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
1064
    }
1065
}
1066