Failed Conditions
Push — master ( 89ac09...9d16ae )
by chihiro
24:27
created

Application::parseConfig()   D

Complexity

Conditions 13
Paths 192

Size

Total Lines 41
Code Lines 29

Duplication

Lines 6
Ratio 14.63 %

Code Coverage

Tests 8
CRAP Score 38.0748

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 6
loc 41
ccs 8
cts 17
cp 0.4706
rs 4.8178
cc 13
eloc 29
nc 192
nop 5
crap 38.0748

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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