Passed
Push — master ( 81f334...c86e8c )
by Mihail
03:35
created

ActionGalleryUpload   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 85
Duplicated Lines 3.53 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
dl 3
loc 85
rs 10
c 0
b 0
f 0
wmc 13
lcom 1
cbo 11

1 Method

Rating   Name   Duplication   Size   Complexity  
C galleryUpload() 3 74 13

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Apps\Controller\Api\Content;
4
5
use Ffcms\Core\App;
6
use Ffcms\Core\Exception\ForbiddenException;
7
use Ffcms\Core\Exception\NativeException;
8
use Ffcms\Core\Helper\FileSystem\Directory;
9
use Ffcms\Core\Helper\FileSystem\File;
10
use Ffcms\Core\Helper\FileSystem\Normalize;
11
use Ffcms\Core\Helper\Type\Arr;
12
use Ffcms\Core\Helper\Type\Str;
13
use Ffcms\Core\Network\Request;
14
use Ffcms\Core\Network\Response;
15
use Gregwar\Image\Image;
16
17
/**
18
 * Trait ActionGalleryUpload
19
 * @package Apps\Controller\Api\Content
20
 * @property Request $request
21
 * @property Response $response
22
 * @method void setJsonHeader()
23
 */
24
trait ActionGalleryUpload
25
{
26
    /**
27
     * Upload new files to content item gallery
28
     * @param string $id
29
     * @return string
30
     * @throws ForbiddenException
31
     * @throws NativeException
32
     * @throws \Exception
33
     */
34
    public function galleryUpload(string $id)
35
    {
36
        $this->setJsonHeader();
37
38
        // check if id is passed
39
        if (Str::likeEmpty($id)) {
40
            throw new NativeException('Wrong input data');
41
        }
42
43
        // check if user have permission to access there
44 View Code Duplication
        if (!App::$User->isAuth() || !App::$User->identity()->role->can('global/file')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
45
            throw new NativeException(__('Permissions to upload is denied'));
46
        }
47
48
        // check if directory exist
49
        if (!Directory::exist('/upload/gallery/' . $id)) {
50
            Directory::create('/upload/gallery/' . $id);
51
        }
52
53
        // get file object
54
        /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */
55
        $file = $this->request->files->get('file');
56
        if ($file === null || $file->getError() !== 0) {
57
            throw new NativeException(__('Unexpected error in upload process'));
58
        }
59
60
        // check file size
61
        if ($file->getSize() < 1 || $file->getSize() > $this->maxSize) {
62
            throw new ForbiddenException(__('File size is too big. Max size: %size%kb', ['size' => (int)($this->maxSize/1024)]));
0 ignored issues
show
Bug introduced by
The property maxSize does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
63
        }
64
65
        // check file extension
66
        if (!Arr::in($file->guessExtension(), $this->allowedExt)) {
67
            throw new ForbiddenException(__('File extension is not allowed to upload. Allowed: %s%', ['s' => implode(', ', $this->allowedExt)]));
0 ignored issues
show
Bug introduced by
The property allowedExt does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
68
        }
69
70
        // create origin directory
71
        $originPath = '/upload/gallery/' . $id . '/orig/';
72
        if (!Directory::exist($originPath)) {
73
            Directory::create($originPath);
74
        }
75
76
        // lets make a new file name
77
        $fileName = App::$Security->simpleHash($file->getClientOriginalName() . $file->getSize());
78
        $fileNewName = $fileName . '.' . $file->guessExtension();
79
        // check if image is already loaded
80
        if (File::exist($originPath . $fileNewName)) {
81
            throw new ForbiddenException(__('File is always exists!'));
82
        }
83
        // save file from tmp to gallery origin directory
84
        $file->move(Normalize::diskFullPath($originPath), $fileNewName);
85
86
        // lets resize preview image for it
87
        $thumbPath = '/upload/gallery/' . $id . '/thumb/';
88
        if (!Directory::exist($thumbPath)) {
89
            Directory::create($thumbPath);
90
        }
91
92
        $thumb = new Image();
93
        $thumb->setCacheDir(root . '/Private/Cache/images');
94
95
        // open original file, resize it and save
96
        $thumbSaveName = Normalize::diskFullPath($thumbPath) . '/' . $fileName . '.jpg';
97
        $thumb->open(Normalize::diskFullPath($originPath) . DIRECTORY_SEPARATOR . $fileNewName)
98
            ->cropResize($this->maxResize)
0 ignored issues
show
Bug introduced by
The property maxResize does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
99
            ->save($thumbSaveName, 'jpg', 90);
100
        $thumb = null;
0 ignored issues
show
Unused Code introduced by
$thumb is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
101
102
        return json_encode(['status' => 1, 'file' => [
103
            'thumbnailUrl' => '/upload/gallery/' . $id . '/thumb/' . $fileName . '.jpg',
104
            'url' => '/upload/gallery/' . $id . '/orig/' . $fileNewName,
105
            'name' => $fileNewName
106
        ]]);
107
    }
108
}
109