|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use Illuminate\Console\Command; |
| 6 | +use Illuminate\Support\Facades\Route; |
| 7 | +use Illuminate\Support\Str; |
| 8 | +use Spatie\Sitemap\Sitemap; |
| 9 | +use Spatie\Sitemap\Tags\Url; |
| 10 | + |
| 11 | +class SitemapGenerate extends Command |
| 12 | +{ |
| 13 | + const EXCLUDE = [ |
| 14 | + '_dusk', |
| 15 | + 'api', |
| 16 | + 'sanctum', |
| 17 | + '_ignition', |
| 18 | + 'vapor', |
| 19 | + ]; |
| 20 | + |
| 21 | + /** |
| 22 | + * The name and signature of the console command. |
| 23 | + * |
| 24 | + * @var string |
| 25 | + */ |
| 26 | + protected $signature = 'sitemap'; |
| 27 | + |
| 28 | + /** |
| 29 | + * The console command description. |
| 30 | + * |
| 31 | + * @var string |
| 32 | + */ |
| 33 | + protected $description = 'generate the sitemap for the current page'; |
| 34 | + |
| 35 | + /** |
| 36 | + * Execute the console command. |
| 37 | + * |
| 38 | + * @return int |
| 39 | + */ |
| 40 | + public function handle() |
| 41 | + { |
| 42 | + $routes = array_map(function (\Illuminate\Routing\Route $route) { |
| 43 | + return $route->uri; |
| 44 | + }, (array) Route::getRoutes()->getIterator()); |
| 45 | + |
| 46 | + $sitemap = Sitemap::create(); |
| 47 | + |
| 48 | + foreach ($routes as $route) { |
| 49 | + if (! $this->shouldExcludePath($route)) { |
| 50 | + $url = 'https://mapmarker.io/'; |
| 51 | + if ($route != '/') { |
| 52 | + $url .= $route; |
| 53 | + } |
| 54 | + $sitemap->add(Url::create($url)->setPriority(1)->setChangeFrequency(Url::CHANGE_FREQUENCY_ALWAYS)); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + $sitemap->writeToFile(public_path('sitemap.xml')); |
| 59 | + |
| 60 | + return Command::SUCCESS; |
| 61 | + } |
| 62 | + |
| 63 | + protected function shouldExcludePath($route) |
| 64 | + { |
| 65 | + foreach (self::EXCLUDE as $pathToExclude) { |
| 66 | + if (Str::startsWith($route, $pathToExclude)) { |
| 67 | + return true; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return false; |
| 72 | + } |
| 73 | +} |
0 commit comments