Completed
Pull Request — master (#1771)
by Ryo
234:13 queued 227:08
created

Application::__clone()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.037

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 3
cp 0.6667
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1.037
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 969
    public static function getInstance(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
49
    {
50 969
        if (!is_object(self::$instance)) {
51 968
            self::$instance = new Application($values);
52 968
        }
53
54 969
        return self::$instance;
55
    }
56
57 969
    public static function clearInstance()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
58
    {
59 969
        self::$instance = null;
60 969
    }
61
62 1
    final public function __clone()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
63 1
    {
64
        throw new \Exception('Clone is not allowed against '.get_class($this));
65
    }
66
67 983
    public function __construct(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
68 983
    {
69 983
        parent::__construct($values);
70
71 983
        if (is_null(self::$instance)) {
72 969
            self::$instance = $this;
73 969
        }
74
75
        // load config
76 983
        $this->initConfig();
77
78
        // init monolog
79 983
        $this->initLogger();
80 983
    }
81
82 984
    public function initConfig()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
83 983
    {
84
        // load config
85 983
        $app = $this;
86
        $this['config'] = $this->share(function() use ($app) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
87 984
            $configAll = array();
88 976
            $app->parseConfig('constant', $configAll)
89 976
                ->parseConfig('path', $configAll)
90 976
                ->parseConfig('config', $configAll)
91 984
                ->parseConfig('database', $configAll)
92 984
                ->parseConfig('mail', $configAll)
93 976
                ->parseConfig('log', $configAll)
94 976
                ->parseConfig('nav', $configAll, true)
95 976
                ->parseConfig('doctrine_cache', $configAll)
96 976
                ->parseConfig('http_cache', $configAll)
97 976
                ->parseConfig('session_handler', $configAll);
98
99 976
            return $configAll;
100 983
        });
101 983
    }
102
103 983
    public function initLogger()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
104
    {
105 983
        $app = $this;
106 983
        $this->register(new ServiceProvider\EccubeMonologServiceProvider($app));
0 ignored issues
show
Unused Code introduced by
The call to EccubeMonologServiceProvider::__construct() has too many arguments starting with $app.

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

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

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

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

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

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

Loading history...
891
                    $this['monolog']->warning("skip {$code} loading. event class not foud.", array(
892
                        'class' => $class,
893
                    ));
894
                    $eventExists = false;
895
                }
896
897 139
                if ($eventExists && file_exists($dir->getRealPath().'/event.yml')) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
898
899 139
                    $subscriber = new $class($this);
900
901 139
                    foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {
902 139
                        foreach ($handlers as $handler) {
903 139
                            if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする
904 139
                                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;
905 139
                            } else {
906
                                $priority = $priorities[$config['event']][$event][$handler[0]];
907
                            }
908
                            // 優先度が0のプラグインは登録しない
909 139
                            if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {
910 139
                                $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);
911 139
                            }
912 139
                        }
913 139
                    }
914 139
                }
915 139
            }
916
            // Type: ServiceProvider
917 139
            if (isset($config['service'])) {
918
                foreach ($config['service'] as $service) {
919
                    $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;
920 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...
921
                        $this['monolog']->warning("skip {$code} loading. service provider class not foud.", array(
922
                            'class' => $class,
923
                        ));
924
                        continue;
925
                    }
926
                    $this->register(new $class($this));
927
                }
928
            }
929 973
        }
930 973
    }
931
932
    /**
933
     * PHPUnit を実行中かどうかを設定する.
934
     *
935
     * @param boolean $testMode PHPUnit を実行中の場合 true
936
     */
937 959
    public function setTestMode($testMode)
938
    {
939 959
        $this->testMode = $testMode;
940 959
    }
941
942
    /**
943
     * PHPUnit を実行中かどうか.
944
     *
945
     * @return boolean PHPUnit を実行中の場合 true
946
     */
947 385
    public function isTestMode()
948
    {
949 385
        return $this->testMode;
950
    }
951
952
    /**
953
     *
954
     * データベースの接続を確認
955
     * 成功 : trueを返却
956
     * 失敗 : \Doctrine\DBAL\DBALExceptionエラーが発生( 接続に失敗した場合 )、エラー画面を表示しdie()
957
     * 備考 : app['debug']がtrueの際は処理を行わない
958
     *
959
     * @return boolean true
960
     *
961
     */
962 973
    protected function checkDatabaseConnection()
963
    {
964 973
        if ($this['debug']) {
965 969
            return;
966
        }
967
        try {
968 4
            $this['db']->connect();
969 4
        } catch (\Doctrine\DBAL\DBALException $e) {
970
            $this['monolog']->error($e->getMessage());
971
            $this['twig.path'] = array(__DIR__.'/Resource/template/exception');
972
            $html = $this['twig']->render('error.twig', array(
973
                'error_title' => 'データーベース接続エラー',
974
                'error_message' => 'データーベースを確認してください',
975
            ));
976
            $response = new Response();
977
            $response->setContent($html);
978
            $response->setStatusCode('500');
979
            $response->headers->set('Content-Type', 'text/html');
980
            $response->send();
981
            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...
982
        }
983
984 4
        return true;
985
    }
986
987
    /**
988
     * Config ファイルをパースし、連想配列を返します.
989
     *
990
     * $config_name.yml ファイルをパースし、連想配列を返します.
991
     * $config_name.php が存在する場合は、 PHP ファイルに記述された連想配列を使用します。
992
     *
993
     * @param string $config_name Config 名称
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
994
     * @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...
995
     * @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...
996
     * @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...
997
     * @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...
998
     * @return Application
999
     */
1000 976
    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...
1001
    {
1002 976
        $ymlPath = $ymlPath ? $ymlPath : __DIR__.'/../../app/config/eccube';
1003 976
        $distPath = $distPath ? $distPath : __DIR__.'/../../src/Eccube/Resource/config';
1004 976
        $config = array();
1005 976
        $config_php = $ymlPath.'/'.$config_name.'.php';
1006 976
        if (!file_exists($config_php)) {
1007 976
            $config_yml = $ymlPath.'/'.$config_name.'.yml';
1008 976
            if (file_exists($config_yml)) {
1009 976
                $config = Yaml::parse(file_get_contents($config_yml));
1010 976
                $config = empty($config) ? array() : $config;
1011 976 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...
1012
                    file_put_contents($config_php, sprintf('<?php return %s', var_export($config, true)).';');
1013
                }
1014 976
            }
1015 976
        } else {
1016
            $config = require $config_php;
1017
        }
1018
1019 976
        $config_dist = array();
1020 976
        $config_php_dist = $distPath.'/'.$config_name.'.dist.php';
1021 976
        if (!file_exists($config_php_dist)) {
1022 976
            $config_yml_dist = $distPath.'/'.$config_name.'.yml.dist';
1023 976
            if (file_exists($config_yml_dist)) {
1024 976
                $config_dist = Yaml::parse(file_get_contents($config_yml_dist));
1025 976 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...
1026
                    file_put_contents($config_php_dist, sprintf('<?php return %s', var_export($config_dist, true)).';');
1027
                }
1028 976
            }
1029 976
        } else {
1030
            $config_dist = require $config_php_dist;
1031
        }
1032
1033 976
        if ($wrap_key) {
1034 976
            $configAll = array_replace_recursive($configAll, array($config_name => $config_dist), array($config_name => $config));
1035 976
        } else {
1036 976
            $configAll = array_replace_recursive($configAll, $config_dist, $config);
1037
        }
1038
1039 976
        return $this;
1040
    }
1041
1042
    /**
1043
     * セッションが開始されているかどうか.
1044
     *
1045
     * @return boolean セッションが開始済みの場合 true
1046
     * @link http://php.net/manual/ja/function.session-status.php#113468
1047
     */
1048 973
    protected function isSessionStarted()
1049
    {
1050 973
        if (php_sapi_name() !== 'cli') {
1051
            if (version_compare(phpversion(), '5.4.0', '>=')) {
1052
                return session_status() === PHP_SESSION_ACTIVE ? true : false;
1053
            } else {
1054
                return session_id() === '' ? false : true;
1055
            }
1056
        }
1057
1058 973
        return false;
1059
    }
1060
1061
    /**
1062
     * Http Cache対応
1063
     */
1064 973
    protected function initCacheRequest()
1065
    {
1066
        // httpキャッシュが無効の場合はイベント設定を行わない.
1067 973
        if (!$this['config']['http_cache']['enabled']) {
1068 973
            return;
1069
        }
1070
1071
        $app = $this;
1072
1073
        // Response Event(http cache対応、event実行は一番遅く設定)
1074
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function (\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
1075
1076
            $request = $event->getRequest();
1077
            $response = $event->getResponse();
1078
1079
            $route = $request->attributes->get('_route');
1080
1081
            $etag = md5($response->getContent());
1082
1083
            if (strpos($route, 'admin') === 0) {
1084
                // 管理画面
1085
1086
                // 管理画面ではコンテンツの中身が変更された時点でキャッシュを更新し、キャッシュの適用範囲はprivateに設定
1087
                $response->setCache(array(
1088
                    'etag' => $etag,
1089
                    'private' => true,
1090
                ));
1091
1092
                if ($response->isNotModified($request)) {
1093
                    return $response;
1094
                }
1095
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
1096
            } else {
1097
                // フロント画面
1098
                $cacheRoute = $app['config']['http_cache']['route'];
1099
1100
                if (in_array($route, $cacheRoute) === true) {
1101
                    // キャッシュ対象となる画面lが含まれていた場合、キャッシュ化
1102
                    // max-ageを設定しているためExpiresは不要
1103
                    // Last-Modifiedだと比較する項目がないためETagで対応
1104
                    // max-ageを設定していた場合、contentの中身が変更されても変更されない
1105
1106
                    $age = $app['config']['http_cache']['age'];
1107
1108
                    $response->setCache(array(
1109
                        'etag' => $etag,
1110
                        'max_age' => $age,
1111
                        's_maxage' => $age,
1112
                        'public' => true,
1113
                    ));
1114
1115
                    if ($response->isNotModified($request)) {
1116
                        return $response;
1117
                    }
1118
                }
1119
            }
1120
1121
        }, -1024);
1122
    }
1123
}
1124