Failed Conditions
Pull Request — master (#1378)
by Kentaro
19:17
created

Application::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
ccs 3
cts 3
cp 1
rs 9.4286
cc 2
eloc 4
nc 2
nop 1
crap 2
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 Symfony\Component\EventDispatcher\EventDispatcher;
29
use Symfony\Component\Finder\Finder;
30
use Symfony\Component\HttpFoundation\Request;
31
use Symfony\Component\HttpFoundation\Response;
32
use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
33
use Symfony\Component\Yaml\Yaml;
34
35
class Application extends ApplicationTrait
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
36
{
37
    protected static $instance;
38
39
    protected $initialized = false;
40
41 697
    public static function getInstance(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
42
    {
43
        if (!is_object(self::$instance)) {
44
            self::$instance = new Application($values);
45
        }
46
47 697
        return self::$instance;
48 697
    }
49
50 697
    public static function clearInstance()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
51
    {
52 697
        self::$instance = null;
53 697
    }
54
55
    final public function __clone()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
56
    {
57
        throw new \Exception('Clone is not allowed against' . get_class($this));
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
58
    }
59
60 697
    public function __construct(array $values = array())
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
61
    {
62
        parent::__construct($values);
63
64
        if (is_null(self::$instance)) {
65 697
            self::$instance = $this;
66
        }
67
68
        // load config
69
        $this->initConfig();
70
71
        // init monolog
72
        $this->initLogger();
73
    }
74
75 711
    public function initConfig()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
76
    {
77
        // load config
78
        $this['config'] = $this->share(function() {
79 700
            $ymlPath = __DIR__.'/../../app/config/eccube';
80 700
            $distPath = __DIR__.'/../../src/Eccube/Resource/config';
81
82 700
            $config = array();
83 700
            $config_yml = $ymlPath.'/config.yml';
84
            if (file_exists($config_yml)) {
85
                $config = Yaml::parse(file_get_contents($config_yml));
86
            }
87
88 700
            $config_dist = array();
89 700
            $config_yml_dist = $distPath.'/config.yml.dist';
90
            if (file_exists($config_yml_dist)) {
91
                $config_dist = Yaml::parse(file_get_contents($config_yml_dist));
92
            }
93
94 700
            $config_path = array();
95 700
            $path_yml = $ymlPath.'/path.yml';
96
            if (file_exists($path_yml)) {
97
                $config_path = Yaml::parse(file_get_contents($path_yml));
98
            }
99
100 700
            $config_constant = array();
101 700
            $constant_yml = $ymlPath.'/constant.yml';
102
            if (file_exists($constant_yml)) {
103
                $config_constant = Yaml::parse(file_get_contents($constant_yml));
104
                $config_constant = empty($config_constant) ? array() : $config_constant;
105
            }
106
107 700
            $config_constant_dist = array();
108 700
            $constant_yml_dist = $distPath.'/constant.yml.dist';
109
            if (file_exists($constant_yml_dist)) {
110
                $config_constant_dist = Yaml::parse(file_get_contents($constant_yml_dist));
111
            }
112
113
            $configAll = array_replace_recursive($config_constant_dist, $config_dist, $config_constant, $config_path, $config);
114
115 700
            $database = array();
116 700
            $yml = $ymlPath.'/database.yml';
117
            if (file_exists($yml)) {
118
                $database = Yaml::parse(file_get_contents($yml));
119
            }
120
121 700
            $mail = array();
122 700
            $yml = $ymlPath.'/mail.yml';
123
            if (file_exists($yml)) {
124
                $mail = Yaml::parse(file_get_contents($yml));
125
            }
126
            $configAll = array_replace_recursive($configAll, $database, $mail);
127
128 700
            $config_log = array();
129 700
            $yml = $ymlPath.'/log.yml';
130
            if (file_exists($yml)) {
131
                $config_log = Yaml::parse(file_get_contents($yml));
132
            }
133 700
            $config_log_dist = array();
134 700
            $log_yml_dist = $distPath.'/log.yml.dist';
135
            if (file_exists($log_yml_dist)) {
136
                $config_log_dist = Yaml::parse(file_get_contents($log_yml_dist));
137
            }
138
139
            $configAll = array_replace_recursive($configAll, $config_log_dist, $config_log);
140
141 700
            $config_nav = array();
142 700
            $yml = $ymlPath.'/nav.yml';
143
            if (file_exists($yml)) {
144
                $config_nav = array('nav' => Yaml::parse(file_get_contents($yml)));
145
            }
146 700
            $config_nav_dist = array();
147 700
            $nav_yml_dist = $distPath.'/nav.yml.dist';
148
            if (file_exists($nav_yml_dist)) {
149
                $config_nav_dist = array('nav' => Yaml::parse(file_get_contents($nav_yml_dist)));
150
            }
151
152
            $configAll = array_replace_recursive($configAll, $config_nav_dist, $config_nav);
153
154 700
            return $configAll;
155
        });
156 711
    }
157
158 711
    public function initLogger()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
159
    {
160 711
        $app = $this;
161
        $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...
162
        $this['monolog.logfile'] = __DIR__.'/../../app/log/site.log';
163
        $this['monolog.name'] = 'eccube';
164 711
    }
165
166 697
    public function initialize()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
167
    {
168 697
        if ($this->initialized) {
169
            return;
170
        }
171
172
        // init locale
173
        $this->initLocale();
174
175
        // init session
176
        $this->initSession();
177
178
        // init twig
179
        $this->initRendering();
180
181
        // init provider
182
        $this->register(new \Silex\Provider\HttpFragmentServiceProvider());
183
        $this->register(new \Silex\Provider\UrlGeneratorServiceProvider());
184
        $this->register(new \Silex\Provider\FormServiceProvider());
185
        $this->register(new \Silex\Provider\SerializerServiceProvider());
186
        $this->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
187
188 697
        $app = $this;
189
        $this->error(function(\Exception $e, $code) use ($app) {
190
            if ($app['debug']) {
191 5
                return;
192
            }
193
194
            switch ($code) {
195
                case 403:
196
                    $title = 'アクセスできません。';
197
                    $message = 'お探しのページはアクセスができない状況にあるか、移動もしくは削除された可能性があります。';
198
                    break;
199
                case 404:
200
                    $title = 'ページがみつかりません。';
201
                    $message = 'URLに間違いがないかご確認ください。';
202
                    break;
203
                default:
204
                    $title = 'システムエラーが発生しました。';
205
                    $message = '大変お手数ですが、サイト管理者までご連絡ください。';
206
                    break;
207
            }
208
209
            return $app['twig']->render('error.twig', array(
210
                'error_title' => $title,
211
                'error_message' => $message,
212
            ));
213
        });
214
215
        // init mailer
216
        $this->initMailer();
217
218
        // init doctrine orm
219
        $this->initDoctrine();
220
221
        // init security
222
        $this->initSecurity();
223
224
        // init ec-cube service provider
225
        $this->register(new ServiceProvider\EccubeServiceProvider());
226
227
        // mount controllers
228
        $this->register(new \Silex\Provider\ServiceControllerServiceProvider());
229
        $this->mount('', new ControllerProvider\FrontControllerProvider());
230
        $this->mount('/'.trim($this['config']['admin_route'], '/').'/', new ControllerProvider\AdminControllerProvider());
231
        Request::enableHttpMethodParameterOverride(); // PUTやDELETEできるようにする
232
233 697
        $this->initialized = true;
234 697
    }
235
236 697
    public function initLocale()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
237
    {
238
239
        // timezone
240
        if (!empty($this['config']['timezone'])) {
241
            date_default_timezone_set($this['config']['timezone']);
242
        }
243
244
        $this->register(new \Silex\Provider\TranslationServiceProvider(), array(
245 697
            'locale' => $this['config']['locale'],
246
        ));
247
        $this['translator'] = $this->share($this->extend('translator', function($translator, \Silex\Application $app) {
248
            $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());
249
250
            $r = new \ReflectionClass('Symfony\Component\Validator\Validator');
251
            $file = dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf';
252
            if (file_exists($file)) {
253
                $translator->addResource('xliff', $file, $app['locale'], 'validators');
254
            }
255
256
            $file = __DIR__.'/Resource/locale/validator.'.$app['locale'].'.yml';
257
            if (file_exists($file)) {
258
                $translator->addResource('yaml', $file, $app['locale'], 'validators');
259
            }
260
261
            $file = __DIR__.'/Resource/locale/message.'.$app['locale'].'.yml';
262
            if (file_exists($file)) {
263
                $translator->addResource('yaml', $file, $app['locale']);
264
            }
265
266 372
            return $translator;
267
        }));
268 697
    }
269
270 697
    public function initSession()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
271
    {
272
        $this->register(new \Silex\Provider\SessionServiceProvider(), array(
273
            'session.storage.options' => array(
274 697
                'name' => 'eccube',
275
                'cookie_path' => $this['config']['root_urlpath'] ?: '/',
276 697
                'cookie_secure' => $this['config']['force_ssl'],
277 697
                'cookie_lifetime' => $this['config']['cookie_lifetime'],
278 697
                'cookie_httponly' => true,
279
                // cookie_domainは指定しない
280
                // http://blog.tokumaru.org/2011/10/cookiedomain.html
281 697
            ),
282
        ));
283 697
        $this['session.db_options'] = array(
284
            'db_table'      => 'dtb_session',
285
        );
286
287 697
        $app = $this;
288
        $this['session.storage.handler'] = function() use ($app) {
289
            return new PdoSessionHandler(
290
                $app['dbs']['session']->getWrappedConnection(),
291
                $app['session.db_options']
292
            );
293
        };
294 697
    }
295
296 697
    public function initRendering()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
297
    {
298
        $this->register(new \Silex\Provider\TwigServiceProvider(), array(
299
            'twig.form.templates' => array('Form/form_layout.twig'),
300
        ));
301
        $this['twig'] = $this->share($this->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
302
            $twig->addExtension(new \Eccube\Twig\Extension\EccubeExtension($app));
303
            $twig->addExtension(new \Twig_Extension_StringLoader());
304
305 132
            return $twig;
306
        }));
307
308
        $this->before(function(Request $request, \Silex\Application $app) {
309
            // フロント or 管理画面ごとにtwigの探索パスを切り替える.
310
            $app['twig'] = $app->share($app->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
311 101
                $paths = array();
312
313
                // 互換性がないのでprofiler とproduction 時のcacheを分離する
314
315
                if (isset($app['profiler'])) {
316
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/profiler/';
317
                } else {
318 101
                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/production/';
319
                }
320
                if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {
321
                    if (file_exists(__DIR__.'/../../app/template/admin')) {
322 55
                        $paths[] = __DIR__.'/../../app/template/admin';
323
                    }
324
                    $paths[] = $app['config']['template_admin_realdir'];
325 55
                    $paths[] = __DIR__.'/../../app/Plugin';
326 55
                    $cache = $cacheBaseDir.'admin';
327
                } else {
328
                    if (file_exists($app['config']['template_realdir'])) {
329
                        $paths[] = $app['config']['template_realdir'];
330
                    }
331
                    $paths[] = $app['config']['template_default_realdir'];
332 46
                    $paths[] = __DIR__.'/../../app/Plugin';
333
                    $cache = $cacheBaseDir.$app['config']['template_code'];
334 55
                }
335
                $twig->setCache($cache);
336
                $app['twig.loader']->addLoader(new \Twig_Loader_Filesystem($paths));
337
338 101
                return $twig;
339
            }));
340
341
            // 管理画面のIP制限チェック.
342
            if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {
343
                // IP制限チェック
344
                $allowHost = $app['config']['admin_allow_host'];
345
                if (count($allowHost) > 0) {
346
                    if (array_search($app['request']->getClientIp(), $allowHost) === false) {
347
                        throw new \Exception();
348
                    }
349
                }
350
            }
351
        }, self::EARLY_EVENT);
352
353
        // twigのグローバル変数を定義.
354 697
        $app = $this;
355
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {
356
            // ショップ基本情報
357
            $BaseInfo = $app['eccube.repository.base_info']->get();
358
            $app['twig']->addGlobal('BaseInfo', $BaseInfo);
359
360
            if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {
361
                // 管理画面
362
                // 管理画面メニュー
363 55
                $menus = array('', '', '');
364
                $app['twig']->addGlobal('menus', $menus);
365
366
                $Member = $app->user();
367
                if (is_object($Member)) {
368
                    // ログインしていれば管理者のロールを取得
369
                    $AuthorityRoles = $app['eccube.repository.authority_role']->findBy(array('Authority' => $Member->getAuthority()));
370
371 52
                    $roles = array();
372
                    foreach ($AuthorityRoles as $AuthorityRole) {
373
                        // 管理画面でメニュー制御するため相対パス全てをセット
374
                        $roles[] = $app['request']->getBaseUrl() . '/' . $app['config']['admin_route'] . $AuthorityRole->getDenyUrl();
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
375 52
                    }
376
377
                    $app['twig']->addGlobal('AuthorityRoles', $roles);
378
                }
379
380
            } else {
381
                // フロント画面
382
                $request = $event->getRequest();
383
                $route = $request->attributes->get('_route');
384
385
                // ユーザ作成画面
386
                if ($route === trim($app['config']['user_data_route'])) {
387
                    $params = $request->attributes->get('_route_params');
388 2
                    $route = $params['route'];
389
                    // プレビュー画面
390
                } elseif ($request->get('preview')) {
391
                    $route = 'preview';
392 2
                }
393
394
                try {
395
                    $DeviceType = $app['eccube.repository.master.device_type']
396
                        ->find(\Eccube\Entity\Master\DeviceType::DEVICE_TYPE_PC);
397
                    $PageLayout = $app['eccube.repository.page_layout']->getByUrl($DeviceType, $route);
398
                } catch (\Doctrine\ORM\NoResultException $e) {
399
                    $PageLayout = $app['eccube.repository.page_layout']->newPageLayout($DeviceType);
400 23
                }
401
402
                $app['twig']->addGlobal('PageLayout', $PageLayout);
403
                $app['twig']->addGlobal('title', $PageLayout->getName());
404 55
            }
405
        });
406 697
    }
407
408 697
    public function initMailer()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
409
    {
410
411
        // メール送信時の文字エンコード指定(デフォルトは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...
412
        if (isset($this['config']['mail']['charset_iso_2022_jp']) && is_bool($this['config']['mail']['charset_iso_2022_jp'])) {
413
            if ($this['config']['mail']['charset_iso_2022_jp'] === true) {
414
                \Swift::init(function() {
415
                    \Swift_DependencyContainer::getInstance()
416
                        ->register('mime.qpheaderencoder')
417
                        ->asAliasOf('mime.base64headerencoder');
418
                    \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
419
                });
420
            }
421
        }
422
423
        $this->register(new \Silex\Provider\SwiftmailerServiceProvider());
424
        $this['swiftmailer.options'] = $this['config']['mail'];
425
426
        if (isset($this['config']['mail']['spool']) && is_bool($this['config']['mail']['spool'])) {
427
            $this['swiftmailer.use_spool'] = $this['config']['mail']['spool'];
428
        }
429
        // デフォルトはsmtpを使用
430
        $transport = $this['config']['mail']['transport'];
431 697
        if ($transport == 'sendmail') {
432
            $this['swiftmailer.transport'] = \Swift_SendmailTransport::newInstance();
433 697
        } elseif ($transport == 'mail') {
434
            $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance();
435
        }
436 697
    }
437
438 697
    public function initDoctrine()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
439
    {
440
        $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...
441
            'dbs.options' => array(
442 697
                'default' => $this['config']['database'],
443 697
                'session' => $this['config']['database'],
444
        )));
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
445
        $this->register(new \Saxulum\DoctrineOrmManagerRegistry\Silex\Provider\DoctrineOrmManagerRegistryProvider());
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
446
447
        // プラグインのmetadata定義を合わせて行う.
448 697
        $pluginBasePath = __DIR__.'/../../app/Plugin';
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
449 696
        $finder = Finder::create()
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
450 697
            ->in($pluginBasePath)
451 697
            ->directories()
452
            ->depth(0);
453
454 697
        $ormMappings = array();
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
455
        $ormMappings[] = array(
0 ignored issues
show
Coding Style introduced by
It seems like the identation of this line is off (expected at least 12 spaces, but found 8).
Loading history...
456 697
            'type' => 'yml',
457 697
            'namespace' => 'Eccube\Entity',
458
            'path' => array(
459 697
                __DIR__.'/Resource/doctrine',
460 697
                __DIR__.'/Resource/doctrine/master',
461 697
            ),
462 697
        );
463
464
        foreach ($finder as $dir) {
465
            $config = Yaml::parse(file_get_contents($dir->getRealPath().'/config.yml'));
466
467
            // Doctrine Extend
468
            if (isset($config['orm.path']) && is_array($config['orm.path'])) {
469
                $paths = array();
470
                foreach ($config['orm.path'] as $path) {
471
                    $paths[] = $pluginBasePath.'/'.$config['code'].$path;
472
                }
473
                $ormMappings[] = array(
474
                    'type' => 'yml',
475
                    'namespace' => 'Plugin\\'.$config['code'].'\\Entity',
476
                    'path' => $paths,
477
                );
478
            }
479 697
        }
480
481
        $this->register(new \Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
482 697
            'orm.proxies_dir' => __DIR__.'/../../app/cache/doctrine',
483
            'orm.em.options' => array(
484
                'mappings' => $ormMappings,
485 697
            ),
486
        ));
487 697
    }
488
489 697
    public function initSecurity()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
490
    {
491
        $this->register(new \Silex\Provider\SecurityServiceProvider());
492
        $this->register(new \Silex\Provider\RememberMeServiceProvider());
493
494 697
        $this['security.firewalls'] = array(
495
            'admin' => array(
496
                'pattern' => "^/{$this['config']['admin_route']}",
497
                'form' => array(
498
                    'login_path' => "/{$this['config']['admin_route']}/login",
499
                    'check_path' => "/{$this['config']['admin_route']}/login_check",
500 697
                    'username_parameter' => 'login_id',
501 697
                    'password_parameter' => 'password',
502 697
                    'with_csrf' => true,
503 697
                    'use_forward' => true,
504 697
                ),
505
                'logout' => array(
506
                    'logout_path' => "/{$this['config']['admin_route']}/logout",
507
                    'target_url' => "/{$this['config']['admin_route']}/",
508 697
                ),
509
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Member'),
510 697
                'anonymous' => true,
511
            ),
512
            'customer' => array(
513 697
                'pattern' => '^/',
514
                'form' => array(
515
                    'login_path' => '/mypage/login',
516
                    'check_path' => '/login_check',
517
                    'username_parameter' => 'login_email',
518
                    'password_parameter' => 'login_pass',
519
                    'with_csrf' => true,
520
                    'use_forward' => true,
521 697
                ),
522
                'logout' => array(
523
                    'logout_path' => '/logout',
524
                    'target_url' => '/',
525 697
                ),
526
                'remember_me' => array(
527
                    'key' => sha1($this['config']['auth_magic']),
528 697
                    'name' => 'eccube_rememberme',
529
                    // lifetimeはデフォルトの1年間にする
530
                    // '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...
531
                    'path' => $this['config']['root_urlpath'] ?: '/',
532 697
                    'secure' => $this['config']['force_ssl'],
533 697
                    'httponly' => true,
534 697
                    'always_remember_me' => false,
535 697
                    'remember_me_parameter' => 'login_memory',
536
                ),
537
                'users' => $this['orm.em']->getRepository('Eccube\Entity\Customer'),
538 697
                'anonymous' => true,
539
            ),
540
        );
541
542 697
        $this['security.access_rules'] = array(
543
            array("^/{$this['config']['admin_route']}/login", 'IS_AUTHENTICATED_ANONYMOUSLY'),
544
            array("^/{$this['config']['admin_route']}", 'ROLE_ADMIN'),
545 697
            array('^/mypage/login', 'IS_AUTHENTICATED_ANONYMOUSLY'),
546 697
            array('^/mypage/withdraw_complete', 'IS_AUTHENTICATED_ANONYMOUSLY'),
547 697
            array('^/mypage/change', 'IS_AUTHENTICATED_FULLY'),
548 697
            array('^/mypage', 'ROLE_USER'),
549
        );
550
551
        $this['eccube.password_encoder'] = $this->share(function($app) {
552
            return new \Eccube\Security\Core\Encoder\PasswordEncoder($app['config']);
553
        });
554
        $this['security.encoder_factory'] = $this->share(function($app) {
555
            return new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array(
556 697
                'Eccube\Entity\Customer' => $app['eccube.password_encoder'],
557 697
                'Eccube\Entity\Member' => $app['eccube.password_encoder'],
558
            ));
559
        });
560
        $this['eccube.event_listner.security'] = $this->share(function($app) {
561
            return new \Eccube\EventListener\SecurityEventListener($app['orm.em']);
562
        });
563
        $this['user'] = $this->share(function($app) {
564
            $token = $app['security']->getToken();
565
566
            return ($token !== null) ? $token->getUser() : null;
567
        });
568
569
        // ログイン時のイベントを設定.
570
        $this['dispatcher']->addListener(\Symfony\Component\Security\Http\SecurityEvents::INTERACTIVE_LOGIN, array($this['eccube.event_listner.security'], 'onInteractiveLogin'));
571
572
        // Voterの設定
573 697
        $app = $this;
574
        $this['authority_voter'] = $this->share(function($app) {
575
            return new \Eccube\Security\Voter\AuthorityVoter($app);
576
        });
577
578
        $app['security.voters'] = $app->extend('security.voters', function($voters) use ($app) {
579
            $voters[] = $app['authority_voter'];
580
581 697
            return $voters;
582
        });
583
584
        $this['security.access_manager'] = $this->share(function($app) {
585
            return new \Symfony\Component\Security\Core\Authorization\AccessDecisionManager($app['security.voters'], 'unanimous');
586
        });
587
588 697
    }
589
590
    public function initializePlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
591
    {
592
        // setup event dispatcher
593
        $this->initPluginEventDispatcher();
594
595
        // load plugin
596
        $this->loadPlugin();
597
    }
598
599 697
    public function initPluginEventDispatcher()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
600
    {
601
        // EventDispatcher
602
        $this['eccube.event.dispatcher'] = $this->share(function() {
603
            return new EventDispatcher();
604
        });
605
606
        // hook point
607
        $this->before(function(Request $request, \Silex\Application $app) {
608
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.before');
609
        }, self::EARLY_EVENT);
610
611
        $this->before(function(Request $request, \Silex\Application $app) {
612
            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.before';
613
            $app['eccube.event.dispatcher']->dispatch($event);
614
        });
615
616 View Code Duplication
        $this->after(function(Request $request, Response $response, \Silex\Application $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...
617
            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.after';
618
            $app['eccube.event.dispatcher']->dispatch($event);
619
        });
620
621
        $this->after(function(Request $request, Response $response, \Silex\Application $app) {
622
            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.after');
623
        }, self::LATE_EVENT);
624
625 View Code Duplication
        $this->finish(function(Request $request, Response $response, \Silex\Application $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
            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.finish';
627
            $app['eccube.event.dispatcher']->dispatch($event);
628
        });
629
630 697
        $app = $this;
631
        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
632
            $route = $event->getRequest()->attributes->get('_route');
633
            $app['eccube.event.dispatcher']->dispatch('eccube.event.render.'.$route.'.before', $event);
634
        });
635 697
    }
636
637
    public function loadPlugin()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
638
    {
639
        // プラグインディレクトリを探索.
640
        $basePath = __DIR__.'/../../app/Plugin';
641
        $finder = Finder::create()
642
            ->in($basePath)
643
            ->directories()
644
            ->depth(0);
645
646
        $finder->sortByName();
647
648
        // ハンドラ優先順位をdbから持ってきてハッシュテーブルを作成
649
        $priorities = array();
650
        $handlers = $this['orm.em']
651
            ->getRepository('Eccube\Entity\PluginEventHandler')
652
            ->getHandlers();
653
        foreach ($handlers as $handler) {
654
            if ($handler->getPlugin()->getEnable() && !$handler->getPlugin()->getDelFlg()) {
655
                $priority = $handler->getPriority();
656
            } else {
657
                // Pluginがdisable、削除済みの場合、EventHandlerのPriorityを全て0とみなす
658
                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED;
659
            }
660
            $priorities[$handler->getPlugin()->getClassName()][$handler->getEvent()][$handler->getHandler()] = $priority;
661
        }
662
663
        // プラグインをロードする.
664
        // config.yml/event.ymlの定義に沿ってインスタンスの生成を行い, イベント設定を行う.
665
        foreach ($finder as $dir) {
666
            //config.ymlのないディレクトリは無視する
667
            if (!file_exists($dir->getRealPath().'/config.yml')) {
668
                continue;
669
            }
670
            $config = Yaml::parse(file_get_contents($dir->getRealPath().'/config.yml'));
671
672
            $plugin = $this['orm.em']
673
                ->getRepository('Eccube\Entity\Plugin')
674
                ->findOneBy(array('code' => $config['code']));
675
676
            // const
677
            if (isset($config['const'])) {
678
                $this['config'] = $this->share($this->extend('config', function($eccubeConfig) use ($config) {
679
                    $eccubeConfig[$config['code']] = array(
680
                        'const' => $config['const'],
681
                    );
682
683
                    return $eccubeConfig;
684
                }));
685
            }
686
687
            if ($plugin && $plugin->getEnable() == Constant::DISABLED) {
688
                // プラグインが無効化されていれば読み込まない
689
                continue;
690
            }
691
692
            // Type: Event
693
            if (isset($config['event'])) {
694
                $class = '\\Plugin\\'.$config['code'].'\\'.$config['event'];
695
                $subscriber = new $class($this);
696
697
                if (file_exists($dir->getRealPath().'/event.yml')) {
698
                    foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {
0 ignored issues
show
Bug introduced by
The expression \Symfony\Component\Yaml\...Path() . '/event.yml')) of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
699
                        foreach ($handlers as $handler) {
700
                            if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする
701
                                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;
702
                            } else {
703
                                $priority = $priorities[$config['event']][$event][$handler[0]];
704
                            }
705
                            // 優先度が0のプラグインは登録しない
706
                            if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {
707
                                $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);
708
                            }
709
                        }
710
                    }
711
                }
712
            }
713
            // Type: ServiceProvider
714
            if (isset($config['service'])) {
715
                foreach ($config['service'] as $service) {
716
                    $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;
717
                    $this->register(new $class($this));
718
                }
719
            }
720
        }
721
    }
722
}
723