Passed
Push — dbal ( 23f922...9cad68 )
by Greg
15:01
created

UpdateDatabaseSchema::process()   C

Complexity

Conditions 12
Paths 126

Size

Total Lines 64
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 40
nc 126
nop 2
dl 0
loc 64
rs 6.75
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2023 webtrees development team
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Http\Middleware;
21
22
use Doctrine\DBAL\Driver\AbstractMySQLDriver;
23
use Fisharebest\Webtrees\DB;
24
use Fisharebest\Webtrees\DB\WebtreesSchema;
25
use Fisharebest\Webtrees\Services\MigrationService;
26
use Fisharebest\Webtrees\Webtrees;
27
use PDO;
28
use Psr\Http\Message\ResponseInterface;
29
use Psr\Http\Message\ServerRequestInterface;
30
use Psr\Http\Server\MiddlewareInterface;
31
use Psr\Http\Server\RequestHandlerInterface;
32
33
use Throwable;
34
35
use function implode;
36
use function microtime;
37
use function str_contains;
38
use function usort;
39
40
/**
41
 * Middleware to update the database automatically, after an upgrade.
42
 */
43
class UpdateDatabaseSchema implements MiddlewareInterface
44
{
45
    private MigrationService $migration_service;
46
47
    /**
48
     * @param MigrationService $migration_service
49
     */
50
    public function __construct(MigrationService $migration_service)
51
    {
52
        $this->migration_service = $migration_service;
53
    }
54
55
    /**
56
     * Update the database schema, if necessary.
57
     *
58
     * @param ServerRequestInterface  $request
59
     * @param RequestHandlerInterface $handler
60
     *
61
     * @return ResponseInterface
62
     */
63
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
64
    {
65
        $this->migration_service
66
            ->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
67
68
        $platform = DB::connection()->getDatabasePlatform();
69
        $platform->registerDoctrineTypeMapping(dbType: 'enum', doctrineType: 'string');
70
71
        $schema_manager = DB::connection()->createSchemaManager();
72
        $comparator     = $schema_manager->createComparator();
73
        $source         = $schema_manager->introspectSchema();
74
        $target         = WebtreesSchema::schema();
75
76
        // doctrine/dbal 4.0 does not have the concept of "saveSQL"
77
        foreach ($source->getTables() as $table) {
78
            if (!$target->hasTable($table->getName())) {
79
                $source->dropTable($table->getName());
80
            }
81
        }
82
83
        $schema_diff    = $comparator->compareSchemas(oldSchema: $source, newSchema: $target);
84
        $queries        = $platform->getAlterSchemaSQL($schema_diff);
85
86
        foreach ($target->getTables() as $table) {
87
            foreach ($table->getForeignKeys() as $foreign_key) {
88
                $queries[] =
89
                    'DELETE FROM ' . $table->getName() .
90
                    ' WHERE (' . implode(', ', $foreign_key->getLocalColumns()) . ')' .
91
                    ' NOT IN (SELECT ' . implode(', ', $foreign_key->getForeignColumns()) . ' FROM ' . $foreign_key->getForeignTableName() . ')';
92
            }
93
        }
94
95
        // SQLite, PostgreSQL and SQL-Server all support DDL in transactions
96
        if (DB::connection()->getDriver() instanceof AbstractMySQLDriver) {
97
            $phase = fn (string $query): int => str_contains($query, 'DROP FOREIGN KEY') ? 1 : (str_contains($query, 'FOREIGN KEY') ? 3 : 2);
98
            usort($queries, fn (string $x, string $y): int => $phase($x) <=> $phase($y));
99
        } else {
100
            $queries = [
101
                'START TRANSACTION',
102
                ...$queries,
103
                'COMMIT',
104
            ];
105
        }
106
107
        foreach ($queries as $query) {
108
            if (str_contains($query, 'RENAME INDEX')) {
109
                echo '<p><i>', $query, ';</i></p>';
110
            } elseif (str_contains($query, 'CHANGE')) {
111
                echo '<p><b>', $query, ';</b></p>';
112
            } else {
113
                echo '<p>', $query, ';</p>';
114
            }
115
            try {
116
                //$t = microtime(true);
117
                DB::connection()->executeStatement($query);
118
                //echo '<p>', (int) (1000.8 * (microtime(true) - $t)), 'ms</p>';
119
            } catch (Throwable $ex) {
120
                echo '<p style="color:red">', $ex->getMessage(), ';</p>';
121
            }
122
        }
123
124
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
125
126
        return $handler->handle($request);
0 ignored issues
show
Unused Code introduced by
return $handler->handle($request) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
127
    }
128
}
129