Failed Conditions
Pull Request — master (#1861)
by k-yamamura
474:27 queued 464:07
created

Application::isTestMode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

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

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

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