GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — analysis-OM5eeJ ( 49ecbc )
by butschster
07:58
created

UploadController::uploadFile()   C

Complexity

Conditions 13
Paths 20

Size

Total Lines 65
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 13
eloc 47
c 2
b 1
f 1
nc 20
nop 3
dl 0
loc 65
rs 6.6166

How to fix   Long Method    Complexity   

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
2
3
namespace SleepingOwl\Admin\Http\Controllers;
4
5
use Illuminate\Http\JsonResponse;
6
use Illuminate\Http\Request;
7
use Illuminate\Http\UploadedFile;
8
use Illuminate\Routing\Controller;
9
use SleepingOwl\Admin\Contracts\ModelConfigurationInterface;
10
use SleepingOwl\Admin\Form\Element\File;
11
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
12
use Validator;
13
14
class UploadController extends Controller
15
{
16
    private $uploadFilenameBehaviors = [
0 ignored issues
show
introduced by
The private property $uploadFilenameBehaviors is not used, and could be removed.
Loading history...
17
        'UPLOAD_HASH', // Использовать Хеш файла
18
19
        'UPLOAD_ORIGINAL_ALERT', // Если такой файл есть - сообщать об этом
20
        'UPLOAD_ORIGINAL_ADD_HASH', // Если такой файл есть - добавляем хеш f.png -> f_jfhsjfy8s7df8a7.png
21
        'UPLOAD_ORIGINAL_ADD_INCREMENT', // Если такой файл есть - инкрементировать имя, пока не найдется вариант f.png -> f_1.png ... f_10.png
22
23
        'UPLOAD_ORIGINAL_REWRITE', // Если такой файл есть - просто перезаписываем.
24
    ];
25
26
    private $uploadFilenameBehaviorDefault = 'UPLOAD_HASH'; // По умолчанию
27
    private $uploadFilenameIncrementMax = 10; // Максимально число попыток для подбора инкремента. f_10.png не будет создан
28
29
    /**
30
     * @param Request $request
31
     * @param ModelConfigurationInterface $model
32
     * @param string $field
33
     * @param int|null $id
34
     *
35
     * @return JsonResponse
36
     */
37
    public function fromField(Request $request, ModelConfigurationInterface $model, $field, $id = null)
38
    {
39
        if (! is_null($id)) {
40
            $item = $model->getRepository()->find($id);
41
            if (is_null($item) || ! $model->isEditable($item)) {
42
                return new JsonResponse([
43
                    'message' => trans('lang.message.access_denied'),
44
                ], 403);
45
            }
46
47
            $form = $model->fireEdit($id);
48
        } else {
49
            if (! $model->isCreatable()) {
50
                return new JsonResponse([
51
                    'message' => trans('lang.message.access_denied'),
52
                ], 403);
53
            }
54
55
            $form = $model->fireCreate();
56
        }
57
58
        /*
59
         * @var File
60
         */
61
        if (is_null($element = $form->getElement($field))) {
62
            throw new NotFoundHttpException("Field [{$field}] not found");
63
        }
64
65
        $rules = $element->getUploadValidationRules();
66
        $messages = $element->getUploadValidationMessages();
67
        $labels = $element->getUploadValidationLabels();
68
69
        /**
70
         * @var \Illuminate\Contracts\Validation\Validator
71
         */
72
        $validator = Validator::make($request->all(), $rules, $messages, $labels);
73
74
        $element->customValidation($validator);
75
76
        if ($validator->fails()) {
77
            return new JsonResponse([
78
                'message' => trans('lang.message.validation_error'),
79
                'errors' => $validator->errors()->get('file'),
80
            ], 400);
81
        }
82
83
        $file = $request->file('file');
84
85
        $filename = $element->getUploadFileName($file);
86
        $path = $element->getUploadPath($file);
87
        $settings = $element->getUploadSettings();
88
89
        $result = $element->saveFile($file, $path, $filename, $settings);
90
91
        /*
92
         * When driver not file
93
         */
94
        return new JsonResponse($result);
95
    }
96
97
    /**
98
     * @param Request $request
99
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
100
     */
101
    public function ckEditorStore(Request $request)
102
    {
103
        /**
104
         * dropZone && CKEDITOR fileBrowser && CKEDITOR drag&drop.
105
         * @var UploadedFile
106
         */
107
        $file = $request->image ? $request->image : $request->file;
108
        $file = $file ? $file : $request->upload;
109
        if (is_array($file)) {
110
            $file = $file[0];
111
        }
112
113
        $result = [];
114
115
        $imagesAllowedExtensions = collect(
116
            config('sleeping_owl.imagesAllowedExtensions', ['jpe', 'jpeg', 'jpg', 'bmp', 'ico', 'gif'])
117
        );
118
119
        if ($imagesAllowedExtensions->search($file->getClientOriginalExtension()) !== false) {
120
            $uploadDirectory = config('sleeping_owl.imagesUploadDirectory');
121
            $uploadFilenameBehavior = config('sleeping_owl.imagesUploadFilenameBehavior', $this->uploadFilenameBehaviorDefault);
122
            $result = $this->uploadFile($file, $uploadDirectory, $uploadFilenameBehavior);
123
        }
124
125
        $filesAllowedExtensions = collect(
126
            config('sleeping_owl.filesAllowedExtensions', [])
127
        );
128
129
        if ($filesAllowedExtensions->search($file->getClientOriginalExtension()) !== false) {
130
            $uploadDirectory = config('sleeping_owl.filesUploadDirectory');
131
            $uploadFilenameBehavior = config('sleeping_owl.filesUploadFilenameBehavior', $this->uploadFilenameBehaviorDefault);
132
            $result = $this->uploadFile($file, $uploadDirectory, $uploadFilenameBehavior);
133
        }
134
135
        if ($result && $result['uploaded'] == 1) {
136
            if ($request->CKEditorFuncNum && $request->CKEditor && $request->langCode) {
137
                return app('sleeping_owl.template')
138
                    ->view('helper.ckeditor.ckeditor_upload_file', compact('result'));
0 ignored issues
show
Bug introduced by
The method view() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

138
                    ->/** @scrutinizer ignore-call */ view('helper.ckeditor.ckeditor_upload_file', compact('result'));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
139
            }
140
141
            return response($result);
142
        }
143
144
        if ($result && $result['uploaded'] == 0) {
145
            return response($result, 500);
146
        }
147
148
        return response('Something wrong', 500);
149
    }
150
151
    /**
152
     * @param UploadedFile $file
153
     * @param string $uploadDirectory
154
     * @param string $uploadFilenameBehavior
155
     *
156
     * @return array
157
     */
158
    private function uploadFile(UploadedFile $file, string $uploadDirectory, string $uploadFilenameBehavior): array
159
    {
160
        $isFileExists = file_exists(public_path($uploadDirectory).DIRECTORY_SEPARATOR.$file->getClientOriginalName());
161
        $uploadFileName = $file->getClientOriginalName();
162
163
        $filenameWithoutExtensions = substr($file->getClientOriginalName(), 0, strrpos($file->getClientOriginalName(), '.'));
164
165
        //Варианты
166
        switch ($uploadFilenameBehavior) {
167
            case 'UPLOAD_ORIGINAL_ALERT':
168
                if ($isFileExists) {
169
                    $result['uploaded'] = 0;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.
Loading history...
170
                    $result['error']['message'] = 'Файл с таким именем уже существует. Измените имя файла и попробуйте еще раз';
171
                    $uploadFileName = false;
172
                }
173
                break;
174
            case 'UPLOAD_ORIGINAL_ADD_HASH':
175
                if ($isFileExists) {
176
                    $uploadFileName = $filenameWithoutExtensions
177
                        .'_'.md5(time().$filenameWithoutExtensions)
178
                        .'.'.$file->getClientOriginalExtension();
179
                    $result['error']['message'] = "Файл с таким именем уже существовал. Загружаемый файл был переименован в '{$uploadFileName}'";
180
                }
181
                break;
182
            case 'UPLOAD_ORIGINAL_ADD_INCREMENT':
183
                if ($isFileExists) {
184
                    $index = 1;
185
                    $uploadFileName = $filenameWithoutExtensions.'_'.$index.'.'.$file->getClientOriginalExtension();
186
                    while (
187
                        file_exists(public_path($uploadDirectory).DIRECTORY_SEPARATOR.$uploadFileName)
188
                        and
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
189
                        $index < $this->uploadFilenameIncrementMax
190
                    ) {
191
                        $index++;
192
                        $uploadFileName = $filenameWithoutExtensions.'_'.$index.'.'.$file->getClientOriginalExtension();
193
                    }
194
                    $result['error']['message'] = "Файл с таким именем уже существовал. Загружаемый файл был переименован в '{$uploadFileName}'";
195
                    if ($index == $this->uploadFilenameIncrementMax) {
196
                        $uploadFileName = false;
197
                        $result['uploaded'] = 0;
198
                        $result['error']['message'] = 'Файл с таким именем уже существовал. Имя подобрать не удалось. Переименуйте файл и попробуйте еще раз';
199
                    }
200
                }
201
                break;
202
            case 'UPLOAD_ORIGINAL_REWRITE':
203
                if ($isFileExists) {
204
                    $result['error']['message'] = 'Файл с таким именем уже существовал и был перезаписан';
205
                }
206
                break;
207
            default:
208
                //UPLOAD_HASH
209
                $uploadFileName = md5(time().$filenameWithoutExtensions).'.'.$file->getClientOriginalExtension();
210
                $result['error']['message'] = "Файл был переименован в '{$uploadFileName}'";
211
                break;
212
        }
213
214
        if ($uploadFileName) {
215
            $file->move(public_path($uploadDirectory), $uploadFileName);
216
217
            $result['uploaded'] = 1;
218
            $result['url'] = asset($uploadDirectory.'/'.$uploadFileName);
219
            $result['fileName'] = $uploadFileName;
220
        }
221
222
        return $result;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
223
    }
224
}
225