Failed Conditions
Pull Request — master (#919)
by Asmir
02:25
created

DbalExecutor   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 321
Duplicated Lines 0 %

Test Coverage

Coverage 93.51%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 149
c 1
b 0
f 0
dl 0
loc 321
ccs 144
cts 154
cp 0.9351
rs 9.2
wmc 40

13 Methods

Rating   Name   Duplication   Size   Complexity  
A logResult() 0 18 3
A executeResult() 0 21 4
A getExecutionStateAsString() 0 11 4
A getMigrationHeader() 0 16 3
A outputSqlQuery() 0 10 1
B executeMigration() 0 84 9
A addSql() 0 3 1
A migrationEnd() 0 22 5
A getSql() 0 3 1
A getFromSchema() 0 8 3
A execute() 0 29 3
A __construct() 0 16 1
A startMigration() 0 18 2

How to fix   Complexity   

Complex Class

Complex classes like DbalExecutor often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DbalExecutor, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations\Version;
6
7
use DateTimeImmutable;
8
use Doctrine\DBAL\Connection;
9
use Doctrine\DBAL\Schema\Schema;
10
use Doctrine\Migrations\AbstractMigration;
11
use Doctrine\Migrations\EventDispatcher;
12
use Doctrine\Migrations\Events;
13
use Doctrine\Migrations\Exception\SkipMigration;
14
use Doctrine\Migrations\Metadata\MigrationPlan;
15
use Doctrine\Migrations\Metadata\Storage\MetadataStorage;
16
use Doctrine\Migrations\MigratorConfiguration;
17
use Doctrine\Migrations\ParameterFormatter;
18
use Doctrine\Migrations\Provider\SchemaDiffProvider;
19
use Doctrine\Migrations\Query\Query;
20
use Doctrine\Migrations\Stopwatch;
21
use Doctrine\Migrations\Tools\BytesFormatter;
22
use Psr\Log\LoggerInterface;
23
use Throwable;
24
use function count;
25
use function ucfirst;
26
27
/**
28
 * The DbalExecutor class is responsible for executing a single migration version.
29
 *
30
 * @internal
31
 */
32
final class DbalExecutor implements Executor
33
{
34
    /** @var Connection */
35
    private $connection;
36
37
    /** @var SchemaDiffProvider */
38
    private $schemaProvider;
39
40
    /** @var ParameterFormatter */
41
    private $parameterFormatter;
42
43
    /** @var Stopwatch */
44
    private $stopwatch;
45
46
    /** @var Query[] */
47
    private $sql = [];
48
49
    /** @var MetadataStorage */
50
    private $metadataStorage;
51
52
    /** @var LoggerInterface */
53
    private $logger;
54
55
    /** @var EventDispatcher */
56
    private $dispatcher;
57
58 13
    public function __construct(
59
        MetadataStorage $metadataStorage,
60
        EventDispatcher $dispatcher,
61
        Connection $connection,
62
        SchemaDiffProvider $schemaProvider,
63
        LoggerInterface $logger,
64
        ParameterFormatter $parameterFormatter,
65
        Stopwatch $stopwatch
66
    ) {
67 13
        $this->connection         = $connection;
68 13
        $this->schemaProvider     = $schemaProvider;
69 13
        $this->parameterFormatter = $parameterFormatter;
70 13
        $this->stopwatch          = $stopwatch;
71 13
        $this->metadataStorage    = $metadataStorage;
72 13
        $this->logger             = $logger;
73 13
        $this->dispatcher         = $dispatcher;
74 13
    }
75
76
    /**
77
     * @return Query[]
78
     */
79 1
    public function getSql() : array
80
    {
81 1
        return $this->sql;
82
    }
83
84 9
    public function addSql(Query $sqlQuery) : void
85
    {
86 9
        $this->sql[] = $sqlQuery;
87 9
    }
88
89 11
    public function execute(
90
        MigrationPlan $plan,
91
        MigratorConfiguration $configuration
92
    ) : ExecutionResult {
93 11
        $result = new ExecutionResult($plan->getVersion(), $plan->getDirection(), new DateTimeImmutable());
94
95 11
        $this->startMigration($plan, $configuration);
96
97
        try {
98 11
            $this->executeMigration(
99 11
                $plan,
100 11
                $result,
101 11
                $configuration
102
            );
103
104 7
            $result->setSql($this->sql);
105 4
        } catch (SkipMigration $e) {
106 1
            $result->setSkipped(true);
107
108 1
            $this->migrationEnd($e, $plan, $result, $configuration);
109 3
        } catch (Throwable $e) {
110 3
            $result->setError(true, $e);
111
112 3
            $this->migrationEnd($e, $plan, $result, $configuration);
113
114 3
            throw $e;
115
        }
116
117 8
        return $result;
118
    }
119
120 11
    private function startMigration(
121
        MigrationPlan $plan,
122
        MigratorConfiguration $configuration
123
    ) : void {
124 11
        $this->sql = [];
125
126 11
        $this->dispatcher->dispatchVersionEvent(
127 11
            Events::onMigrationsVersionExecuting,
128 11
            $plan,
129 11
            $configuration
130
        );
131
132 11
        if (! $plan->getMigration()->isTransactional()) {
133
            return;
134
        }
135
136
        // only start transaction if in transactional mode
137 11
        $this->connection->beginTransaction();
138 11
    }
139
140 11
    private function executeMigration(
141
        MigrationPlan $plan,
142
        ExecutionResult $result,
143
        MigratorConfiguration $configuration
144
    ) : ExecutionResult {
145 11
        $stopwatchEvent = $this->stopwatch->start('execute');
146
147 11
        $migration = $plan->getMigration();
148 11
        $direction = $plan->getDirection();
149
150 11
        $result->setState(State::PRE);
151
152 11
        $fromSchema = $this->getFromSchema($configuration);
153
154 11
        $migration->{'pre' . ucfirst($direction)}($fromSchema);
155
156 11
        $this->logger->info(...$this->getMigrationHeader($plan, $migration, $direction));
0 ignored issues
show
Bug introduced by
It seems like $this->getMigrationHeade...$migration, $direction) can also be of type array<string,string>; however, parameter $message of Psr\Log\LoggerInterface::info() 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

156
        $this->logger->info(/** @scrutinizer ignore-type */ ...$this->getMigrationHeader($plan, $migration, $direction));
Loading history...
157
158 11
        $result->setState(State::EXEC);
159
160 11
        $toSchema = $this->schemaProvider->createToSchema($fromSchema);
161
162 11
        $result->setToSchema($toSchema);
163
164 11
        $migration->$direction($toSchema);
165
166 8
        foreach ($migration->getSql() as $sqlQuery) {
167 8
            $this->addSql($sqlQuery);
168
        }
169
170 8
        foreach ($this->schemaProvider->getSqlDiffToMigrate($fromSchema, $toSchema) as $sql) {
171
            $this->addSql(new Query($sql));
172
        }
173
174 8
        if (count($this->sql) !== 0) {
175 8
            if (! $configuration->isDryRun()) {
176 8
                $this->executeResult($configuration);
177
            } else {
178 8
                foreach ($this->sql as $query) {
179
                    $this->outputSqlQuery($query);
180
                }
181
            }
182
        } else {
183
            $this->logger->warning('Migration {version} was executed but did not result in any SQL statements.', [
184
                'version' => (string) $plan->getVersion(),
185
            ]);
186
        }
187
188 8
        $result->setState(State::POST);
189
190 8
        $migration->{'post' . ucfirst($direction)}($toSchema);
191 8
        $stopwatchEvent->stop();
192
193 8
        $result->setTime((float) $stopwatchEvent->getDuration());
194 8
        $result->setMemory($stopwatchEvent->getMemory());
195
196
        $params = [
197 8
            'version' => (string) $plan->getVersion(),
198 8
            'time' => $stopwatchEvent->getDuration(),
199 8
            'memory' => BytesFormatter::formatBytes($stopwatchEvent->getMemory()),
200 8
            'direction' => $direction === Direction::UP ? 'migrated' : 'reverted',
201
        ];
202
203 8
        $this->logger->info('Migration {version} {direction} (took {time}ms, used {memory} memory)', $params);
204
205 8
        if (! $configuration->isDryRun()) {
206 8
            $this->metadataStorage->complete($result);
207
        }
208
209 7
        if ($migration->isTransactional()) {
210
            //commit only if running in transactional mode
211 7
            $this->connection->commit();
212
        }
213
214 7
        $plan->markAsExecuted($result);
215 7
        $result->setState(State::NONE);
216
217 7
        $this->dispatcher->dispatchVersionEvent(
218 7
            Events::onMigrationsVersionExecuted,
219 7
            $plan,
220 7
            $configuration
221
        );
222
223 7
        return $result;
224
    }
225
226
    /**
227
     * @return mixed[]
228
     */
229 11
    private function getMigrationHeader(MigrationPlan $planItem, AbstractMigration $migration, string $direction) : array
230
    {
231 11
        $versionInfo = (string) $planItem->getVersion();
232 11
        $description = $migration->getDescription();
233
234 11
        if ($description !== '') {
235 1
            $versionInfo .= ' (' . $description . ')';
236
        }
237
238 11
        $params = ['version_name' => $versionInfo];
239
240 11
        if ($direction === Direction::UP) {
241 9
            return ['++ migrating {version_name}', $params];
242
        }
243
244 2
        return ['++ reverting {version_name}', $params];
245
    }
246
247 4
    private function migrationEnd(Throwable $e, MigrationPlan $plan, ExecutionResult $result, MigratorConfiguration $configuration) : void
248
    {
249 4
        $migration = $plan->getMigration();
250 4
        if ($migration->isTransactional()) {
251
            //only rollback transaction if in transactional mode
252 4
            $this->connection->rollBack();
253
        }
254
255 4
        $plan->markAsExecuted($result);
256 4
        $this->logResult($e, $result, $plan);
257
258 4
        $this->dispatcher->dispatchVersionEvent(
259 4
            Events::onMigrationsVersionSkipped,
260 4
            $plan,
261 4
            $configuration
262
        );
263
264 4
        if ($configuration->isDryRun() || $result->isSkipped() || $result->hasError()) {
265 4
            return;
266
        }
267
268
        $this->metadataStorage->complete($result);
269
    }
270
271 4
    private function logResult(Throwable $e, ExecutionResult $result, MigrationPlan $plan) : void
272
    {
273 4
        if ($result->isSkipped()) {
274 1
            $this->logger->error(
275 1
                'Migration {version} skipped during {state}. Reason: "{reason}"',
276
                [
277 1
                    'version' => (string) $plan->getVersion(),
278 1
                    'reason' => $e->getMessage(),
279 1
                    'state' => $this->getExecutionStateAsString($result->getState()),
280
                ]
281
            );
282 3
        } elseif ($result->hasError()) {
283 3
            $this->logger->error(
284 3
                'Migration {version} failed during {state}. Error: "{error}"',
285
                [
286 3
                    'version' => (string) $plan->getVersion(),
287 3
                    'error' => $e->getMessage(),
288 3
                    'state' => $this->getExecutionStateAsString($result->getState()),
289
                ]
290
            );
291
        }
292 4
    }
293
294 8
    private function executeResult(MigratorConfiguration $configuration) : void
295
    {
296 8
        foreach ($this->sql as $key => $query) {
297 8
            $stopwatchEvent = $this->stopwatch->start('query');
298
299 8
            $this->outputSqlQuery($query);
300
301 8
            if (count($query->getParameters()) === 0) {
302 6
                $this->connection->executeQuery($query->getStatement());
303
            } else {
304 6
                $this->connection->executeQuery($query->getStatement(), $query->getParameters(), $query->getTypes());
305
            }
306
307 8
            $stopwatchEvent->stop();
308
309 8
            if (! $configuration->getTimeAllQueries()) {
310 2
                continue;
311
            }
312
313 6
            $this->logger->debug('{duration}ms', [
314 6
                'duration' => $stopwatchEvent->getDuration(),
315
            ]);
316
        }
317 8
    }
318
319 8
    private function outputSqlQuery(Query $query) : void
320
    {
321 8
        $params = $this->parameterFormatter->formatParameters(
322 8
            $query->getParameters(),
323 8
            $query->getTypes()
324
        );
325
326 8
        $this->logger->debug('{query} {params}', [
327 8
            'query' => $query->getStatement(),
328 8
            'params' => $params,
329
        ]);
330 8
    }
331
332 11
    private function getFromSchema(MigratorConfiguration $configuration) : Schema
333
    {
334
        // if we're in a dry run, use the from Schema instead of reading the schema from the database
335 11
        if ($configuration->isDryRun() && $configuration->getFromSchema() !== null) {
336
            return $configuration->getFromSchema();
337
        }
338
339 11
        return $this->schemaProvider->createFromSchema();
340
    }
341
342 4
    private function getExecutionStateAsString(int $state) : string
343
    {
344
        switch ($state) {
345 4
            case State::PRE:
346
                return 'Pre-Checks';
347 4
            case State::POST:
348 1
                return 'Post-Checks';
349 3
            case State::EXEC:
350 3
                return 'Execution';
351
            default:
352
                return 'No State';
353
        }
354
    }
355
}
356