Completed
Push — master ( 0fe6f9...d3b3ff )
by Ryo
24s
created

Application::initCacheRequest()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 59
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 59
ccs 0
cts 0
cp 0
rs 8.7117
cc 6
eloc 27
nc 2
nop 0
crap 42

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

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