| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Class Optml_Attachment_Cache. |
| 5 |
*/ |
| 6 |
class Optml_Attachment_Cache { |
| 7 |
const CACHE_GROUP = 'om_att'; |
| 8 |
/** |
| 9 |
* Local cache map. |
| 10 |
* |
| 11 |
* @var array |
| 12 |
*/ |
| 13 |
private static $cache_map = []; |
| 14 |
/** |
| 15 |
* Reset the memory cache. |
| 16 |
*/ |
| 17 |
public static function reset() { |
| 18 |
self::$cache_map = []; |
| 19 |
} |
| 20 |
/** |
| 21 |
* Get the cached attachment ID. |
| 22 |
* |
| 23 |
* @param string $url the URL of the attachment. |
| 24 |
* |
| 25 |
* @return bool|mixed |
| 26 |
*/ |
| 27 |
public static function get_cached_attachment_id( $url ) { |
| 28 |
|
| 29 |
// We cache also in memory to avoid calling DB every time when not using Object Cache. |
| 30 |
$cache_key = self::get_cache_key( $url ); |
| 31 |
if ( isset( self::$cache_map[ $cache_key ] ) ) { |
| 32 |
return self::$cache_map[ $cache_key ]; |
| 33 |
} |
| 34 |
|
| 35 |
$value = wp_using_ext_object_cache() |
| 36 |
? wp_cache_get( $cache_key, self::CACHE_GROUP ) |
| 37 |
: get_transient( self::CACHE_GROUP . $cache_key ); |
| 38 |
self::$cache_map[ $cache_key ] = $value; |
| 39 |
|
| 40 |
return $value; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Set the cached attachment ID. |
| 45 |
* |
| 46 |
* @param string $url the URL of the attachment. |
| 47 |
* @param int $id the attachment ID. |
| 48 |
* |
| 49 |
* @return void |
| 50 |
*/ |
| 51 |
public static function set_cached_attachment_id( $url, $id ) { |
| 52 |
$cache_key = self::get_cache_key( $url ); |
| 53 |
// We cache also in memory to avoid calling DB every time when not using Object Cache. |
| 54 |
self::$cache_map[ $cache_key ] = $id; |
| 55 |
// If the ID is not found we cache for 10 minutes, otherwise for a week. |
| 56 |
// We try to reduce the cache time when is not found to |
| 57 |
// avoid caching for situation when this might be temporary. |
| 58 |
$expiration = $id === 0 ? ( 10 * MINUTE_IN_SECONDS ) : WEEK_IN_SECONDS; |
| 59 |
wp_using_ext_object_cache() |
| 60 |
? wp_cache_set( $cache_key, $id, self::CACHE_GROUP, $expiration ) |
| 61 |
: set_transient( self::CACHE_GROUP . $cache_key, $id, $expiration ); |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Generate cache key for URL. |
| 66 |
* |
| 67 |
* @param string $url the URL to generate the cache key for. |
| 68 |
* |
| 69 |
* @return string |
| 70 |
*/ |
| 71 |
private static function get_cache_key( $url ) { |
| 72 |
$url = strtok( $url, '?' ); |
| 73 |
|
| 74 |
return 'id_' . crc32( $url ); |
| 75 |
} |
| 76 |
} |
| 77 |
|