FileTraits   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 33
c 2
b 0
f 1
dl 0
loc 62
rs 10
wmc 14

4 Methods

Rating   Name   Duplication   Size   Complexity  
B deleteFiles() 0 29 9
A getImage() 0 9 2
A getFileName() 0 5 1
A getImages() 0 9 2
1
<?php
2
3
namespace FaithGen\SDK\Traits;
4
5
use Illuminate\Support\Facades\App;
6
use Illuminate\Support\Facades\Storage;
7
use Illuminate\Support\Str;
8
9
trait FileTraits
10
{
11
    private $dimensions = [0, 50, 100];
12
13
    public function getFileName(string $path)
14
    {
15
        $pieces = explode('/', $path);
16
17
        return $pieces[count($pieces) - 1];
18
    }
19
20
    public function getImage(string $dir, string $imageName, int $dimen = 0)
21
    {
22
        if ($dimen) {
23
            $dimen = $dimen.'-'.$dimen.'/';
24
        } else {
25
            $dimen = 'original/';
26
        }
27
28
        return storage_path('app/public/'.$dir.'/'.$dimen.$imageName);
29
    }
30
31
    public function getImages(string $dir, string $fileName, $dimensions = [])
32
    {
33
        if (! count($dimensions)) {
34
            $dimensions = $this->dimensions;
35
        }
36
37
        return collect($dimensions)
38
            ->map(fn ($dimension) => $this->getImage($dir, $fileName, $dimension))
39
            ->toArray();
40
    }
41
42
    public function deleteFiles($model)
43
    {
44
        $images = [];
45
        foreach ($model->getImageDimensions() as $imageDimension) {
46
            if (is_string($model->getFileName())) {
47
                array_push($images, $this->getImage($model->filesDir(), $model->getFileName(), $imageDimension));
48
            } elseif (is_array($model->getFileName())) {
49
                foreach ($model->getFileName() as $filename) {
50
                    array_push($images, $this->getImage($model->filesDir(), $filename, $imageDimension));
51
                }
52
            } else {
53
                throw new \InvalidArgumentException('The file name is invalid, string or array required', 500);
54
            }
55
        }
56
        try {
57
            foreach ($images as $file) {
58
                unlink($file);
59
            }
60
61
            if (App::environment('production')) {
62
                foreach ($images as $image) {
63
                    $imageName = Str::of($image)->after('public/');
64
                    Storage::disk('s3')->delete($imageName);
65
                }
66
            }
67
68
            return true;
69
        } catch (\Exception $e) {
70
            return false;
71
        }
72
    }
73
}
74