Skip to content

Commit 7394837

Browse files
authored
NTO-520 reworked url caching to avoid cache-misses and bugs (#7)
1 parent 8190567 commit 7394837

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
@@ -230,16 +230,7 @@ public function generate($params, $context = [], $absolute = false)
230230
throw new InvalidArgumentException($message);
231231
}
232232

233-
$elements = array_merge(
234-
[SharedCacheHelper::ROUTING_NAMESPACE],
235-
$tparams
236-
);
237-
238-
if ($absolute) {
239-
$elements[] = 'Absolute';
240-
}
241-
242-
$cache_key = SharedCacheHelper::getNamespace($elements);
233+
$cache_key = $this->generateCacheKey($tparams, $absolute);
243234
$cached = SharedCacheHelper::getValue($cache_key);
244235
if ($cached) {
245236
return $cached;
@@ -279,6 +270,45 @@ public function generate($params, $context = [], $absolute = false)
279270
return $url;
280271
}
281272

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

0 commit comments

Comments
 (0)