Completed
Pull Request — master (#1813)
by chihiro
248:19 queued 240:17
created

Application::checkDatabaseConnection()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5.667

Importance

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

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

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

Loading history...
899
                    $this['monolog']->warning("skip {$code} loading. event class not foud.", array(
900
                        'class' => $class,
901
                    ));
902
                    $eventExists = false;
903
                }
904
905 139
                if ($eventExists && file_exists($dir->getRealPath().'/event.yml')) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
906
907 139
                    $subscriber = new $class($this);
908
909 139
                    foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {
910 139
                        foreach ($handlers as $handler) {
911 139
                            if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする
912 139
                                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;
913 139
                            } else {
914
                                $priority = $priorities[$config['event']][$event][$handler[0]];
915
                            }
916
                            // 優先度が0のプラグインは登録しない
917 139
                            if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {
918 139
                                $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);
919 139
                            }
920 139
                        }
921 139
                    }
922 139
                }
923 139
            }
924
            // Type: ServiceProvider
925 139
            if (isset($config['service'])) {
926
                foreach ($config['service'] as $service) {
927
                    $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;
928 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...
929
                        $this['monolog']->warning("skip {$code} loading. service provider class not foud.", array(
930
                            'class' => $class,
931
                        ));
932
                        continue;
933
                    }
934
                    $this->register(new $class($this));
935
                }
936
            }
937 1047
        }
938 1047
    }
939
940
    /**
941
     * PHPUnit を実行中かどうかを設定する.
942
     *
943
     * @param boolean $testMode PHPUnit を実行中の場合 true
944
     */
945 1033
    public function setTestMode($testMode)
946
    {
947 1033
        $this->testMode = $testMode;
948 1033
    }
949
950
    /**
951
     * PHPUnit を実行中かどうか.
952
     *
953
     * @return boolean PHPUnit を実行中の場合 true
954
     */
955 456
    public function isTestMode()
956
    {
957 456
        return $this->testMode;
958
    }
959
960
    /**
961
     *
962
     * データベースの接続を確認
963
     * 成功 : trueを返却
964
     * 失敗 : \Doctrine\DBAL\DBALExceptionエラーが発生( 接続に失敗した場合 )、エラー画面を表示しdie()
965
     * 備考 : app['debug']がtrueの際は処理を行わない
966
     *
967
     * @return boolean true
968
     *
969
     */
970 1047
    protected function checkDatabaseConnection()
971
    {
972 1047
        if ($this['debug']) {
973 1043
            return;
974
        }
975
        try {
976 4
            $this['db']->connect();
977 4
        } catch (\Doctrine\DBAL\DBALException $e) {
978
            $this['monolog']->error($e->getMessage());
979
            $this['twig.path'] = array(__DIR__.'/Resource/template/exception');
980
            $html = $this['twig']->render('error.twig', array(
981
                'error_title' => 'データーベース接続エラー',
982
                'error_message' => 'データーベースを確認してください',
983
            ));
984
            $response = new Response();
985
            $response->setContent($html);
986
            $response->setStatusCode('500');
987
            $response->headers->set('Content-Type', 'text/html');
988
            $response->send();
989
            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...
990
        }
991
992 4
        return true;
993
    }
994
995
    /**
996
     * Config ファイルをパースし、連想配列を返します.
997
     *
998
     * $config_name.yml ファイルをパースし、連想配列を返します.
999
     * $config_name.php が存在する場合は、 PHP ファイルに記述された連想配列を使用します。
1000
     *
1001
     * @param string $config_name Config 名称
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
1002
     * @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...
1003
     * @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...
1004
     * @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...
1005
     * @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...
1006
     * @return Application
1007
     */
1008 1050
    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...
1009
    {
1010 1050
        $ymlPath = $ymlPath ? $ymlPath : __DIR__.'/../../app/config/eccube';
1011 1050
        $distPath = $distPath ? $distPath : __DIR__.'/../../src/Eccube/Resource/config';
1012 1050
        $config = array();
1013 1050
        $config_php = $ymlPath.'/'.$config_name.'.php';
1014 1050
        if (!file_exists($config_php)) {
1015 1050
            $config_yml = $ymlPath.'/'.$config_name.'.yml';
1016 1050
            if (file_exists($config_yml)) {
1017 1050
                $config = Yaml::parse(file_get_contents($config_yml));
1018 1050
                $config = empty($config) ? array() : $config;
1019 1050 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...
1020
                    file_put_contents($config_php, sprintf('<?php return %s', var_export($config, true)).';');
1021
                }
1022 1050
            }
1023 1050
        } else {
1024
            $config = require $config_php;
1025
        }
1026
1027 1050
        $config_dist = array();
1028 1050
        $config_php_dist = $distPath.'/'.$config_name.'.dist.php';
1029 1050
        if (!file_exists($config_php_dist)) {
1030 1050
            $config_yml_dist = $distPath.'/'.$config_name.'.yml.dist';
1031 1050
            if (file_exists($config_yml_dist)) {
1032 1050
                $config_dist = Yaml::parse(file_get_contents($config_yml_dist));
1033 1050 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...
1034
                    file_put_contents($config_php_dist, sprintf('<?php return %s', var_export($config_dist, true)).';');
1035
                }
1036 1050
            }
1037 1050
        } else {
1038
            $config_dist = require $config_php_dist;
1039
        }
1040
1041 1050
        if ($wrap_key) {
1042 1050
            $configAll = array_replace_recursive($configAll, array($config_name => $config_dist), array($config_name => $config));
1043 1050
        } else {
1044 1050
            $configAll = array_replace_recursive($configAll, $config_dist, $config);
1045
        }
1046
1047 1050
        return $this;
1048
    }
1049
1050
    /**
1051
     * セッションが開始されているかどうか.
1052
     *
1053
     * @return boolean セッションが開始済みの場合 true
1054
     * @link http://php.net/manual/ja/function.session-status.php#113468
1055
     */
1056 1047
    protected function isSessionStarted()
1057
    {
1058 1047
        if (php_sapi_name() !== 'cli') {
1059
            if (version_compare(phpversion(), '5.4.0', '>=')) {
1060
                return session_status() === PHP_SESSION_ACTIVE ? true : false;
1061
            } else {
1062
                return session_id() === '' ? false : true;
1063
            }
1064
        }
1065
1066 1047
        return false;
1067
    }
1068
1069
    /**
1070
     * Http Cache対応
1071
     */
1072 1047
    protected function initCacheRequest()
1073
    {
1074
        // httpキャッシュが無効の場合はイベント設定を行わない.
1075 1047
        if (!$this['config']['http_cache']['enabled']) {
1076 1047
            return;
1077
        }
1078
1079
        $app = $this;
1080
1081
        // Response Event(http cache対応、event実行は一番遅く設定)
1082
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function (\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
1083
1084
            if (!$event->isMasterRequest()) {
1085
                return;
1086
            }
1087
1088
            $request = $event->getRequest();
1089
            $response = $event->getResponse();
1090
1091
            $route = $request->attributes->get('_route');
1092
1093
            $etag = md5($response->getContent());
1094
1095
            if (strpos($route, 'admin') === 0) {
1096
                // 管理画面
1097
1098
                // 管理画面ではコンテンツの中身が変更された時点でキャッシュを更新し、キャッシュの適用範囲はprivateに設定
1099
                $response->setCache(array(
1100
                    'etag' => $etag,
1101
                    'private' => true,
1102
                ));
1103
1104
                if ($response->isNotModified($request)) {
1105
                    return $response;
1106
                }
1107
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
1108
            } else {
1109
                // フロント画面
1110
                $cacheRoute = $app['config']['http_cache']['route'];
1111
1112
                if (in_array($route, $cacheRoute) === true) {
1113
                    // キャッシュ対象となる画面lが含まれていた場合、キャッシュ化
1114
                    // max-ageを設定しているためExpiresは不要
1115
                    // Last-Modifiedだと比較する項目がないためETagで対応
1116
                    // max-ageを設定していた場合、contentの中身が変更されても変更されない
1117
1118
                    $age = $app['config']['http_cache']['age'];
1119
1120
                    $response->setCache(array(
1121
                        'etag' => $etag,
1122
                        'max_age' => $age,
1123
                        's_maxage' => $age,
1124
                        'public' => true,
1125
                    ));
1126
1127
                    if ($response->isNotModified($request)) {
1128
                        return $response;
1129
                    }
1130
                }
1131
            }
1132
1133
        }, -1024);
1134
    }
1135
}
1136