Files
opentextsummaries/app/Http/Controllers/SitemapController.php
T
2025-09-20 16:47:41 +03:00

63 lines
1.8 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Book;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\URL;
class SitemapController extends Controller
{
/**
* Generate the XML sitemap.
*/
public function index(): Response
{
$urls = [];
// Static and index pages
$urls[] = [URL::to('/'), now()];
$urls[] = [URL::to('/about'), null];
$urls[] = [URL::to('/privacy'), null];
$urls[] = [URL::to('/terms'), null];
$urls[] = [URL::to('/contact'), null];
$urls[] = [URL::to('/books'), now()];
$urls[] = [URL::to('/categories'), now()];
// Individual book pages
Book::select(['slug', 'updated_at'])->orderBy('updated_at', 'desc')->chunk(500, function ($books) use (&$urls) {
foreach ($books as $book) {
$urls[] = [URL::to('/books/' . $book->slug), optional($book->updated_at)];
}
});
$xml = $this->buildXml($urls);
return response($xml, 200)->header('Content-Type', 'application/xml');
}
/**
* Build a basic XML sitemap string.
*
* @param array<int, array{0:string,1:\DateTimeInterface|null}> $urls
*/
protected function buildXml(array $urls): string
{
$xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>';
$urlsetOpen = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
$urlsetClose = '</urlset>';
$body = '';
foreach ($urls as [$loc, $lastmod]) {
$body .= "\n <url>\n";
$body .= ' <loc>' . e($loc) . "</loc>\n";
if ($lastmod) {
$body .= ' <lastmod>' . $lastmod->format('c') . "</lastmod>\n";
}
$body .= " </url>";
}
return $xmlHeader . "\n" . $urlsetOpen . $body . "\n" . $urlsetClose . "\n";
}
}