Completed
Push — master ( 46f2fd...b9ab61 )
by Ryo
448:52 queued 432:08
created

Application::isSessionStarted()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5.9256

Importance

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