Skip to content

Commit

Permalink
Implement FileStream::lock() and unlock()
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Feb 28, 2019
1 parent ffaa1f7 commit d19162f
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/Io/FileStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down

0 comments on commit d19162f

Please sign in to comment.