FileSaveBehavior::saveFile()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 15
rs 9.6111
cc 5
nc 4
nop 1
1
<?php
2
3
namespace carono\yii2file\behaviors;
4
5
use carono\yii2file\FileUploadTrait;
6
use yii\db\ActiveRecord;
7
use yii\web\UploadedFile;
8
9
/**
10
 * Class FileSaveBehavior
11
 *
12
 * @package app\behaviors
13
 * @property ActiveRecord $owner
14
 */
15
class FileSaveBehavior extends \yii\base\Behavior
16
{
17
    protected $_file;
18
    public $attribute;
19
    public $field;
20
    /**
21
     * @var FileUploadTrait
22
     */
23
    public $fileClass;
24
    public $saveFile;
25
    public $removeFileValue = 'remove';
26
27
    public function canSetProperty($name, $checkVars = true)
28
    {
29
        return $name == $this->attribute;
30
    }
31
32
    public function __set($name, $value)
33
    {
34
        if ($this->canSetProperty($name)) {
35
            $this->setFile($value);
36
        } else {
37
            parent::__set($name, $value);
38
        }
39
    }
40
41
    protected function setFile($value)
42
    {
43
        if ($value instanceof UploadedFile) {
44
            $this->_file = $value;
45
        } else {
46
            $this->_file = UploadedFile::getInstance($this->owner, $this->attribute);
47
        }
48
        $eventName = $this->owner->isNewRecord ? ActiveRecord::EVENT_BEFORE_INSERT : ActiveRecord::EVENT_BEFORE_UPDATE;
49
50
        $data = [
51
            'file' => $this->_file,
52
            'field' => $this->field,
53
            'attribute' => $this->attribute,
54
            'fileClass' => $this->fileClass,
55
            'remove' => $value == $this->removeFileValue
56
        ];
57
58
        $this->owner->on($eventName, $this->saveFile instanceof \Closure ? $this->saveFile : [$this, 'saveFile'], $data);
59
    }
60
61
    public function saveFile($event)
62
    {
63
        $file = $event->data['file'];
64
        $field = $event->data['field'];
65
        $attribute = $event->data['attribute'];
66
        $fileClass = $event->data['fileClass'];
67
        $remove = $event->data['remove'];
68
69
        if ($file && $file instanceof UploadedFile) {
70
            $field = $field ?: $attribute . '_id';
71
            $this->owner->{$field} = $fileClass::startUpload($file)->process()->id;
72
        }
73
        
74
        if ($remove) {
75
            $this->owner->{$field} = null;
76
        }
77
    }
78
}