Completed
Push — master ( 6db6da...5370d9 )
by Angel
03:42
created

LoadFileTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 0
loc 39
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A parseFileAttributes() 0 16 4
1
<?php
2
3
namespace roaresearch\yii2\roa\actions;
4
5
use yii\{base\Model, web\UploadedFile};
6
7
/**
8
 * Trait to configure and load uploaded files to a model.
9
 * @author Angel (Faryshta) Guevara <[email protected]>
10
 */
11
trait LoadFileTrait
12
{
13
    /**
14
     * @var string[] that defines which attributes will be recibe files.
15
     *
16
     * Example
17
     * ```php
18
     * [
19
     *     // 'avatar' attribute load file uploaded as 'avatar'
20
     *     'avatar',
21
     *     // 'background_fullsize' attribute load file uploaded as 'background'
22
     *     'background_fullsize' => 'background',
23
     * ]
24
     * ```
25
     */
26
    public $fileAttributes = [];
27
28
    /**
29
     * Parse the allowed uploaded files.
30
     *
31
     * @return UploadedFile[] files sent to the action.
32
     */
33
    protected function parseFileAttributes(): array
34
    {
35
        $files = [];
36
        foreach ($this->fileAttributes as $attribute => $value) {
37
            if (is_int($attribute)) {
38
                $attribute = $value;
39
            }
40
            if (null !== ($uploadedFile = UploadedFile::getInstanceByName(
41
                $value
42
            ))) {
43
                $files[$attribute] = $uploadedFile;
44
            }
45
        }
46
47
        return $files;
48
    }
49
}
50