-
Notifications
You must be signed in to change notification settings - Fork 5
/
DateTimeAttribute.php
82 lines (74 loc) · 1.86 KB
/
DateTimeAttribute.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
<?php
namespace omnilight\datetime;
use yii\base\Arrayable;
use yii\base\Object;
use yii\helpers\FormatConverter;
/**
* Class DateTimeAttribute
* @property string $value
*/
class DateTimeAttribute extends Object
{
/**
* @var DateTimeBehavior
*/
public $behavior;
/**
* @var string
*/
public $originalAttribute;
/**
* @var string|array
*/
public $originalFormat;
/**
* @var string|array
*/
public $targetFormat;
/**
* @var string
*/
public $nullValue;
/**
* @var string
*/
protected $_value;
function __toString()
{
return $this->getValue();
}
function __invoke()
{
return $this->getValue();
}
/**
* @return string
*/
public function getValue()
{
try {
if ($this->_value !== null) {
return $this->_value;
} else {
$originalValue = $this->behavior->owner->{$this->originalAttribute};
if ($originalValue === null)
return $this->nullValue;
else
return $this->behavior->formatter->format($originalValue, $this->targetFormat);
}
} catch (\Exception $e) {
return $this->nullValue;
}
}
/**
* @param string $value
*/
public function setValue($value)
{
$this->_value = $value;
$normalizedFormat = DateTimeBehavior::normalizeIcuFormat($this->targetFormat, $this->behavior->formatter);
$phpFormat = FormatConverter::convertDateIcuToPhp($normalizedFormat[1], $normalizedFormat[0], \Yii::$app->language);
$dateTime = date_create_from_format($phpFormat, $value);
$this->behavior->owner->{$this->originalAttribute} = $this->behavior->formatter->format($dateTime, $this->originalFormat);
}
}