| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Yatra\Sitemap; |
| 6 |
|
| 7 |
/** |
| 8 |
* Renders sitemaps.org XML. |
| 9 |
* |
| 10 |
* - urlset(): the consolidated /yatra-sitemap.xml document. |
| 11 |
* - indexEntries(): a single <sitemap> pointer to that file, for injecting |
| 12 |
* into an SEO plugin's sitemap index (Yoast, Rank Math). |
| 13 |
* |
| 14 |
* Pure string output — no I/O, no platform coupling. Every node is escaped. |
| 15 |
*/ |
| 16 |
class SitemapRenderer |
| 17 |
{ |
| 18 |
/** |
| 19 |
* A <urlset> document. |
| 20 |
* |
| 21 |
* @param array<int, array{loc: string, lastmod: string}> $entries |
| 22 |
*/ |
| 23 |
public function urlset(array $entries): string |
| 24 |
{ |
| 25 |
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n"; |
| 26 |
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n"; |
| 27 |
|
| 28 |
foreach ($entries as $entry) { |
| 29 |
$loc = (string) ($entry['loc'] ?? ''); |
| 30 |
if ($loc === '') { |
| 31 |
continue; |
| 32 |
} |
| 33 |
$xml .= "\t<url>\n"; |
| 34 |
$xml .= "\t\t<loc>" . esc_url($loc) . "</loc>\n"; |
| 35 |
$lastmod = (string) ($entry['lastmod'] ?? ''); |
| 36 |
if ($lastmod !== '') { |
| 37 |
$xml .= "\t\t<lastmod>" . esc_html($lastmod) . "</lastmod>\n"; |
| 38 |
} |
| 39 |
$xml .= "\t</url>\n"; |
| 40 |
} |
| 41 |
|
| 42 |
$xml .= '</urlset>' . "\n"; |
| 43 |
|
| 44 |
return $xml; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* One or more inner <sitemap> nodes — for injecting into another plugin's |
| 49 |
* sitemap index (Yoast, Rank Math) without our document wrapper. |
| 50 |
* |
| 51 |
* @param array<int, array{loc: string, lastmod: string}> $sitemaps |
| 52 |
*/ |
| 53 |
public function indexEntries(array $sitemaps): string |
| 54 |
{ |
| 55 |
$xml = ''; |
| 56 |
foreach ($sitemaps as $sitemap) { |
| 57 |
$loc = (string) ($sitemap['loc'] ?? ''); |
| 58 |
if ($loc === '') { |
| 59 |
continue; |
| 60 |
} |
| 61 |
$xml .= "\t<sitemap>\n"; |
| 62 |
$xml .= "\t\t<loc>" . esc_url($loc) . "</loc>\n"; |
| 63 |
$lastmod = (string) ($sitemap['lastmod'] ?? ''); |
| 64 |
if ($lastmod !== '') { |
| 65 |
$xml .= "\t\t<lastmod>" . esc_html($lastmod) . "</lastmod>\n"; |
| 66 |
} |
| 67 |
$xml .= "\t</sitemap>\n"; |
| 68 |
} |
| 69 |
|
| 70 |
return $xml; |
| 71 |
} |
| 72 |
} |
| 73 |
|