From b52cd9381f975f0e715335f27a572ae5f6b413a1 Mon Sep 17 00:00:00 2001 From: Alexis Saettler Date: Tue, 20 Feb 2024 04:45:16 +0100 Subject: [PATCH] refactor: add logs to sitemap generator (#54) Co-authored-by: Mazarin --- app/Console/Commands/GenerateSitemap.php | 49 ++++++++++++++++++------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/app/Console/Commands/GenerateSitemap.php b/app/Console/Commands/GenerateSitemap.php index 6583c19..b05698b 100644 --- a/app/Console/Commands/GenerateSitemap.php +++ b/app/Console/Commands/GenerateSitemap.php @@ -35,21 +35,32 @@ class GenerateSitemap extends Command */ public function handle(): void { + $file = $this->file('sitemap.xml'); + $sitemapIndex = SitemapIndex::create(); + $this->sitemap_root($sitemapIndex); + $this->sitemap_names($sitemapIndex); + $sitemapIndex->writeToFile($file['file']); - SitemapGenerator::create(config('app.url')) - ->writeToFile(public_path(static::PREFIX_PATH . '/sitemap_00.xml')); + // Replace sitemap in robots.txt + $robots = public_path('robots.txt'); + $content = Str::of(File::get($robots)) + ->replaceMatches('/Sitemap: .*/', 'Sitemap: ' . $file['url']); - $sitemapIndex->add(SitemapTag::create(url(static::PREFIX_PATH . '/sitemap_00.xml'))); + File::put($robots, $content); + } - $this->sitemap_names($sitemapIndex); + /** + * Get root sitemap. + */ + private function sitemap_root(SitemapIndex $sitemapIndex): void + { + $file = $this->file('sitemap_00.xml'); - $sitemapIndex->writeToFile(public_path(static::PREFIX_PATH . '/sitemap.xml')); + SitemapGenerator::create(config('app.url')) + ->writeToFile($file['file']); - // Replace sitemap in robots.txt - $robots = File::get(public_path('robots.txt')); - $robots = Str::of($robots)->replaceMatches('/Sitemap: .*/', 'Sitemap: ' . url(static::PREFIX_PATH . '/sitemap.xml')); - File::put(public_path('robots.txt'), $robots); + $sitemapIndex->add(SitemapTag::create($file['url'])); } /** @@ -60,13 +71,27 @@ private function sitemap_names(SitemapIndex $sitemapIndex): void Name::where('name', '!=', '_PRENOMS_RARES') ->chunkById(2000, function (Collection $names, int $key) use ($sitemapIndex) { - $file = static::PREFIX_PATH . '/sitemap_' . Str::padLeft("$key", 2, '0') . '.xml'; + $file = $this->file('sitemap_' . Str::padLeft("$key", 2, '0') . '.xml'); Sitemap::create() ->add($names) - ->writeToFile(public_path($file)); + ->writeToFile($file['file']); - $sitemapIndex->add(SitemapTag::create(url($file))); + $sitemapIndex->add(SitemapTag::create($file['url'])); }, 'id'); } + + /** + * Get file path and url. + */ + private function file(string $name): array + { + $file = public_path(static::PREFIX_PATH . '/' . $name); + $this->line("$file ..."); + + return [ + 'file' => $file, + 'url' => url(static::PREFIX_PATH . '/' . $name), + ]; + } }