forked from omnilight/yii2-datetime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DateTimeRangeBehavior.php
117 lines (102 loc) · 2.98 KB
/
DateTimeRangeBehavior.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
<?php
namespace omnilight\datetime;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
/**
* Class DateTimeRangeBehavior
*/
class DateTimeRangeBehavior extends Behavior
{
/**
* @var string
*/
public $startAttribute;
/**
* @var string
*/
public $endAttribute;
/**
* @var string Separator between start and end dates
*/
public $separator = ' - ';
/**
* @var string Defines name of the target attribute. {start} and {end} placeholders can be used.
* After behaviour initialization this name will be replaced with real name of the target attribute
*/
public $targetAttribute = '{start}_{end}_range';
/**
* @var string
*/
protected $_value;
public function init()
{
parent::init();
if ($this->startAttribute === null)
throw new InvalidConfigException('$startAttribute is not set');
if ($this->endAttribute === null)
throw new InvalidConfigException('$endAttribute is not set');
$this->targetAttribute = strtr($this->targetAttribute, [
'{start}' => $this->startAttribute,
'{end}' => $this->endAttribute,
]);
}
public function canSetProperty($name, $checkVars = true)
{
if ($this->hasAttribute($name)) {
return true;
}
return parent::canSetProperty($name, $checkVars);
}
public function hasAttribute($attribute)
{
return $attribute === $this->targetAttribute;
}
public function canGetProperty($name, $checkVars = true)
{
if ($this->hasAttribute($name)) {
return true;
}
return parent::canGetProperty($name, $checkVars);
}
public function __get($name)
{
if ($this->hasAttribute($name)) {
return $this->getAttribute($name);
}
return parent::__get($name);
}
public function __set($name, $value)
{
if ($this->hasAttribute($name)) {
$this->setAttribute($value);
return;
}
parent::__set($name, $value);
}
public function getAttribute($name)
{
if ($this->_value) {
return $this->_value;
}
return (string)$this->owner->{$this->startAttribute} . $this->separator . (string)$this->owner->{$this->endAttribute};
}
public function setAttribute($value)
{
$this->_value = $value;
if ($this->validateValue($value)) {
$separator = preg_quote($this->separator, '/');
list($start, $end) = preg_split("/\\s*{$separator}\\s*/", $value, 2, PREG_SPLIT_NO_EMPTY);
$this->owner->{$this->startAttribute} = $start;
$this->owner->{$this->endAttribute} = $end;
}
}
/**
* @param string $value
* @return bool
*/
public function validateValue($value)
{
$separator = preg_quote($this->separator, '/');
return preg_match("/^.+{$separator}.+$/", $value) === 1;
}
}