Last active
January 30, 2020 23:04
-
-
Save non-senses/b8bd0e4228b77826e7e70292eff676c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function unlock($orderId, $userId) | |
{ | |
if (empty($this->type)) { | |
throw new LockException("Can not unlock the order: type is mandatory."); | |
} | |
if (empty($orderId)) { | |
throw new LockException("Can not unlock the order: no orderId was provided"); | |
} | |
if (!in_array($this->type, $this->availableType)) { | |
throw new LockException("Can not unlock the order: the provided type (".$this->type.") is none of " . implode($this->availableType)); | |
} | |
$redis = $this->app['cache']; // Assign the variable once all validations passed. | |
$result = $redis->hGet(sprintf(self::REDIS_CACHE_TEMPORARY_LOCK, $this->type), $orderId); | |
if (empty($result)) { | |
throw new LockException("This order wasn't locked. Can't unlock"); | |
} | |
// lock if it's the same user who try to unlock | |
$data = json_decode($result, true); | |
if ($userId != $data['user']['id']) { | |
throw new LockException("Unlock failed. You can't unlock something that isn't yours"); | |
} | |
$result = $redis->hDel(sprintf(self::REDIS_CACHE_TEMPORARY_LOCK, $this->type), $orderId); | |
if ($result != true) { | |
/* This unlock should be atomic to avoid a race condition, but it's out of the scope of this article */ | |
throw new LockException("Unlock failed. Please try again"); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment