Files

35 lines
1005 B
PHP
Raw Permalink Normal View History

2016-10-12 11:31:52 -04:00
<?php
class CurlWithCache extends Curl
{
2018-05-21 11:49:15 -04:00
const DEFAULT_CACHE = 600000;
2016-10-12 11:31:52 -04:00
2018-05-21 11:49:15 -04:00
public static function doCurl($method, $url, $params = [], $options = [])
2016-10-12 11:31:52 -04:00
{
2018-05-21 11:49:15 -04:00
$cacheAllowed = $options['cache'] ?? true;
$cacheEnabled = Apc::isEnabled();
$cacheTimeout = is_numeric($options['cache'] ?? null) ? $options['cache'] : static::DEFAULT_CACHE;
unset($options['cache']);
$cacheKey = $cacheEnabled ? md5($url . $method . serialize($options) . serialize($params)) : null;
if ($cacheAllowed && $cacheKey) {
2018-12-11 16:11:43 -05:00
$cachedData = apcu_fetch($cacheKey);
2018-05-21 11:49:15 -04:00
if ($cachedData) {
return $cachedData;
}
}
$response = parent::doCurl($method, $url, $params, $options);
if ($cacheEnabled) {
if ($cacheAllowed) {
2018-12-11 16:11:43 -05:00
apcu_store($cacheKey, $response, $cacheTimeout);
2018-05-21 11:49:15 -04:00
} else {
2018-12-11 16:11:43 -05:00
apcu_delete($cacheKey);
2018-05-21 11:49:15 -04:00
}
}
return $response;
2016-10-12 11:31:52 -04:00
}
2018-05-21 11:49:15 -04:00
}