-
Notifications
You must be signed in to change notification settings - Fork 0
/
WorkingDaysRequiredValidator.php
120 lines (101 loc) · 2.55 KB
/
WorkingDaysRequiredValidator.php
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
/**
* Created by PhpStorm.
* User: Yarmaliuk Mikhail
* Date: 25.10.2017
* Time: 12:55
*/
namespace MP\WorkingDateTime;
use Yii;
use yii\validators\ValidationAsset;
use yii\validators\Validator;
/**
* Class WorkingDaysRequiredValidator
* @package MP\WorkingDateTime
* @author Yarmaliuk Mikhail
* @version 1.0
*/
class WorkingDaysRequiredValidator extends Validator
{
/**
* Reuired error message
*
* @var string
*/
public $message = NULL;
/**
* Validate array attribute
*
* @var bool
*/
public $each = false;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->message === NULL) {
$this->message = Yii::t('yii', '{attribute} cannot be blank.');
}
}
/**
* @inheritdoc
*
* Implement each validation
*/
public function validateAttribute($model, $attribute)
{
if ($this->each) {
foreach ($model->$attribute as $i => $value) {
$result = $this->validateValue($value);
if (!empty($result)) {
$model->addError($attribute."[$i]", $this->formatMessage($this->message, []));
}
}
} else {
parent::validateAttribute($model, $attribute);
}
}
/**
* @inheritdoc
*/
protected function validateValue($value)
{
if (is_array($value)) {
$empty = true;
foreach ($value as $dayAlias => $workTimes) {
if (!empty($workTimes['work']) || !empty($workTimes['dinner'])) {
$empty = false;
break;
}
}
if ($empty) {
return [$this->message, []];
}
} else {
return [$this->message, []];
}
return NULL;
}
/**
* @inheritdoc
*/
public function clientValidateAttribute($model, $attribute, $view)
{
ValidationAsset::register($view);
$options = $this->getClientOptions($model, $attribute);
return 'yii.validation.requiredWorkingDays(attribute, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
}
/**
* @inheritdoc
*/
public function getClientOptions($model, $attribute)
{
$options = [];
$options['requiredMessage'] = $this->formatMessage($this->message, [
'attribute' => $model->getAttributeLabel($attribute),
]);
return $options;
}
}