-
Notifications
You must be signed in to change notification settings - Fork 5
/
DateTimeBehavior.php
222 lines (200 loc) · 6.67 KB
/
DateTimeBehavior.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php
namespace omnilight\datetime;
use yii\base\Behavior;
use yii\base\Event;
use yii\base\InvalidParamException;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\FormatConverter;
use yii\i18n\Formatter;
use yii\validators\DateValidator;
/**
* Class DateTimeBehavior
*/
class DateTimeBehavior extends Behavior
{
/**
* @var string
*/
public $namingTemplate = '{attribute}_local';
/**
* @var Formatter
*/
public $formatter;
/**
* @var string|array Format of the attributes in the database
*/
public $originalFormat = ['datetime', 'yyyy-MM-dd HH:mm:ss'];
/**
* @var string|array Format of the attribute that should be shown to the user
*/
public $targetFormat = 'date';
/**
* @var string Value in the target format that will be displayed when original value is null
*/
public $nullValue = '';
/**
* @var array List of the model attributes in one of the following formats:
* ```php
* [
* 'first', // This will use default configuration and virtual attribute template
* 'second' => 'target_second', // This will use default configuration with custom attribute template
* 'third' => [
* 'targetAttribute' => 'target_third', // Optional
* // Rest of configuration
* ]
* ]
* ```
*/
public $attributes = [];
/**
* @var array
*/
public $attributeConfig = ['class' => 'omnilight\datetime\DateTimeAttribute'];
/**
* @var bool
*/
public $performValidation = true;
/**
* @var DateTimeAttribute[]
*/
public $attributeValues = [];
public function init()
{
if (is_null($this->formatter))
$this->formatter = \Yii::$app->formatter;
elseif (is_array($this->formatter))
$this->formatter = \Yii::createObject($this->formatter);
$this->prepareAttributes();
}
protected function prepareAttributes()
{
foreach ($this->attributes as $key => $value) {
$config = $this->attributeConfig;
$config['originalFormat'] = $this->originalFormat;
$config['targetFormat'] = $this->targetFormat;
$config['nullValue'] = $this->nullValue;
if (is_integer($key)) {
$originalAttribute = $value;
$targetAttribute = $this->processTemplate($originalAttribute);
} else {
$originalAttribute = $key;
if (is_string($value)) {
$targetAttribute = $value;
} else {
$targetAttribute = ArrayHelper::remove($value, 'targetAttribute', $this->processTemplate($originalAttribute));
$config = array_merge($config, $value);
}
}
$config['behavior'] = $this;
$config['originalAttribute'] = $originalAttribute;
$this->attributeValues[$targetAttribute] = $config;
}
}
protected function processTemplate($originalAttribute)
{
return strtr($this->namingTemplate, [
'{attribute}' => $originalAttribute,
]);
}
public function events()
{
$events = [];
if ($this->performValidation) {
$events[BaseActiveRecord::EVENT_BEFORE_VALIDATE] = 'onBeforeValidate';
}
return $events;
}
/**
* Performs validation for all the attributes
* @param Event $event
*/
public function onBeforeValidate($event)
{
foreach ($this->attributeValues as $targetAttribute => $value) {
if ($value instanceof DateTimeAttribute) {
$validator = \Yii::createObject([
'class' => DateValidator::className(),
'format' => self::normalizeIcuFormat($value->targetFormat, $this->formatter)[1],
]);
$validator->validateAttribute($this->owner, $targetAttribute);
}
}
}
/**
* @param string|array $format
* @param Formatter $formatter
* @throws InvalidParamException
* @return array|string
*/
public static function normalizeIcuFormat($format, $formatter)
{
if (is_string($format)) {
switch ($format) {
case 'date':
$format = $formatter->dateFormat;
if (strncmp($format, 'php:', 4) === 0) {
$format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
}
return ['date', $format];
case 'time':
$format = $formatter->timeFormat;
if (strncmp($format, 'php:', 4) === 0) {
$format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
}
return ['time', $format];
case 'datetime':
$format = $formatter->datetimeFormat;
if (strncmp($format, 'php:', 4) === 0) {
$format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
}
return ['datetime', $format];
default:
throw new InvalidParamException('$format has incorrect value');
}
} elseif (is_array($format) && count($format) < 2) {
throw new InvalidParamException('When $format is presented in array form, it must have at least two elements');
}
return $format;
}
public function canGetProperty($name, $checkVars = true)
{
if ($this->hasAttribute($name)) {
return true;
}
return parent::canGetProperty($name, $checkVars);
}
public function hasAttribute($name)
{
return isset($this->attributeValues[$name]);
}
public function canSetProperty($name, $checkVars = true)
{
if ($this->hasAttribute($name)) {
return true;
}
return parent::canSetProperty($name, $checkVars);
}
public function __get($name)
{
if ($this->hasAttribute($name)) {
return $this->getAttribute($name)->getValue();
}
return parent::__get($name);
}
public function __set($name, $value)
{
if ($this->hasAttribute($name)) {
$this->getAttribute($name)->setValue($value);
return;
}
parent::__set($name, $value);
}
public function getAttribute($name)
{
if (is_array($this->attributeValues[$name])) {
$this->attributeValues[$name] = \Yii::createObject($this->attributeValues[$name]);
}
return $this->attributeValues[$name];
}
}