Completed
Push — master ( f5798f...5cfee9 )
by chihiro
356:49 queued 348:01
created

Application::initialize()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 83
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 6.3833

Importance

Changes 0
Metric Value
dl 0
loc 83
ccs 39
cts 50
cp 0.78
rs 8.3634
c 0
b 0
f 0
cc 6
eloc 46
nc 3
nop 0
crap 6.3833

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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