<?php
namespace nur\sery\file;

use nur\sery\os\IOException;
use nur\sery\os\sh;

/**
 * Class FileWriter: un fichier accédé en lecture/écriture
 */
class FileWriter extends _File {
  const DEFAULT_MODE = "a+b";

  function __construct($output, ?string $mode=null, ?bool $throwOnError=null, ?bool $allowLocking=null) {
    if ($output === null) {
      $fd = STDOUT;
      $close = false;
    } elseif (is_resource($output)) {
      $fd = $output;
      $close = false;
    } else {
      $file = $output;
      if ($mode === null) $mode = static::DEFAULT_MODE;
      IOException::ensure_valid(sh::mkdirof($file));
      $this->file = $file;
      $this->mode = $mode;
      $fd = $this->open();
      $close = true;
    }
    parent::__construct($fd, $close, $throwOnError, $allowLocking);
  }
}
