From 89b63319477b0b96014cdc56bf21673332129622 Mon Sep 17 00:00:00 2001 From: Mark Scherer Date: Thu, 28 Nov 2024 01:13:34 +0100 Subject: [PATCH] Avoid timestamp collisions on bake. (#773) * Avoid timestamp collisions on bake. * Fix BC topic. (#776) * Fix BC topic. * Fix BC topic. * Fix Psalm. --- src/Command/BakeSimpleMigrationCommand.php | 24 +++++++++++++++++++--- src/Util/Util.php | 8 ++++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/Command/BakeSimpleMigrationCommand.php b/src/Command/BakeSimpleMigrationCommand.php index 879ee237..8c75c9f0 100644 --- a/src/Command/BakeSimpleMigrationCommand.php +++ b/src/Command/BakeSimpleMigrationCommand.php @@ -44,6 +44,13 @@ abstract class BakeSimpleMigrationCommand extends SimpleBakeCommand */ protected ?ConsoleIo $io = null; + /** + * Arguments + * + * @var \Cake\Console\Arguments|null + */ + protected ?Arguments $args = null; + /** * @inheritDoc */ @@ -58,8 +65,17 @@ public function name(): string public function fileName($name): string { $name = $this->getMigrationName($name); + $timestamp = Util::getCurrentTimestamp(); + $suffix = '_' . Inflector::camelize($name) . '.php'; + + /** @psalm-suppress PossiblyNullArgument */ + $path = $this->getPath($this->args); + $offset = 0; + while (glob($path . $timestamp . '_*\\.php')) { + $timestamp = Util::getCurrentTimestamp(++$offset); + } - return Util::getCurrentTimestamp() . '_' . Inflector::camelize($name) . '.php'; + return $timestamp . $suffix; } /** @@ -100,6 +116,7 @@ public function execute(Arguments $args, ConsoleIo $io): ?int public function bake(string $name, Arguments $args, ConsoleIo $io): void { $this->io = $io; + $this->args = $args; $migrationWithSameName = glob($this->getPath($args) . '*_' . $name . '.php'); if (!empty($migrationWithSameName)) { $force = $args->getOption('force'); @@ -128,10 +145,11 @@ public function bake(string $name, Arguments $args, ConsoleIo $io): void $renderer->set($this->templateData($args)); $contents = $renderer->generate($this->template()); - $filename = $this->getPath($args) . $this->fileName($name); + $path = $this->getPath($args); + $filename = $path . $this->fileName($name); $this->createFile($filename, $contents, $args, $io); - $emptyFile = $this->getPath($args) . '.gitkeep'; + $emptyFile = $path . '.gitkeep'; $this->deleteEmptyFile($emptyFile, $io); } diff --git a/src/Util/Util.php b/src/Util/Util.php index f24a8f86..32612b09 100644 --- a/src/Util/Util.php +++ b/src/Util/Util.php @@ -57,9 +57,13 @@ class Util * * @return string */ - public static function getCurrentTimestamp(): string + public static function getCurrentTimestamp(?int $offset = null): string { - $dt = new DateTime('now', new DateTimeZone('UTC')); + $time = 'now'; + if ($offset) { + $time = '+' . $offset . ' seconds'; + } + $dt = new DateTime($time, new DateTimeZone('UTC')); return $dt->format(static::DATE_FORMAT); }