Completed
Pull Request — master (#1827)
by chihiro
593:54 queued 586:57
created

Application::initSecurity()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 100
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 68
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 100
ccs 68
cts 68
cp 1
rs 8.2857
c 0
b 0
f 0
cc 3
eloc 67
nc 2
nop 0
crap 3

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