Skip to content

Commit

Permalink
Added a simple token migration for dashes
Browse files Browse the repository at this point in the history
  • Loading branch information
Toflar committed Jan 15, 2025
1 parent a1ddb2c commit 1495807
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
7 changes: 7 additions & 0 deletions config/migrations.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Terminal42\NotificationCenterBundle\Migration\EmailGatewayMigration;
use Terminal42\NotificationCenterBundle\Migration\MailerTransportMigration;
use Terminal42\NotificationCenterBundle\Migration\SimpleTokenMigration;

return static function (ContainerConfigurator $container): void {
$services = $container->services();
Expand All @@ -22,4 +23,10 @@
service('database_connection'),
])
;

$services->set(SimpleTokenMigration::class)
->args([
service('database_connection'),
])
;
};
68 changes: 68 additions & 0 deletions src/Migration/SimpleTokenMigration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

namespace Terminal42\NotificationCenterBundle\Migration;

use Contao\CoreBundle\Migration\AbstractMigration;
use Contao\CoreBundle\Migration\MigrationResult;
use Doctrine\DBAL\Connection;

class SimpleTokenMigration extends AbstractMigration
{
private const REGEX = '/##([a-zA-Z0-9_]+-[a-zA-Z0-9_-]*)##/';

public function __construct(private readonly Connection $connection)
{
}

public function shouldRun(): bool
{
$schemaManager = $this->connection->createSchemaManager();

if (!$schemaManager->tablesExist(['tl_nc_language'])) {
return false;
}

return [] !== $this->getRowsToUpdate();
}

public function run(): MigrationResult
{
foreach ($this->getRowsToUpdate() as $rowId => $columns) {
$rows = $this->connection->fetchAssociative('SELECT '.implode(',', $columns).' FROM tl_nc_language WHERE id=?', [$rowId]);
$set = [];

foreach ($rows as $column => $value) {
$set[$column] = preg_replace_callback(
self::REGEX,
static fn ($matches) => '##'.str_replace('-', '_', $matches[1]).'##',
$value,
);
}

$this->connection->update('tl_nc_language', $set, ['id' => $rowId]);
}

return $this->createResult(true);
}

private function getRowsToUpdate(): array
{
$rowsToUpdate = [];

foreach ($this->connection->fetchAllAssociative('SELECT * FROM tl_nc_language') as $row) {
foreach ($row as $column => $value) {
if (!\is_string($value)) {
continue;
}

if (preg_match(self::REGEX, $value)) {
$rowsToUpdate[$row['id']][] = $this->connection->quoteIdentifier($column);
}
}
}

return $rowsToUpdate;
}
}

0 comments on commit 1495807

Please sign in to comment.