Skip to content

Instantly share code, notes, and snippets.

@crisu83
Created February 28, 2013 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crisu83/5055231 to your computer and use it in GitHub Desktop.
Save crisu83/5055231 to your computer and use it in GitHub Desktop.
Audit active record behavior.
<?php
require(__DIR__ . '/../models/AuditAttribute.php');
require(__DIR__ . '/../models/AuditModel.php');
class AuditBehavior extends CActiveRecordBehavior {
// Audit actions
const ACTION_CREATE = 'create';
const ACTION_DELETE = 'delete';
/**
* @var string the name of the id column.
*/
public $idAttribute = 'id';
/**
* @var array a list of columns that does not create an entry when they change.
*/
public $exclude = array();
private $_oldAttributes;
public function afterFind($event) {
$this->_oldAttributes = $this->owner->getAttributes();
}
public function beforeSave($event) {
/* @var CActiveRecord $owner */
$owner = $this->getOwner();
if (!$owner->isNewRecord) {
foreach ($owner->getAttributes() as $name => $value) {
if (in_array($name, $this->exclude)) {
continue;
}
if ((string)$value !== (string)$this->_oldAttributes[$name]) {
list($changer, $changerId) = $this->getChanger();
list($model, $modelId) = $this->getModel();
$entry = new AuditAttribute;
$entry->changer = $changer;
$entry->changerId = $changerId;
$entry->model = $model;
$entry->modelId = $modelId;
$entry->attribute = $name;
$entry->oldValue = $this->_oldAttributes[$name];
$entry->newValue = $owner->attributes[$name];
$entry->created = new CDbExpression('NOW()');
$entry->save();
}
}
}
}
public function afterSave($event) {
if ($this->owner->isNewRecord) {
$this->createModelEntry(self::ACTION_CREATE);
}
}
public function beforeDelete($event) {
$this->createModelEntry(self::ACTION_DELETE);
}
protected function createModelEntry($action) {
list($changer, $changerId) = $this->getChanger();
list($model, $modelId) = $this->getModel();
$entry = new AuditModel;
$entry->action = $action;
$entry->changer = $changer;
$entry->changerId = $changerId;
$entry->model = $model;
$entry->modelId = $modelId;
$entry->created = new CDbExpression('NOW()');
$entry->save();
}
protected function getChanger() {
$app = Yii::app();
if ($app instanceof CWebApplication) {
/* @var AuditChanger $user */
$user = $app->getUser();
$changer = $user->modelClass;
$changerId = $user->{$user->idAttribute};
} else {
$changer = 'Console';
$changerId = 0;
}
return array($changer, $changerId);
}
protected function getModel() {
$owner = $this->getOwner();
$model = get_class($owner);
$modelId = $owner->{$this->idAttribute};
return array($model, $modelId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment