LoadFileTrait::parseFileAttributes()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 6

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 5
nop 0
dl 0
loc 15
ccs 4
cts 8
cp 0.5
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace roaresearch\yii2\roa\actions;
4
5
use yii\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 array $fileAttributes = [];
27
28
    /**
29
     * Parse the allowed uploaded files.
30
     *
31
     * @return UploadedFile[] files sent to the action.
32
     */
33 5
    protected function parseFileAttributes(): array
34
    {
35 5
        $files = [];
36 5
        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 5
        return $files;
48
    }
49
}
50