Passed
Push — dbal ( f0445f...4c5c13 )
by Greg
23:09 queued 07:46
created

UpdateDatabaseSchema   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B process() 0 55 6
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
use Throwable;
33
34
use function array_map;
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::getDBALConnection()->getDatabasePlatform();
69
        $platform->registerDoctrineTypeMapping(dbType: 'enum', doctrineType: 'string');
70
71
        $schema_manager = DB::getDBALConnection()->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(diff: $schema_diff);
85
86
        // SQLite, PostgreSQL and SQL-Server all support DDL in transactions
87
        if (DB::getDBALConnection()->getDriver() instanceof AbstractMySQLDriver) {
88
            $queries = [
89
                'SET FOREIGN_KEY_CHECKS := 0',
90
                ...$queries,
91
                'SET FOREIGN_KEY_CHECKS := 1',
92
            ];
93
        } else {
94
            $queries = [
95
                'START TRANSACTION',
96
                ...$queries,
97
                'COMMIT',
98
            ];
99
        }
100
101
102
        foreach ($queries as $query) {
103
            echo '<p>', $query, ';';
0 ignored issues
show
Bug introduced by
Are you sure $query of type array|string can be used in echo? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

103
            echo '<p>', /** @scrutinizer ignore-type */ $query, ';';
Loading history...
104
            $t = microtime(true);
105
106
            try {
107
                DB::getDBALConnection()->executeStatement(sql: $query);
0 ignored issues
show
Bug introduced by
It seems like $query can also be of type array; however, parameter $sql of Doctrine\DBAL\Connection::executeStatement() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

107
                DB::getDBALConnection()->executeStatement(/** @scrutinizer ignore-type */ sql: $query);
Loading history...
108
                echo ' /* ', (int) (1000.8 * (microtime(true) - $t)), 'ms */';
109
            } catch (Throwable $ex) {
110
                echo ' <span style="color:red">', $ex->getMessage(), '</span>';
111
            }
112
            echo '</p>';
113
        }
114
115
        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...
116
117
        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...
118
    }
119
}
120