Skip to content

Commit

Permalink
* CDateTimeBehavior: added scenarios
Browse files Browse the repository at this point in the history
* CDateTimeBehavior: added getDateTimeAttr
* CDateTimeBehavior: refactoring
* CDateTimeBehavior: added readme.md and readme_ru.md
  • Loading branch information
tokolist committed Aug 24, 2012
1 parent 3c93c65 commit e387cd6
Show file tree
Hide file tree
Showing 6 changed files with 307 additions and 16 deletions.
Expand Up @@ -3,7 +3,7 @@
* Behaviour for converting date formats between the DB and model
* @author Yaroslav Pelesh aka Tokolist http://tokolist.com
* @link https://github.com/tokolist/yii-components
* @version 1.0
* @version 1.1
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/

Expand All @@ -16,6 +16,9 @@ class CDateTimeBehavior extends CActiveRecordBehavior
public $clientFormat = 'dd.MM.yyyy';
public $attributes = array();

protected $originalValues = array();


protected function convertDateTimeFormat($date, $fromFormat, $toFormat)
{
return Yii::app()->dateFormatter->format(
Expand All @@ -36,34 +39,69 @@ protected function processAttributes($model, $direction)
if(!is_array($attribute))
$attribute = array($attribute);

$attributeNames = split(',', $attribute[0]);
$attributeNames = array_map('trim', explode(',', $attribute[0]));

foreach($attributeNames as $attributeName)
$scenarios = false;
if(is_string($attribute['on']))
{
$attributeName = trim($attributeName);

if(empty($model->$attributeName))
continue;
$scenarios = array_map('trim', explode(',', $attribute['on']));
}

if($scenarios === false || in_array($this->owner->scenario, $scenarios))
{
foreach($attributeNames as $attributeName)
{
if(empty($model->$attributeName))
continue;

$fromFormat = isset($attribute['dbFormat']) ? $attribute['dbFormat'] : $this->dbFormat;
$toFormat = isset($attribute['clientFormat']) ? $attribute['clientFormat'] : $this->clientFormat;

$fromFormat = isset($attribute['dbFormat']) ? $attribute['dbFormat'] : $this->dbFormat;
$toFormat = isset($attribute['clientFormat']) ? $attribute['clientFormat'] : $this->clientFormat;
if($direction == self::DIRECTION_CLIENT)
{
$this->originalValues[$attributeName] = array(
'value'=>$model->$attributeName,
'format'=>$fromFormat,
);
}

if($direction == self::DIRECTION_DB)
list($fromFormat, $toFormat) = array($toFormat, $fromFormat);
if($direction == self::DIRECTION_DB)
{
list($fromFormat, $toFormat) = array($toFormat, $fromFormat);
}

$model->$attributeName = $this->convertDateTimeFormat(
$model->$attributeName, $fromFormat, $toFormat);
$model->$attributeName = $this->convertDateTimeFormat(
$model->$attributeName, $fromFormat, $toFormat);
}
}
}
}

public function beforeSave($event)
{
parent::beforeSave($event);
$this->processAttributes($event->sender, self::DIRECTION_DB);
}

public function afterFind($event)
{
parent::afterFind($event);
$this->processAttributes($event->sender, self::DIRECTION_CLIENT);
}

public function getDateTimeAttr($attribute, $format=false)
{
if(!isset($this->originalValues[$attribute]['value']))
return $this->owner->$attribute;

$result = $this->originalValues[$attribute]['value'];

if($format !== false)
{
$result = $this->convertDateTimeFormat($result,
$this->originalValues[$attribute]['format'], $format);
}

return $result;
}
}
127 changes: 127 additions & 0 deletions protected/extensions/yiicomp/behaviors/DateTimeBehavior/readme.md
@@ -0,0 +1,127 @@
CDateTimeBehavior
=================

`CDateTimeBehavior` - flexible behavior, that automatically converts date attribute values
into specified formats between the client and database.

Installation
------------

1. Copy DateTimeBehavior directory to Yii `components` directory

2. Add an import path

~~~php
'import'=>array(

...

'application.components.DateTimeBehavior.CDateTimeBehavior',

...

)
~~~

3. Attach the behavior to your model

~~~php
public function behaviors()
{
return array(
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'attributes'=>'date_of_birth, passport_expiration',
),
);
}
~~~

Date/time format patterns
-------------------------

Please see http://www.unicode.org/reports/tr35/#Date_Format_Patterns for details
about the recognized pattern characters.

Properties
----------

`dbFormat` - default DB format for each processed attribute. Default value is `yyyy-MM-dd`.

`clientFormat` - default client format for each processed attribute. Default value is `dd.MM.yyyy`.

`attributes` - which attributes should be processed, their formats etc. (please see samples below)

Methods
-------

~~~php
public function getDateTimeAttr($attribute, $format=false);
~~~

Retrieves date/time attribute value in unmodified or in specified in the second parameter format.
If an attribute is not processed by behavior, than model unmodified attribute value is
returned (the second method parameter is ignored).

`$attribute` - name of an attribute

`$format` - date/time format, in which attribute value will be returned. Function returns unmodified
attribute value if this attribute is unspecified or equal to `false`.


Usage samples
-------------

Simple usage:

~~~php
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'attributes'=>'date_of_birth, passport_expiration',
),
~~~

In the above sample behavior converts attributes with default date formats.

You can change default formats:

~~~php
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'dbFormat'=>'dd-MM-yyyy',
'clientFormat'=>'MM/dd/yyyy',
'attributes'=>'date_of_birth, passport_expiration',
),
~~~

Advanced sample:

~~~php
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'attributes' => array(
'date_start, date_end', //default formats

//Attribute with formats, that differ from default ones
array(
'date_created',
'dbFormat' => 'yyyy-MM-dd HH:mm:ss',
'clientFormat' => 'dd.MM.yyyy HH:mm:ss'
),

array(
'date_scenario',
'dbFormat' => 'yyyy-MM-dd',
'clientFormat' => 'dd.MM.yyyy'
'on'=>'scenario1, scenario2', //scenarios can be specified
),

array(
'date_scenario',
'dbFormat' => 'dd-MM-yyyy',
'clientFormat' => 'MM/dd/yyyy'
'on'=>'scenario3', //scenarios can be specified
),
),
),
~~~
127 changes: 127 additions & 0 deletions protected/extensions/yiicomp/behaviors/DateTimeBehavior/readme_ru.md
@@ -0,0 +1,127 @@
CDateTimeBehavior
=================

`CDateTimeBehavior` - гибко настраиваемое поведение, позволяющее конвертировать
форматы дат/времени между базой и клиентом.

Installation
------------

1. Скопируйте директорию DateTimeBehavior в директорию `components`

2. Добавьте импорт

~~~php
'import'=>array(

...

'application.components.DateTimeBehavior.CDateTimeBehavior',

...

)
~~~

3. Привяжите поведение к модели

~~~php
public function behaviors()
{
return array(
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'attributes'=>'date_of_birth, passport_expiration',
),
);
}
~~~

Паттерны даты/времени
---------------------

Пожалуйста, смотрите по нижеследующей ссылке возможные значения паттернов
http://www.unicode.org/reports/tr35/#Date_Format_Patterns

Свойства
--------

`dbFormat` - формат дат в БД по умолчанию для всех атрибутов. Значение по умолчанию равно `yyyy-MM-dd`.

`clientFormat` - формат дат клиента по умолчанию для всех атрибутов. Значение по умолчанию равно `dd.MM.yyyy`.

`attributes` - какие атрибуты должны обрабатываться, их значения и т.п. (см. примеры ниже)

Методы
------

~~~php
public function getDateTimeAttr($attribute, $format=false);
~~~

Получает значение даты/времени не модифицированным или в указанном во втором параметре формате.
Если атрибут не обрабатывается поведением, то будет возвращено не модифицированное
значение атрибута модели (второй параметр в таком случае игнорируется).

`$attribute` - название атрибута

`$format` - формат, в котором будет возвращена дата/время. Если параметр не указан
или его значение равно `false`, будет возвращено не модифицированное значение.


Примеры использования
---------------------

Простое использование:

~~~php
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'attributes'=>'date_of_birth, passport_expiration',
),
~~~

В примере выше атрибуты будут конвертированы в форматы по умолчанию.

Можно изменить форматы по умолчанию:

~~~php
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'dbFormat'=>'dd-MM-yyyy',
'clientFormat'=>'MM/dd/yyyy',
'attributes'=>'date_of_birth, passport_expiration',
),
~~~

Сложный пример:

~~~php
'dateTimeBehavior' => array(
'class'=>'CDateTimeBehavior',
'attributes' => array(
'date_start, date_end', //в форматах по умолчанию

//Атрибут с форматами отличными от форматов по умолчанию
array(
'date_created',
'dbFormat' => 'yyyy-MM-dd HH:mm:ss',
'clientFormat' => 'dd.MM.yyyy HH:mm:ss'
),

array(
'date_scenario',
'dbFormat' => 'yyyy-MM-dd',
'clientFormat' => 'dd.MM.yyyy'
'on'=>'scenario1, scenario2', //можно указывать сценарии
),

array(
'date_scenario',
'dbFormat' => 'dd-MM-yyyy',
'clientFormat' => 'MM/dd/yyyy'
'on'=>'scenario3', //можно указывать сценарии
),
),
),
~~~
@@ -1,7 +1,7 @@
CButtonColumnEx
===============

CButtonColumnEx - extended CButtonColumn, in which template and button options
`CButtonColumnEx` - extended CButtonColumn, in which template and button options
can be php expressions.

Installation
Expand Down
@@ -1,7 +1,7 @@
CButtonColumnEx
===============

CButtonColumnEx - потомок CButtonColumn, в котором свойство template и свойства options
`CButtonColumnEx` - потомок CButtonColumn, в котором свойство template и свойства options
кнопок могут быть php-выражениями.

Подключение
Expand Down
Expand Up @@ -545,7 +545,6 @@ public function resizeCanvas($toWidth, $toHeight, $backgroundColor = array(255,

public function grayscale()
{
//$newImage=$this->createImage($this->width, $this->height, $this->trueColor);
$newImage = imagecreatetruecolor($this->width, $this->height);

imagecopy($newImage, $this->image, 0, 0, 0, 0, $this->width, $this->height);
Expand Down

0 comments on commit e387cd6

Please sign in to comment.