1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
<?php
class DateCompareValidator extends CValidator {
/**
* @var mixed the format pattern that the date value should follow.
* This can be either a string or an array representing multiple formats.
* Defaults to 'MM/dd/yyyy'. Please see {@link CDateTimeParser} for details
* about how to specify a date format.
*/
public $format='MM/dd/yyyy';
/**
* @var boolean whether the attribute value can be null or empty. Defaults to true,
* meaning that if the attribute is empty, it is considered valid.
*/
public $allowEmpty=true;
/**
* @var string the name of the attribute to receive the parsing result.
* When this property is not null and the validation is successful, the named attribute will
* receive the parsing result.
*/
public $timestampAttribute;
public $operator = '>';
public $compareAttribute;
public $compareValue;
/**
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
*/
protected function validateAttribute($object, $attribute) {
if ((empty($this->compareAttribute) && empty($this->compareValue)) || empty($this->operator)) {
$this->addError($attribute, 'Invalid Parameters to dateCompare');
}
$compareAttribute = $this->compareAttribute;
$this->compareValue = empty($compareAttribute) ? $this->compareValue : $object->$compareAttribute;;
if ($this->allowEmpty && empty($this->compareValue)) {
return;
}
$start = $object->$attribute;
$end = $this->compareValue;
$pattern = '/[0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}/';
if (preg_match($pattern, $start)) {
$start = CDateTimeParser::parse($start, "dd.MM.yyyy HH:mm");
}
if (preg_match($pattern, $end)) {
$end = CDateTimeParser::parse($end, "dd.MM.yyyy HH:mm");
}
//a little php trick - safe than eval and easier than a big switch statement
if (version_compare($start, $end, $this->operator)) {
Yii::trace('Input value: '.$start.' - compare value: '.$end.' - operator: '.$this->operator.' - result: OK', 'ccwn.astaf.date.validate');
return;
} else {
Yii::trace('Input value: '.$start.' - compare value: '.$end.' - operator: '.$this->operator.' - result: FAIL', 'ccwn.astaf.date.validate');
$message = $this->message !== null ? $this->message : Yii::t('astaf', 'The value of {attribute} ({value}) is not {operator} {compareAttribute} ({compareValue}).');
$this->addError($object, $attribute, $message, array('{operator}'=>$this->operator, '{compareValue}'=>$this->compareValue, '{value}'=>$object->$attribute, '{compareAttribute}'=>($object->getAttributeLabel($this->compareAttribute))));
}
}
}
|