<?php
namespace nur\sery\file;

use nur\sery\os\IOException;
use nur\sery\web\http;

abstract class _File extends Stream {
  /** @var string */
  protected $file;

  function getFile(): ?string {
    return $this->file;
  }

  /** @var string */
  protected $mode;

  function getMode(): string {
    return $this->mode;
  }

  /** @return resource */
  protected function open() {
    return IOException::ensure_valid(@fopen($this->file, $this->mode));
  }

  /** @return resource */
  function getResource() {
    if ($this->fd === null && $this->file !== null) $this->fd = $this->open();
    return parent::getResource();
  }

  /** streamer le contenu du fichier en sortie */
  function readfile(?string $contentType=null, ?string $charset=null, ?string $filename=null, string $disposition=null): bool {
    if ($contentType !== null) http::content_type($contentType, $charset);
    if ($filename !== null) http::download_as($filename, $disposition);
    return readfile($this->file) !== false;
  }
}
