Failed Conditions
Push — master ( faced6...c4ab7a )
by Kentaro
41:53
created

Application::initDoctrine()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 50
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

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