index/src/IO/Stream.php

89 lines
2.1 KiB
PHP

<?php
// Stream.php
// Created: 2021-04-30
// Updated: 2022-02-27
namespace Index\IO;
use Stringable;
use Index\Environment;
use Index\ICloseable;
abstract class Stream implements Stringable, ICloseable {
public const START = SEEK_SET;
public const CURRENT = SEEK_CUR;
public const END = SEEK_END;
abstract public function getPosition(): int;
abstract public function getLength(): int;
abstract public function setLength(int $length): void;
abstract public function canRead(): bool;
abstract public function canWrite(): bool;
abstract public function canSeek(): bool;
abstract public function hasTimedOut(): bool;
abstract public function isBlocking(): bool;
abstract public function isEnded(): bool;
abstract public function readChar(): ?string;
public function readByte(): int {
$char = $this->readChar();
if($char === null)
return -1;
return ord($char);
}
abstract public function readLine(): ?string;
abstract public function read(int $length): ?string;
abstract public function seek(int $offset, int $origin = self::START): int;
abstract public function write(string $buffer, int $length = -1): void;
public function writeLine(string $line): void {
$this->write($line);
$this->write(Environment::NEWLINE);
}
abstract public function writeChar(string $char): void;
public function writeByte(int $byte): void {
$this->writeChar(chr($byte & 0xFF));
}
public function copyTo(Stream $other): void {
if($this->canSeek())
$this->seek(0);
while(!$this->isEnded())
$other->write($this->read(8192));
}
abstract public function flush(): void;
abstract public function close(): void;
public function __toString(): string {
if($this->canSeek())
$this->seek(0);
$string = '';
while(!$this->isEnded())
$string .= $this->read(8192);
return $string;
}
public function __destruct() {
$this->close();
}
}