diff --git a/app/Console/Commands/GenerateSitemap.php b/app/Console/Commands/GenerateSitemap.php index f17e4d9..6e3da18 100644 --- a/app/Console/Commands/GenerateSitemap.php +++ b/app/Console/Commands/GenerateSitemap.php @@ -4,7 +4,11 @@ use App\Models\Name; use Illuminate\Console\Command; +use Illuminate\Support\Collection; +use Illuminate\Support\Str; use Spatie\Sitemap\Sitemap; +use Spatie\Sitemap\SitemapIndex; +use Spatie\Sitemap\Tags\Sitemap as SitemapTag; use Spatie\Sitemap\Tags\Url; class GenerateSitemap extends Command @@ -28,21 +32,32 @@ class GenerateSitemap extends Command */ public function handle(): void { - $sitemap = Sitemap::create(); + $sitemapIndex = SitemapIndex::create(); Name::where('name', '!=', '_PRENOMS_RARES') - ->get() - ->each(function (Name $name) use ($sitemap) { - $sitemap->add( - Url::create(route('name.show', [ - 'id' => $name->id, - 'name' => $name->name, - ])) - ->setPriority(0.9) - ->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY) - ); - }); - - $sitemap->writeToFile(public_path('sitemap.xml')); + ->chunkById(2000, function (Collection $names, int $key) use ($sitemapIndex) { + + $file = 'sitemap_' . Str::padLeft($key, 2, '0') . '.xml'; + $sitemap = Sitemap::create(); + + $names->each(function (Name $name) use ($sitemap) { + $sitemap->add( + Url::create(route('name.show', [ + 'id' => $name->id, + 'name' => Str::lower($name->name), + ])) + ->setPriority(0.9) + ->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY) + ->setLastModificationDate($name->updated_at) + ); + }); + + $sitemap->writeToFile(public_path($file)); + $sitemap = null; + + $sitemapIndex->add(SitemapTag::create(url($file))); + }, 'id'); + + $sitemapIndex->writeToFile(public_path('sitemap.xml')); } }