Completed
Pull Request — master (#1663)
by chihiro
20:50
created

Application::initDoctrine()   D

Complexity

Conditions 12
Paths 165

Size

Total Lines 79
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 17.3317

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 79
ccs 28
cts 42
cp 0.6667
rs 4.7657
cc 12
eloc 50
nc 165
nop 0
crap 17.3317

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