]> git.mxchange.org Git - friendica.git/blob - src/Core/Cache/TraitCompareSet.php
Merge pull request #7540 from vinzv/patch-1
[friendica.git] / src / Core / Cache / TraitCompareSet.php
1 <?php
2
3 namespace Friendica\Core\Cache;
4
5 /**
6  * Trait TraitCompareSetDelete
7  *
8  * This Trait is to compensate non native "exclusive" sets/deletes in caches
9  *
10  * @package Friendica\Core\Cache
11  */
12 trait TraitCompareSet
13 {
14         abstract public function get($key);
15
16         abstract public function set($key, $value, $ttl = Cache::FIVE_MINUTES);
17
18         abstract public function delete($key);
19
20         abstract public function add($key, $value, $ttl = Cache::FIVE_MINUTES);
21
22         /**
23          * NonNative - Compares if the old value is set and sets the new value
24          *
25          * @param string $key         The cache key
26          * @param mixed  $oldValue    The old value we know from the cache
27          * @param mixed  $newValue    The new value we want to set
28          * @param int    $ttl      The cache lifespan, must be one of the Cache constants
29          *
30          * @return bool
31          */
32         public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES) {
33                 if ($this->add($key . "_lock", true)) {
34                         if ($this->get($key) === $oldValue) {
35                                 $this->set($key, $newValue, $ttl);
36                                 $this->delete($key . "_lock");
37                                 return true;
38                         } else {
39                                 $this->delete($key . "_lock");
40                                 return false;
41                         }
42                 } else {
43                         return false;
44                 }
45         }
46 }