1
0
mirror of https://github.com/danog/file.git synced 2024-12-02 09:17:57 +01:00
file/lib/BlockingDescriptor.php

93 lines
2.0 KiB
PHP
Raw Normal View History

2015-07-11 03:59:39 +02:00
<?php
namespace Amp\Fs;
2015-07-17 16:27:38 +02:00
use Amp\Promise;
use Amp\Success;
use Amp\Failure;
2015-07-11 03:59:39 +02:00
class BlockingDescriptor implements Descriptor {
private $fh;
/**
* @param resource $fh An open uv filesystem descriptor
*/
2015-07-17 16:27:38 +02:00
public function __construct($fh, $path) {
2015-07-11 03:59:39 +02:00
$this->fh = $fh;
$this->path = $path;
}
/**
* {@inheritdoc}
*/
2015-07-17 16:27:38 +02:00
public function read($offset, $len) {
2015-07-11 03:59:39 +02:00
\fseek($this->fh, $offset);
$data = \fread($this->fh, $len);
if ($data !== false) {
return new Success($data);
} else {
return new Failure(new \RuntimeException(
"Failed reading from file handle"
));
}
}
/**
* {@inheritdoc}
*/
2015-07-17 16:27:38 +02:00
public function write($offset, $data) {
2015-07-11 03:59:39 +02:00
\fseek($this->fh, $offset);
$len = \fwrite($this->fh, $data);
if ($len !== false) {
return new Success($data);
} else {
return new Failure(new \RuntimeException(
"Failed writing to file handle"
));
}
}
/**
* {@inheritdoc}
*/
2015-07-17 16:27:38 +02:00
public function truncate($length = 0) {
2015-07-11 03:59:39 +02:00
if (ftruncate($this->fh, $length)) {
return new Success;
} else {
return new Failure(new \RuntimeException(
"Failed truncating file handle"
));
}
}
/**
* {@inheritdoc}
*/
2015-07-17 16:27:38 +02:00
public function stat() {
2015-07-11 03:59:39 +02:00
if ($stat = fstat($this->fh)) {
$stat["isfile"] = (bool) is_file($this->path);
$stat["isdir"] = empty($stat["isfile"]);
return new Success($stat);
} else {
return new Failure(new \RuntimeException(
"File handle stat failed"
));
}
}
/**
* {@inheritdoc}
*/
2015-07-17 16:27:38 +02:00
public function close() {
2015-07-11 03:59:39 +02:00
if (\fclose($this->fh)) {
return new Success;
} else {
return new Failure(new \RuntimeException(
"Failed closing file handle"
));
}
}
}