-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySQLDateTimeBehavior.php
More file actions
80 lines (75 loc) · 2.19 KB
/
MySQLDateTimeBehavior.php
File metadata and controls
80 lines (75 loc) · 2.19 KB
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
<?php
/**
* Class MySQLDateTimeBehavior
* Automatically converts date and datetime fields between ActiveRecord model and MySQL database.
*
* Author: kikimor <i@kikimor.ru>
* Version: 1.1.2
* Requires: Yii 1.0.9 version
*/
class MySQLDateTimeBehavior extends CActiveRecordBehavior
{
/**
* Date format (PHP date format)
* @var string
*/
public $dateFormat = 'd.m.Y';
/**
* DateTime format (PHP date format)
* @var string
*/
public $dateTimeFormat = 'd.m.Y H:i';
/*
* Source columns data.
*/
private $sourceValues;
/**
* @param CEvent $event
*/
public function afterFind($event)
{
foreach ($event->sender->tableSchema->columns as $columnName => $column) {
if ($column->dbType != 'date' and $column->dbType != 'datetime') continue;
if (($timestamp = strtotime($event->sender->$columnName)) !== false) {
switch ($column->dbType) {
case 'date':
$event->sender->$columnName = date($this->dateFormat, $timestamp);
break;
case 'datetime':
$event->sender->$columnName = date($this->dateTimeFormat, $timestamp);
break;
}
}
}
}
/**
* @param CModelEvent $event
*/
public function beforeSave($event)
{
$this->sourceValues = [];
foreach ($event->sender->tableSchema->columns as $columnName => $column) {
if ($column->dbType != 'date' and $column->dbType != 'datetime') continue;
$this->sourceValues[$columnName] = $event->sender->$columnName;
if (($timestamp = strtotime($event->sender->$columnName)) !== false) {
$key = ':date' . md5($columnName);
$event->sender->$columnName = new CDbExpression(
'STR_TO_DATE(' . $key . ', "%d%m%Y%H%i%s")',
[$key => date('dmYHis', $timestamp)]
);
} elseif ($column->allowNull && !is_object($event->sender->$columnName)) {
$event->sender->$columnName = new CDbExpression('NULL');
}
}
}
/**
* @param CModelEvent $event
*/
public function afterSave($event)
{
foreach ($event->sender->tableSchema->columns as $columnName => $column) {
if ($column->dbType != 'date' and $column->dbType != 'datetime') continue;
$event->sender->$columnName = $this->sourceValues[$columnName];
}
}
}