Add check for duplicate migrations names when loading migrations

[MAILPOET-5416]
This commit is contained in:
Rostislav Wolny
2023-07-24 15:26:52 +02:00
committed by Aschepikov
parent ec8b5260dd
commit 725d81077f
5 changed files with 46 additions and 1 deletions

View File

@ -18,6 +18,12 @@ class MigratorException extends InvalidStateException {
);
}
public static function duplicateMigrationNames(array $names): self {
return self::create()->withMessage(
sprintf('Duplicate migration names are not allowed. Duplicate names found: "%s".', join(', ', $names))
);
}
public static function migrationFileWriteFailed(string $path): self {
return self::create()->withMessage(
sprintf('Could not write migration file "%s".', $path)

View File

@ -55,10 +55,15 @@ class Repository {
* @return array<array{level: string, name: string}>
*/
public function loadAll(): array {
return array_merge(
$migrations = array_merge(
$this->loadForLevel(self::MIGRATIONS_LEVEL_DB),
$this->loadForLevel(self::MIGRATIONS_LEVEL_APP)
);
$duplicateNames = array_diff_assoc(array_column($migrations, 'name'), array_unique(array_column($migrations, 'name')));
if (!empty($duplicateNames)) {
throw MigratorException::duplicateMigrationNames($duplicateNames);
}
return $migrations;
}
private function loadForLevel(string $level): array {

View File

@ -59,6 +59,18 @@ class RepositoryTest extends MailPoetUnitTest {
$repository->create('abc');
}
public function testItFailsWhenThereAreMigrationsWithDuplicateNames(): void {
$migrationsDir = __DIR__ . '/TestMigrationsDuplicates';
$repository = $this->make(Repository::class, [
'migrationsDir' => $migrationsDir,
'templateFile' => self::TEMPLATE_FILE,
]);
$this->expectException(MigratorException::class);
$this->expectExceptionMessage('Duplicate migration names are not allowed. Duplicate names found: "MigrationDuplicate".');
$repository->loadAll();
}
public function testItLoadsMigrationFiles(): void {
$repository = $this->make(Repository::class, [
'migrationsDir' => __DIR__ . '/TestMigrations',

View File

@ -0,0 +1,11 @@
<?php declare(strict_types = 1);
namespace MailPoet\Migrations\App;
use MailPoet\Migrator\AppMigration;
//phpcs:disable Squiz.Classes.ValidClassName.NotCamelCaps
class MigrationDuplicate extends AppMigration {
public function run(): void {
}
}

View File

@ -0,0 +1,11 @@
<?php declare(strict_types = 1);
namespace MailPoet\Migrations\Db;
use MailPoet\Migrator\DbMigration;
//phpcs:disable Squiz.Classes.ValidClassName.NotCamelCaps
class MigrationDuplicate extends DbMigration {
public function run(): void {
}
}