Passed
Push — master ( b7618a...8c3cc9 )
by Mihail
15:19
created

Content::actionGallerylist()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 36
Code Lines 21

Duplication

Lines 3
Ratio 8.33 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 3
loc 36
rs 5.3846
cc 8
eloc 21
nc 6
nop 1
1
<?php
2
3
namespace Apps\Controller\Api;
4
5
use Extend\Core\Arch\ApiController;
6
use Apps\ActiveRecord\App as AppRecord;
7
use Ffcms\Core\App;
8
use Ffcms\Core\Exception\JsonException;
9
use Ffcms\Core\Exception\NativeException;
10
use Ffcms\Core\Helper\FileSystem\Directory;
11
use Ffcms\Core\Helper\FileSystem\Normalize;
12
use Ffcms\Core\Helper\Type\Arr;
13
use Ffcms\Core\Helper\Type\Obj;
14
use Ffcms\Core\Helper\Type\Str;
15
use Gregwar\Image\Image;
16
17
class Content extends ApiController
18
{
19
    public $maxSize = 512000; // in bytes, 500 * 1024
20
    public $maxResize = 150;
21
22
    public $allowedExt = ['jpg', 'png', 'gif', 'jpeg', 'bmp', 'webp'];
23
24
    public function before()
25
    {
26
        parent::before();
27
        $configs = AppRecord::getConfigs('app', 'Content');
28
        // prevent null-type config data
29
        if ((int)$configs['gallerySize'] > 0) {
30
            $this->maxSize = (int)$configs['gallerySize'] * 1024;
31
        }
32
33
        if ((int)$configs['galleryResize'] > 0) {
34
            $this->maxResize = (int)$configs['galleryResize'];
35
        }
36
    }
37
38
    /**
39
     * Upload new files to content item gallery
40
     * @param $id
41
     * @throws JsonException
42
     * @throws NativeException
43
     * @throws \Exception
44
     */
45
    public function actionGalleryupload($id)
46
    {
47
        // check if id is passed
48
        if (Str::likeEmpty($id)) {
49
            throw new JsonException('Wrong input data');
50
        }
51
52
        // check if user have permission to access there
53 View Code Duplication
        if (!App::$User->isAuth() || !App::$User->identity()->getRole()->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...
54
            throw new NativeException('Permission denied');
55
        }
56
57
        // check if directory exist
58
        if (!Directory::exist('/upload/gallery/' . $id)) {
59
            Directory::create('/upload/gallery/' . $id);
60
        }
61
62
        // get file object
63
        /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */
64
        $file = App::$Request->files->get('gallery-files');
65
        if ($file === null || $file->getError() !== 0) {
66
            throw new JsonException('File not uploaded');
67
        }
68
69
        // check file size
70
        if ($file->getSize() < 1 || $file->getSize() > $this->maxSize) {
71
            throw new JsonException('File wrong size');
72
        }
73
74
        // check file extension
75
        if (!Arr::in($file->guessExtension(), $this->allowedExt)) {
76
            throw new JsonException('Wrong file extension');
77
        }
78
79
        // create origin directory
80
        $originPath = '/upload/gallery/' . $id . '/orig/';
81
        if (!Directory::exist($originPath)) {
82
            Directory::create($originPath);
83
        }
84
85
        // lets make a new file name
86
        $fileName = App::$Security->simpleHash($file->getFilename() . $file->getSize());
87
        $fileNewName = $fileName . '.' . $file->guessExtension();
88
        // save file from tmp to gallery origin directory
89
        $file->move(Normalize::diskFullPath($originPath), $fileNewName);
90
91
        // lets resize preview image for it
92
        $thumbPath = '/upload/gallery/' . $id . '/thumb/';
93
        if (!Directory::exist($thumbPath)) {
94
            Directory::create($thumbPath);
95
        }
96
97
        $thumb = new Image();
98
        $thumb->setCacheDir(root . '/Private/Cache/images');
99
100
        // open original file, resize it and save
101
        $thumbSaveName = Normalize::diskFullPath($thumbPath) . '/' . $fileName . '.jpg';
102
        $thumb->open(Normalize::diskFullPath($originPath) . DIRECTORY_SEPARATOR . $fileNewName)
103
            ->cropResize($this->maxResize)
104
            ->save($thumbSaveName, 'jpg', 90);
105
        $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...
106
107
        $output[] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$output was never initialized. Although not strictly required by PHP, it is generally a good practice to add $output = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
108
            'thumbnailUrl' => '/upload/gallery/' . $id . '/thumb/' . $fileName . '.jpg',
109
            'url' => '/upload/gallery/' . $id . '/orig/' . $fileNewName,
110
            'name' => $fileNewName
111
        ];
112
113
        $this->setJsonHeader();
114
115
        // generate success response
116
        $this->response = json_encode(['files' => $output]);
117
    }
118
119
    public function actionGallerylist($id)
120
    {
121
        // check if id is passed
122
        if (Str::likeEmpty($id)) {
123
            throw new JsonException('Wrong input data');
124
        }
125
126
        // check if user have permission to access there
127 View Code Duplication
        if (!App::$User->isAuth() || !App::$User->identity()->getRole()->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...
128
            throw new NativeException('Permission denied');
129
        }
130
131
        $thumbDir = Normalize::diskFullPath('/upload/gallery/' . $id . '/orig/');
132
        if (!Directory::exist($thumbDir)) {
133
            throw new JsonException('Nothing found');
134
        }
135
136
        $files = Directory::scan($thumbDir, null, true);
137
        if (!Obj::isArray($files) || count($files) < 1) {
138
            throw new JsonException('Nothing found');
139
        }
140
141
        $output = [];
142
        foreach ($files as $file) {
0 ignored issues
show
Bug introduced by
The expression $files of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
143
            $fileExt = Str::lastIn($file, '.');
144
            $fileName = Str::substr($file, 0, -Str::length($fileExt));
145
            $output[] = [
146
                'thumbnailUrl' => '/upload/gallery/' . $id . '/thumb/' . $fileName . '.jpg',
147
                'url' => '/upload/gallery/' . $id . '/orig/' . $file,
148
                'name' => $file
149
            ];
150
        }
151
152
        $this->setJsonHeader();
153
        $this->response = json_encode(['files' => $output]);
154
    }
155
}