FileTraits::deleteFiles()   B
last analyzed

Complexity

Conditions 9
Paths 53

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 9
eloc 19
c 2
b 0
f 1
nc 53
nop 1
dl 0
loc 29
rs 8.0555
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