-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHreflangHelper.php
More file actions
172 lines (150 loc) · 5.67 KB
/
HreflangHelper.php
File metadata and controls
172 lines (150 loc) · 5.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
<?php
declare(strict_types=1);
namespace App\Support;
use App\Controllers\SeoController;
/**
* Generates hreflang alternate URLs for the current page.
*
* Given the current REQUEST_URI, this class produces alternate URLs
* for every active locale so search engines and LLMs can link
* language variants together.
*/
class HreflangHelper
{
/**
* Get hreflang alternate links for the current URL.
*
* @return array<int, array{hreflang: string, href: string}>
*/
public static function getAlternates(): array
{
$locales = I18n::getAvailableLocales();
if (count($locales) < 2) {
return [];
}
$defaultLocale = I18n::getInstallationLocale();
$basePath = HtmlHelper::getBasePath();
$baseUrl = SeoController::resolveBaseUrl();
// Current request path, stripped of query string and base path
$rawUri = (string)($_SERVER['REQUEST_URI'] ?? '/');
$requestUri = strtok($rawUri, '?') ?: '/';
// Strip base path prefix
$corePath = $requestUri;
if ($basePath !== '' && str_starts_with($corePath, $basePath)) {
$corePath = substr($corePath, strlen($basePath)) ?: '/';
}
// Detect current locale from path prefix and strip it
$currentLocale = $defaultLocale;
foreach ($locales as $localeCode => $langName) {
if ($localeCode === $defaultLocale) {
continue;
}
$prefix = '/' . strtolower(substr($localeCode, 0, 2));
if ($corePath === $prefix || str_starts_with($corePath, $prefix . '/')) {
$currentLocale = $localeCode;
$corePath = substr($corePath, strlen($prefix)) ?: '/';
break;
}
}
// Build reverse map: translated path => route key (from default locale)
$reverseMap = self::buildReverseMap($locales, $currentLocale);
// Try to match corePath against known routes
$matchedKey = null;
$suffix = '';
foreach ($reverseMap as $routePath => $routeKey) {
if ($corePath === $routePath) {
$matchedKey = $routeKey;
$suffix = '';
break;
}
// Prefix match for entity routes (e.g. /autore/Name or /eventi/slug)
if (str_starts_with($corePath, $routePath . '/')) {
$matchedKey = $routeKey;
$suffix = substr($corePath, strlen($routePath));
break;
}
}
$alternates = [];
foreach ($locales as $localeCode => $langName) {
$langCode = strtolower(substr($localeCode, 0, 2));
$localePrefix = ($localeCode === $defaultLocale) ? '' : '/' . $langCode;
if ($matchedKey !== null) {
$translatedPath = RouteTranslator::getRouteForLocale($matchedKey, $localeCode);
$fullPath = $localePrefix . $translatedPath . $suffix;
} else {
// No known route matched — keep path as-is, just swap prefix
$fullPath = $localePrefix . $corePath;
}
$alternates[] = [
'hreflang' => $langCode,
'href' => $baseUrl . $fullPath,
];
}
// Add x-default pointing to the default locale version
$defaultLangCode = strtolower(substr($defaultLocale, 0, 2));
foreach ($alternates as $alt) {
if ($alt['hreflang'] === $defaultLangCode) {
$alternates[] = [
'hreflang' => 'x-default',
'href' => $alt['href'],
];
break;
}
}
return $alternates;
}
/**
* Build a reverse map from translated route path => route key
* for the current locale, sorted longest-first for greedy matching.
*
* @param array<string, string> $locales
* @return array<string, string> path => route key
*/
private static function buildReverseMap(array $locales, string $currentLocale): array
{
$reverseMap = [];
// Get all route keys from JSON + fallback
$allKeys = self::getAllRouteKeys();
foreach ($allKeys as $key) {
$path = RouteTranslator::getRouteForLocale($key, $currentLocale);
// Only map leaf routes, skip API/internal routes
if (str_starts_with($path, '/api/') || str_starts_with($path, '/admin/')) {
continue;
}
$reverseMap[$path] = $key;
}
// Sort by path length descending (longest first for greedy prefix matching)
uksort($reverseMap, function (string $a, string $b): int {
return strlen($b) <=> strlen($a);
});
return $reverseMap;
}
/**
* Get all route keys from JSON files + fallback routes.
*
* @return array<int, string>
*/
private static function getAllRouteKeys(): array
{
$keys = RouteTranslator::getAvailableKeys();
// Also scan JSON files for keys not in fallbackRoutes (e.g. "events")
$localeDir = __DIR__ . '/../../locale';
$pattern = $localeDir . '/routes_*.json';
foreach (glob($pattern) ?: [] as $file) {
$content = file_get_contents($file);
if ($content === false) {
continue;
}
$decoded = json_decode($content, true);
if (!is_array($decoded)) {
continue;
}
foreach (array_keys($decoded) as $key) {
if (is_string($key) && !in_array($key, $keys, true)) {
$keys[] = $key;
}
}
}
return $keys;
}
}