1
0
Fork 0
mirror of https://we.phorge.it/source/phorge.git synced 2024-12-04 04:32:43 +01:00
phorge-phorge/src/applications/cache/PhabricatorKeyValueSerializingCacheProxy.php
epriestley 125fb332de Introduce a serializing key-value cache proxy
Summary:
Ref T11954. I want to store some lists/arrays in the mutable (database) cache, but it only supports string storage.

Provide a serializing wrapper which flattens when values are written and expands them when they're read.

Test Plan: Used by D16997. See that revision.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T11954

Differential Revision: https://secure.phabricator.com/D16999
2016-12-06 09:11:32 -08:00

55 lines
1.4 KiB
PHP

<?php
/**
* Proxies another cache and serializes values.
*
* This allows more complex data to be stored in a cache which can only store
* strings.
*/
final class PhabricatorKeyValueSerializingCacheProxy
extends PhutilKeyValueCacheProxy {
public function getKeys(array $keys) {
$results = parent::getKeys($keys);
$reads = array();
foreach ($results as $key => $result) {
$structure = @unserialize($result);
// The unserialize() function returns false when unserializing a
// literal `false`, and also when it fails. If we get a literal
// `false`, test if the serialized form is the same as the
// serialization of `false` and miss the cache otherwise.
if ($structure === false) {
static $serialized_false;
if ($serialized_false === null) {
$serialized_false = serialize(false);
}
if ($result !== $serialized_false) {
continue;
}
}
$reads[$key] = $structure;
}
return $reads;
}
public function setKeys(array $keys, $ttl = null) {
$writes = array();
foreach ($keys as $key => $value) {
if (is_object($value)) {
throw new Exception(
pht(
'Serializing cache can not write objects (for key "%s")!',
$key));
}
$writes[$key] = serialize($value);
}
return parent::setKeys($writes, $ttl);
}
}