Skip to content

Commit

Permalink
url specific cache key & add (small) cache for failed requests
Browse files Browse the repository at this point in the history
  • Loading branch information
ilicfilip committed Nov 6, 2024
1 parent e9de219 commit 54c3fab
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions classes/class-lessons.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,37 +42,45 @@ public function get_items() {
* @return array
*/
public function get_remote_api_items() {
$cached = \progress_planner()->get_cache()->get( 'lessons' );
if ( is_array( $cached ) && ! empty( $cached ) ) {

/**
* Filter the endpoint url for the lessons.
*
* @param string $endpoint The endpoint url.
*/
$url = apply_filters(
'progress_planner_lessons_endpoint',
'https://progressplanner.com/wp-json/progress-planner-saas/v1/free-lessons'
);

$cache_key = 'lessons-' . $url;

$cached = \progress_planner()->get_cache()->get( $cache_key );
if ( is_array( $cached ) ) {
return $cached;
}

$response = \wp_remote_get(
/**
* Filter the endpoint url for the lessons.
*
* @param string $endpoint The endpoint url.
*/
apply_filters(
'progress_planner_lessons_endpoint',
'https://progressplanner.com/wp-json/progress-planner-saas/v1/free-lessons'
)
$url
);

if ( \is_wp_error( $response ) ) {
\progress_planner()->get_cache()->set( $cache_key, [], 5 * MINUTE_IN_SECONDS );
return [];
}

if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
\progress_planner()->get_cache()->set( $cache_key, [], 5 * MINUTE_IN_SECONDS );
return [];
}

$json = json_decode( \wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $json ) ) {
\progress_planner()->get_cache()->set( $cache_key, [], 5 * MINUTE_IN_SECONDS );
return [];
}

\progress_planner()->get_cache()->set( 'lessons', $json, WEEK_IN_SECONDS );
\progress_planner()->get_cache()->set( $cache_key, $json, WEEK_IN_SECONDS );

return $json;
}
Expand Down

0 comments on commit 54c3fab

Please sign in to comment.