Skip to content

Commit

Permalink
fix: implement the runtime cache on preparePost functions. (#951)
Browse files Browse the repository at this point in the history
* fix: implement the runtime cache on preparePost functions.

* fix: prevent unicode chars in cache keys.

---------

Co-authored-by: Sebastian Thulin <sebastian.thulin@helsingborg.se>
  • Loading branch information
sebastianthulin and Sebastian Thulin committed Jun 14, 2024
1 parent b5e18b4 commit 4112021
Showing 1 changed file with 38 additions and 12 deletions.
50 changes: 38 additions & 12 deletions library/Helper/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,38 @@ class Post
*/
public static function preparePostObject(\WP_Post $post, $data = null): object
{
// Create a unique cache key based on the post ID and serialized data
$cacheKey = md5($post->ID . '_' . serialize($data));

if (!isset(self::$runtimeCache['preparePostObject'])) {
self::$runtimeCache['preparePostObject'] = [];
}

if (isset(self::$runtimeCache['preparePostObject'][$cacheKey])) {
return self::$runtimeCache['preparePostObject'][$cacheKey];
}

// Perform the original operations
$post = self::complementObject(
$post,
[
'excerpt',
'post_content_filtered',
'post_title_filtered',
'permalink',
'terms',
'post_language',
'reading_time',
'quicklinks',
'call_to_action_items',
'term_icon'
'excerpt',
'post_content_filtered',
'post_title_filtered',
'permalink',
'terms',
'post_language',
'reading_time',
'quicklinks',
'call_to_action_items',
'term_icon'
],
$data
);

return \Municipio\Helper\FormatObject::camelCase($post);
return self::$runtimeCache['preparePostObject'][$cacheKey] = \Municipio\Helper\FormatObject::camelCase(
$post
);
}

/**
Expand All @@ -70,6 +84,16 @@ public static function preparePostObjectSingular(\WP_Post $post, $data = null):
*/
public static function preparePostObjectArchive(\WP_Post $post, $data = null): object
{
$cacheKey = md5($post->ID . '_' . serialize($data));

if (!isset(self::$runtimeCache['preparePostObjectArchive'])) {
self::$runtimeCache['preparePostObjectArchive'] = [];
}

if (isset(self::$runtimeCache['preparePostObjectArchive'][$cacheKey])) {
return self::$runtimeCache['preparePostObjectArchive'][$cacheKey];
}

$post = self::complementObject(
$post,
[
Expand All @@ -84,7 +108,9 @@ public static function preparePostObjectArchive(\WP_Post $post, $data = null): o
$data
);

return \Municipio\Helper\FormatObject::camelCase($post);
return self::$runtimeCache['preparePostObjectArchive'][$cacheKey] = \Municipio\Helper\FormatObject::camelCase(
$post
);
}

/**
Expand Down

0 comments on commit 4112021

Please sign in to comment.