cleanup
[xendri.git] / lib / io / FileInputStream.php
blob78c5d14c5399a42a8f6b9ebe37d0b259a56c7873
1 <?php
3 lib('io.InputStream');
5 class FileInputStream implements InputStream {
6 protected $source;
7 protected $readed = 0;
8 protected $size = 0;
10 public function __construct(string $file) {
11 $this->source = $file;
12 $this->size = filesize($this->source);
15 public function open() {
16 $this->source = fopen($this->source, "r");
19 public function is_opened() {
20 return is_resource($this->source);
22 public function is_ended() {
23 return feof($this->source);
26 public function close() {
27 $this->checks();
28 fclose($this->source);
31 public function read(integer $size = NULL) {
32 if ($size == NULL) $size = 1;
33 $this->checks();
34 $buf = fread($this->source, $size);
35 $this->readed += sizeof($buf);
36 return $buf;
39 public function read_line() {
40 $line = '';
41 $buf = '';
42 try {
43 while (true) {
44 $buf = $this->read();
45 if ($buf == "\n") break;
46 $line .= $buf;
48 } catch (IOException $e) {
49 if (($e->getCode() == IOConst::X_STREAM_ENDED) && $line != '') return $line;
50 else throw $e;
52 return $line;
55 public function available() {
56 return $this->size - $this->readed;
59 protected function checks() {
60 if (!$this->is_opened()) {
61 throw new IOException(IOConst::X_STREAM_NOT_OPENED, "You cannot operate with stream before you open it.");
63 if ($this->is_ended()) {
64 throw new IOException(IOConst::X_STREAM_ENDED, "Unable to operate with free stream.");