nur-sery/nur_src/b/io/FileReader.php

37 lines
816 B
PHP

<?php
namespace nur\b\io;
use nur\base;
class FileReader extends StreamReader {
const DEFAULT_MODE = "rb";
/** @throws IOException */
function __construct($input, string $mode=self::DEFAULT_MODE) {
$close = false;
$file = null;
if (base::z($input)) {
$fd = STDIN;
} elseif (is_resource($input)) {
$fd = $input;
} elseif (is_string($input)) {
$fd = IOException::ensure_not_false(@fopen($input, $mode), "open");
$close = true;
$file = $input;
}
parent::__construct($fd, $close);
$this->file = $file;
}
protected $file;
function getContents(bool $close=true): string {
if ($this->file === null) return parent::getContents();
try {
return file_get_contents($this->file);
} finally {
$this->close($close);
}
}
}