Failed Conditions
Push — master ( 3bcbc5...584953 )
by Kentaro
16:12
created

InstallController::insert()   A

Complexity

Conditions 2
Paths 10

Size

Total Lines 59
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6
Metric Value
dl 0
loc 59
ccs 0
cts 0
cp 0
rs 9.597
cc 2
eloc 28
nc 10
nop 0
crap 6

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Controller\Install;
26
27
use Doctrine\DBAL\Migrations\Configuration\Configuration;
28
use Doctrine\DBAL\Migrations\Migration;
29
use Doctrine\DBAL\Migrations\MigrationException;
30
use Doctrine\ORM\EntityManager;
31
use Doctrine\ORM\Tools\SchemaTool;
32
use Eccube\Common\Constant;
33
use Eccube\InstallApplication;
34
use Eccube\Util\Str;
35
use Symfony\Component\Filesystem\Filesystem;
36
use Symfony\Component\Finder\Finder;
37
use Symfony\Component\Form\Form;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\Yaml\Yaml;
40
41
class InstallController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
42
{
43
    private $app;
44
45
    private $PDO;
46
47
    private $config_path;
48
49
    private $dist_path;
50
51
    private $cache_path;
52
53
    private $session_data;
54
55
    private $required_modules = array('pdo', 'phar', 'mbstring', 'zlib', 'ctype', 'session', 'JSON', 'xml', 'libxml', 'OpenSSL', 'zip', 'cURL', 'fileinfo');
56
57
    private $recommended_module = array('hash', 'mcrypt');
58
59
    const SESSION_KEY = 'eccube.session.install';
60
61 7
    public function __construct()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
62
    {
63 7
        $this->config_path = __DIR__ . '/../../../../app/config/eccube';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
64 7
        $this->dist_path = __DIR__ . '/../../Resource/config';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
65 7
        $this->cache_path = __DIR__ . '/../../../../app/cache';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
66 7
    }
67
68 4
    private function isValid(Request $request, Form $form)
69
    {
70
        $session = $request->getSession();
71
        if ('POST' === $request->getMethod()) {
72
            $form->handleRequest($request);
73
            if ($form->isValid()) {
74
                $sessionData = $session->get(self::SESSION_KEY) ?: array();
75
                $formData = array_replace_recursive($sessionData, $form->getData());
76
                $session->set(self::SESSION_KEY, $formData);
77
78
                return true;
79
            }
80
        }
81
82 4
        return false;
83 4
    }
84
85 5
    private function getSessionData(Request $request)
86
    {
87
        return $this->session_data = $request->getSession()->get(self::SESSION_KEY);
88 5
    }
89
90
    // 最初からやり直す場合、SESSION情報をクリア
91 1
    public function index(InstallApplication $app, Request $request)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
introduced by
You must use "/**" style comments for a function comment
Loading history...
92
    {
93
        $request->getSession()->remove(self::SESSION_KEY);
94
95
        return $app->redirect($app->url('install_step1'));
96 1
    }
97
98
    // ようこそ
99 1 View Code Duplication
    public function step1(InstallApplication $app, Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
introduced by
You must use "/**" style comments for a function comment
Loading history...
100
    {
101
        $form = $app['form.factory']
102
            ->createBuilder('install_step1')
103
            ->getForm();
104
        $sessionData = $this->getSessionData($request);
105
        $form->setData($sessionData);
106
107
        if ($this->isValid($request, $form)) {
108
            return $app->redirect($app->url('install_step2'));
109
        }
110
111
        $this->checkModules($app);
112
113 1
        return $app['twig']->render('step1.twig', array(
114 1
            'form' => $form->createView(),
115
        ));
116 1
    }
117
118
    // 権限チェック
119 1
    public function step2(InstallApplication $app, Request $request)
0 ignored issues
show
introduced by
You must use "/**" style comments for a function comment
Loading history...
120
    {
121
        $this->getSessionData($request);
122
123
        $protectedDirs = $this->getProtectedDirs();
124
125
        // 権限がある場合, キャッシュディレクトリをクリア
126 1
        if (empty($protectedDirs)) {
127 1
            $finder = Finder::create()
128 1
                ->in($this->cache_path)
129 1
                ->directories()
130
                ->depth(0);
131
            $fs = new Filesystem();
132
            $fs->remove($finder);
133
        }
134
135 1
        return $app['twig']->render('step2.twig', array(
136
            'protectedDirs' => $protectedDirs,
137
        ));
138 1
    }
139
140
    //    サイトの設定
141 1
    public function step3(InstallApplication $app, Request $request)
0 ignored issues
show
introduced by
You must use "/**" style comments for a function comment
Loading history...
142
    {
143
        $form = $app['form.factory']
144
            ->createBuilder('install_step3')
145
            ->getForm();
146
        $sessionData = $this->getSessionData($request);
147
        $form->setData($sessionData);
148
        if ($this->isValid($request, $form)) {
149
            $data = $form->getData();
150
            $this
151
                ->createConfigYamlFile($data)
152
                ->createMailYamlFile($data)
153
                ->createPathYamlFile($data, $request);
154
155
            return $app->redirect($app->url('install_step4'));
156
        }
157
158 1
        return $app['twig']->render('step3.twig', array(
159 1
            'form' => $form->createView(),
160
        ));
161 1
    }
162
163
    //    データベースの設定
164 1 View Code Duplication
    public function step4(InstallApplication $app, Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
introduced by
You must use "/**" style comments for a function comment
Loading history...
165
    {
166
        $form = $app['form.factory']
167
            ->createBuilder('install_step4')
168
            ->getForm();
169
170
        $sessionData = $this->getSessionData($request);
171
        $form->setData($sessionData);
172
173
        if ($this->isValid($request, $form)) {
174
            $this->createDatabaseYamlFile($form->getData());
175
176
            return $app->redirect($app->url('install_step5'));
177
        }
178
179 1
        return $app['twig']->render('step4.twig', array(
180 1
            'form' => $form->createView(),
181
        ));
182 1
    }
183
184
    //    データベースの初期化
185 1
    public function step5(InstallApplication $app, Request $request)
0 ignored issues
show
introduced by
You must use "/**" style comments for a function comment
Loading history...
186
    {
187
        set_time_limit(0);
188 1
        $this->app = $app;
189
        $form = $app['form.factory']
190
            ->createBuilder('install_step5')
191
            ->getForm();
192
        $sessionData = $this->getSessionData($request);
193
        $form->setData($sessionData);
194
195
        if ($this->isValid($request, $form)) {
196
            if (!$form['no_update']->getData()) {
197
                set_time_limit(0);
198
199
                $this
200
                    ->setPDO()
201
                    ->dropTables()
202
                    ->createTables()
203
                    ->doMigrate()
204
                    ->insert();
205
            }
206
            if (isset($sessionData['agree']) && $sessionData['agree'] == '1') {
207
                $host = $request->getSchemeAndHttpHost();
208
                $basePath = $request->getBasePath();
209
                $params = array(
210
                    'http_url' => $host . $basePath,
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
211
                    'shop_name' => $sessionData['shop_name'],
212
                );
213
214
                $this->sendAppData($params);
215
            }
216
            $this->addInstallStatus();
217
218
            $request->getSession()->remove(self::SESSION_KEY);
219
220
            return $app->redirect($app->url('install_complete'));
221
        }
222
223 1
        return $app['twig']->render('step5.twig', array(
224 1
            'form' => $form->createView(),
225
        ));
226 1
    }
227
228
    //    インストール完了
229 1
    public function complete(InstallApplication $app, Request $request)
0 ignored issues
show
introduced by
You must use "/**" style comments for a function comment
Loading history...
230
    {
231 1
        $config_file = $this->config_path . '/path.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
232
        $config = Yaml::parse($config_file);
233
234
        $host = $request->getSchemeAndHttpHost();
235
        $basePath = $request->getBasePath();
236
237 1
        $adminUrl = $host . $basePath . '/' . $config['admin_dir'];
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
238
239 1
        return $app['twig']->render('complete.twig', array(
240
            'admin_url' => $adminUrl,
241
        ));
242 1
    }
243
244
    private function resetNatTimer()
245
    {
246
        // NATの無通信タイマ対策(仮)
247
        echo str_repeat(' ', 4 * 1024);
248
        ob_flush();
249
        flush();
250
    }
251
252
253 1
    private function checkModules($app)
0 ignored issues
show
Coding Style introduced by
checkModules uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
254
    {
255 1
        foreach ($this->required_modules as $module) {
256
            if (!extension_loaded($module)) {
257
                $app->addDanger('[必須] ' . $module . ' 拡張モジュールが有効になっていません。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
258
            }
259
        }
260
261
        if (!extension_loaded('pdo_mysql') && !extension_loaded('pdo_pgsql')) {
262
            $app->addDanger('[必須] ' . 'pdo_pgsql又はpdo_mysql 拡張モジュールを有効にしてください。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
263
        }
264
265 1
        foreach ($this->recommended_module as $module) {
266
            if (!extension_loaded($module)) {
267
                $app->addWarning('[推奨] ' . $module . ' 拡張モジュールが有効になっていません。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
268
            }
269
        }
270
271 1
        if ('\\' === DIRECTORY_SEPARATOR) { // for Windows
272
            if (!extension_loaded('wincache')) {
273
                $app->addWarning('[推奨] WinCache 拡張モジュールが有効になっていません。', 'install');
274
            }
275
        } else {
276
            if (!extension_loaded('apc')) {
277
                $app->addWarning('[推奨] APC 拡張モジュールが有効になっていません。', 'install');
278
            }
279
        }
280
281 1
        if (isset($_SERVER['SERVER_SOFTWARE']) && strpos('Apache', $_SERVER['SERVER_SOFTWARE']) !== false) {
282
            if (!function_exists('apache_get_modules')) {
283
                $app->addWarning('mod_rewrite が有効になっているか不明です。', 'install');
284
            } elseif (!in_array('mod_rewrite', apache_get_modules())) {
285
                $app->addDanger('[必須] ' . 'mod_rewriteを有効にしてください。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
286
            }
287 1
        } elseif (isset($_SERVER['SERVER_SOFTWARE']) && strpos('Microsoft-IIS', $_SERVER['SERVER_SOFTWARE']) !== false) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
288
            // iis
289 1
        } elseif (isset($_SERVER['SERVER_SOFTWARE']) && strpos('nginx', $_SERVER['SERVER_SOFTWARE']) !== false) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
290
            // nginx
291
        }
292 1
    }
293
294
    private function setPDO()
295
    {
296
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
297
        $config = Yaml::parse($config_file);
298
299
        try {
300
            $this->PDO = \Doctrine\DBAL\DriverManager::getConnection($config['database'], new \Doctrine\DBAL\Configuration());
301
            $this->PDO->connect();
302
303
        } catch (\Exception $e) {
304
            $this->PDO->close();
305
            throw $e;
306
        }
307
308
        return $this;
309
    }
310
311 View Code Duplication
    private function dropTables()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
312
    {
313
        $this->resetNatTimer();
314
315
        $em = $this->getEntityManager();
316
        $metadatas = $em->getMetadataFactory()->getAllMetadata();
317
        $schemaTool = new SchemaTool($em);
318
319
        $schemaTool->dropSchema($metadatas);
320
321
        $em->getConnection()->executeQuery('DROP TABLE IF EXISTS doctrine_migration_versions');
322
323
        return $this;
324
    }
325
326
    /**
327
     * @return EntityManager
328
     */
329
    private function getEntityManager()
330
    {
331
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
332
        $database = Yaml::parse($config_file);
333
334
        $this->app->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...
335
            'db.options' => $database['database']
336
        ));
337
338
        $this->app->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...
339
            'orm.proxies_dir' => __DIR__ . '/../../app/cache/doctrine',
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
340
            'orm.em.options' => array(
341
                'mappings' => array(
342
                    array(
343
                        'type' => 'yml',
344
                        'namespace' => 'Eccube\Entity',
345
                        'path' => array(
346
                            __DIR__ . '/../../Resource/doctrine',
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
347
                            __DIR__ . '/../../Resource/doctrine/master',
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
348
                        ),
349
                    ),
350
351
                ),
352
            )
353
        ));
354
355
        return $em = $this->app['orm.em'];
0 ignored issues
show
Unused Code introduced by
$em is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
356
    }
357
358 View Code Duplication
    private function createTables()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
359
    {
360
        $this->resetNatTimer();
361
362
        $em = $this->getEntityManager();
363
        $metadatas = $em->getMetadataFactory()->getAllMetadata();
364
        $schemaTool = new SchemaTool($em);
365
366
        $schemaTool->createSchema($metadatas);
367
368
        return $this;
369
    }
370
371
    private function insert()
372
    {
373
        $this->resetNatTimer();
374
375
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
376
        $database = Yaml::parse($config_file);
377
        $config['database'] = $database['database'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
378
379
        $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
380
        $baseConfig = Yaml::parse($config_file);
381
        $config['config'] = $baseConfig;
382
383
        $this->PDO->beginTransaction();
384
385
        try {
386
387
            $config = array(
388
                'auth_type' => '',
389
                'auth_magic' => $config['config']['auth_magic'],
390
                'password_hash_algos' => 'sha256',
391
            );
392
            $passwordEncoder = new \Eccube\Security\Core\Encoder\PasswordEncoder($config);
393
            $salt = \Eccube\Util\Str::random();
394
395
            $encodedPassword = $passwordEncoder->encodePassword($this->session_data['login_pass'], $salt);
396
            $sth = $this->PDO->prepare('INSERT INTO dtb_base_info (
397
                id,
398
                shop_name,
399
                email01,
400
                email02,
401
                email03,
402
                email04,
403
                update_date,
404
                option_product_tax_rule
405
            ) VALUES (
406
                1,
407
                :shop_name,
408
                :admin_mail,
409
                :admin_mail,
410
                :admin_mail,
411
                :admin_mail,
412
                current_timestamp,
413
                0);');
414
            $sth->execute(array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
415
                ':shop_name' => $this->session_data['shop_name'],
416
                ':admin_mail' => $this->session_data['email']
417
            ));
418
419
            $sth = $this->PDO->prepare("INSERT INTO dtb_member (member_id, login_id, password, salt, work, del_flg, authority, creator_id, rank, update_date, create_date,name,department) VALUES (2, :login_id, :admin_pass , :salt , '1', '0', '0', '1', '1', current_timestamp, current_timestamp,'管理者','EC-CUBE SHOP');");
420
            $sth->execute(array(':login_id' => $this->session_data['login_id'], ':admin_pass' => $encodedPassword, ':salt' => $salt));
421
422
            $this->PDO->commit();
423
        } catch (\Exception $e) {
424
            $this->PDO->rollback();
425
            throw $e;
426
        }
427
428
        return $this;
429
    }
430
431
    private function getMigration()
432
    {
433
        $app = new \Eccube\Application();
434
        $app->initDoctrine();
435
        $config = new Configuration($app['db']);
436
        $config->setMigrationsNamespace('DoctrineMigrations');
437
438
        $migrationDir = __DIR__ . '/../../Resource/doctrine/migration';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
439
        $config->setMigrationsDirectory($migrationDir);
440
        $config->registerMigrationsFromDirectory($migrationDir);
441
442
        $migration = new Migration($config);
443
444
        return $migration;
445
    }
446
447
    private function doMigrate()
448
    {
449
        try {
450
            $migration = $this->getMigration();
451
            // nullを渡すと最新バージョンまでマイグレートする
452
            $migration->migrate(null, false);
453
        } catch (MigrationException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
454
        }
455
456
        return $this;
457
    }
458
459 1
    private function getProtectedDirs()
460
    {
461 1
        $protectedDirs = array();
462 1
        $base = __DIR__ . '/../../../..';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
463
        $dirs = array(
464
            '/html',
465
            '/app',
466
            '/app/template',
467
            '/app/cache',
468
            '/app/config',
469
            '/app/config/eccube',
470
            '/app/log',
471
            '/app/Plugin',
472 1
        );
473
474
        foreach ($dirs as $dir) {
475
            if (!is_writable($base . $dir)) {
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
476
                $protectedDirs[] = $dir;
477
            }
478
        }
479
480 1
        return $protectedDirs;
481
    }
482
483
    private function createConfigYamlFile($data)
484
    {
485
        $fs = new Filesystem();
486
        $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
487
        if ($fs->exists($config_file)) {
488
            $fs->remove($config_file);
489
        }
490
491
        $auth_magic = Str::random(32);
492
        $allowHost = Str::convertLineFeed($data['admin_allow_hosts']);
493
        if (empty($allowHost)) {
494
            $adminAllowHosts = array();
495
        } else {
496
            $adminAllowHosts = explode("\n", $allowHost);
497
        }
498
499
        $target = array('${AUTH_MAGIC}', '${SHOP_NAME}', '${ECCUBE_INSTALL}', '${FORCE_SSL}');
500
        $replace = array($auth_magic, $data['shop_name'], '0', $data['admin_force_ssl']);
501
502
        $fs = new Filesystem();
503
        $content = str_replace(
504
            $target,
505
            $replace,
506
            file_get_contents($this->dist_path . '/config.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
507
        );
508
        $fs->dumpFile($config_file, $content);
509
510
        $config = Yaml::Parse($config_file);
511
        $config['admin_allow_host'] = $adminAllowHosts;
512
        $yml = Yaml::dump($config);
0 ignored issues
show
Bug introduced by
It seems like $config defined by \Symfony\Component\Yaml\Yaml::Parse($config_file) on line 510 can also be of type string; however, Symfony\Component\Yaml\Yaml::dump() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
513
        file_put_contents($config_file, $yml);
514
515
        return $this;
516
    }
517
518
    private function addInstallStatus()
519
    {
520
        $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
521
        $config = Yaml::parse($config_file);
522
        $config['eccube_install'] = 1;
523
        $yml = Yaml::dump($config);
0 ignored issues
show
Bug introduced by
It seems like $config defined by \Symfony\Component\Yaml\Yaml::parse($config_file) on line 521 can also be of type string; however, Symfony\Component\Yaml\Yaml::dump() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
524
        file_put_contents($config_file, $yml);
525
526
        return $this;
527
    }
528
529
    private function createDatabaseYamlFile($data)
530
    {
531
        $fs = new Filesystem();
532
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
533
        if ($fs->exists($config_file)) {
534
            $fs->remove($config_file);
535
        }
536
537
        switch ($data['database']) {
538
            case 'pdo_pgsql':
539
                if (empty($data['db_port'])) {
540
                    $data['db_port'] = '5432';
541
                }
542
                $data['db_driver'] = 'pdo_pgsql';
543
                break;
544
            case 'pdo_mysql':
545
                if (empty($data['db_port'])) {
546
                    $data['db_port'] = '3306';
547
                }
548
                $data['db_driver'] = 'pdo_mysql';
549
                break;
550
        }
551
        $target = array('${DBDRIVER}', '${DBSERVER}', '${DBNAME}', '${DBPORT}', '${DBUSER}', '${DBPASS}');
552
        $replace = array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
553
            $data['db_driver'],
554
            $data['database_host'],
555
            $data['database_name'],
556
            $data['database_port'],
557
            $data['database_user'],
558
            $data['database_password']
559
        );
560
561
        $fs = new Filesystem();
562
        $content = str_replace(
563
            $target,
564
            $replace,
565
            file_get_contents($this->dist_path . '/database.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
566
        );
567
568
        $fs->dumpFile($config_file, $content);
569
570
        return $this;
571
    }
572
573
    private function createMailYamlFile($data)
574
    {
575
        $fs = new Filesystem();
576
        $config_file = $this->config_path . '/mail.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
577
        if ($fs->exists($config_file)) {
578
            $fs->remove($config_file);
579
        }
580
        $target = array('${MAIL_BACKEND}', '${MAIL_HOST}', '${MAIL_PORT}', '${MAIL_USER}', '${MAIL_PASS}');
581
        $replace = array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
582
            $data['mail_backend'],
583
            $data['smtp_host'],
584
            $data['smtp_port'],
585
            $data['smtp_username'],
586
            $data['smtp_password']
587
        );
588
589
        $fs = new Filesystem();
590
        $content = str_replace(
591
            $target,
592
            $replace,
593
            file_get_contents($this->dist_path . '/mail.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
594
        );
595
        $fs->dumpFile($config_file, $content);
596
597
        return $this;
598
    }
599
600
    private function createPathYamlFile($data, Request $request)
601
    {
602
        $fs = new Filesystem();
603
        $config_file = $this->config_path . '/path.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
604
        if ($fs->exists($config_file)) {
605
            $fs->remove($config_file);
606
        }
607
608
        $ADMIN_ROUTE = $data['admin_dir'];
609
        $TEMPLATE_CODE = 'default';
610
        $USER_DATA_ROUTE = 'user_data';
611
        $ROOT_DIR = realpath(__DIR__ . '/../../../../');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
612
        $ROOT_URLPATH = $request->getBasePath();
613
614
        $target = array('${ADMIN_ROUTE}', '${TEMPLATE_CODE}', '${USER_DATA_ROUTE}', '${ROOT_DIR}', '${ROOT_URLPATH}');
615
        $replace = array($ADMIN_ROUTE, $TEMPLATE_CODE, $USER_DATA_ROUTE, $ROOT_DIR, $ROOT_URLPATH);
616
617
        $fs = new Filesystem();
618
        $content = str_replace(
619
            $target,
620
            $replace,
621
            file_get_contents($this->dist_path . '/path.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
622
        );
623
        $fs->dumpFile($config_file, $content);
624
625
        return $this;
626
    }
627
628
    private function sendAppData($params)
629
    {
630
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
631
        $db_config = Yaml::parse($config_file);
632
633
        $this->setPDO();
634
        $stmt = $this->PDO->query('select version() as v');
635
636
        $version = '';
637
        foreach ($stmt as $row) {
638
            $version = $row['v'];
639
        }
640
641
        if ($db_config['database']['driver'] === 'pdo_mysql') {
642
            $db_ver = 'MySQL:' . $version;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
643
        } else {
644
            $db_ver = $version;
645
        }
646
647
        $data = http_build_query(
648
            array(
649
                'site_url' => $params['http_url'],
650
                'shop_name' => $params['shop_name'],
651
                'cube_ver' => Constant::VERSION,
652
                'php_ver' => phpversion(),
653
                'db_ver' => $db_ver,
654
                'os_type' => php_uname(),
655
            )
656
        );
657
658
        $header = array(
659
            'Content-Type: application/x-www-form-urlencoded',
660
            'Content-Length: ' . strlen($data),
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
661
        );
662
        $context = stream_context_create(
663
            array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
664
                'http' => array(
665
                    'method' => 'POST',
666
                    'header' => $header,
667
                    'content' => $data,
668
                )
669
            )
670
        );
671
        file_get_contents('http://www.ec-cube.net/mall/use_site.php', false, $context);
672
673
        return $this;
674
    }
675
676
677
    /**
678
     * マイグレーション画面を表示する.
679
     *
680
     * @param InstallApplication $app
681
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
682
     *
683
     * @return \Symfony\Component\HttpFoundation\Response
684
     */
685
    public function migration(InstallApplication $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
686
    {
687
        return $app['twig']->render('migration.twig');
688
    }
689
690
    /**
691
     * インストール済プラグインの一覧を表示する.
692
     * プラグインがインストールされていない場合は, マイグレーション実行画面へリダイレクトする.
693
     *
694
     * @param InstallApplication $app
695
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
696
     *
697
     * @return \Symfony\Component\HttpFoundation\Response
698
     */
699
    public function migration_plugin(InstallApplication $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
Method name "InstallController::migration_plugin" is not in camel caps format
Loading history...
700
    {
701
        $eccube = new \Eccube\Application();
702
        $eccube->initDoctrine();
703
704
        $pluginRepository = $eccube['orm.em']->getRepository('Eccube\Entity\Plugin');
705
        $Plugins = $pluginRepository->findBy(array('del_flg' => Constant::DISABLED));
706
707
        if (empty($Plugins)) {
708
            // インストール済プラグインがない場合はマイグレーション実行画面へリダイレクト.
709
            return $app->redirect($app->url('migration_end'));
710
        } else {
711
            return $app['twig']->render('migration_plugin.twig', array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
712
                'Plugins' => $Plugins,
713
                'version' => Constant::VERSION));
714
        }
715
    }
716
717
    /**
718
     * マイグレーションを実行し, 完了画面を表示させる
719
     *
720
     * @param InstallApplication $app
721
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
722
     *
723
     * @return \Symfony\Component\HttpFoundation\Response
724
     */
725
    public function migration_end(InstallApplication $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
Method name "InstallController::migration_end" is not in camel caps format
Loading history...
726
    {
727
        $this->doMigrate();
728
729
        $config_app = new \Eccube\Application(); // install用のappだとconfigが取れないので
730
        $config_app->initialize();
731
        $config_app->boot();
732
        \Eccube\Util\Cache::clear($config_app, true);
0 ignored issues
show
Documentation introduced by
$config_app is of type object<Eccube\Application>, but the function expects a object<Eccube\Util\Application>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
733
734
        return $app['twig']->render('migration_end.twig');
735
    }
736
}
737