Completed
Push — master ( f7b119...9e4c7b )
by Yangsin
353:17 queued 347:09
created

Application::clearInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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