PersistUploadedFile::handle()   C
last analyzed

Complexity

Conditions 8
Paths 24

Size

Total Lines 78
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 78
ccs 0
cts 43
cp 0
rs 6.102
cc 8
eloc 42
nc 24
nop 1
crap 72

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace App\Listeners\Files;
2
3
use App\Events\Files\Uploaded;
4
use App\Models\File;
5
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
6
use Illuminate\Http\Response as IlluminateResponse;
7
use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
8
9
class PersistUploadedFile
10
{
11
    /**
12
     * @param \App\Events\Files\Uploaded $event
13
     *
14
     * @return \Symfony\Component\HttpFoundation\JsonResponse
15
     */
16
    public function handle(Uploaded $event)
17
    {
18
        $uploadUuid = $event->uploadUuid;
19
        $request = $event->request;
20
21
        /*
22
        |--------------------------------------------------
23
        | Move file to its final permanent destination.
24
        |--------------------------------------------------
25
        */
26
27
        $hash = hash_file('sha256', app('filestream')->getAbsolutePath($uploadUuid));
28
        $destination = $hash;
29
        if (config('filesystems.load_balancing.enabled')) {
30
            $config = config('filesystems.load_balancing');
31
            $folders = [];
32
            for ($i = 0; $i < $config['depth']; $i++) {
33
                $folders[] = substr($hash, -1 * ($i + 1) * $config['length'], $config['length']);
34
            }
35
            $destination = implode(DIRECTORY_SEPARATOR, array_merge($folders, [$hash]));
36
        }
37
        $filesystem = app('filesystem')->disk();
38
        (!$filesystem->exists($destination)) ? $filesystem->move($uploadUuid, $destination) : $filesystem->delete($uploadUuid);
39
40
        /*
41
        |---------------------------------
42
        | Check the tag and its limit.
43
        |---------------------------------
44
        */
45
46
        /** @var \App\Models\User $me */
47
        $me = app('sentinel')->getUser();
48
        $tag = $request->get('qqtag');
49
        $tagLimit = config('filesystems.allowed_tags_and_limits.' . $tag);
50
        if ($tagLimit > 0) {
51
            $allFilesWithSameTagBelongingToUser = $me->load([
52
                'files' => function (BelongsToMany $query) use ($tag) {
53
                    $query->wherePivot('tag', '=', $tag);
54
                }
55
            ])->files;
56
            if (($numberOfFilesToDeleteToComplyWitTagLimit = $allFilesWithSameTagBelongingToUser->count() - $tagLimit + 1) > 0) {
57
                while ($numberOfFilesToDeleteToComplyWitTagLimit > 0) {
58
                    $pivotToDelete = $allFilesWithSameTagBelongingToUser->shift();
59
                    app('filestream')->deleteFile($pivotToDelete->hash, $tag);
60
                    $numberOfFilesToDeleteToComplyWitTagLimit--;
61
                }
62
            }
63
        }
64
65
        /*
66
        |------------------------------------
67
        | Persist file record in database.
68
        |------------------------------------
69
        */
70
71
        $uploadedFile = new SymfonyFile(app('filestream')->getAbsolutePath($destination));
72
        if (!$file = File::find($hash = $uploadedFile->getFilename())) {
73
            $file = new File();
74
            $file->hash = $hash;
75
            $file->disk = 'local';
76
            $file->path = trim(str_replace(config('filesystems.disks.local.root'), '', $uploadedFile->getPathname()), DIRECTORY_SEPARATOR);
77
            $file->mime = $uploadedFile->getMimeType();
78
            $file->size = $uploadedFile->getSize();
79
            $file->save();
80
        }
81
82
        $me->files()->newPivotStatement()->whereTag($tag)->whereFileHash($hash)->delete();
83
84
        $file->uploaders()->attach([
85
            $me->getUserId() => [
0 ignored issues
show
Documentation Bug introduced by
The method getUserId does not exist on object<App\Models\User>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
86
                'uuid' => $request->get('qquuid'),
87
                'original_client_name' => $request->get('qqfilename'),
88
                'tag' => $tag
89
            ]
90
        ]);
91
92
        return response()->json(['success' => true, 'hash' => $file->hash])->setStatusCode(IlluminateResponse::HTTP_CREATED);
93
    }
94
}
95