friendica-github/src/Core/Cache/DatabaseCacheDriver.php

94 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Friendica\Core\Cache;
use Friendica\Core\Cache;
use Friendica\Database\DBA;
use Friendica\Util\DateTimeFormat;
/**
* Database Cache Driver
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
class DatabaseCacheDriver extends AbstractCacheDriver implements ICacheDriver
{
2018-09-26 02:52:32 +00:00
/**
* (@inheritdoc)
*/
public function getAllKeys($prefix = null)
2018-09-26 02:52:32 +00:00
{
if (empty($prefix)) {
$where = ['`expires` >= ?', DateTimeFormat::utcNow()];
} else {
2018-10-07 20:14:05 +00:00
$where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
}
2018-09-26 02:52:32 +00:00
$stmt = DBA::select('cache', ['k'], $where);
2018-10-07 20:14:05 +00:00
$keys = [];
while ($key = DBA::fetch($stmt)) {
2018-10-07 20:14:05 +00:00
array_push($keys, $key['k']);
}
DBA::close($stmt);
2018-10-07 20:14:05 +00:00
return $keys;
2018-09-26 02:52:32 +00:00
}
2018-09-26 02:51:41 +00:00
/**
* (@inheritdoc)
*/
public function get($key)
{
$cache = DBA::selectFirst('cache', ['v'], ['`k` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
2018-07-21 12:46:04 +00:00
if (DBA::isResult($cache)) {
$cached = $cache['v'];
$value = @unserialize($cached);
// Only return a value if the serialized value is valid.
// We also check if the db entry is a serialized
// boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) {
return $value;
}
}
return null;
}
2018-09-26 02:51:41 +00:00
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
{
$fields = [
'v' => serialize($value),
'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
'updated' => DateTimeFormat::utcNow()
];
return DBA::update('cache', $fields, ['k' => $key], true);
}
2018-09-26 02:51:41 +00:00
/**
* (@inheritdoc)
*/
public function delete($key)
{
return DBA::delete('cache', ['k' => $key]);
}
2018-09-26 02:51:41 +00:00
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
{
if ($outdated) {
return DBA::delete('cache', ['`expires` < NOW()']);
} else {
return DBA::delete('cache', ['`k` IS NOT NULL ']);
}
}
}