CASTrait.php 878 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Memcache;
  8. trait CASTrait {
  9. abstract public function get($key);
  10. abstract public function set($key, $value, $ttl = 0);
  11. abstract public function remove($key);
  12. abstract public function add($key, $value, $ttl = 0);
  13. /**
  14. * Compare and set
  15. *
  16. * @param string $key
  17. * @param mixed $old
  18. * @param mixed $new
  19. * @return bool
  20. */
  21. public function cas($key, $old, $new) {
  22. //no native cas, emulate with locking
  23. if ($this->add($key . '_lock', true)) {
  24. if ($this->get($key) === $old) {
  25. $this->set($key, $new);
  26. $this->remove($key . '_lock');
  27. return true;
  28. } else {
  29. $this->remove($key . '_lock');
  30. return false;
  31. }
  32. } else {
  33. return false;
  34. }
  35. }
  36. }