Skip to content

Instantly share code, notes, and snippets.

@kagg-design
Created April 24, 2021 15:17
Show Gist options
  • Save kagg-design/1d7bb19daccec54d4e63b928a38c3eed to your computer and use it in GitHub Desktop.
Save kagg-design/1d7bb19daccec54d4e63b928a38c3eed to your computer and use it in GitHub Desktop.
Keep cache size within limit
public function shutdown_action() {
$keys = $this->get_data_keys();
$data = [];
foreach ( $keys as $key ) {
$this->data[ $key ] = isset( $this->data[ $key ] ) ? $this->data[ $key ] : [];
$data[ $key ] = array_replace( $this->data[ $key ], $this->{$key} );
}
wp_cache_set( $this->get_cache_key(), $this->maybe_reduce_cache_size( $data ) );
$this->onShutDown();
}
/**
* @param array $data
*
* @return string
*/
private function maybe_reduce_cache_size( $data ) {
$json = wp_json_encode( $data );
$size = strlen( $json );
while ( $size > self::MAX_CACHE_SIZE ) {
$count = count( $data['element_data'] );
$keep_count = intval( $count / ( $size / self::MAX_CACHE_SIZE ) );
$remove_count = $count - $keep_count;
foreach ( $data['element_data'] as $key => &$element_datum ) {
if ( 0 === $remove_count ) {
break;
}
// Remove 'element_data' and relevant items on FIFO principle.
unset( $data['translations'][ $key ] );
unset( $data['trid_groups'][ $element_datum['trid'] ] );
unset( $data['translation_ids_element'][ $element_datum['translation_id'] ] );
unset( $data['element_data'][ $key ] );
$remove_count --;
}
$json = wp_json_encode( $data );
$new_size = strlen( $json );
if ( $new_size === $size ) {
break; // Prevent infinite loop if remove_count was estimated improperly.
}
$size = $new_size;
}
return $json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment