Forked from kagg-design/class-wpml-element-translation.php
Created
August 29, 2022 10:47
-
-
Save ValeriiVasyliev/5970524c2857a3c775dc7610310b61e6 to your computer and use it in GitHub Desktop.
Keep cache size within limit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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