Skip to content

Commit

Permalink
Merge pull request #86 from Nemmo/event-after-attach
Browse files Browse the repository at this point in the history
#69 Add event after attach files
  • Loading branch information
drtsb authored Sep 26, 2020
2 parents 697eff6 + f19feee commit ae041ad
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,21 @@ Usage
}
```

Using Events
------------
You may add the following function to your model

```php
public function init(){
$this->on(\nemmo\attachments\behaviors\FileBehavior::EVENT_AFTER_ATTACH_FILES, function ($event) {
/** @var $files \nemmo\attachments\models\File[] */
$files = $event->files;
//your custom code
});
parent::init();
}
```

Change log
----------

Expand Down
12 changes: 11 additions & 1 deletion src/behaviors/FileBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

namespace nemmo\attachments\behaviors;

use nemmo\attachments\events\FileEvent;
use nemmo\attachments\models\File;
use nemmo\attachments\ModuleTrait;
use yii\base\Behavior;
Expand All @@ -21,6 +22,8 @@ class FileBehavior extends Behavior
{
use ModuleTrait;

const EVENT_AFTER_ATTACH_FILES = 'afterAttachFiles';

public function events()
{
return [
Expand All @@ -43,11 +46,18 @@ public function saveUploads($event)
}

$userTempDir = $this->getModule()->getUserDirPath();
$attachedFiles = [];
foreach (FileHelper::findFiles($userTempDir) as $file) {
if (!$this->getModule()->attachFile($file, $this->owner)) {
if (!($attachedFile = $this->getModule()->attachFile($file, $this->owner))) {
throw new \Exception(\Yii::t('yii', 'File upload failed.'));
}else{
$attachedFiles[] = $attachedFile;
}
}
if(count($attachedFiles)){
$event = \Yii::createObject(['class' => FileEvent::class, 'files' => $attachedFiles]);
$this->owner->trigger(self::EVENT_AFTER_ATTACH_FILES, $event);
}
rmdir($userTempDir);
}

Expand Down
29 changes: 29 additions & 0 deletions src/events/FileEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace nemmo\attachments\events;

use yii\base\Event;

class FileEvent extends Event
{
/**
* @var nemmo\attachments\models\File[]
*/
private $_files;

/**
* @return nemmo\attachments\models\File[]
*/
public function getFiles()
{
return $this->_files;
}

/**
* @param nemmo\attachments\models\File[] $files
*/
public function setFiles($files)
{
$this->_files = $files;
}
}

0 comments on commit ae041ad

Please sign in to comment.