74 lines
2.1 KiB
PHP
74 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace Modules\Sitemap\Http\Controllers;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use Illuminate\Http\Request;
|
|
use Spatie\Crawler\Crawler;
|
|
use Spatie\Sitemap\SitemapGenerator;
|
|
use Psr\Http\Message\UriInterface;
|
|
use Modules\Sitemap\Models\SitemapConfig;
|
|
|
|
class SitemapController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$path = public_path('sitemap.xml');
|
|
|
|
if (!file_exists($path)) {
|
|
return response('Sitemap not found.', 404);
|
|
}
|
|
|
|
return response()->file($path, [
|
|
'Content-Type' => 'application/xml',
|
|
]);
|
|
}
|
|
|
|
public function generate(Request $request)
|
|
{
|
|
$path = public_path('sitemap.xml');
|
|
|
|
$sitemapConfig = SitemapConfig::active()->latest()->first();
|
|
$sitemapExcludes = $sitemapConfig->sitemap_excludes;
|
|
$ignoreRobots = $sitemapConfig->ignore_robot;
|
|
|
|
if (is_string($sitemapExcludes)) {
|
|
$sitemapExcludes = array_map('trim', explode(',', $sitemapExcludes));
|
|
}
|
|
|
|
$generator = SitemapGenerator::create(config('app.url'))
|
|
->configureCrawler(function (Crawler $crawler) use ($ignoreRobots, $sitemapConfig) {
|
|
if ($ignoreRobots) {
|
|
$crawler->ignoreRobots();
|
|
}
|
|
if ($sitemapConfig->max_depth) {
|
|
$crawler->setMaximumDepth($sitemapConfig->max_depth);
|
|
}
|
|
})
|
|
->shouldCrawl(function (UriInterface $url) use ($sitemapExcludes) {
|
|
$path = $url->getPath();
|
|
foreach ($sitemapExcludes as $exclude) {
|
|
if (str_starts_with($path, $exclude)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
});
|
|
|
|
if ($sitemapConfig->max_crawl_count) {
|
|
$generator->setMaximumCrawlCount($sitemapConfig->max_crawl_count);
|
|
}
|
|
|
|
$generator->writeToFile($path);
|
|
|
|
|
|
if (!file_exists($path)) {
|
|
return response('Failed to generate sitemap.', 404);
|
|
}
|
|
|
|
return response()->file($path, [
|
|
'Content-Type' => 'application/xml',
|
|
]);
|
|
}
|
|
}
|