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
Pull Request — master (#1162)
by
unknown
09:15
created

UploadController::getFileName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 6
rs 10
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
    /**
17
     * @param Request $request
18
     * @param ModelConfigurationInterface $model
19
     * @param string $field
20
     * @param int|null $id
21
     *
22
     * @return JsonResponse
23
     */
24
    public function fromField(Request $request, ModelConfigurationInterface $model, $field, $id = null)
25
    {
26
        if (! is_null($id)) {
27
            $item = $model->getRepository()->find($id);
28
            if (is_null($item) || ! $model->isEditable($item)) {
29
                return new JsonResponse([
30
                    'message' => trans('lang.message.access_denied'),
31
                ], 403);
32
            }
33
34
            $form = $model->fireEdit($id);
35
        } else {
36
            if (! $model->isCreatable()) {
37
                return new JsonResponse([
38
                    'message' => trans('lang.message.access_denied'),
39
                ], 403);
40
            }
41
42
            $form = $model->fireCreate();
43
        }
44
45
        /** @var File $element */
46
        if (is_null($element = $form->getElement($field))) {
47
            throw new NotFoundHttpException("Field [{$field}] not found");
48
        }
49
50
        $rules = $element->getUploadValidationRules();
51
        $messages = $element->getUploadValidationMessages();
52
        $labels = $element->getUploadValidationLabels();
53
54
        /** @var \Illuminate\Contracts\Validation\Validator $validator */
55
        $validator = Validator::make($request->all(), $rules, $messages, $labels);
56
57
        $element->customValidation($validator);
58
59
        if ($validator->fails()) {
60
            return new JsonResponse([
61
                'message' => trans('lang.message.validation_error'),
62
                'errors' => $validator->errors()->get('file'),
63
            ], 400);
64
        }
65
66
        $file = $request->file('file');
67
68
        $filename = $element->getUploadFileName($file);
69
        $path = $element->getUploadPath($file);
70
        $settings = $element->getUploadSettings();
71
72
        $result = $element->saveFile($file, $path, $filename, $settings);
73
74
        /* When driver not file */
75
        return new JsonResponse($result);
76
    }
77
78
    /**
79
     * @param Request $request
80
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
81
     */
82
    public function ckEditorStore(Request $request)
83
    {
84
        //dropZone && CKEDITOR fileBrowser && CKEDITOR drag&drop
85
        /** @var UploadedFile $file */
86
        $file = $request->image ? $request->image : $request->file;
87
        $file = $file ? $file : $request->upload;
0 ignored issues
show
introduced by
$file is of type Illuminate\Http\UploadedFile, thus it always evaluated to true.
Loading history...
88
        if (is_array($file)) {
0 ignored issues
show
introduced by
The condition is_array($file) is always false.
Loading history...
89
            $file = $file[0];
90
        }
91
92
        $result = [];
93
94
        $imagesAllowedExtensions = collect(
95
            config('sleeping_owl.imagesAllowedExtensions', ['jpe', 'jpeg', 'jpg', 'bmp', 'ico', 'gif'])
96
        );
97
98
        if ($imagesAllowedExtensions->search($file->getClientOriginalExtension()) !== false) {
99
            $useOriginalName = config('sleeping_owl.imagesUseOriginalName', false);
100
            $uploadFileName = $this->getFileName($useOriginalName, $file);
101
102
            // fixme: что-то делать с одинаковыми названиями - при хешировании проблемы не было
103
            $file->move(public_path(config('sleeping_owl.imagesUploadDirectory')), $uploadFileName);
104
105
            $result['url'] = asset(
106
                config('sleeping_owl.imagesUploadDirectory').'/'.$uploadFileName
107
            );
108
        }
109
110
        $filesAllowedExtensions = collect(
111
            config('sleeping_owl.filesAllowedExtensions', [])
112
        );
113
114
        if ($filesAllowedExtensions->search($file->getClientOriginalExtension()) !== false) {
115
            $useOriginalName = config('sleeping_owl.filesUseOriginalName', false);
116
            $uploadFileName = $this->getFileName($useOriginalName, $file);
117
118
            // fixme: что-то делать с одинаковыми названиями - при хешировании проблемы не было
119
            $file->move(public_path(config('sleeping_owl.filesUploadDirectory')), $uploadFileName);
120
121
            $result['url'] = asset(
122
                config('sleeping_owl.filesUploadDirectory').'/'.$uploadFileName
123
            );
124
        }
125
126
        if ($result) {
127
            $result['uploaded'] = 1;
128
            $result['fileName'] = $uploadFileName;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $uploadFileName does not seem to be defined for all execution paths leading up to this point.
Loading history...
129
130
            if ($request->CKEditorFuncNum && $request->CKEditor && $request->langCode) {
131
                return app('sleeping_owl.template')
132
                    ->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

132
                    ->/** @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...
133
            }
134
135
            return response($result);
136
        }
137
138
        return response('Something wrong', 500);
139
    }
140
141
    /**
142
     * @param bool $useOriginalName
143
     * @param UploadedFile $file
144
     * @return string
145
     */
146
    private function getFileName(bool $useOriginalName, UploadedFile $file): string
147
    {
148
        if ($useOriginalName) {
149
            return $file->getClientOriginalName();
150
        }
151
152
        return md5(time().$file->getClientOriginalName()).'.'.$file->getClientOriginalExtension();
153
    }
154
}
155