Failed Conditions
Push — master ( 36ccc8...f8bd2f )
by Kentaro
34:47
created

Application::initPluginEventDispatcher()   D

Complexity

Conditions 15
Paths 1

Size

Total Lines 185
Code Lines 86

Duplication

Lines 146
Ratio 78.92 %

Code Coverage

Tests 4
CRAP Score 15
Metric Value
dl 146
loc 185
ccs 4
cts 4
cp 1
rs 4.9121
cc 15
eloc 86
nc 1
nop 0
crap 15

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 Monolog\Logger;
29
use Symfony\Component\EventDispatcher\EventDispatcher;
30
use Symfony\Component\Finder\Finder;
31
use Symfony\Component\HttpFoundation\Request;
32
use Symfony\Component\HttpFoundation\Response;
33
use Symfony\Component\Yaml\Yaml;
34
35
class Application extends ApplicationTrait
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
36
{
37
    protected static $instance;
38
39
    protected $initialized = false;
40
    protected $initializedPlugin = false;
41 424
42
    public static function getInstance(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
43
    {
44
        if (!is_object(self::$instance)) {
45
            self::$instance = new Application($values);
46
        }
47 424
48 424
        return self::$instance;
49
    }
50 770
51
    public static function clearInstance()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
52 770
    {
53 770
        self::$instance = null;
54
    }
55
56
    final public function __clone()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
57
    {
58
        throw new \Exception('Clone is not allowed against '.get_class($this));
59
    }
60 770
61
    public function __construct(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
62
    {
63
        parent::__construct($values);
64
65 770
        if (is_null(self::$instance)) {
66
            self::$instance = $this;
67
        }
68
69
        // load config
70
        $this->initConfig();
71
72
        // init monolog
73
        $this->initLogger();
74
    }
75 784
76
    public function initConfig()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
77
    {
78
        // load config
79 773
        $this['config'] = $this->share(function() {
80 773
            $ymlPath = __DIR__.'/../../app/config/eccube';
81
            $distPath = __DIR__.'/../../src/Eccube/Resource/config';
82 773
83 773
            $config = array();
84
            $config_yml = $ymlPath.'/config.yml';
85
            if (file_exists($config_yml)) {
86
                $config = Yaml::parse(file_get_contents($config_yml));
87
            }
88 773
89 773
            $config_dist = array();
90
            $config_yml_dist = $distPath.'/config.yml.dist';
91
            if (file_exists($config_yml_dist)) {
92
                $config_dist = Yaml::parse(file_get_contents($config_yml_dist));
93
            }
94 773
95 773
            $config_path = array();
96
            $path_yml = $ymlPath.'/path.yml';
97
            if (file_exists($path_yml)) {
98
                $config_path = Yaml::parse(file_get_contents($path_yml));
99
            }
100 773
101 773
            $config_constant = array();
102
            $constant_yml = $ymlPath.'/constant.yml';
103
            if (file_exists($constant_yml)) {
104
                $config_constant = Yaml::parse(file_get_contents($constant_yml));
105
                $config_constant = empty($config_constant) ? array() : $config_constant;
106
            }
107 773
108 773
            $config_constant_dist = array();
109
            $constant_yml_dist = $distPath.'/constant.yml.dist';
110
            if (file_exists($constant_yml_dist)) {
111
                $config_constant_dist = Yaml::parse(file_get_contents($constant_yml_dist));
112
            }
113
114
            $configAll = array_replace_recursive($config_constant_dist, $config_dist, $config_constant, $config_path, $config);
115 773
116 773
            $database = array();
117
            $yml = $ymlPath.'/database.yml';
118
            if (file_exists($yml)) {
119
                $database = Yaml::parse(file_get_contents($yml));
120
            }
121 773
122 773
            $mail = array();
123
            $yml = $ymlPath.'/mail.yml';
124
            if (file_exists($yml)) {
125
                $mail = Yaml::parse(file_get_contents($yml));
126
            }
127
            $configAll = array_replace_recursive($configAll, $database, $mail);
128 773
129 773
            $config_log = array();
130
            $yml = $ymlPath.'/log.yml';
131
            if (file_exists($yml)) {
132
                $config_log = Yaml::parse(file_get_contents($yml));
133 773
            }
134 773
            $config_log_dist = array();
135
            $log_yml_dist = $distPath.'/log.yml.dist';
136
            if (file_exists($log_yml_dist)) {
137
                $config_log_dist = Yaml::parse(file_get_contents($log_yml_dist));
138
            }
139
140
            $configAll = array_replace_recursive($configAll, $config_log_dist, $config_log);
141 773
142 773
            $config_nav = array();
143
            $yml = $ymlPath.'/nav.yml';
144
            if (file_exists($yml)) {
145
                $config_nav = array('nav' => Yaml::parse(file_get_contents($yml)));
146 773
            }
147 773
            $config_nav_dist = array();
148
            $nav_yml_dist = $distPath.'/nav.yml.dist';
149
            if (file_exists($nav_yml_dist)) {
150
                $config_nav_dist = array('nav' => Yaml::parse(file_get_contents($nav_yml_dist)));
151
            }
152
153
            $configAll = array_replace_recursive($configAll, $config_nav_dist, $config_nav);
154 773
155
            return $configAll;
156 784
        });
157
    }
158 784
159
    public function initLogger()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
160 784
    {
161
        $app = $this;
162
        $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...
163
        $this['monolog.logfile'] = __DIR__.'/../../app/log/site.log';
164 784
        $this['monolog.name'] = 'eccube';
165
    }
166 770
167
    public function initialize()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
168 770
    {
169
        if ($this->initialized) {
170
            return;
171
        }
172
173
        // init locale
174
        $this->initLocale();
175
176
        // init session
177
        $this->initSession();
178
179
        // init twig
180
        $this->initRendering();
181
182
        // init provider
183
        $this->register(new \Silex\Provider\HttpFragmentServiceProvider());
184
        $this->register(new \Silex\Provider\UrlGeneratorServiceProvider());
185
        $this->register(new \Silex\Provider\FormServiceProvider());
186
        $this->register(new \Silex\Provider\SerializerServiceProvider());
187
        $this->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
188 770
189
        $app = $this;
190
        $this->error(function(\Exception $e, $code) use ($app) {
191 10
            if ($app['debug']) {
192
                return;
193
            }
194
195
            switch ($code) {
196
                case 403:
197
                    $title = 'アクセスできません。';
198
                    $message = 'お探しのページはアクセスができない状況にあるか、移動もしくは削除された可能性があります。';
199
                    break;
200
                case 404:
201
                    $title = 'ページがみつかりません。';
202
                    $message = 'URLに間違いがないかご確認ください。';
203
                    break;
204
                default:
205
                    $title = 'システムエラーが発生しました。';
206
                    $message = '大変お手数ですが、サイト管理者までご連絡ください。';
207
                    break;
208
            }
209
210
            return $app->render('error.twig', array(
211
                'error_title' => $title,
212
                'error_message' => $message,
213
            ));
214
        });
215
216
        // init mailer
217
        $this->initMailer();
218
219
        // init doctrine orm
220
        $this->initDoctrine();
221
222
        // Set up the DBAL connection now to check for a proper connection to the database.
223
        $this->checkDatabaseConnection();
224
225
        // init security
226
        $this->initSecurity();
227
228
        // init ec-cube service provider
229
        $this->register(new ServiceProvider\EccubeServiceProvider());
230
231
        // mount controllers
232
        $this->register(new \Silex\Provider\ServiceControllerServiceProvider());
233
        $this->mount('', new ControllerProvider\FrontControllerProvider());
234
        $this->mount('/'.trim($this['config']['admin_route'], '/').'/', new ControllerProvider\AdminControllerProvider());
235
        Request::enableHttpMethodParameterOverride(); // PUTやDELETEできるようにする
236 770
237 770
        $this->initialized = true;
238
    }
239 770
240
    public function initLocale()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
241
    {
242
243
        // timezone
244
        if (!empty($this['config']['timezone'])) {
245
            date_default_timezone_set($this['config']['timezone']);
246
        }
247
248 770
        $this->register(new \Silex\Provider\TranslationServiceProvider(), array(
249
            'locale' => $this['config']['locale'],
250
        ));
251
        $this['translator'] = $this->share($this->extend('translator', function($translator, \Silex\Application $app) {
252
            $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());
253
254
            $r = new \ReflectionClass('Symfony\Component\Validator\Validator');
255
            $file = dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf';
256
            if (file_exists($file)) {
257
                $translator->addResource('xliff', $file, $app['locale'], 'validators');
258
            }
259
260
            $file = __DIR__.'/Resource/locale/validator.'.$app['locale'].'.yml';
261
            if (file_exists($file)) {
262
                $translator->addResource('yaml', $file, $app['locale'], 'validators');
263
            }
264
265
            $file = __DIR__.'/Resource/locale/message.'.$app['locale'].'.yml';
266
            if (file_exists($file)) {
267
                $translator->addResource('yaml', $file, $app['locale']);
268
            }
269 445
270
            return $translator;
271 770
        }));
272
    }
273 770
274
    public function initSession()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
275
    {
276
        $this->register(new \Silex\Provider\SessionServiceProvider(), array(
277
            'session.storage.save_path' => $this['config']['root_dir'].'/app/cache/eccube/session',
278 770
            'session.storage.options' => array(
279
                'name' => 'eccube',
280 770
                'cookie_path' => $this['config']['root_urlpath'] ?: '/',
281 770
                'cookie_secure' => $this['config']['force_ssl'],
282 770
                'cookie_lifetime' => $this['config']['cookie_lifetime'],
283
                'cookie_httponly' => true,
284
                // cookie_domainは指定しない
285 770
                // http://blog.tokumaru.org/2011/10/cookiedomain.html
286
            ),
287 770
        ));
288
    }
289 770
290
    public function initRendering()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
291
    {
292
        $this->register(new \Silex\Provider\TwigServiceProvider(), array(
293
            'twig.form.templates' => array('Form/form_layout.twig'),
294
        ));
295
        $this['twig'] = $this->share($this->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
296
            $twig->addExtension(new \Eccube\Twig\Extension\EccubeExtension($app));
297
            $twig->addExtension(new \Twig_Extension_StringLoader());
298 204
299
            return $twig;
300
        }));
301
302
        $this->before(function(Request $request, \Silex\Application $app) {
303
            // フロント or 管理画面ごとにtwigの探索パスを切り替える.
304 169
            $app['twig'] = $app->share($app->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
305
                $paths = array();
306
307
                // 互換性がないのでprofiler とproduction 時のcacheを分離する
308
309
                $app['admin'] = false;
310
                $app['front'] = false;
311 169
312
                if (isset($app['profiler'])) {
313
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/profiler/';
314
                } else {
315 102
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/production/';
316
                }
317
                if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {
318 102
                    if (file_exists(__DIR__.'/../../app/template/admin')) {
319 102
                        $paths[] = __DIR__.'/../../app/template/admin';
320
                    }
321
                    $paths[] = $app['config']['template_admin_realdir'];
322
                    $paths[] = __DIR__.'/../../app/Plugin';
323
                    $cache = $cacheBaseDir.'admin';
324
                    $app['admin'] = true;
325 68
                } else {
326
                    if (file_exists($app['config']['template_realdir'])) {
327 102
                        $paths[] = $app['config']['template_realdir'];
328
                    }
329
                    $paths[] = $app['config']['template_default_realdir'];
330
                    $paths[] = __DIR__.'/../../app/Plugin';
331 169
                    $cache = $cacheBaseDir.$app['config']['template_code'];
332
                    $app['front'] = true;
333
                }
334
                $twig->setCache($cache);
335
                $app['twig.loader']->addLoader(new \Twig_Loader_Filesystem($paths));
336
337
                return $twig;
338
            }));
339
340
            // 管理画面のIP制限チェック.
341
            if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {
342
                // IP制限チェック
343
                $allowHost = $app['config']['admin_allow_host'];
344
                if (count($allowHost) > 0) {
345
                    if (array_search($app['request']->getClientIp(), $allowHost) === false) {
346
                        throw new \Exception();
347 770
                    }
348
                }
349
            }
350
        }, self::EARLY_EVENT);
351
352
        // twigのグローバル変数を定義.
353
        $app = $this;
354
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {
355
            // ショップ基本情報
356 102
            $BaseInfo = $app['eccube.repository.base_info']->get();
357
            $app['twig']->addGlobal('BaseInfo', $BaseInfo);
358
359
            if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {
360
                // 管理画面
361
                // 管理画面メニュー
362
                $menus = array('', '', '');
363
                $app['twig']->addGlobal('menus', $menus);
364 99
365
                $Member = $app->user();
366
                if (is_object($Member)) {
367
                    // ログインしていれば管理者のロールを取得
368 99
                    $AuthorityRoles = $app['eccube.repository.authority_role']->findBy(array('Authority' => $Member->getAuthority()));
369
370
                    $roles = array();
371
                    foreach ($AuthorityRoles as $AuthorityRole) {
372
                        // 管理画面でメニュー制御するため相対パス全てをセット
373
                        $roles[] = $app['request']->getBaseUrl().'/'.$app['config']['admin_route'].$AuthorityRole->getDenyUrl();
374
                    }
375
376
                    $app['twig']->addGlobal('AuthorityRoles', $roles);
377
                }
378
379
            } else {
380
                // フロント画面
381 2
                $request = $event->getRequest();
382
                $route = $request->attributes->get('_route');
383
384
                // ユーザ作成画面
385 2
                if ($route === trim($app['config']['user_data_route'])) {
386
                    $params = $request->attributes->get('_route_params');
387
                    $route = $params['route'];
388
                    // プレビュー画面
389
                } elseif ($request->get('preview')) {
390
                    $route = 'preview';
391
                }
392
393 34
                try {
394
                    $DeviceType = $app['eccube.repository.master.device_type']
395
                        ->find(\Eccube\Entity\Master\DeviceType::DEVICE_TYPE_PC);
396
                    $PageLayout = $app['eccube.repository.page_layout']->getByUrl($DeviceType, $route);
397 102
                } catch (\Doctrine\ORM\NoResultException $e) {
398
                    $PageLayout = $app['eccube.repository.page_layout']->newPageLayout($DeviceType);
399 770
                }
400
401 770
                $app['twig']->addGlobal('PageLayout', $PageLayout);
402
                $app['twig']->addGlobal('title', $PageLayout->getName());
403
            }
404
        });
405
    }
406
407
    public function initMailer()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
408
    {
409
410
        // メール送信時の文字エンコード指定(デフォルトは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...
411
        if (isset($this['config']['mail']['charset_iso_2022_jp']) && is_bool($this['config']['mail']['charset_iso_2022_jp'])) {
412
            if ($this['config']['mail']['charset_iso_2022_jp'] === true) {
413
                \Swift::init(function() {
414
                    \Swift_DependencyContainer::getInstance()
415
                        ->register('mime.qpheaderencoder')
416
                        ->asAliasOf('mime.base64headerencoder');
417
                    \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
418
                });
419
            }
420
        }
421
422
        $this->register(new \Silex\Provider\SwiftmailerServiceProvider());
423
        $this['swiftmailer.options'] = $this['config']['mail'];
424 770
425
        if (isset($this['config']['mail']['spool']) && is_bool($this['config']['mail']['spool'])) {
426 770
            $this['swiftmailer.use_spool'] = $this['config']['mail']['spool'];
427
        }
428
        // デフォルトはsmtpを使用
429 770
        $transport = $this['config']['mail']['transport'];
430
        if ($transport == 'sendmail') {
431 770
            $this['swiftmailer.transport'] = \Swift_SendmailTransport::newInstance();
432
        } elseif ($transport == 'mail') {
433
            $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance();
434
        }
435 770
    }
436
437
    public function initDoctrine()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
438
    {
439
        $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...
440 770
            'dbs.options' => array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
441 769
                'default' => $this['config']['database']
442 770
        )));
1 ignored issue
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
443 770
        $this->register(new \Saxulum\DoctrineOrmManagerRegistry\Silex\Provider\DoctrineOrmManagerRegistryProvider());
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
444
445
        // プラグインのmetadata定義を合わせて行う.
446 770
        $pluginBasePath = __DIR__.'/../../app/Plugin';
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
447
        $finder = Finder::create()
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
448 770
            ->in($pluginBasePath)
449 770
            ->directories()
450
            ->depth(0);
451 770
452 770
        $ormMappings = array();
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
453 770
        $ormMappings[] = array(
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
454 770
            'type' => 'yml',
455
            'namespace' => 'Eccube\Entity',
456
            'path' => array(
457
                __DIR__.'/Resource/doctrine',
458
                __DIR__.'/Resource/doctrine/master',
459
            ),
460
        );
461
462
        foreach ($finder as $dir) {
463
464
            $file = $dir->getRealPath().'/config.yml';
465
466
            if (file_exists($file)) {
467
                $config = Yaml::parse(file_get_contents($file));
468
            } else {
469
                $code = $dir->getBaseName();
470
                $this['monolog']->warning("skip {$code} orm.path loading. config.yml not found.", array('path' => $file));
471
                continue;
472
            }
473
474
            // Doctrine Extend
475
            if (isset($config['orm.path']) && is_array($config['orm.path'])) {
476
                $paths = array();
477
                foreach ($config['orm.path'] as $path) {
478
                    $paths[] = $pluginBasePath.'/'.$config['code'].$path;
479
                }
480 770
                $ormMappings[] = array(
481
                    'type' => 'yml',
482
                    'namespace' => 'Plugin\\'.$config['code'].'\\Entity',
483 770
                    'path' => $paths,
484
                );
485
            }
486 770
        }
487
488 770
        $this->register(new \Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
489
            'orm.proxies_dir' => __DIR__.'/../../app/cache/doctrine',
490 770
            'orm.em.options' => array(
491
                'mappings' => $ormMappings,
492
            ),
493
        ));
494
    }
495 770
496
    public function initSecurity()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
497
    {
498
        $this->register(new \Silex\Provider\SecurityServiceProvider());
499
        $this->register(new \Silex\Provider\RememberMeServiceProvider());
500
501 770
        $this['security.firewalls'] = array(
502 770
            'admin' => array(
503 770
                'pattern' => "^/{$this['config']['admin_route']}",
504 770
                'form' => array(
505 770
                    'login_path' => "/{$this['config']['admin_route']}/login",
506
                    'check_path' => "/{$this['config']['admin_route']}/login_check",
507
                    'username_parameter' => 'login_id',
508
                    'password_parameter' => 'password',
509 770
                    'with_csrf' => true,
510
                    'use_forward' => true,
511 770
                ),
512
                'logout' => array(
513
                    'logout_path' => "/{$this['config']['admin_route']}/logout",
514 770
                    'target_url' => "/{$this['config']['admin_route']}/",
515
                ),
516
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Member'),
517
                'anonymous' => true,
518
            ),
519
            'customer' => array(
520
                'pattern' => '^/',
521
                'form' => array(
522 770
                    'login_path' => '/mypage/login',
523
                    'check_path' => '/login_check',
524
                    'username_parameter' => 'login_email',
525
                    'password_parameter' => 'login_pass',
526 770
                    'with_csrf' => true,
527
                    'use_forward' => true,
528
                ),
529 770
                'logout' => array(
530
                    'logout_path' => '/logout',
531
                    'target_url' => '/',
532
                ),
533 770
                'remember_me' => array(
534 770
                    'key' => sha1($this['config']['auth_magic']),
535 770
                    'name' => 'eccube_rememberme',
536 770
                    // lifetimeはデフォルトの1年間にする
537
                    // '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...
538
                    'path' => $this['config']['root_urlpath'] ?: '/',
539 770
                    'secure' => $this['config']['force_ssl'],
540
                    'httponly' => true,
541
                    'always_remember_me' => false,
542
                    'remember_me_parameter' => 'login_memory',
543 770
                ),
544
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Customer'),
545
                'anonymous' => true,
546 770
            ),
547 770
        );
548 770
549 770
        $this['security.access_rules'] = array(
550
            array("^/{$this['config']['admin_route']}/login", 'IS_AUTHENTICATED_ANONYMOUSLY'),
551
            array("^/{$this['config']['admin_route']}", 'ROLE_ADMIN'),
552
            array('^/mypage/login', 'IS_AUTHENTICATED_ANONYMOUSLY'),
553
            array('^/mypage/withdraw_complete', 'IS_AUTHENTICATED_ANONYMOUSLY'),
554
            array('^/mypage/change', 'IS_AUTHENTICATED_FULLY'),
555
            array('^/mypage', 'ROLE_USER'),
556
        );
557 770
558 770
        $this['eccube.password_encoder'] = $this->share(function($app) {
559
            return new \Eccube\Security\Core\Encoder\PasswordEncoder($app['config']);
560
        });
561
        $this['security.encoder_factory'] = $this->share(function($app) {
562
            return new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array(
563
                'Eccube\Entity\Customer' => $app['eccube.password_encoder'],
564
                'Eccube\Entity\Member' => $app['eccube.password_encoder'],
565
            ));
566
        });
567
        $this['eccube.event_listner.security'] = $this->share(function($app) {
568
            return new \Eccube\EventListener\SecurityEventListener($app['orm.em']);
569
        });
570
        $this['user'] = function($app) {
571
            $token = $app['security']->getToken();
572
573
            return ($token !== null) ? $token->getUser() : null;
574 770
        };
575
576
        // ログイン時のイベントを設定.
577
        $this['dispatcher']->addListener(\Symfony\Component\Security\Http\SecurityEvents::INTERACTIVE_LOGIN, array($this['eccube.event_listner.security'], 'onInteractiveLogin'));
578
579
        // Voterの設定
580
        $app = $this;
581
        $this['authority_voter'] = $this->share(function($app) {
582 770
            return new \Eccube\Security\Voter\AuthorityVoter($app);
583
        });
584
585
        $app['security.voters'] = $app->extend('security.voters', function($voters) use ($app) {
586
            $voters[] = $app['authority_voter'];
587
588
            return $voters;
589 770
        });
590
591
        $this['security.access_manager'] = $this->share(function($app) {
592
            return new \Symfony\Component\Security\Core\Authorization\AccessDecisionManager($app['security.voters'], 'unanimous');
593
        });
594
595
    }
596
597
    public function initializePlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
598
    {
599
        if ($this->initializedPlugin) {
600
            return;
601
        }
602
603
        // setup event dispatcher
604
        $this->initPluginEventDispatcher();
605
606 770
        // load plugin
607
        $this->loadPlugin();
608
609
        $this->initializedPlugin = true;
610
    }
611
612
    public function initPluginEventDispatcher()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
613
    {
614
        // EventDispatcher
615
        $this['eccube.event.dispatcher'] = $this->share(function() {
616
            return new EventDispatcher();
617
        });
618
619
        // hook point
620
        $this->before(function(Request $request, \Silex\Application $app) {
621
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.before');
622
        }, self::EARLY_EVENT);
623
624
        $this->before(function(Request $request, \Silex\Application $app) {
625
            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.before';
626
            $app['eccube.event.dispatcher']->dispatch($event);
627
        });
628
629 View Code Duplication
        $this->after(function(Request $request, Response $response, \Silex\Application $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...
630
            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.after';
631
            $app['eccube.event.dispatcher']->dispatch($event);
632
        });
633
634
        $this->after(function(Request $request, Response $response, \Silex\Application $app) {
635
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.after');
636
        }, self::LATE_EVENT);
637 770
638 View Code Duplication
        $this->finish(function(Request $request, Response $response, \Silex\Application $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...
639
            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.finish';
640
            $app['eccube.event.dispatcher']->dispatch($event);
641
        });
642 770
643
        $app = $this;
644
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
645
            $route = $event->getRequest()->attributes->get('_route');
646
            $app['eccube.event.dispatcher']->dispatch('eccube.event.render.'.$route.'.before', $event);
647
        });
648
649
        // Request Event
650 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...
651
652
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
653
                return;
654
            }
655
656
            $route = $event->getRequest()->attributes->get('_route');
657
658
            if (is_null($route)) {
659
                return;
660
            }
661
662
            $app['monolog']->debug('KernelEvents::REQUEST '.$route);
663
664
            // 全体
665
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.request', $event);
666
667
            if (strpos('admin', $route) === 0) {
668
                // 管理画面
669
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.request', $event);
670
            } else {
671
                // フロント画面
672
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.request', $event);
673
            }
674
675
            // ルーティング単位
676
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.request", $event);
677
678
        }, 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...
679
680
        // Controller Event
681 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...
682
683
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
684
                return;
685
            }
686
687
688
            $route = $event->getRequest()->attributes->get('_route');
689
690
            if (is_null($route)) {
691
                return;
692
            }
693
694
            $app['monolog']->debug('KernelEvents::CONTROLLER '.$route);
695
696
            // 全体
697
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.controller', $event);
698
699
            if (strpos('admin', $route) === 0) {
700
                // 管理画面
701
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.controller', $event);
702
            } else {
703
                // フロント画面
704
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.controller', $event);
705
            }
706
707
            // ルーティング単位
708
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.controller", $event);
709
        });
710
711
        // Response Event
712 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...
713
714
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
715
                return;
716
            }
717
718
            $route = $event->getRequest()->attributes->get('_route');
719
720
            if (is_null($route)) {
721
                return;
722
            }
723
724
            $app['monolog']->debug('KernelEvents::RESPONSE '.$route);
725
726
            // ルーティング単位
727
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.response", $event);
728
729
            if (strpos('admin', $route) === 0) {
730
                // 管理画面
731
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.response', $event);
732
            } else {
733
                // フロント画面
734
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.response', $event);
735
            }
736
737
            // 全体
738
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.response', $event);
739
        });
740
741
        // Exception Event
742 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...
743
744
            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
745
                return;
746
            }
747
748
            $route = $event->getRequest()->attributes->get('_route');
749
750
            if (is_null($route)) {
751
                return;
752
            }
753
754
            $app['monolog']->debug('KernelEvents::EXCEPTION '.$route);
755
756
            // ルーティング単位
757
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.exception", $event);
758
759
            if (strpos('admin', $route) === 0) {
760
                // 管理画面
761
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.exception', $event);
762
            } else {
763
                // フロント画面
764 770
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.exception', $event);
765
            }
766
767 770
            // 全体
768
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.exception', $event);
769
        });
770
771
        // Terminate Event
772 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...
773
774
            $route = $event->getRequest()->attributes->get('_route');
775
776
            if (is_null($route)) {
777
                return;
778
            }
779
780
            $app['monolog']->debug('KernelEvents::TERMINATE '.$route);
781
782
            // ルーティング単位
783
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.terminate", $event);
784
785
            if (strpos('admin', $route) === 0) {
786
                // 管理画面
787
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.terminate', $event);
788
            } else {
789
                // フロント画面
790
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.terminate', $event);
791
            }
792
793
            // 全体
794
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.terminate', $event);
795
        });
796
    }
797
798
    public function loadPlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
799
    {
800
        // プラグインディレクトリを探索.
801
        $basePath = __DIR__.'/../../app/Plugin';
802
        $finder = Finder::create()
803
            ->in($basePath)
804
            ->directories()
805
            ->depth(0);
806
807
        $finder->sortByName();
808
809
        // ハンドラ優先順位をdbから持ってきてハッシュテーブルを作成
810
        $priorities = array();
811
        $handlers = $this['orm.em']
812
            ->getRepository('Eccube\Entity\PluginEventHandler')
813
            ->getHandlers();
814
        foreach ($handlers as $handler) {
815
            if ($handler->getPlugin()->getEnable() && !$handler->getPlugin()->getDelFlg()) {
816
817
                $priority = $handler->getPriority();
818
            } else {
819
                // Pluginがdisable、削除済みの場合、EventHandlerのPriorityを全て0とみなす
820
                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED;
821
            }
822
            $priorities[$handler->getPlugin()->getClassName()][$handler->getEvent()][$handler->getHandler()] = $priority;
823
        }
824
825
        // プラグインをロードする.
826
        // config.yml/event.ymlの定義に沿ってインスタンスの生成を行い, イベント設定を行う.
827
        foreach ($finder as $dir) {
828
            //config.ymlのないディレクトリは無視する
829
            $path = $dir->getRealPath();
830
            $code = $dir->getBaseName();
831
            try {
832
                $this['eccube.service.plugin']->checkPluginArchiveContent($path);
833
            } catch (\Eccube\Exception\PluginException $e) {
834
                $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...
835
                    'path' =>  $path,
836
                    'original-message' => $e->getMessage()
837
                ));
838
                continue;
839
            }
840
            $config = $this['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');
841
842
            $plugin = $this['orm.em']
843
                ->getRepository('Eccube\Entity\Plugin')
844
                ->findOneBy(array('code' => $config['code']));
845
846
            // const
847
            if (isset($config['const'])) {
848
                $this['config'] = $this->share($this->extend('config', function($eccubeConfig) use ($config) {
849
                    $eccubeConfig[$config['code']] = array(
850
                        'const' => $config['const'],
851
                    );
852
853
                    return $eccubeConfig;
854
                }));
855
            }
856
857
            if ($plugin && $plugin->getEnable() == Constant::DISABLED) {
858
                // プラグインが無効化されていれば読み込まない
859
                continue;
860
            }
861
862
            // Type: Event
863
            if (isset($config['event'])) {
864
                $class = '\\Plugin\\'.$config['code'].'\\'.$config['event'];
865
                $eventExists = true;
866
867 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...
868
                    $this['monolog']->warning("skip {$code} loading. event class not foud.", array(
869
                        'class' =>  $class,
870
                    ));
871
                    $eventExists = false;
872
                }
873
874
                if ($eventExists && file_exists($dir->getRealPath().'/event.yml')) {
875
876
                    $subscriber = new $class($this);
877
878
                    foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {
879
                        foreach ($handlers as $handler) {
880
                            if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする
881
                                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;
882
                            } else {
883
                                $priority = $priorities[$config['event']][$event][$handler[0]];
884
                            }
885
                            // 優先度が0のプラグインは登録しない
886
                            if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {
887
                                $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);
888
                            }
889
                        }
890
                    }
891
                }
892
            }
893
            // Type: ServiceProvider
894
            if (isset($config['service'])) {
895
                foreach ($config['service'] as $service) {
896
                    $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;
897 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...
898
                        $this['monolog']->warning("skip {$code} loading. service provider class not foud.", array(
899
                            'class' =>  $class,
900
                        ));
901
                        continue;
902
                    }
903
                    $this->register(new $class($this));
904
                }
905
            }
906
        }
907
    }
908
909
    /**
910
     *
911
     * データベースの接続を確認
912
     * 成功 : trueを返却
913
     * 失敗 : \Doctrine\DBAL\DBALExceptionエラーが発生( 接続に失敗した場合 )、エラー画面を表示しdie()
914
     * 備考 : app['debug']がtrueの際は処理を行わない
915
     * @return boolean true
916
     *
917
     */
918
    protected function checkDatabaseConnection()
919
    {
920
        if ($this['debug']) {
921
            return;
922
        }
923
        try {
924
            $this['db']->connect();
925
        } catch (\Doctrine\DBAL\DBALException $e) {
926
            $this['monolog']->error($e->getMessage());
927
            $this['twig.path'] = array(__DIR__.'/Resource/template/exception');
928
            $html = $this['twig']->render('error.twig', array(
929
                'error_title' => 'データーベース接続エラー',
930
                'error_message' => 'データーベースを確認してください',
931
            ));
932
            $response = new Response();
933
            $response->setContent($html);
934
            $response->setStatusCode('500');
935
            $response->headers->set('Content-Type', 'text/html');
936
            $response->send();
937
            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...
938
        }
939
        return true;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
940
    }
941
}
942