Skip to content

Commit

Permalink
refactor: add logs to sitemap generator (#54)
Browse files Browse the repository at this point in the history
Co-authored-by: Mazarin <[email protected]>
  • Loading branch information
asbiin and djaiss authored Feb 20, 2024
1 parent 6316fa6 commit b52cd93
Showing 1 changed file with 37 additions and 12 deletions.
49 changes: 37 additions & 12 deletions app/Console/Commands/GenerateSitemap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']));
}

/**
Expand All @@ -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),
];
}
}

0 comments on commit b52cd93

Please sign in to comment.