nur-sery/nur_src/data/template/StreamTemplate.php

63 lines
1.4 KiB
PHP

<?php
namespace nur\data\template;
use nur\b\io\FileReader;
use nur\b\io\IReader;
use nur\b\io\IWriter;
use nur\b\ValueException;
use nur\data\expr\SimpleContext;
class StreamTemplate extends SimpleContext implements ITemplate {
use TTemplate;
/**
* retourner un nom de fichier à utiliser par défaut en entrée si l'argument
* $input n'est pas spécifié.
*/
protected function INPUT(): ?string {
return static::INPUT;
} const INPUT = null;
/** @var IReader */
private $input;
/** @var IWriter */
private $output;
/** @var bool */
private $autoClose;
function __construct(IWriter $output, ?IReader $input=null, bool $autoClose=true) {
parent::__construct();
$this->input = $input;
$this->output = $output;
$this->autoClose = $autoClose;
$this->context = $this;
}
protected function ensureInput(): IReader {
$input = $this->input;
if ($input === null) {
$input = $this->INPUT();
if ($input === null) {
throw new ValueException("input is required");
}
$input = new FileReader($input);
}
return $input;
}
/** retourner true */
function apply() {
$context = $this->getContext();
$input = $this->ensureInput();
$output = $this->output;
foreach ($input as $line) {
$line = $this->applyRules($line, $context);
$output->wnl($line);
}
$output->close($this->autoClose);
return true;
}
}