Gentics Portal.Node PHP API
 All Classes Namespaces Functions Variables Pages
DateTimeI18NBehavior.php
1 <?php
2 /*
3  * DateTimeI18NBehavior
4  * Automatically converts date and datetime fields to I18N format
5  *
6  * Author: Ricardo Grana <rickgrana@yahoo.com.br>, <ricardo.grana@pmm.am.gov.br>
7  * Version: 1.1
8  * Requires: Yii 1.0.9 version
9  */
10 
11 class DateTimeI18NBehavior extends CActiveRecordBehavior
12 {
13  public $dateOutcomeFormat = 'Y-m-d';
14  public $dateTimeOutcomeFormat = 'Y-m-d H:i:s';
15 
16  public $dateIncomeFormat = 'yyyy-MM-dd';
17  public $dateTimeIncomeFormat = 'yyyy-MM-dd hh:mm:ss';
18 
19  public $timeFields = array('date', 'datetime', 'timestamp');
20 
21  public function beforeSave($event){
22 
23  //search for date/datetime columns. Convert it to pure PHP date format
24  foreach($event->sender->tableSchema->columns as $columnName => $column){
25  if (!in_array($column->dbType, $this->timeFields)) continue;
26  if (!strlen($event->sender->$columnName)){
27  $event->sender->$columnName = null;
28  continue;
29  }
30  if (($column->dbType == 'date')) {
31  $timestamp = CDateTimeParser::parse($event->sender->$columnName, Yii::app()->locale->dateFormat);
32  if($timestamp === false) {
33  $timestamp = strtotime($event->sender->$columnName);
34  }
35  $event->sender->$columnName = date($this->dateOutcomeFormat, $timestamp);
36  }else{
37  $pattern = strtr(Yii::app()->locale->dateTimeFormat, array(
38  '{0}' => Yii::app()->locale->timeFormat,
39  '{1}' => Yii::app()->locale->dateFormat
40  ));
41  $timestamp = CDateTimeParser::parse($event->sender->$columnName, $pattern);
42  if($timestamp === false) {
43  $timestamp = strtotime($event->sender->$columnName);
44  }
45  if($timestamp === false) {
46  $timestamp = $event->sender->$columnName;
47  }
48  if(!$timestamp) return false;
49  $event->sender->$columnName = date($this->dateTimeOutcomeFormat, $timestamp);
50  }
51  }
52  return true;
53  }
54 
55  public function afterFind($event){
56 
57  foreach($event->sender->tableSchema->columns as $columnName => $column){
58  if (!in_array($column->dbType, $this->timeFields)) continue;
59 
60  if (!strlen($event->sender->$columnName)) {
61  $event->sender->$columnName = null;
62  continue;
63  }
64  if ($column->dbType == 'date') {
65  $timestamp = CDateTimeParser::parse($event->sender->$columnName, $this->dateIncomeFormat);
66  if(!$timestamp) return false;
67  $event->sender->$columnName = Yii::app()->dateFormatter->formatDateTime($timestamp, 'medium', null);
68  } else {
69  $timestamp = CDateTimeParser::parse($event->sender->$columnName, $this->dateTimeIncomeFormat);
70  if(!$timestamp) return false;
71  $event->sender->$columnName = Yii::app()->dateFormatter->formatDateTime($timestamp, 'medium', 'medium');
72  }
73  }
74  return true;
75  }
76 }