Failed Conditions
Push — experimental/3.1 ( 36d064...2457e2 )
by Kiyotaka
128:07 queued 120:55
created

eccube_install.php ➔ createEnvFile()   C

Complexity

Conditions 8
Paths 19

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 21
nc 19
nop 0
dl 0
loc 35
rs 5.3846
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 10 and the first side effect is on line 4.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
if (php_sapi_name() !== 'cli') {
4
    exit(1);
5
}
6
7
set_time_limit(0);
8
ini_set('display_errors', 1);
9
10
define('COMPOSER_FILE', 'composer.phar');
11
define('COMPOSER_SETUP_FILE', 'composer-setup.php');
12
13
setUseAnsi($argv);
14
15
$argv = is_array($argv) ? $argv : array();
16
17
$argv[1] = isset($argv[1]) ? $argv[1] : null;
18
$argv[2] = isset($argv[2]) ? $argv[2] : null;
19
20
if (in_array('--help', $argv) || empty($argv[1])) {
21
    displayHelp($argv);
22
    exit(0);
23
}
24
25
if (in_array('-v', $argv) || in_array('--version', $argv)) {
26
    require __DIR__.'/src/Eccube/Common/Constant.php';
27
    echo 'EC-CUBE '.Eccube\Common\Constant::VERSION.PHP_EOL;
28
    exit(0);
29
}
30
31
out('EC-CUBE3 installer use database driver of ', null, false);
32
33
switch ($argv[1]) {
34
    case 'mysql':
35
        $database = 'mysql';
36
        break;
37
    case 'pgsql':
38
    case 'postgres':
39
    case 'postgresql':
40
        $database = 'pgsql';
41
        break;
42
    case 'sqlite':
43
    case 'sqlite3':
44
    default:
45
        $database = 'sqlite';
46
}
47
out($database);
48
49
if ($argv[2] != 'none') {
50
    composerSetup();
51
    composerInstall();
52
}
53
54
require __DIR__.'/autoload.php';
55
56
initializeDefaultVariables($database);
57
58
if (in_array('-V', $argv) || in_array('--verbose', $argv)) {
59
    displayEnvironmentVariables();
60
}
61
62
out('update permissions...');
63
updatePermissions($argv);
64
65
if (!in_array('--skip-createdb', $argv)) {
66
    $params = getDatabaseConfig();
67
    if ($params['driver'] === 'pdo_sqlite') {
68
        $dbname = $params['path'];
69
    } else {
70
        $dbname = $params['dbname'];
71
    }
72
    $conn = createConnection($params, true);
73
    createDatabase($conn, $dbname);
74
}
75
76
out('Created database connection...', 'info');
77
78
$conn = createConnection(getDatabaseConfig());
79
80
if (!in_array('--skip-initdb', $argv)) {
81
    $em = createEntityManager($conn);
82
    initializeDatabase($em);
83
}
84
85
createEnvFile();
86
copyConfigFiles();
87
88
out('EC-CUBE3 install finished successfully!', 'success');
89
$root_urlpath = env('ROOT_URLPATH');
90
if (PHP_VERSION_ID >= 50400 && empty($root_urlpath)) {
91
    out('PHP built-in web server to run applications, `php -S localhost:8080`', 'info');
92
    out('Open your browser and access the http://localhost:8080/', 'info');
93
}
94
exit(0);
95
96
function displayHelp($argv)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "displayHelp" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
97
{
98
    echo <<<EOF
99
EC-CUBE3 Installer
100
------------------
101
Usage:
102
${argv[0]} [mysql|pgsql|sqlite3] [none] [options]
103
104
Arguments[1]:
105
Specify database types
106
107
Arguments[2]:
108
Specifying the "none" to skip the installation of Composer
109
110
Options:
111
-v, --version        print ec-cube version
112
-V, --verbose        enable verbose output
113
--skip-createdb      skip to create database
114
--skip-initdb        skip to initialize database
115
--help               this help
116
--ansi               force ANSI color output
117
--no-ansi            disable ANSI color output
118
119
Environment variables:
120
121
EOF;
122
    foreach (getExampleVariables() as $name => $value) {
123
        echo $name.'='.$value.PHP_EOL;
124
    }
125
}
126
127
function initializeDefaultVariables($database)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "initializeDefaultVariables" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
128
{
129
    // heroku用定義
130
    $database_url = env('DATABASE_URL');
131
    if ($database_url) {
132
        $url = parse_url($database_url);
133
        putenv('DB_DEFAULT='.$url['scheme']);
134
        putenv('DB_HOST='.$url['host']);
135
        putenv('DB_DATABASE='.substr($url['path'], 1));
136
        putenv('DB_USERNAME='.$url['user']);
137
        putenv('DB_PORT='.$url['port']);
138
        putenv('DB_PASSWORD='.$url['pass']);
139
    }
140
141
    switch ($database) {
142
        case 'pgsql':
143
            putenv('ROOTUSER='.env('ROOTUSER', env('DB_USERNAME', 'postgres')));
144
            putenv('ROOTPASS='.env('ROOTPASS', env('DB_PASSWORD', 'password')));
145
            break;
146
        case 'mysql':
147
            putenv('ROOTUSER='.env('ROOTUSER', env('DB_USERNAME', 'root')));
148
            putenv('ROOTPASS='.env('ROOTPASS', env('DB_PASSWORD', 'password')));
149
            if (env('TRAVIS')) {
150
                putenv('ROOTPASS=');
151
                putenv('DB_PASSWORD=');
152
            }
153
            break;
154
        case 'sqlite':
155
            putenv('DB_DATABASE='.__DIR__.'/app/config/eccube/eccube.db');
156
            break;
157
        default:
158
    }
159
    putenv('DB_DEFAULT='.$database);
160
    putenv('AUTH_MAGIC='.env('AUTH_MAGIC', \Eccube\Util\Str::random(32)));
161
    putenv('ADMIN_USER='.env('ADMIN_USER', 'admin'));
162
    putenv('ADMIN_MAIL='.env('ADMIN_MAIL', '[email protected]'));
163
    putenv('SHOP_NAME='.env('SHOP_NAME', 'EC-CUBE SHOP'));
164
}
165
166
function getExampleVariables()
0 ignored issues
show
Coding Style introduced by
Consider putting global function "getExampleVariables" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
167
{
168
    return [
169
        'ADMIN_USER' => 'admin',
170
        'ADMIN_MAIL' => '[email protected]',
171
        'SHOP_NAME' => 'EC-CUBE SHOP',
172
        'ROOTUSER' => 'root|postgres',
173
        'ROOTPASS' => 'password',
174
        'AUTH_MAGIC' => '<auth magic>',
175
        'FORCE_SSL' => 'false',
176
        'ADMIN_ALLOW_HOSTS' => '[]',
177
        'COOKIE_LIFETIME' => '0',
178
        'COOKIE_NAME' => 'eccube',
179
        'LOCALE' => 'ja',
180
        'TIMEZONE' => 'Asia/Tokyo',
181
        'CURRENCY' => 'JPY',
182
        'ROOT_URLPATH' => '<eccube root url>',
183
        'TEMPLATE_CODE' => 'default',
184
        'ADMIN_ROUTE' => 'admin',
185
        'USER_DATA_ROUTE' => 'user_data',
186
        'TRUSTED_PROXIES_CONNECTION_ONLY' => 'false',
187
        'TRUSTED_PROXIES' => '["127.0.0.1/8", "::1"]',
188
        'DB_DEFAULT' => 'mysql',
189
        'DB_HOST' => '127.0.0.1',
190
        'DB_PORT' => '<database port>',
191
        'DB_DATABASE' => 'eccube_db',
192
        'DB_USERNAME' => 'eccube_db_user',
193
        'DB_PASSWORD' => 'password',
194
        'DB_CHARASET' => 'utf8',
195
        'DB_COLLATE' => 'utf8_general_ci',
196
        'MAIL_TRANSPORT' => 'smtp',
197
        'MAIL_HOST' => 'localhost',
198
        'MAIL_PORT' => '1025',
199
        'MAIL_USERNAME' => '<SMTP AUTH user>',
200
        'MAIL_PASSWORD' => '<SMTP AUTH password>',
201
        'MAIL_ENCRYPTION' => null,
202
        'MAIL_AUTH_MODE' => null,
203
        'MAIL_CHARSET_ISO_2022_JP' => 'false',
204
        'MAIL_SPOOL' => 'false',
205
    ];
206
}
207
208
function displayEnvironmentVariables()
0 ignored issues
show
Coding Style introduced by
Consider putting global function "displayEnvironmentVariables" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
209
{
210
    echo 'Environment variables:'.PHP_EOL;
211
    foreach (array_keys(getExampleVariables()) as $name) {
212
        echo $name.'='.env($name).PHP_EOL;
213
    }
214
}
215
216
function composerSetup()
0 ignored issues
show
Coding Style introduced by
Consider putting global function "composerSetup" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
217
{
218
    if (!file_exists(__DIR__.'/'.COMPOSER_FILE)) {
219
        if (!file_exists(__DIR__.'/'.COMPOSER_SETUP_FILE)) {
220
            copy('https://getcomposer.org/installer', COMPOSER_SETUP_FILE);
221
        }
222
223
        $sha = hash_file('SHA384', COMPOSER_SETUP_FILE).PHP_EOL;
224
        out(COMPOSER_SETUP_FILE.': '.$sha);
225
226
        $command = 'php '.COMPOSER_SETUP_FILE;
227
        out("execute: $command", 'info');
228
        passthru($command);
229
        unlink(COMPOSER_SETUP_FILE);
230
    } else {
231
        $command = 'php '.COMPOSER_FILE.' self-update';
232
        passthru($command);
233
    }
234
}
235
236
function composerInstall()
0 ignored issues
show
Coding Style introduced by
Consider putting global function "composerInstall" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
237
{
238
    $command = 'php '.COMPOSER_FILE.' install --dev --no-interaction';
239
    passthru($command);
240
}
241
242
function getDatabaseConfig()
0 ignored issues
show
Coding Style introduced by
Consider putting global function "getDatabaseConfig" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
243
{
244
    $config = require __DIR__.'/src/Eccube/Resource/config/database.php';
245
    $default = $config['database']['default'];
246
247
    return $config['database'][$default];
248
}
249
250
function createDatabase(\Doctrine\DBAL\Connection $conn, $dbname)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "createDatabase" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
251
{
252
    $sm = $conn->getSchemaManager();
253
254
    if ($conn->getDatabasePlatform()->getName() === 'sqlite') {
255
        out('unlink database to '.$dbname, 'info');
256
        unlink($dbname);
257
    } else {
258
        $databases = $sm->listDatabases();
259
        if (in_array($dbname, $databases)) {
260
            out('database exists '.$dbname, 'info');
261
            out('drop database to '.$dbname, 'info');
262
            $sm->dropDatabase($dbname);
263
        }
264
    }
265
    out('create database to '.$dbname, 'info');
266
    $sm->createDatabase($dbname);
267
}
268
269
function createConnection(array $params, $noDb = false)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "createConnection" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
270
{
271
    if ($noDb) {
272
        unset($params['dbname']);
273
    }
274
    return \Doctrine\DBAL\DriverManager::getConnection($params);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
275
}
276
277
function createEntityManager(\Doctrine\DBAL\Connection $conn)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "createEntityManager" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
278
{
279
    $paths = [
280
        __DIR__.'/src/Eccube/Entity',
281
        __DIR__.'/app/Acme/Entity',
282
    ];
283
    // todo プロキシ, プラグインの対応
284
    $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($paths, true, null, null, false);
285
286
    return \Doctrine\ORM\EntityManager::create($conn, $config);
287
}
288
289 View Code Duplication
function createMigration(\Doctrine\DBAL\Connection $conn)
0 ignored issues
show
Duplication introduced by
This function 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...
Coding Style introduced by
Consider putting global function "createMigration" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
290
{
291
    $config = new \Doctrine\DBAL\Migrations\Configuration\Configuration($conn);
292
    $config->setMigrationsNamespace('DoctrineMigrations');
293
    $migrationDir = __DIR__.'/src/Eccube/Resource/doctrine/migration';
294
    $config->setMigrationsDirectory($migrationDir);
295
    $config->registerMigrationsFromDirectory($migrationDir);
296
297
    $migration = new \Doctrine\DBAL\Migrations\Migration($config);
298
    $migration->setNoMigrationException(true);
299
300
    return $migration;
301
}
302
303
function initializeDatabase(\Doctrine\ORM\EntityManager $em)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "initializeDatabase" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
304
{
305
    // Clear Doctrine to be safe
306
    $em->getConnection()->getConfiguration()->setSQLLogger(null);
307
    $em->clear();
308
    gc_collect_cycles();
309
310
    // Schema Tool to process our entities
311
    $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
312
    $classes = $em->getMetaDataFactory()->getAllMetaData();
313
314
    // Drop all classes and re-build them for each test case
315
    out('Dropping database schema...', 'info');
316
    $tool->dropSchema($classes);
317
    out('Creating database schema...', 'info');
318
    $tool->createSchema($classes);
319
    out('Database schema created successfully!', 'success');
320
321
    $loader = new \Eccube\Doctrine\Common\CsvDataFixtures\Loader();
322
    $loader->loadFromDirectory(__DIR__.'/src/Eccube/Resource/doctrine/import_csv');
323
    $executer = new \Eccube\Doctrine\Common\CsvDataFixtures\Executor\DbalExecutor($em);
324
    $fixtures = $loader->getFixtures();
325
    $executer->execute($fixtures);
326
327
    out('Migrating database schema...', 'info');
328
    $migration = createMigration($em->getConnection());
329
    $migration->migrate();
330
    out('Database migration successfully!', 'success');
331
332
    out('Creating admin accounts...', 'info');
333
    $login_id = env('ADMIN_USER');
334
    $login_password = env('ADMIN_PASS');
335
336
    $encoder = new \Eccube\Security\Core\Encoder\PasswordEncoder([
337
        'auth_type' => '',
338
        'auth_magic' => env('AUTH_MAGIC'),
339
        'password_hash_algos' => 'sha256',
340
    ]);
341
    $salt = \Eccube\Util\Str::random(32);
342
    $password = $encoder->encodePassword($login_password, $salt);
343
344
    $conn = $em->getConnection();
345
    $member_id = ('postgresql' === $conn->getDatabasePlatform()->getName())
346
        ? $conn->fetchColumn("select nextval('dtb_member_member_id_seq')")
347
        : null;
348
349
    $conn->insert('dtb_member', [
350
        'member_id' => $member_id,
351
        'login_id' => $login_id,
352
        'password' => $password,
353
        'salt' => $salt,
354
        'work' => 1,
355
        'authority' => 0,
356
        'creator_id' => 1,
357
        'rank' => 1,
358
        'update_date' => new \DateTime(),
359
        'create_date' => new \DateTime(),
360
        'name' => '管理者',
361
        'department' => 'EC-CUBE SHOP',
362
        'discriminator_type' => 'member',
363
    ], [
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 8 spaces, but found 4.
Loading history...
364
        'update_date' => Doctrine\DBAL\Types\Type::DATETIME,
365
        'create_date' => Doctrine\DBAL\Types\Type::DATETIME,
366
    ]);
367
368
    $shop_name = env('SHOP_NAME');
369
    $admin_mail = env('ADMIN_MAIL');
370
371
    $id = ('postgresql' === $conn->getDatabasePlatform()->getName())
372
        ? $conn->fetchColumn("select nextval('dtb_base_info_id_seq')")
373
        : null;
374
375
    $conn->insert('dtb_base_info', [
376
        'id' => $id,
377
        'shop_name' => $shop_name,
378
        'email01' => $admin_mail,
379
        'email02' => $admin_mail,
380
        'email03' => $admin_mail,
381
        'email04' => $admin_mail,
382
        'update_date' => new \DateTime(),
383
        'discriminator_type' => 'baseinfo',
384
    ], [
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 8 spaces, but found 4.
Loading history...
385
        'update_date' => \Doctrine\DBAL\Types\Type::DATETIME,
386
    ]);
387
}
388
389
function updatePermissions($argv)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "updatePermissions" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
390
{
391
    $finder = \Symfony\Component\Finder\Finder::create();
392
    $finder
393
        ->in('html')->notName('.htaccess')
394
        ->in('app')->notName('console');
395
396
    $verbose = false;
397
    if (in_array('-V', $argv) || in_array('--verbose', $argv)) {
398
        $verbose = true;
399
    }
400
    foreach ($finder as $content) {
401
        $permission = $content->getPerms();
402
        // see also http://www.php.net/fileperms
403
        if (!($permission & 0x0010) || !($permission & 0x0002)) {
404
            $realPath = $content->getRealPath();
405
            if ($verbose) {
406
                out(sprintf('%s %s to ', $realPath, substr(sprintf('%o', $permission), -4)), 'info', false);
407
            }
408
            $permission = !($permission & 0x0020) ? $permission += 040 : $permission; // g+r
409
            $permission = !($permission & 0x0010) ? $permission += 020 : $permission; // g+w
410
            $permission = !($permission & 0x0004) ? $permission += 04 : $permission;  // o+r
411
            $permission = !($permission & 0x0002) ? $permission += 02 : $permission;  // o+w
412
            $result = chmod($realPath, $permission);
413
            if ($verbose) {
414
                if ($result) {
415
                    out(substr(sprintf('%o', $permission), -4), 'info');
416
                } else {
417
                    out('failure', 'error');
418
                }
419
            }
420
        }
421
    }
422
}
423
424
function copyConfigFiles()
0 ignored issues
show
Coding Style introduced by
Consider putting global function "copyConfigFiles" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
425
{
426
    $src = __DIR__.'/src/Eccube/Resource/config';
427
    $dist = __DIR__.'/app/config/eccube';
428
    $fs = new \Symfony\Component\Filesystem\Filesystem();
429
    $fs->mirror($src, $dist, null, ['override' => true]);
430
}
431
432
function createEnvFile()
0 ignored issues
show
Coding Style introduced by
Consider putting global function "createEnvFile" in a static class
Loading history...
introduced by
Missing function doc comment
Loading history...
433
{
434
    $content = '';
435
    foreach (array_keys(getExampleVariables()) as $key) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
436
437
        // 環境変数が未定義の場合はスキップ.
438
        $value = getenv($key);
439
        if ($value === false) {
440
            continue;
441
        }
442
        // インストール時のみ必要な環境はスキップ.
443
        $installOnly = ['ADMIN_USER', 'ADMIN_MAIL', 'SHOP_NAME'];
444
        if (in_array($key, $installOnly)) {
445
            continue;
446
        }
447
        $value = env($key);
448
        if ($value === true) {
449
            $value = 'true';
450
        }
451
        if ($value === false) {
452
            $value = 'false';
453
        }
454
        if ($value === null) {
455
            $value = 'null';
456
        }
457
        if (is_array($value)) {
458
            $value = json_encode($value);
459
        }
460
        $content .= sprintf('%s=%s', $key, $value).PHP_EOL;
461
    }
462
463
    $content .= 'ECCUBE_INSTALL=1';
464
465
    file_put_contents(__DIR__.'/app/config/eccube/.env', $content);
466
}
467
468
/**
0 ignored issues
show
introduced by
Doc comment for parameter "$argv" missing
Loading history...
469
 * @link https://github.com/composer/windows-setup/blob/master/src/php/installer.php
470
 */
471
function setUseAnsi($argv)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "setUseAnsi" in a static class
Loading history...
472
{
473
    // --no-ansi wins over --ansi
474
    if (in_array('--no-ansi', $argv)) {
475
        define('USE_ANSI', false);
476
    } elseif (in_array('--ansi', $argv)) {
477
        define('USE_ANSI', true);
478
    } else {
479
        // On Windows, default to no ANSI, except in ANSICON and ConEmu.
480
        // Everywhere else, default to ANSI if stdout is a terminal.
481
        define(
482
            'USE_ANSI',
483
            (DIRECTORY_SEPARATOR == '\\')
484
                ? (false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI'))
485
                : (function_exists('posix_isatty') && posix_isatty(1))
486
        );
487
    }
488
}
489
490
/**
0 ignored issues
show
introduced by
Doc comment for parameter "$text" missing
Loading history...
introduced by
Doc comment for parameter "$color" missing
Loading history...
introduced by
Doc comment for parameter "$newLine" missing
Loading history...
491
 * @link https://github.com/composer/windows-setup/blob/master/src/php/installer.php
492
 */
493
function out($text, $color = null, $newLine = true)
0 ignored issues
show
Coding Style introduced by
Consider putting global function "out" in a static class
Loading history...
494
{
495
    $styles = array(
496
        'success' => "\033[0;32m%s\033[0m",
497
        'error' => "\033[31;31m%s\033[0m",
498
        'info' => "\033[33;33m%s\033[0m",
499
    );
500
    $format = '%s';
501
    if (isset($styles[$color]) && USE_ANSI) {
502
        $format = $styles[$color];
503
    }
504
    if ($newLine) {
505
        $format .= PHP_EOL;
506
    }
507
    printf($format, $text);
508
}
509