You are here

public function NumericFieldValidationRule::validate in Field Validation 8

Overrides FieldValidationRuleBase::validate

File

src/Plugin/FieldValidationRule/NumericFieldValidationRule.php, line 85

Class

NumericFieldValidationRule
NumericFieldValidationRule.

Namespace

Drupal\field_validation\Plugin\FieldValidationRule

Code

public function validate($params) {
  $value = isset($params['value']) ? $params['value'] : '';
  $rule = isset($params['rule']) ? $params['rule'] : null;
  $context = isset($params['context']) ? $params['context'] : null;
  $settings = array();
  if (!empty($rule) && !empty($rule->configuration)) {
    $settings = $rule->configuration;
  }

  //$settings = $this->rule->settings;
  if ($value !== '' && !is_null($value)) {
    $flag = TRUE;
    if (!is_numeric($value)) {
      $flag = FALSE;
    }
    else {
      if (isset($settings['min']) && $settings['min'] != '') {
        $min = $settings['min'];
        if ($value < $min) {
          $flag = FALSE;
        }
      }
      if (isset($settings['max']) && $settings['max'] != '') {
        $max = $settings['max'];
        if ($value > $max) {
          $flag = FALSE;
        }
      }
      if (isset($settings['step']) && strtolower($settings['step']) != 'any') {

        // Check that the input is an allowed multiple of #step (offset by #min if
        // #min is set).
        $offset = isset($settings['min']) ? $settings['min'] : 0.0;
        $step = $settings['step'];

        //The logic code was copied from Drupal 8 core.
        if ($step > 0 && !$this
          ->valid_number_step($value, $step, $offset)) {
          $flag = FALSE;
        }
      }
    }
    if (!$flag) {
      $context
        ->addViolation($rule
        ->getErrorMessage());
    }
  }

  //return true;
}