Skip to content

Instantly share code, notes, and snippets.

@Mfalm3
Forked from duncanmcclean/console.php
Created October 25, 2021 09:27
Show Gist options
  • Save Mfalm3/4ff29e7d00aa08aa90c9d2ca2f4ae460 to your computer and use it in GitHub Desktop.
Save Mfalm3/4ff29e7d00aa08aa90c9d2ca2f4ae460 to your computer and use it in GitHub Desktop.
Identify & fix Duplicate IDs in Statamic 3.

Duplicate ID Identifier & Fixer for Statamic 3

Instructions:

  • Copy the contents of this gist's console.php into routes/console.php
  • Run php artisan identify-duplicates

At the start of the script, it will ask you if you want to replace any identied duplicate IDs. If you choose to do so, new Stache IDs will be generated and the Laravel cache will be cleared.

<?php // copy everything after this line
Artisan::command('identify-duplicates', function () {
$duplicates = [];
$shouldFixDuplicates = $this->confirm('Should Duplicate IDs be replaced with fresh IDs?');
$items = collect(\Illuminate\Support\Facades\File::allFiles(__DIR__.'/../content'))
->filter(function ($file) {
return $file->isFile();
})
->map(function (SplFileInfo $file) {
$data = \Statamic\Facades\YAML::parse(file_get_contents($file->getRealPath()));
return [
'path' => $file->getRealPath(),
'stache_id' => isset($data['id']) ? $data['id'] : null,
];
})
->reject(function ($item) {
return is_null($item['stache_id']);
});
$items->each(function ($item) use (&$duplicates, $items) {
$itemsWithCurrentId = $items->where('stache_id', $item['stache_id']);
if ($itemsWithCurrentId->count() > 1) {
if (array_key_exists($item['stache_id'], $duplicates)) {
$duplicates[$item['stache_id']] = array_merge($duplicates[$item['stache_id']], [
$item['path'],
]);
} else {
$duplicates[$item['stache_id']] = [
$item['path'],
];
}
}
});
foreach ($duplicates as $id => $items) {
$this->error("Duplicate ID Found: {$id}");
foreach ($items as $item) {
$this->line($item);
if ($shouldFixDuplicates) {
$contents = file_get_contents($item);
$contents = str_replace($id, \Statamic\Facades\Stache::generateId(), $contents);
file_put_contents($item, $contents);
}
}
$this->line('');
}
if ($shouldFixDuplicates) {
Artisan::call('cache:clear');
$this->info('Duplicate IDs have been replaced and your Cache has been cleared. Have a good day!');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment