Skip to content

Instantly share code, notes, and snippets.

@damcclean

damcclean/console.php

Last active Jan 13, 2021
Embed
What would you like to do?
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!');
}
});
@jmartsch

This comment has been minimized.

Copy link

@jmartsch jmartsch commented Nov 25, 2020

The success message should only be triggered if there were duplicate IDs.
I also think it is better to tell the user if there are duplicate IDs and ask him then if he wants to replace them.

@damcclean

This comment has been minimized.

Copy link
Owner Author

@damcclean damcclean commented Nov 25, 2020

The success message should only be triggered if there were duplicate IDs.
I also think it is better to tell the user if there are duplicate IDs and ask him then if he wants to replace them.

Yeah, I might need to refactor the way that's done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.