<?php
namespace nur\b\io;

use nur\A;

trait Tfilter {
  private $filters = null;

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

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

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

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

  /**
   * @param $rw IReader|IWriter
   */
  protected function _rwAppendFilters($rw): void {
    if ($this->filters !== null) {
      foreach ($this->filters as [$filterName, $readWrite, $params]) {
        $rw->appendFilter($filterName, $readWrite, $params);
      }
    }
  }
}
