Skip to content

Commit 8abba55

Browse files
authored
NTO-520 reworked url caching to avoid cache-misses and bugs (#8)
1 parent 2619eaf commit 8abba55

File tree

1 file changed

+40
-10
lines changed

1 file changed

+40
-10
lines changed

lib/routing/sfRoute.class.php

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -224,16 +224,7 @@ public function generate($params, $context = [], $absolute = false)
224224
throw new InvalidArgumentException(sprintf('The "%s" route has some missing mandatory parameters (%s).', $this->pattern, implode(', ', $diff)));
225225
}
226226

227-
$elements = array_merge(
228-
[SharedCacheHelper::ROUTING_NAMESPACE],
229-
$tparams
230-
);
231-
232-
if ($absolute) {
233-
$elements[] = 'Absolute';
234-
}
235-
236-
$cache_key = SharedCacheHelper::getNamespace($elements);
227+
$cache_key = $this->generateCacheKey($tparams, $absolute);
237228
$cached = SharedCacheHelper::getValue($cache_key);
238229
if ($cached) {
239230
return $cached;
@@ -273,6 +264,45 @@ public function generate($params, $context = [], $absolute = false)
273264
return $url;
274265
}
275266

267+
/**
268+
* Generates a consistent cache key for a route
269+
*/
270+
protected function generateCacheKey(array $elements = [], bool $absolute = false): string
271+
{
272+
$elements = [
273+
SharedCacheHelper::ROUTING_NAMESPACE,
274+
$this->flattenArrayElements($elements),
275+
];
276+
277+
if ($absolute) {
278+
$elements[] = 'Absolute';
279+
}
280+
281+
return SharedCacheHelper::getNamespace($elements);
282+
}
283+
284+
/**
285+
* Recursive method to pack a key => value pair array down into a flat
286+
* numerically-indexed array, with a consistent ordering of elements.
287+
*/
288+
protected function flattenArrayElements(array $elements = []): array
289+
{
290+
$flattened = [];
291+
ksort($elements);
292+
foreach ($elements as $key => $value) {
293+
$flattened[] = $key;
294+
295+
if (is_array($value)) {
296+
$flattened[] = $this->flattenArrayElements($value);
297+
continue;
298+
}
299+
300+
$flattened[] = $value;
301+
}
302+
303+
return $flattened;
304+
}
305+
276306
static private function generateCompareVarsByStrlen($a, $b)
277307
{
278308
return strlen($a) < strlen($b);

0 commit comments

Comments
 (0)