You are here

public function DateRangeFieldValidationRule::validate in Field Validation 8

Overrides FieldValidationRuleBase::validate

File

src/Plugin/FieldValidationRule/DateRangeFieldValidationRule.php, line 95

Class

DateRangeFieldValidationRule
DateRangeFieldValidationRule.

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 = FALSE;

    //$settings =  $this->rule->settings;
    $cycle = isset($settings['cycle']) ? $settings['cycle'] : '';

    // support date, datetime
    if (!is_numeric($value)) {
      $value = strtotime($value);
    }
    $date_str = date("Y-m-d H:i:s", $value);
    if ($cycle == 'global') {
      if (!empty($settings['min'])) {

        //$settings['min'] = $settings['min'];
        $settings['min'] = strtotime($settings['min']);
        $settings['min'] = date("Y-m-d H:i:s", $settings['min']);
      }
      if (!empty($settings['max'])) {

        //$settings['max'] = strtr($settings['max'], $tokens);
        $settings['max'] = strtotime($settings['max']);
        $settings['max'] = date("Y-m-d H:i:s", $settings['max']);
        $str_place = 0;
      }
    }
    if ($cycle == 'year') {
      $str_place = 5;
      $date_str = substr($date_str, $str_place);
    }
    elseif ($cycle == 'month') {
      $str_place = 8;
      $date_str = substr($date_str, $str_place);
    }
    elseif ($cycle == 'week') {
      $str_place = 10;
      $week_day = date('w', strtotime($date_str));
      $date_str = substr($date_str, $str_place);
      $date_str = $week_day . $date_str;
    }
    elseif ($cycle == 'day') {
      $str_place = 11;
      $date_str = substr($date_str, $str_place);
    }
    elseif ($cycle == 'hour') {
      $str_place = 14;
      $date_str = substr($date_str, $str_place);
    }
    elseif ($cycle == 'minute') {
      $str_place = 17;
      $date_str = substr($date_str, $str_place);
    }
    if (!empty($settings['min']) && $date_str < substr($settings['min'], $str_place)) {
      $flag = TRUE;
    }
    if (!empty($settings['max']) && $date_str > substr($settings['max'], $str_place)) {
      $flag = TRUE;
    }
    if ($flag) {
      $context
        ->addViolation($rule
        ->getErrorMessage());
    }
  }

  //return true;
}