FileSaveBehavior   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 20
dl 0
loc 41
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __set() 0 6 2
A canSetProperty() 0 3 1
A setFile() 0 9 3
A saveFile() 0 6 4
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
25
    public function canSetProperty($name, $checkVars = true)
26
    {
27
        return $name == $this->attribute;
28
    }
29
30
    public function __set($name, $value)
31
    {
32
        if ($this->canSetProperty($name)) {
33
            $this->setFile($value);
34
        } else {
35
            parent::__set($name, $value);
36
        }
37
    }
38
39
    protected function setFile($value)
40
    {
41
        if ($value instanceof UploadedFile) {
42
            $this->_file = $value;
43
        } else {
44
            $this->_file = UploadedFile::getInstance($this->owner, $this->attribute);
45
        }
46
        $eventName = $this->owner->isNewRecord ? ActiveRecord::EVENT_BEFORE_INSERT : ActiveRecord::EVENT_BEFORE_UPDATE;
47
        $this->owner->on($eventName, [$this, 'saveFile']);
48
    }
49
50
    public function saveFile()
51
    {
52
        if ($this->_file && $this->_file instanceof UploadedFile) {
53
            $field = $this->field ?: $this->attribute . '_id';
54
            $class = $this->fileClass;
55
            $this->owner->{$field} = $class::startUpload($this->_file)->process()->id;
56
        }
57
    }
58
}