<?php
/**
 * Copyright (c) 2012-2014, Agence Française Informatique (AFI). All rights reserved.
 *
 * BOKEH is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
 * BOKEH is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with BOKEH; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
 */


abstract class Class_SearchCriteria_Abstract {
  use Trait_Translator;

  const ALL_VALUES = 'all';
  const NAME_PREFIX = 'search_';

  protected
    $_name = '',
    $_value = '',
    $_element;


  public static function isCriteriaName($name) {
    return preg_match('/^' . static::NAME_PREFIX . '.+/', $name);
  }


  public function __construct($params) {
    if (isset($params[$this->getName()]))
      $this->_value = $params[$this->getName()];

    $this->_element = $this->buildElement();
  }


  public function getElement() {
    return $this->_element;
  }


  public function buildElement() {
    return new Zend_Form_Element_Hidden($this->getName(), ['value' => $this->_value]);
  }


  public function getName() {
    return static::NAME_PREFIX . $this->_name;
  }


  public function getCompositeValues() {
    return [];
  }


  public function acceptSearchVisitor($visitor) {
    if ($this->_isAllValues())
      return;

    $visitor->addParam($this->_name, $this->_value);
  }


  public function describeOn($view) {
  }


  public function modelMatch($model) {
    return $this->_isAllValues()
      ? true
      : $model->callGetterByAttributeName($this->_name) == $this->_value;
  }


  protected function _isAllValues() {
    return static::ALL_VALUES == $this->_value;
  }
}