Skip to content

Commit

Permalink
add ability to autosave and autodelete
Browse files Browse the repository at this point in the history
  • Loading branch information
mdmunir committed Nov 3, 2014
1 parent 0138ae5 commit 0cd917d
Showing 1 changed file with 58 additions and 1 deletion.
59 changes: 58 additions & 1 deletion UploadBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Yii;
use yii\web\UploadedFile;
use yii\db\BaseActiveRecord;

/**
* UploadBehavior save uploaded file into [[$uploadPath]] and store information in database.
Expand Down Expand Up @@ -52,6 +53,21 @@ class UploadBehavior extends \yii\base\Behavior
*/
public $directoryLevel = 1;

/**
* @var boolean when true `saveUploadedFile()` will be called on event 'beforeSave'
*/
public $autoSave = false;

/**
* @var boolean when true then related file will be deleted on event 'beforeDelete'
*/
public $autoDelete = false;

/**
* @var boolean
*/
public $deleteOldFile = false;

/**
* @var UploadedFile
*/
Expand All @@ -65,6 +81,21 @@ public function init()
$this->uploadPath = Yii::getAlias($this->uploadPath);
}

/**
* @inheritdoc
*/
public function events()
{
$event = [];
if ($this->autoSave) {
$event[BaseActiveRecord::EVENT_BEFORE_INSERT] = 'beforeSave';
$event[BaseActiveRecord::EVENT_BEFORE_UPDATE] = 'beforeSave';
}
if ($this->autoDelete && $this->savedAttribute !== null) {
$event[BaseActiveRecord::EVENT_BEFORE_DELETE] = 'beforeDelete';
}
}

/**
* @inheritdoc
*/
Expand Down Expand Up @@ -116,14 +147,17 @@ public function canGetProperty($name, $checkVars = true)
* @return boolean|null if success return true, fault return false.
* Return null mean no uploaded file.
*/
public function saveUploadedFile($deleteOldFile = false)
public function saveUploadedFile($deleteOldFile = null)
{
/* @var $file UploadedFile */
$file = $this->{$this->attribute};
if ($file !== null) {
$model = FileModel::saveAs($file, $this->uploadPath, $this->directoryLevel);
if ($model) {
if ($this->savedAttribute !== null) {
if ($deleteOldFile === null) {
$deleteOldFile = $this->deleteOldFile;
}
$oldId = $this->owner->{$this->savedAttribute};
$this->owner->{$this->savedAttribute} = $model->id;
if ($deleteOldFile && ($oldModel = FileModel::findOne($oldId)) !== null) {
Expand All @@ -135,4 +169,27 @@ public function saveUploadedFile($deleteOldFile = false)
return false;
}
}

/**
* Event handler for beforeSave
* @param \yii\base\ModelEvent $event
*/
public function beforeSave($event)
{
if ($this->saveUploadedFile() === false) {
$event->isValid = false;
}
}

/**
* Event handler for beforeDelete
* @param \yii\base\ModelEvent $event
*/
public function beforeDelete($event)
{
$oldId = $this->owner->{$this->savedAttribute};
if (($oldModel = FileModel::findOne($oldId)) !== null) {
$event->isValid = $event->isValid && $oldModel->delete();
}
}
}

0 comments on commit 0cd917d

Please sign in to comment.