1
0
mirror of https://github.com/danog/file.git synced 2024-11-30 04:19:39 +01:00
file/lib/BlockingHandle.php
Aaron Piotrowski 4f9630298f Throw FilesytemException on closed file
We may wish to change this later, but at least it is consistent between drivers now.
2017-06-16 18:21:56 -05:00

153 lines
3.6 KiB
PHP

<?php
namespace Amp\File;
use Amp\{ Success, Failure, Promise };
class BlockingHandle implements Handle {
private $fh;
private $path;
private $mode;
/**
* @param resource $fh An open uv filesystem descriptor
* @param string $path
* @param string $mode
*/
public function __construct($fh, string $path, string $mode) {
$this->fh = $fh;
$this->path = $path;
$this->mode = $mode;
}
public function __destruct() {
if ($this->fh !== null) {
\fclose($this->fh);
}
}
/**
* {@inheritdoc}
*/
public function read(int $length = self::DEFAULT_READ_LENGTH): Promise {
if ($this->fh === null) {
throw new FilesystemException("The file has been closed");
}
$data = \fread($this->fh, $length);
if ($data !== false) {
return new Success(\strlen($data) ? $data : null);
} else {
return new Failure(new FilesystemException(
"Failed reading from file handle"
));
}
}
/**
* {@inheritdoc}
*/
public function write(string $data): Promise {
if ($this->fh === null) {
throw new FilesystemException("The file has been closed");
}
$len = \fwrite($this->fh, $data);
if ($len !== false) {
return new Success($len);
} else {
return new Failure(new FilesystemException(
"Failed writing to file handle"
));
}
}
/**
* {@inheritdoc}
*/
public function end(string $data = ""): Promise {
$promise = $this->write($data);
$promise->onResolve([$this, "close"]);
return $promise;
}
/**
* {@inheritdoc}
*/
public function close(): Promise {
if ($this->fh === null) {
throw new FilesystemException("The file has already been closed");
}
$fh = $this->fh;
$this->fh = null;
if (@\fclose($fh)) {
return new Success;
} else {
return new Failure(new FilesystemException(
"Failed closing file handle"
));
}
}
/**
* {@inheritdoc}
*/
public function seek(int $position, int $whence = \SEEK_SET): Promise {
if ($this->fh === null) {
throw new FilesystemException("The file has been closed");
}
switch ($whence) {
case \SEEK_SET:
case \SEEK_CUR:
case \SEEK_END:
if (@\fseek($this->fh, $position, $whence) === -1) {
return new Failure(new FilesystemException("Could not seek in file"));
}
return new Success($this->tell());
default:
throw new \Error(
"Invalid whence parameter; SEEK_SET, SEEK_CUR or SEEK_END expected"
);
}
}
/**
* {@inheritdoc}
*/
public function tell(): int {
if ($this->fh === null) {
throw new FilesystemException("The file has been closed");
}
return \ftell($this->fh);
}
/**
* {@inheritdoc}
*/
public function eof(): bool {
if ($this->fh === null) {
throw new FilesystemException("The file has been closed");
}
return \feof($this->fh);
}
/**
* {@inheritdoc}
*/
public function path(): string {
return $this->path;
}
/**
* {@inheritdoc}
*/
public function mode(): string {
return $this->mode;
}
}