Completed
Pull Request — master (#1813)
by chihiro
601:14 queued 594:15
created

Application::isSessionStarted()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 8.125

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 3
cts 6
cp 0.5
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 7
nc 5
nop 0
crap 8.125
1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
namespace Eccube;
25
26
use Eccube\Application\ApplicationTrait;
27
use Eccube\Common\Constant;
28
use Eccube\Doctrine\ORM\Mapping\Driver\YamlDriver;
29
use Eccube\EventListener\TransactionListener;
30
use Symfony\Component\EventDispatcher\EventDispatcher;
31
use Symfony\Component\Finder\Finder;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\Response;
34
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
35
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
36
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
37
use Symfony\Component\HttpKernel\KernelEvents;
38
use Symfony\Component\Yaml\Yaml;
39
40
class Application extends ApplicationTrait
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
41
{
42
    protected static $instance;
43
44
    protected $initialized = false;
45
    protected $initializedPlugin = false;
46
    protected $testMode = false;
47
48 1047
    public static function getInstance(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
49
    {
50 1047
        if (!is_object(self::$instance)) {
51 1046
            self::$instance = new Application($values);
52 1046
        }
53
54 1047
        return self::$instance;
55
    }
56
57 1047
    public static function clearInstance()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
58
    {
59 1047
        self::$instance = null;
60 1047
    }
61
62
    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 1061
    public function __construct(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
68 1061
    {
69 1061
        parent::__construct($values);
70
71 1061
        if (is_null(self::$instance)) {
72 1047
            self::$instance = $this;
73 1047
        }
74
75
        // load config
76 1061
        $this->initConfig();
77
78
        // init monolog
79 1061
        $this->initLogger();
80 1061
    }
81
82 1062
    public function initConfig()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
83 1061
    {
84
        // load config
85 1061
        $app = $this;
86
        $this['config'] = $this->share(function() use ($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
87 1062
            $configAll = array();
88 1054
            $app->parseConfig('constant', $configAll)
89 1054
                ->parseConfig('path', $configAll)
90 1054
                ->parseConfig('config', $configAll)
91 1062
                ->parseConfig('database', $configAll)
92 1062
                ->parseConfig('mail', $configAll)
93 1054
                ->parseConfig('log', $configAll)
94 1054
                ->parseConfig('nav', $configAll, true)
95 1054
                ->parseConfig('doctrine_cache', $configAll)
96 1054
                ->parseConfig('http_cache', $configAll)
97 1054
                ->parseConfig('session_handler', $configAll);
98
99 1054
            return $configAll;
100 1061
        });
101 1061
    }
102
103 1061
    public function initLogger()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
104
    {
105 1061
        $app = $this;
106 1061
        $this->register(new ServiceProvider\EccubeMonologServiceProvider($app));
0 ignored issues
show
Unused Code introduced by
The call to EccubeMonologServiceProvider::__construct() has too many arguments starting with $app.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
107 1061
        $this['monolog.logfile'] = __DIR__.'/../../app/log/site.log';
108 1061
        $this['monolog.name'] = 'eccube';
109 1061
    }
110
111 1062
    public function initialize()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
112
    {
113 1051
        if ($this->initialized) {
114
            return;
115
        }
116
117
        // init locale
118 1062
        $this->initLocale();
119
120
        // init session
121 1051
        if (!$this->isSessionStarted()) {
122 1062
            $this->initSession();
123 1051
        }
124
125
        // init twig
126 1062
        $this->initRendering();
127
128
        // init provider
129 1051
        $this->register(new \Silex\Provider\HttpCacheServiceProvider(), array(
130 1062
            'http_cache.cache_dir' => __DIR__.'/../../app/cache/http/',
131 1051
        ));
132 1051
        $this->register(new \Silex\Provider\HttpFragmentServiceProvider());
133 1051
        $this->register(new \Silex\Provider\UrlGeneratorServiceProvider());
134 1051
        $this->register(new \Silex\Provider\FormServiceProvider());
135 1051
        $this->register(new \Silex\Provider\SerializerServiceProvider());
136 1062
        $this->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
137
138 1051
        $app = $this;
139
        $this->error(function (\Exception $e, $code) use ($app) {
140 17
            if ($app['debug']) {
141 17
                return;
142
            }
143
144
            switch ($code) {
145 1061
                case 403:
146
                    $title = 'アクセスできません。';
147
                    $message = 'お探しのページはアクセスができない状況にあるか、移動もしくは削除された可能性があります。';
148
                    break;
149 1061
                case 404:
150
                    $title = 'ページがみつかりません。';
151
                    $message = 'URLに間違いがないかご確認ください。';
152
                    break;
153 1061
                default:
154
                    $title = 'システムエラーが発生しました。';
155 1061
                    $message = '大変お手数ですが、サイト管理者までご連絡ください。';
156 1061
                    break;
157 1061
            }
158
159 1061
            return $app->render('error.twig', array(
160
                'error_title' => $title,
161
                'error_message' => $message,
162
            ));
163 1051
        });
164
165
        // init mailer
166 1051
        $this->initMailer();
167
168
        // init doctrine orm
169 1051
        $this->initDoctrine();
170
171
        // Set up the DBAL connection now to check for a proper connection to the database.
172 1051
        $this->checkDatabaseConnection();
173
174
        // init security
175 1051
        $this->initSecurity();
176
177
        // init ec-cube service provider
178 1051
        $this->register(new ServiceProvider\EccubeServiceProvider());
179
180
        // mount controllers
181 1051
        $this->register(new \Silex\Provider\ServiceControllerServiceProvider());
182 1051
        $this->mount('', new ControllerProvider\FrontControllerProvider());
183 1051
        $this->mount('/'.trim($this['config']['admin_route'], '/').'/', new ControllerProvider\AdminControllerProvider());
184 1051
        Request::enableHttpMethodParameterOverride(); // PUTやDELETEできるようにする
185
186
        // add transaction listener
187 1051
        $this['dispatcher']->addSubscriber(new TransactionListener($this));
188
189
        // init http cache
190 1051
        $this->initCacheRequest();
191
192 1051
        $this->initialized = true;
193 1051
    }
194
195 1051
    public function initLocale()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
196
    {
197
198
        // timezone
199 1051
        if (!empty($this['config']['timezone'])) {
200 1051
            date_default_timezone_set($this['config']['timezone']);
201 1051
        }
202
203 1051
        $this->register(new \Silex\Provider\TranslationServiceProvider(), array(
204 1051
            'locale' => $this['config']['locale'],
205 1051
        ));
206
        $this['translator'] = $this->share($this->extend('translator', function ($translator, \Silex\Application $app) {
207 715
            $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());
208
209 715
            $r = new \ReflectionClass('Symfony\Component\Validator\Validator');
210 715
            $file = dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf';
211 715
            if (file_exists($file)) {
212 715
                $translator->addResource('xliff', $file, $app['locale'], 'validators');
213 715
            }
214
215 715
            $file = __DIR__.'/Resource/locale/validator.'.$app['locale'].'.yml';
216 715
            if (file_exists($file)) {
217 715
                $translator->addResource('yaml', $file, $app['locale'], 'validators');
218 715
            }
219
220 715
            $file = __DIR__.'/Resource/locale/message.'.$app['locale'].'.yml';
221 715
            if (file_exists($file)) {
222 715
                $translator->addResource('yaml', $file, $app['locale']);
223 715
            }
224
225 715
            return $translator;
226 1051
        }));
227 1051
    }
228
229 1051
    public function initSession()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
230
    {
231 1051
        $this->register(new \Silex\Provider\SessionServiceProvider(), array(
232 1051
            'session.storage.save_path' => $this['config']['root_dir'].'/app/cache/eccube/session',
233
            'session.storage.options' => array(
234 1051
                'name' => 'eccube',
235 1051
                'cookie_path' => $this['config']['root_urlpath'] ?: '/',
236 1051
                'cookie_secure' => $this['config']['force_ssl'],
237 1051
                'cookie_lifetime' => $this['config']['cookie_lifetime'],
238 1051
                'cookie_httponly' => true,
239
                // cookie_domainは指定しない
240
                // http://blog.tokumaru.org/2011/10/cookiedomain.html
241 1051
            ),
242 1051
        ));
243
244 1051
        $options = $this['config']['session_handler'];
245
246 1051
        if ($options['enabled']) {
247
            // @see http://silex.sensiolabs.org/doc/providers/session.html#custom-session-configurations
248
            $this['session.storage.handler'] = null;
249
            ini_set('session.save_handler', $options['save_handler']);
250
            ini_set('session.save_path', $options['save_path']);
251
        }
252 1051
    }
253
254 1051
    public function initRendering()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
255
    {
256 1051
        $this->register(new \Silex\Provider\TwigServiceProvider(), array(
257 1051
            'twig.form.templates' => array('Form/form_layout.twig'),
258 1051
        ));
259
        $this['twig'] = $this->share($this->extend('twig', function (\Twig_Environment $twig, \Silex\Application $app) {
260 472
            $twig->addExtension(new \Eccube\Twig\Extension\EccubeExtension($app));
261 472
            $twig->addExtension(new \Twig_Extension_StringLoader());
262
263 472
            return $twig;
264 1051
        }));
265
266
        $this->before(function (Request $request, \Silex\Application $app) {
267
            // フロント or 管理画面ごとにtwigの探索パスを切り替える.
268
            $app['twig'] = $app->share($app->extend('twig', function (\Twig_Environment $twig, \Silex\Application $app) {
269 458
                $paths = array();
270
271
                // 互換性がないのでprofiler とproduction 時のcacheを分離する
272
273 458
                $app['admin'] = false;
274 458
                $app['front'] = false;
275
276 458
                if (isset($app['profiler'])) {
277
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/profiler/';
278
                } else {
279 458
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/production/';
280
                }
281 458
                $pathinfo = rawurldecode($app['request']->getPathInfo());
282 458
                if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/').'/') === 0) {
283 291
                    if (file_exists(__DIR__.'/../../app/template/admin')) {
284 291
                        $paths[] = __DIR__.'/../../app/template/admin';
285 291
                    }
286 291
                    $paths[] = $app['config']['template_admin_realdir'];
287 291
                    $paths[] = __DIR__.'/../../app/Plugin';
288 291
                    $cache = $cacheBaseDir.'admin';
289 291
                    $app['admin'] = true;
290 291
                } else {
291 169
                    if (file_exists($app['config']['template_realdir'])) {
292 169
                        $paths[] = $app['config']['template_realdir'];
293 169
                    }
294 169
                    $paths[] = $app['config']['template_default_realdir'];
295 169
                    $paths[] = __DIR__.'/../../app/Plugin';
296 169
                    $cache = $cacheBaseDir.$app['config']['template_code'];
297 169
                    $app['front'] = true;
298
                }
299 458
                $twig->setCache($cache);
300 458
                $app['twig.loader']->addLoader(new \Twig_Loader_Filesystem($paths));
301
302 458
                return $twig;
303 460
            }));
304
305
            // 管理画面のIP制限チェック.
306 460
            $pathinfo = rawurldecode($app['request']->getPathInfo());
307 460
            if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/').'/') === 0) {
308
                // IP制限チェック
309 291
                $allowHost = $app['config']['admin_allow_host'];
310 291
                if (count($allowHost) > 0) {
311
                    if (array_search($app['request']->getClientIp(), $allowHost) === false) {
312
                        throw new \Exception();
313 1051
                    }
314
                }
315 291
            }
316 1051
        }, self::EARLY_EVENT);
317
318
        // twigのグローバル変数を定義.
319 1051
        $app = $this;
320
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function (\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {
321
            // 未ログイン時にマイページや管理画面以下にアクセスするとSubRequestで実行されるため,
322
            // $event->isMasterRequest()ではなく、グローバル変数が初期化済かどうかの判定を行う
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
323 458
            if (isset($app['twig_global_initialized']) && $app['twig_global_initialized'] === true) {
324 113
                return;
325
            }
326
            // ショップ基本情報
327 458
            $BaseInfo = $app['eccube.repository.base_info']->get();
328 458
            $app['twig']->addGlobal('BaseInfo', $BaseInfo);
329
330 458
            $pathinfo = rawurldecode($app['request']->getPathInfo());
331 458
            if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/').'/') === 0) {
332
                // 管理画面
333
                // 管理画面メニュー
334 291
                $menus = array('', '', '');
335 291
                $app['twig']->addGlobal('menus', $menus);
336
337 291
                $Member = $app->user();
338 291
                if (is_object($Member)) {
339
                    // ログインしていれば管理者のロールを取得
340 285
                    $AuthorityRoles = $app['eccube.repository.authority_role']->findBy(array('Authority' => $Member->getAuthority()));
341
342 285
                    $roles = array();
343 285
                    foreach ($AuthorityRoles as $AuthorityRole) {
344
                        // 管理画面でメニュー制御するため相対パス全てをセット
345 3
                        $roles[] = $app['request']->getBaseUrl().'/'.$app['config']['admin_route'].$AuthorityRole->getDenyUrl();
346 285
                    }
347
348 285
                    $app['twig']->addGlobal('AuthorityRoles', $roles);
349 285
                }
350
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
351 291
            } else {
352
                // フロント画面
353 167
                $request = $event->getRequest();
354 167
                $route = $request->attributes->get('_route');
355
356
                // ユーザ作成画面
357 167
                if ($route === 'user_data') {
358 2
                    $params = $request->attributes->get('_route_params');
359 2
                    $route = $params['route'];
360
                    // プレビュー画面
361 167
                } elseif ($request->get('preview')) {
362
                    $route = 'preview';
363
                }
364
365
                try {
366 167
                    $DeviceType = $app['eccube.repository.master.device_type']
367 167
                        ->find(\Eccube\Entity\Master\DeviceType::DEVICE_TYPE_PC);
368 167
                    $PageLayout = $app['eccube.repository.page_layout']->getByUrl($DeviceType, $route);
369 167
                } catch (\Doctrine\ORM\NoResultException $e) {
370 65
                    $PageLayout = $app['eccube.repository.page_layout']->newPageLayout($DeviceType);
371 1
                }
372
373 167
                $app['twig']->addGlobal('PageLayout', $PageLayout);
374 167
                $app['twig']->addGlobal('title', $PageLayout->getName());
375
            }
376
377 458
            $app['twig_global_initialized'] = true;
378 1051
        });
379 1051
    }
380
381 1051
    public function initMailer()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
382
    {
383
384
        // メール送信時の文字エンコード指定(デフォルトはUTF-8)
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
385 1051
        if (isset($this['config']['mail']['charset_iso_2022_jp']) && is_bool($this['config']['mail']['charset_iso_2022_jp'])) {
386 1051
            if ($this['config']['mail']['charset_iso_2022_jp'] === true) {
387
                \Swift::init(function () {
388
                    \Swift_DependencyContainer::getInstance()
389
                        ->register('mime.qpheaderencoder')
390
                        ->asAliasOf('mime.base64headerencoder');
391
                    \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
392
                });
393
            }
394 1051
        }
395
396 1051
        $this->register(new \Silex\Provider\SwiftmailerServiceProvider());
397 1051
        $this['swiftmailer.options'] = $this['config']['mail'];
398
399 1051
        if (isset($this['config']['mail']['spool']) && is_bool($this['config']['mail']['spool'])) {
400
            $this['swiftmailer.use_spool'] = $this['config']['mail']['spool'];
401
        }
402
        // デフォルトはsmtpを使用
403 1051
        $transport = $this['config']['mail']['transport'];
404 1051
        if ($transport == 'sendmail') {
405
            $this['swiftmailer.transport'] = \Swift_SendmailTransport::newInstance();
406 1051
        } elseif ($transport == 'mail') {
407
            $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance();
408
        }
409 1051
    }
410
411 1051
    public function initDoctrine()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
412
    {
413 1051
        $this->register(new \Silex\Provider\DoctrineServiceProvider(), array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
414
            'dbs.options' => array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
415 1051
                'default' => $this['config']['database']
416 1051
            )));
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 8 spaces, but found 12.
Loading history...
417 1051
        $this->register(new \Saxulum\DoctrineOrmManagerRegistry\Silex\Provider\DoctrineOrmManagerRegistryProvider());
418
419
        // プラグインのmetadata定義を合わせて行う.
420 1051
        $pluginBasePath = __DIR__.'/../../app/Plugin';
421 1051
        $finder = Finder::create()
422 1051
            ->in($pluginBasePath)
423 1051
            ->directories()
424 1051
            ->depth(0);
425
426 1051
        $ormMappings = array();
427 1051
        $ormMappings[] = array(
428 1051
            'type' => 'yml',
429 1051
            'namespace' => 'Eccube\Entity',
430
            'path' => array(
431 1051
                __DIR__.'/Resource/doctrine',
432 1051
                __DIR__.'/Resource/doctrine/master',
433 1051
            ),
434
        );
435
436 1051
        foreach ($finder as $dir) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
437
438 139
            $file = $dir->getRealPath().'/config.yml';
439
440 139
            if (file_exists($file)) {
441 139
                $config = Yaml::parse(file_get_contents($file));
442 139
            } else {
443
                $code = $dir->getBaseName();
444
                $this['monolog']->warning("skip {$code} orm.path loading. config.yml not found.", array('path' => $file));
445
                continue;
446
            }
447
448
            // Doctrine Extend
449 139
            if (isset($config['orm.path']) && is_array($config['orm.path'])) {
450
                $paths = array();
451
                foreach ($config['orm.path'] as $path) {
452
                    $paths[] = $pluginBasePath.'/'.$config['code'].$path;
453
                }
454
                $ormMappings[] = array(
455
                    'type' => 'yml',
456
                    'namespace' => 'Plugin\\'.$config['code'].'\\Entity',
457
                    'path' => $paths,
458
                );
459
            }
460 1051
        }
461
462
        $options = array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
463
            'mappings' => $ormMappings
464 1051
        );
465
466 1051
        if (!$this['debug']) {
467 4
            $cacheDrivers = array();
468 4
            if (array_key_exists('doctrine_cache', $this['config'])) {
469 4
                $cacheDrivers = $this['config']['doctrine_cache'];
470 4
            }
471
472 4
            if (array_key_exists('metadata_cache', $cacheDrivers)) {
473 4
                $options['metadata_cache'] = $cacheDrivers['metadata_cache'];
474 4
            }
475 4
            if (array_key_exists('query_cache', $cacheDrivers)) {
476 4
                $options['query_cache'] = $cacheDrivers['query_cache'];
477 4
            }
478 4
            if (array_key_exists('result_cache', $cacheDrivers)) {
479 4
                $options['result_cache'] = $cacheDrivers['result_cache'];
480 4
            }
481 4
            if (array_key_exists('hydration_cache', $cacheDrivers)) {
482 4
                $options['hydration_cache'] = $cacheDrivers['hydration_cache'];
483 4
            }
484 4
        }
485
486 1051
        $this->register(new \Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
487 1051
            'orm.proxies_dir' => __DIR__.'/../../app/cache/doctrine/proxies',
488 1051
            'orm.em.options' => $options,
489
            'orm.custom.functions.numeric' => array(
490 1051
                'EXTRACT' => 'Eccube\Doctrine\ORM\Query\Extract',
491 1051
            ),
492 1051
        ));
493
494
        /**
495
         * YamlDriverのPHP7対応. Doctrine2.4で修正されれば不要.
496
         * @see https://github.com/EC-CUBE/ec-cube/issues/1338
497
         */
498 1051
        $config = $this['orm.em']->getConfiguration();
499
        /** @var $driver \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain */
500 1051
        $chain = $config->getMetadataDriverImpl();
501
        // $ormMappingsの1要素ごとにDriverが生成されている.
502 1051
        $drivers = $chain->getDrivers();
503 1051
        foreach ($drivers as $namespace => $oldDriver) {
504
            /** @var $newDriver \Eccube\Doctrine\ORM\Mapping\Driver\YamlDriver */
505 1051
            $newDriver = new YamlDriver($oldDriver->getLocator());
506
            // 修正したDriverに差し替える. メソッド名はaddだけど実際はsetしてる.
507 1051
            $chain->addDriver($newDriver, $namespace);
508 1051
        }
509 1051
    }
510
511 1051
    public function initSecurity()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
512
    {
513 1051
        $this->register(new \Silex\Provider\SecurityServiceProvider());
514 1051
        $this->register(new \Silex\Provider\RememberMeServiceProvider());
515
516 1051
        $this['security.firewalls'] = array(
517
            'admin' => array(
518 1051
                'pattern' => "^/{$this['config']['admin_route']}/",
519
                'form' => array(
520 1051
                    'login_path' => "/{$this['config']['admin_route']}/login",
521 1051
                    'check_path' => "/{$this['config']['admin_route']}/login_check",
522 1051
                    'username_parameter' => 'login_id',
523 1051
                    'password_parameter' => 'password',
524 1051
                    'with_csrf' => true,
525 1051
                    'use_forward' => true,
526 1051
                ),
527
                'logout' => array(
528 1051
                    'logout_path' => "/{$this['config']['admin_route']}/logout",
529 1051
                    'target_url' => "/{$this['config']['admin_route']}/",
530 1051
                ),
531 1051
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Member'),
532 1051
                'anonymous' => true,
533 1051
            ),
534
            'customer' => array(
535 1051
                'pattern' => '^/',
536
                'form' => array(
537 1051
                    'login_path' => '/mypage/login',
538 1051
                    'check_path' => '/login_check',
539 1051
                    'username_parameter' => 'login_email',
540 1051
                    'password_parameter' => 'login_pass',
541 1051
                    'with_csrf' => true,
542 1051
                    'use_forward' => true,
543 1051
                ),
544
                'logout' => array(
545 1051
                    'logout_path' => '/logout',
546 1051
                    'target_url' => '/',
547 1051
                ),
548
                'remember_me' => array(
549 1051
                    'key' => sha1($this['config']['auth_magic']),
550 1051
                    'name' => 'eccube_rememberme',
551
                    // lifetimeはデフォルトの1年間にする
552
                    // '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...
553 1051
                    'path' => $this['config']['root_urlpath'] ?: '/',
554 1051
                    'secure' => $this['config']['force_ssl'],
555 1051
                    'httponly' => true,
556 1051
                    'always_remember_me' => false,
557 1051
                    'remember_me_parameter' => 'login_memory',
558 1051
                ),
559 1051
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Customer'),
560 1051
                'anonymous' => true,
561 1051
            ),
562
        );
563
564 1051
        $this['security.access_rules'] = array(
565 1051
            array("^/{$this['config']['admin_route']}/login", 'IS_AUTHENTICATED_ANONYMOUSLY'),
566 1051
            array("^/{$this['config']['admin_route']}/", 'ROLE_ADMIN'),
567 1051
            array('^/mypage/login', 'IS_AUTHENTICATED_ANONYMOUSLY'),
568 1051
            array('^/mypage/withdraw_complete', 'IS_AUTHENTICATED_ANONYMOUSLY'),
569 1051
            array('^/mypage/change', 'IS_AUTHENTICATED_FULLY'),
570 1051
            array('^/mypage', 'ROLE_USER'),
571
        );
572
573
        $this['eccube.password_encoder'] = $this->share(function ($app) {
574 1051
            return new \Eccube\Security\Core\Encoder\PasswordEncoder($app['config']);
575 1051
        });
576
        $this['security.encoder_factory'] = $this->share(function ($app) {
577 1051
            return new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array(
578 1051
                'Eccube\Entity\Customer' => $app['eccube.password_encoder'],
579 1051
                'Eccube\Entity\Member' => $app['eccube.password_encoder'],
580 1051
            ));
581 1051
        });
582
        $this['eccube.event_listner.security'] = $this->share(function ($app) {
583 1051
            return new \Eccube\EventListener\SecurityEventListener($app['orm.em']);
584 1051
        });
585
        $this['user'] = function ($app) {
586 362
            $token = $app['security']->getToken();
587
588 362
            return ($token !== null) ? $token->getUser() : null;
589
        };
590
591
        // ログイン時のイベントを設定.
592 1051
        $this['dispatcher']->addListener(\Symfony\Component\Security\Http\SecurityEvents::INTERACTIVE_LOGIN, array($this['eccube.event_listner.security'], 'onInteractiveLogin'));
593
594
        // Voterの設定
595 1051
        $app = $this;
596
        $this['authority_voter'] = $this->share(function ($app) {
597 1051
            return new \Eccube\Security\Voter\AuthorityVoter($app);
598 1051
        });
599
600
        $app['security.voters'] = $app->extend('security.voters', function ($voters) use ($app) {
601 1051
            $voters[] = $app['authority_voter'];
602
603 1051
            return $voters;
604 1051
        });
605
606
        $this['security.access_manager'] = $this->share(function ($app) {
607 1051
            return new \Symfony\Component\Security\Core\Authorization\AccessDecisionManager($app['security.voters'], 'unanimous');
608 1051
        });
609
610 1051
    }
611
612 1051
    public function initializePlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
613
    {
614 1051
        if ($this->initializedPlugin) {
615
            return;
616
        }
617
618
        // setup event dispatcher
619 1051
        $this->initPluginEventDispatcher();
620
621
        // load plugin
622 1051
        $this->loadPlugin();
623
624 1051
        $this->initializedPlugin = true;
625 1051
    }
626
627 1051
    public function initPluginEventDispatcher()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
628
    {
629
        // EventDispatcher
630
        $this['eccube.event.dispatcher'] = $this->share(function () {
631 474
            return new EventDispatcher();
632 1051
        });
633
634 1051
        $app = $this;
635
636
        // hook point
637
        $this->on(KernelEvents::REQUEST, function (GetResponseEvent $event) use ($app) {
638 460
            if (!$event->isMasterRequest()) {
639 72
                return;
640
            }
641 460
            $hookpoint = 'eccube.event.app.before';
642 460
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
643 1051
        }, self::EARLY_EVENT);
644
645 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...
646 459
            if (!$event->isMasterRequest()) {
647 72
                return;
648
            }
649 457
            $route = $event->getRequest()->attributes->get('_route');
650 457
            $hookpoint = "eccube.event.controller.$route.before";
651 457
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
652 1051
        });
653
654 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...
655 447
            if (!$event->isMasterRequest()) {
656 72
                return;
657
            }
658 447
            $route = $event->getRequest()->attributes->get('_route');
659 447
            $hookpoint = "eccube.event.controller.$route.after";
660 447
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
661 1051
        });
662
663
        $this->on(KernelEvents::RESPONSE, function (FilterResponseEvent $event) use ($app) {
664 447
            if (!$event->isMasterRequest()) {
665 72
                return;
666
            }
667 447
            $hookpoint = 'eccube.event.app.after';
668 447
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
669 1051
        }, self::LATE_EVENT);
670
671
        $this->on(KernelEvents::TERMINATE, function (PostResponseEvent $event) use ($app) {
672 447
            $route = $event->getRequest()->attributes->get('_route');
673 447
            $hookpoint = "eccube.event.controller.$route.finish";
674 447
            $app['eccube.event.dispatcher']->dispatch($hookpoint, $event);
675 1051
        });
676
677
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function (\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
678 447
            if (!$event->isMasterRequest()) {
679 72
                return;
680
            }
681 447
            $route = $event->getRequest()->attributes->get('_route');
682 447
            $app['eccube.event.dispatcher']->dispatch('eccube.event.render.'.$route.'.before', $event);
683 1051
        });
684
685
        // Request Event
686 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...
687
688 459
            if (!$event->isMasterRequest()) {
689 72
                return;
690
            }
691
692 459
            $route = $event->getRequest()->attributes->get('_route');
693
694 459
            if (is_null($route)) {
695
                return;
696
            }
697
698 459
            $app['monolog']->debug('KernelEvents::REQUEST '.$route);
699
700
            // 全体
701 459
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.request', $event);
702
703 459
            if (strpos($route, 'admin') === 0) {
704
                // 管理画面
705 291
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.request', $event);
706 291
            } else {
707
                // フロント画面
708 170
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.request', $event);
709
            }
710
711
            // ルーティング単位
712 459
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.request", $event);
713
714 1051
        }, 30); // Routing(32)が解決しし, 認証判定(8)が実行される前のタイミング.
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
715
716
        // Controller Event
717 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...
718
719 458
            if (!$event->isMasterRequest()) {
720 72
                return;
721
            }
722
723 456
            $route = $event->getRequest()->attributes->get('_route');
724
725 456
            if (is_null($route)) {
726
                return;
727
            }
728
729 456
            $app['monolog']->debug('KernelEvents::CONTROLLER '.$route);
730
731
            // 全体
732 456
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.controller', $event);
733
734 456
            if (strpos($route, 'admin') === 0) {
735
                // 管理画面
736 289
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.controller', $event);
737 289
            } else {
738
                // フロント画面
739 169
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.controller', $event);
740
            }
741
742
            // ルーティング単位
743 456
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.controller", $event);
744 1051
        });
745
746
        // Response Event
747 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...
748 447
            if (!$event->isMasterRequest()) {
749 72
                return;
750
            }
751
752 447
            $route = $event->getRequest()->attributes->get('_route');
753
754 447
            if (is_null($route)) {
755 1
                return;
756
            }
757
758 446
            $app['monolog']->debug('KernelEvents::RESPONSE '.$route);
759
760
            // ルーティング単位
761 446
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.response", $event);
762
763 446
            if (strpos($route, 'admin') === 0) {
764
                // 管理画面
765 284
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.response', $event);
766 284
            } else {
767
                // フロント画面
768 164
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.response', $event);
769
            }
770
771
            // 全体
772 446
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.response', $event);
773 1051
        });
774
775
        // Exception Event
776 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...
777
778 19
            if (!$event->isMasterRequest()) {
779
                return;
780
            }
781
782 19
            $route = $event->getRequest()->attributes->get('_route');
783
784 19
            if (is_null($route)) {
785
                return;
786
            }
787
788 19
            $app['monolog']->debug('KernelEvents::EXCEPTION '.$route);
789
790
            // ルーティング単位
791 19
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.exception", $event);
792
793 19
            if (strpos($route, 'admin') === 0) {
794
                // 管理画面
795 9
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.exception', $event);
796 9
            } else {
797
                // フロント画面
798 10
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.exception', $event);
799
            }
800
801
            // 全体
802 19
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.exception', $event);
803 1051
        });
804
805
        // Terminate Event
806 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...
807
808 447
            $route = $event->getRequest()->attributes->get('_route');
809
810 447
            if (is_null($route)) {
811 1
                return;
812
            }
813
814 446
            $app['monolog']->debug('KernelEvents::TERMINATE '.$route);
815
816
            // ルーティング単位
817 446
            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.terminate", $event);
818
819 446
            if (strpos($route, 'admin') === 0) {
820
                // 管理画面
821 284
                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.terminate', $event);
822 284
            } else {
823
                // フロント画面
824 164
                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.terminate', $event);
825
            }
826
827
            // 全体
828 446
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.terminate', $event);
829 1051
        });
830 1051
    }
831
832 1051
    public function loadPlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
833
    {
834
        // プラグインディレクトリを探索.
835 1051
        $basePath = __DIR__.'/../../app/Plugin';
836 1051
        $finder = Finder::create()
837 1051
            ->in($basePath)
838 1051
            ->directories()
839 1051
            ->depth(0);
840
841 1051
        $finder->sortByName();
842
843
        // ハンドラ優先順位をdbから持ってきてハッシュテーブルを作成
844 1051
        $priorities = array();
845 1051
        $handlers = $this['orm.em']
846 1051
            ->getRepository('Eccube\Entity\PluginEventHandler')
847 1051
            ->getHandlers();
848 1051
        foreach ($handlers as $handler) {
849
            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...
850
851
                $priority = $handler->getPriority();
852
            } else {
853
                // Pluginがdisable、削除済みの場合、EventHandlerのPriorityを全て0とみなす
854
                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED;
855
            }
856
            $priorities[$handler->getPlugin()->getClassName()][$handler->getEvent()][$handler->getHandler()] = $priority;
857 1051
        }
858
859
        // プラグインをロードする.
860
        // config.yml/event.ymlの定義に沿ってインスタンスの生成を行い, イベント設定を行う.
861 1051
        foreach ($finder as $dir) {
862
            //config.ymlのないディレクトリは無視する
863 140
            $path = $dir->getRealPath();
864 140
            $code = $dir->getBaseName();
865
            try {
866 140
                $this['eccube.service.plugin']->checkPluginArchiveContent($path);
867 140
            } catch (\Eccube\Exception\PluginException $e) {
868
                $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...
869
                    'path' => $path,
870
                    'original-message' => $e->getMessage()
871
                ));
872
                continue;
873
            }
874 140
            $config = $this['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');
875
876 140
            $plugin = $this['orm.em']
877 140
                ->getRepository('Eccube\Entity\Plugin')
878 140
                ->findOneBy(array('code' => $config['code']));
879
880
            // const
881 140
            if (isset($config['const'])) {
882
                $this['config'] = $this->share($this->extend('config', function ($eccubeConfig) use ($config) {
883 1
                    $eccubeConfig[$config['code']] = array(
884 1
                        'const' => $config['const'],
885
                    );
886
887 1
                    return $eccubeConfig;
888 1
                }));
889 1
            }
890
891 140
            if ($plugin && $plugin->getEnable() == Constant::DISABLED) {
892
                // プラグインが無効化されていれば読み込まない
893 1
                continue;
894
            }
895
896
            // Type: Event
897 139
            if (isset($config['event'])) {
898 139
                $class = '\\Plugin\\'.$config['code'].'\\'.$config['event'];
899 139
                $eventExists = true;
900
901 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...
902
                    $this['monolog']->warning("skip {$code} loading. event class not foud.", array(
903
                        'class' => $class,
904
                    ));
905
                    $eventExists = false;
906
                }
907
908 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...
909
910 139
                    $subscriber = new $class($this);
911
912 139
                    foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {
913 139
                        foreach ($handlers as $handler) {
914 139
                            if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする
915 139
                                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;
916 139
                            } else {
917
                                $priority = $priorities[$config['event']][$event][$handler[0]];
918
                            }
919
                            // 優先度が0のプラグインは登録しない
920 139
                            if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {
921 139
                                $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);
922 139
                            }
923 139
                        }
924 139
                    }
925 139
                }
926 139
            }
927
            // Type: ServiceProvider
928 139
            if (isset($config['service'])) {
929
                foreach ($config['service'] as $service) {
930
                    $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;
931 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...
932
                        $this['monolog']->warning("skip {$code} loading. service provider class not foud.", array(
933
                            'class' => $class,
934
                        ));
935
                        continue;
936
                    }
937
                    $this->register(new $class($this));
938
                }
939
            }
940 1051
        }
941 1051
    }
942
943
    /**
944
     * PHPUnit を実行中かどうかを設定する.
945
     *
946
     * @param boolean $testMode PHPUnit を実行中の場合 true
947
     */
948 1037
    public function setTestMode($testMode)
949
    {
950 1037
        $this->testMode = $testMode;
951 1037
    }
952
953
    /**
954
     * PHPUnit を実行中かどうか.
955
     *
956
     * @return boolean PHPUnit を実行中の場合 true
957
     */
958 460
    public function isTestMode()
959
    {
960 460
        return $this->testMode;
961
    }
962
963
    /**
964
     *
965
     * データベースの接続を確認
966
     * 成功 : trueを返却
967
     * 失敗 : \Doctrine\DBAL\DBALExceptionエラーが発生( 接続に失敗した場合 )、エラー画面を表示しdie()
968
     * 備考 : app['debug']がtrueの際は処理を行わない
969
     *
970
     * @return boolean true
971
     *
972
     */
973 1051
    protected function checkDatabaseConnection()
974
    {
975 1051
        if ($this['debug']) {
976 1047
            return;
977
        }
978
        try {
979 4
            $this['db']->connect();
980 4
        } catch (\Doctrine\DBAL\DBALException $e) {
981
            $this['monolog']->error($e->getMessage());
982
            $this['twig.path'] = array(__DIR__.'/Resource/template/exception');
983
            $html = $this['twig']->render('error.twig', array(
984
                'error_title' => 'データーベース接続エラー',
985
                'error_message' => 'データーベースを確認してください',
986
            ));
987
            $response = new Response();
988
            $response->setContent($html);
989
            $response->setStatusCode('500');
990
            $response->headers->set('Content-Type', 'text/html');
991
            $response->send();
992
            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...
993
        }
994
995 4
        return true;
996
    }
997
998
    /**
999
     * Config ファイルをパースし、連想配列を返します.
1000
     *
1001
     * $config_name.yml ファイルをパースし、連想配列を返します.
1002
     * $config_name.php が存在する場合は、 PHP ファイルに記述された連想配列を使用します。
1003
     *
1004
     * @param string $config_name Config 名称
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
1005
     * @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...
1006
     * @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...
1007
     * @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...
1008
     * @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...
1009
     * @return Application
1010
     */
1011 1054
    public function parseConfig($config_name, array &$configAll, $wrap_key = false, $ymlPath = null, $distPath = null)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
1012
    {
1013 1054
        $ymlPath = $ymlPath ? $ymlPath : __DIR__.'/../../app/config/eccube';
1014 1054
        $distPath = $distPath ? $distPath : __DIR__.'/../../src/Eccube/Resource/config';
1015 1054
        $config = array();
1016 1054
        $config_php = $ymlPath.'/'.$config_name.'.php';
1017 1054
        if (!file_exists($config_php)) {
1018 1054
            $config_yml = $ymlPath.'/'.$config_name.'.yml';
1019 1054
            if (file_exists($config_yml)) {
1020 1054
                $config = Yaml::parse(file_get_contents($config_yml));
1021 1054
                $config = empty($config) ? array() : $config;
1022 1054 View Code Duplication
                if (isset($this['output_config_php']) && $this['output_config_php']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1023
                    file_put_contents($config_php, sprintf('<?php return %s', var_export($config, true)).';');
1024
                }
1025 1054
            }
1026 1054
        } else {
1027
            $config = require $config_php;
1028
        }
1029
1030 1054
        $config_dist = array();
1031 1054
        $config_php_dist = $distPath.'/'.$config_name.'.dist.php';
1032 1054
        if (!file_exists($config_php_dist)) {
1033 1054
            $config_yml_dist = $distPath.'/'.$config_name.'.yml.dist';
1034 1054
            if (file_exists($config_yml_dist)) {
1035 1054
                $config_dist = Yaml::parse(file_get_contents($config_yml_dist));
1036 1054 View Code Duplication
                if (isset($this['output_config_php']) && $this['output_config_php']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1037
                    file_put_contents($config_php_dist, sprintf('<?php return %s', var_export($config_dist, true)).';');
1038
                }
1039 1054
            }
1040 1054
        } else {
1041
            $config_dist = require $config_php_dist;
1042
        }
1043
1044 1054
        if ($wrap_key) {
1045 1054
            $configAll = array_replace_recursive($configAll, array($config_name => $config_dist), array($config_name => $config));
1046 1054
        } else {
1047 1054
            $configAll = array_replace_recursive($configAll, $config_dist, $config);
1048
        }
1049
1050 1054
        return $this;
1051
    }
1052
1053
    /**
1054
     * セッションが開始されているかどうか.
1055
     *
1056
     * @return boolean セッションが開始済みの場合 true
1057
     * @link http://php.net/manual/ja/function.session-status.php#113468
1058
     */
1059 1051
    protected function isSessionStarted()
1060
    {
1061 1051
        if (php_sapi_name() !== 'cli') {
1062
            if (version_compare(phpversion(), '5.4.0', '>=')) {
1063
                return session_status() === PHP_SESSION_ACTIVE ? true : false;
1064
            } else {
1065
                return session_id() === '' ? false : true;
1066
            }
1067
        }
1068
1069 1051
        return false;
1070
    }
1071
1072
    /**
1073
     * Http Cache対応
1074
     */
1075 1051
    protected function initCacheRequest()
1076
    {
1077
        // httpキャッシュが無効の場合はイベント設定を行わない.
1078 1051
        if (!$this['config']['http_cache']['enabled']) {
1079 1051
            return;
1080
        }
1081
1082
        $app = $this;
1083
1084
        // Response Event(http cache対応、event実行は一番遅く設定)
1085
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function (\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
1086
1087
            if (!$event->isMasterRequest()) {
1088
                return;
1089
            }
1090
1091
            $request = $event->getRequest();
1092
            $response = $event->getResponse();
1093
1094
            $route = $request->attributes->get('_route');
1095
1096
            $etag = md5($response->getContent());
1097
1098
            if (strpos($route, 'admin') === 0) {
1099
                // 管理画面
1100
1101
                // 管理画面ではコンテンツの中身が変更された時点でキャッシュを更新し、キャッシュの適用範囲はprivateに設定
1102
                $response->setCache(array(
1103
                    'etag' => $etag,
1104
                    'private' => true,
1105
                ));
1106
1107
                if ($response->isNotModified($request)) {
1108
                    return $response;
1109
                }
1110
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
1111
            } else {
1112
                // フロント画面
1113
                $cacheRoute = $app['config']['http_cache']['route'];
1114
1115
                if (in_array($route, $cacheRoute) === true) {
1116
                    // キャッシュ対象となる画面lが含まれていた場合、キャッシュ化
1117
                    // max-ageを設定しているためExpiresは不要
1118
                    // Last-Modifiedだと比較する項目がないためETagで対応
1119
                    // max-ageを設定していた場合、contentの中身が変更されても変更されない
1120
1121
                    $age = $app['config']['http_cache']['age'];
1122
1123
                    $response->setCache(array(
1124
                        'etag' => $etag,
1125
                        'max_age' => $age,
1126
                        's_maxage' => $age,
1127
                        'public' => true,
1128
                    ));
1129
1130
                    if ($response->isNotModified($request)) {
1131
                        return $response;
1132
                    }
1133
                }
1134
            }
1135
1136
        }, -1024);
1137
    }
1138
}
1139