Completed
Pull Request — master (#1827)
by chihiro
150:19 queued 130:40
created

Application::initDoctrine()   F

Complexity

Conditions 13
Paths 330

Size

Total Lines 96
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 55
CRAP Score 13.9708

Importance

Changes 0
Metric Value
dl 0
loc 96
ccs 55
cts 67
cp 0.8209
rs 3.7737
c 0
b 0
f 0
cc 13
eloc 56
nc 330
nop 0
crap 13.9708

How to fix   Long Method    Complexity   

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