Skip to content

Commit 6997592

Browse files
refact: Clean up all UUIDs in a single loop after they’ve been collected
1 parent cdec567 commit 6997592

File tree

1 file changed

+33
-19
lines changed

1 file changed

+33
-19
lines changed

src/CLI/Commands/UUID/Duplicates.php

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,10 @@ protected static function check(CLI $cli, ModelWithContent $model, array &$uuids
2222

2323
// the UUID already exists for another model
2424
if (isset($uuids[$uuid])) {
25-
$duplicates[] = $uuid;
26-
27-
if ($cli->arg('fix') === true) {
28-
29-
// regenerate the UUID for the first model
30-
static::regenerate($uuids[$uuid]);
31-
32-
// regenerate the UUID for this model
33-
static::regenerate($model);
34-
35-
$cli->out('✅ The duplicate UUID ' . $uuid . ' for ' . $model->id() . ' has been regenerated');
36-
} else {
37-
$cli->error('The UUID ' . $uuid . ' for ' . $model->id() . ' exists (' . $uuids[$uuid] . ')');
38-
}
25+
// add this model and the one with the duplicate uuid
26+
// to the duplicates array to clean them up later
27+
$duplicates[] = $model;
28+
$duplicates[] = $uuids[$uuid];
3929
}
4030

4131
$uuids[$uuid] = $model;
@@ -81,14 +71,38 @@ public static function command(CLI $cli): void
8171
}
8272
}
8373

84-
if (count($uuids) === 0) {
74+
// remove duplicates from duplicates array
75+
$duplicates = array_unique($duplicates);
76+
77+
if (count($duplicates) === 0) {
8578
$cli->success('There are no UUID duplicates');
86-
} elseif ($fix === true) {
79+
return;
80+
}
81+
82+
// go through all collected models with duplicate UUIDs
83+
// and print info or fix them.
84+
foreach ($duplicates as $model) {
85+
$uuid = $model->uuid()->toString();
86+
87+
if ($fix === true) {
88+
$model->uuid()->clear();
89+
$model->update([
90+
'uuid' => Uuid::generate()
91+
]);
92+
$model->uuid()->populate(true);
93+
$cli->out('✅ The duplicate UUID ' . $uuid . ' for ' . $model->id() . ' has been regenerated');
94+
} else {
95+
$cli->error('The UUID ' . $uuid . ' for ' . $model->id() . ' exists');
96+
}
97+
}
98+
99+
if ($fix === true) {
87100
$cli->success(count($duplicates) . ' duplicates have been fixed');
88-
} else {
89-
$cli->out(count($duplicates) . ' duplicates! You can fix them with kirby uuid:duplicates --fix');
90-
exit(1);
101+
return;
91102
}
103+
104+
$cli->out(count($duplicates) . ' duplicates! You can fix them with kirby uuid:duplicates --fix');
105+
exit(1);
92106
}
93107

94108
protected static function regenerate(ModelWithContent $model): void

0 commit comments

Comments
 (0)