Completed
Push — master ( bb033c...eaceea )
by Ryo
23:21
created

Application::initDoctrine()   F

Complexity

Conditions 13
Paths 330

Size

Total Lines 95
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 16.7098

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 95
ccs 36
cts 50
cp 0.72
rs 3.7737
cc 13
eloc 56
nc 330
nop 0
crap 16.7098

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