<?php
namespace nur\b\io;

trait Treader {
  function readLines(): array {
    $lines = [];
    try {
      while (true) {
        try {
          $lines[] = $this->readLine();
        } catch (EOFException $e) {
          break;
        }
      }
    } finally {
      $this->close();
    }
    return $lines;
  }

  function unserialize(?array $options=null, bool $close=true) {
    $args = [$this->getContents($close)];
    if ($options !== null) $args[] = $options;
    return unserialize(...$args);
  }

  function copyTo(IWriter $writer, bool $closeWriter=false, bool $closeReader=true): void {
    $inr = $this->getResource();
    $outr = $writer->getResource();
    if ($inr !== null && $outr !== null) {
      while (!feof($inr)) {
        fwrite($outr, fread($inr, 8192));
      }
    } else {
      $writer->write($this->getContents());
    }
    if ($closeWriter) $writer->close();
    if ($closeReader) $this->close();
  }
}