From 81857f48a362769a5e32f867c2df0f10f4f338e0 Mon Sep 17 00:00:00 2001 From: Alexis Saettler Date: Sun, 18 Feb 2024 21:07:44 +0100 Subject: [PATCH] fix: dix sitemap generate --- app/Console/Commands/GenerateSitemap.php | 43 ++++++++++++++++-------- 1 file changed, 29 insertions(+), 14 deletions(-) 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')); } }