From d19162fcefcce457eeaa27904c797f76f9f49007 Mon Sep 17 00:00:00 2001 From: Benjamin Morel Date: Thu, 28 Feb 2019 19:27:37 +0100 Subject: [PATCH] Implement FileStream::lock() and unlock() --- src/Io/FileStream.php | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/Io/FileStream.php b/src/Io/FileStream.php index 00d962d..a511fef 100644 --- a/src/Io/FileStream.php +++ b/src/Io/FileStream.php @@ -176,6 +176,60 @@ public function write(string $data) : void } } + /** + * Obtains an advisory lock. + * + * @param bool $exclusive + * + * @return void + * + * @throws IoException If an error occurs. + */ + public function lock(bool $exclusive) : void + { + if ($this->closed) { + throw new IoException('The stream is closed.'); + } + + try { + $result = ErrorCatcher::run(function() use ($exclusive) { + return flock($this->handle, $exclusive ? LOCK_EX : LOCK_SH); + }); + } catch (\ErrorException $e) { + throw new IoException($e->getMessage(), 0, $e); + } + + if ($result === false) { + throw new IoException('Failed to obtain a lock.'); + } + } + + /** + * Releases an advisory lock. + * + * @return void + * + * @throws IoException + */ + public function unlock() : void + { + if ($this->closed) { + throw new IoException('The stream is closed.'); + } + + try { + $result = ErrorCatcher::run(function() { + return flock($this->handle, LOCK_UN); + }); + } catch (\ErrorException $e) { + throw new IoException($e->getMessage(), 0, $e); + } + + if ($result === false) { + throw new IoException('Failed to release the lock.'); + } + } + /** * @return void *