AttachmentActions::attach()   B
last analyzed

Complexity

Conditions 8
Paths 16

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 14
c 0
b 0
f 0
nc 16
nop 2
dl 0
loc 25
rs 8.4444
1
<?php
2
3
namespace Mostafaznv\Larupload\Concerns\Storage\Attachment;
4
5
use Illuminate\Http\UploadedFile;
6
use Mostafaznv\Larupload\Actions\GuessLaruploadFileTypeAction;
7
use Mostafaznv\Larupload\Actions\OptimizeImageAction;
8
use Mostafaznv\Larupload\Enums\LaruploadFileType;
9
10
11
trait AttachmentActions
12
{
13
    /**
14
     * Attach files into entity
15
     *
16
     * @param mixed $file
17
     * @param UploadedFile|null $cover
18
     * @return bool
19
     */
20
    public function attach(mixed $file, ?UploadedFile $cover = null): bool
21
    {
22
        $fileIsAttachable = (file_has_value($file) or $file == LARUPLOAD_NULL);
23
        $coverIsAttachable = (file_has_value($cover) or $cover == null);
24
25
        if ($fileIsAttachable and $coverIsAttachable) {
26
            file_is_valid($file, $this->name, 'file');
27
            file_is_valid($cover, $this->name, 'cover');
28
29
            $this->file = $file;
0 ignored issues
show
Bug Best Practice introduced by
The property file does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
30
            $this->uploaded = false;
0 ignored issues
show
Bug Best Practice introduced by
The property uploaded does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
31
32
            if ($file != LARUPLOAD_NULL) {
33
                $this->cover = $cover;
0 ignored issues
show
Bug Best Practice introduced by
The property cover does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
34
                $this->type = GuessLaruploadFileTypeAction::make($file)->calc();
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
35
36
                if ($this->type === LaruploadFileType::IMAGE && $this->optimizeImage) {
37
                    $this->file = OptimizeImageAction::make($file)->process();
38
                }
39
            }
40
41
            return true;
42
        }
43
44
        return false;
45
    }
46
47
    public function detach(): bool
48
    {
49
        return $this->attach(LARUPLOAD_NULL);
50
    }
51
}
52