<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\KuferTools\Utils\FilterSearch\Method;

use Kufer\Web\Classes\Dbfilter\ISQLFilter;

class HasAnyArrayMethod extends SQLSearchFilterMethod
{
  public function __construct($fnApply)
  {
    if (is_string($fnApply)) {
      parent::__construct(static function(ISQLFilter $filter, $value) use ($fnApply): ISQLFilter {
        return \call_user_func(array($filter, 'hasAny' . $fnApply), $value);
      });
    } else {
      parent::__construct($fnApply);
    }
  }

  public function apply($filter, $value): ISQLFilter
  {
    if (empty($value)) { 
      return $filter;
    }

    return parent::apply($filter, $value);
  }

  public function fromRequest($value)
  {
    if (!is_array($value)) {
      if (is_null($value) || $value === '') {
        return null;
      }

      $value = array($value);
    }

    return $value;
  }

  public function fromSession($value)
  {
    $result = parent::fromSession($value);
    if ($result === '') {
      return null;
    }

    return $result;
  }
}