LockManager.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace OC\Files\Lock;
  3. use OCP\Files\Lock\ILock;
  4. use OCP\Files\Lock\ILockManager;
  5. use OCP\Files\Lock\ILockProvider;
  6. use OCP\Files\Lock\LockContext;
  7. use OCP\PreConditionNotMetException;
  8. class LockManager implements ILockManager {
  9. private ?ILockProvider $lockProvider = null;
  10. private ?LockContext $lockInScope = null;
  11. public function registerLockProvider(ILockProvider $lockProvider): void {
  12. if ($this->lockProvider) {
  13. throw new PreConditionNotMetException('There is already a registered lock provider');
  14. }
  15. $this->lockProvider = $lockProvider;
  16. }
  17. public function isLockProviderAvailable(): bool {
  18. return $this->lockProvider !== null;
  19. }
  20. public function runInScope(LockContext $lock, callable $callback): void {
  21. if (!$this->lockProvider) {
  22. $callback();
  23. return;
  24. }
  25. if ($this->lockInScope) {
  26. throw new PreConditionNotMetException('Could not obtain lock scope as already in use by ' . $this->lockInScope);
  27. }
  28. try {
  29. $this->lockInScope = $lock;
  30. $callback();
  31. } finally {
  32. $this->lockInScope = null;
  33. }
  34. }
  35. public function getLockInScope(): ?LockContext {
  36. return $this->lockInScope;
  37. }
  38. public function getLocks(int $fileId): array {
  39. if (!$this->lockProvider) {
  40. throw new PreConditionNotMetException('No lock provider available');
  41. }
  42. return $this->lockProvider->getLocks($fileId);
  43. }
  44. public function lock(LockContext $lockInfo): ILock {
  45. if (!$this->lockProvider) {
  46. throw new PreConditionNotMetException('No lock provider available');
  47. }
  48. return $this->lockProvider->lock($lockInfo);
  49. }
  50. public function unlock(LockContext $lockInfo): void {
  51. if (!$this->lockProvider) {
  52. throw new PreConditionNotMetException('No lock provider available');
  53. }
  54. $this->lockProvider->unlock($lockInfo);
  55. }
  56. }