43 lines
926 B
PHP
43 lines
926 B
PHP
<?php
|
|
namespace nur\b\io;
|
|
|
|
use nur\base;
|
|
|
|
/**
|
|
* Class FileWriter: écriture dans un fichier ou un flux
|
|
*/
|
|
class FileWriter extends StreamWriter {
|
|
const DEFAULT_MODE = "a+b";
|
|
|
|
/** @throws IOException */
|
|
function __construct($output, string $mode=self::DEFAULT_MODE) {
|
|
$close = false;
|
|
$file = null;
|
|
if (base::z($output)) {
|
|
$fd = STDOUT;
|
|
} elseif (is_resource($output)) {
|
|
$fd = $output;
|
|
} elseif (is_string($output)) {
|
|
$fd = IOException::ensure_not_false(@fopen($output, $mode), "open");
|
|
$close = true;
|
|
$file = $output;
|
|
}
|
|
parent::__construct($fd, $close);
|
|
$this->file = $file;
|
|
}
|
|
|
|
protected $file;
|
|
|
|
function putContents(string $contents): void {
|
|
if ($this->file === null) {
|
|
parent::putContents($contents);
|
|
} else {
|
|
try {
|
|
file_put_contents($this->file, $contents);
|
|
} finally {
|
|
$this->close();
|
|
}
|
|
}
|
|
}
|
|
}
|