friendica/src/Core/Cache/DatabaseCacheDriver.php

114 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace Friendica\Core\Cache;
use Friendica\Core\Cache;
use Friendica\Database\Database;
use Friendica\Util\DateTimeFormat;
/**
* Database Cache Driver
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
class DatabaseCacheDriver extends AbstractCacheDriver implements ICacheDriver
{
/**
* @var Database
*/
private $dba;
public function __construct(string $hostname, Database $dba)
{
parent::__construct($hostname);
$this->dba = $dba;
}
2018-09-26 04:52:32 +02:00
/**
* (@inheritdoc)
*/
public function getAllKeys($prefix = null)
2018-09-26 04:52:32 +02:00
{
if (empty($prefix)) {
$where = ['`expires` >= ?', DateTimeFormat::utcNow()];
} else {
2018-10-07 22:14:05 +02:00
$where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
}
2018-09-26 04:52:32 +02:00
$stmt = $this->dba->select('cache', ['k'], $where);
2018-10-07 22:14:05 +02:00
$keys = [];
while ($key = $this->dba->fetch($stmt)) {
2018-10-07 22:14:05 +02:00
array_push($keys, $key['k']);
}
$this->dba->close($stmt);
2018-10-07 22:14:05 +02:00
return $keys;
2018-09-26 04:52:32 +02:00
}
2018-09-26 04:51:41 +02:00
/**
* (@inheritdoc)
*/
public function get($key)
{
$cache = $this->dba->selectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()]);
if ($this->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 04:51:41 +02:00
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
{
if ($ttl > 0) {
$fields = [
'v' => serialize($value),
'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
'updated' => DateTimeFormat::utcNow()
];
} else {
$fields = [
'v' => serialize($value),
'expires' => -1,
'updated' => DateTimeFormat::utcNow()
];
}
return $this->dba->update('cache', $fields, ['k' => $key], true);
}
2018-09-26 04:51:41 +02:00
/**
* (@inheritdoc)
*/
public function delete($key)
{
return $this->dba->delete('cache', ['k' => $key]);
}
2018-09-26 04:51:41 +02:00
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
{
if ($outdated) {
return $this->dba->delete('cache', ['`expires` < NOW()']);
} else {
return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
}
}
}