Passed
Push — master ( 51edae...d29a9b )
by Curtis
11:52 queued 05:54
created

UploadManager   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 54
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A existingFiles() 0 5 1
A __construct() 0 4 1
A checkExisting() 0 11 2
A uploadFiles() 0 3 1
A handle() 0 8 1
A uploadFile() 0 7 1
1
<?php
2
3
namespace App\Service\enso\files;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\Support\Facades\DB;
8
use LaravelEnso\Files\Exceptions\File as FileException;
9
use App\Http\Resources\enso\files\File as Resource;
10
use App\Models\enso\files\File;
11
use App\Models\enso\files\Upload;
12
13
class UploadManager
14
{
15
    private Collection $uploadedFiles;
16
    private Collection $files;
17
18
    public function __construct(array $files)
19
    {
20
        $this->uploadedFiles = new Collection();
21
        $this->files = new Collection($files);
22
    }
23
24
    public function handle(): Collection
25
    {
26
        DB::transaction(function () {
27
            $this->checkExisting()
28
                ->uploadFiles();
29
        });
30
31
        return $this->uploadedFiles;
32
    }
33
34
    private function checkExisting(): self
35
    {
36
        $existing = $this->files
37
            ->map(fn ($file) => $file->getClientOriginalName())
38
            ->intersect($this->existingFiles());
39
40
        if ($existing->isNotEmpty()) {
41
            throw FileException::duplicates($existing->implode(', '));
42
        }
43
44
        return $this;
45
    }
46
47
    private function uploadFiles(): void
48
    {
49
        $this->files->each(fn ($file) => $this->uploadFile($file));
50
    }
51
52
    private function uploadFile($file): void
53
    {
54
        $upload = tap(Upload::create())
55
            ->upload($file);
56
57
        $this->uploadedFiles->push(new Resource(
58
            $upload->file->load(['attachable', 'createdBy.avatar']))
59
        );
60
    }
61
62
    private function existingFiles(): Collection
63
    {
64
        return File::forUser(Auth::user())
65
            ->whereAttachableType(Upload::class)
66
            ->pluck('original_name');
67
    }
68
}
69