<?php
namespace nur\sery\file;

use nur\sery\os\IOException;

trait TStreamFilter {
  private $filters = null;

  function appendFilter(string $filterName, ?int $readWrite=null, $params=null): void {
    $this->filters[] = [$filterName, $readWrite, $params];
  }

  function prependFilter(string $filterName, ?int $readWrite=null, $params=null): void {
    if ($this->filters === null) $this->filters = [];
    array_unshift($this->filters, [$filterName, $readWrite, $params]);
  }

  function setEncodingFilter(string $from, string $to): void {
    if ($to !== $from) {
      $this->appendFilter("convert.iconv.$from.$to");
    }
  }

  /**
   * @param $fd resource
   * @throws IOException
   */
  protected function _streamAppendFilters($fd): void {
    if ($this->filters !== null) {
      foreach ($this->filters as [$filterName, $readWrite, $params]) {
        if (stream_filter_append($fd, $filterName, $readWrite, $params) === false) {
          throw new IOException("unable to add filter $filterName");
        }
      }
      $this->filters = null;
    }
  }

  /**
   * @param $file _IFile
   */
  protected function _appendFilters($file): void {
    if ($this->filters !== null) {
      foreach ($this->filters as [$filterName, $readWrite, $params]) {
        $file->appendFilter($filterName, $readWrite, $params);
      }
    }
  }
}
