Completed
Pull Request — master (#1720)
by chihiro
40:58 queued 25:48
created

Application   F

Complexity

Total Complexity 124

Size/Duplication

Total Lines 1010
Duplicated Lines 17.03 %

Coupling/Cohesion

Components 2
Dependencies 52

Test Coverage

Coverage 83.2%

Importance

Changes 15
Bugs 0 Features 0
Metric Value
wmc 124
c 15
b 0
f 0
lcom 2
cbo 52
dl 172
loc 1010
ccs 416
cts 500
cp 0.832
rs 0.9913

21 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 8 2
A clearInstance() 0 4 1
A __clone() 0 4 1
A __construct() 0 14 2
A initLogger() 0 7 1
D parseConfig() 6 41 13
B isSessionStarted() 0 12 5
A initConfig() 0 18 1
B initialize() 0 77 6
B initLocale() 0 33 5
B initSession() 0 24 3
D initRendering() 0 119 14
C initMailer() 0 29 8
F initDoctrine() 0 96 13
B initSecurity() 0 100 3
A initializePlugin() 0 14 2
D initPluginEventDispatcher() 154 203 19
D loadPlugin() 12 110 20
A setTestMode() 0 3 1
A isTestMode() 0 4 1
A checkDatabaseConnection() 0 23 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Application often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Application, and based on these observations, apply Extract Interface, too.

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