CADTrait.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 CADTrait {
  9. abstract public function get($key);
  10. abstract public function remove($key);
  11. abstract public function add($key, $value, $ttl = 0);
  12. /**
  13. * Compare and delete
  14. *
  15. * @param string $key
  16. * @param mixed $old
  17. * @return bool
  18. */
  19. public function cad($key, $old) {
  20. //no native cas, emulate with locking
  21. if ($this->add($key . '_lock', true)) {
  22. if ($this->get($key) === $old) {
  23. $this->remove($key);
  24. $this->remove($key . '_lock');
  25. return true;
  26. } else {
  27. $this->remove($key . '_lock');
  28. return false;
  29. }
  30. } else {
  31. return false;
  32. }
  33. }
  34. public function ncad(string $key, mixed $old): bool {
  35. //no native cad, emulate with locking
  36. if ($this->add($key . '_lock', true)) {
  37. $value = $this->get($key);
  38. if ($value !== null && $value !== $old) {
  39. $this->remove($key);
  40. $this->remove($key . '_lock');
  41. return true;
  42. } else {
  43. $this->remove($key . '_lock');
  44. return false;
  45. }
  46. } else {
  47. return false;
  48. }
  49. }
  50. }