Passed
Push — 2.x ( c00759...e3c99f )
by Quentin
07:55
created

FileLibraryController::getRequestFilters()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.0488

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 8
nop 0
dl 0
loc 15
ccs 7
cts 8
cp 0.875
crap 5.0488
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace A17\Twill\Http\Controllers\Admin;
4
5
use A17\Twill\Http\Requests\Admin\FileRequest;
6
use A17\Twill\Services\Uploader\SignAzureUpload;
7
use A17\Twill\Services\Uploader\SignS3Upload;
8
use A17\Twill\Services\Uploader\SignUploadListener;
9
use Illuminate\Config\Repository as Config;
10
use Illuminate\Contracts\Container\BindingResolutionException;
11
use Illuminate\Contracts\Foundation\Application;
12
use Illuminate\Http\JsonResponse;
13
use Illuminate\Http\Request;
14
use Illuminate\Routing\ResponseFactory;
15
use Illuminate\Routing\UrlGenerator;
16
17
class FileLibraryController extends ModuleController implements SignUploadListener
18
{
19
    /**
20
     * @var string
21
     */
22
    protected $moduleName = 'files';
23
24
    /**
25
     * @var string
26
     */
27
    protected $namespace = 'A17\Twill';
28
29
    /**
30
     * @var array
31
     */
32
    protected $defaultOrders = [
33
        'id' => 'desc',
34
    ];
35
36
    /**
37
     * @var array
38
     */
39
    protected $defaultFilters = [
40
        'search' => 'search',
41
        'tag' => 'tag_id',
42
        'unused' => 'unused'
43
    ];
44
45
    /**
46
     * @var int
47
     */
48
    protected $perPage = 40;
49
50
    /**
51
     * @var string
52
     */
53
    protected $endpointType;
54
55
    /**
56
     * @var Illuminate\Routing\UrlGenerator
0 ignored issues
show
Bug introduced by
The type A17\Twill\Http\Controlle...te\Routing\UrlGenerator was not found. Did you mean Illuminate\Routing\UrlGenerator? If so, make sure to prefix the type with \.
Loading history...
57
     */
58
    protected $urlGenerator;
59
60
    /**
61
     * @var Illuminate\Routing\ResponseFactory
0 ignored issues
show
Bug introduced by
The type A17\Twill\Http\Controlle...Routing\ResponseFactory was not found. Did you mean Illuminate\Routing\ResponseFactory? If so, make sure to prefix the type with \.
Loading history...
62
     */
63
    protected $responseFactory;
64
65
    /**
66
     * @var Illuminate\Config\Repository
0 ignored issues
show
Bug introduced by
The type A17\Twill\Http\Controlle...inate\Config\Repository was not found. Did you mean Illuminate\Config\Repository? If so, make sure to prefix the type with \.
Loading history...
67
     */
68
    protected $config;
69
70 4
    public function __construct(
71
        Application $app,
72
        Request $request,
73
        UrlGenerator $urlGenerator,
74
        ResponseFactory $responseFactory,
75
        Config $config
76
    ) {
77 4
        parent::__construct($app, $request);
78 4
        $this->urlGenerator = $urlGenerator;
0 ignored issues
show
Documentation Bug introduced by
It seems like $urlGenerator of type Illuminate\Routing\UrlGenerator is incompatible with the declared type A17\Twill\Http\Controlle...te\Routing\UrlGenerator of property $urlGenerator.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
79 4
        $this->responseFactory = $responseFactory;
0 ignored issues
show
Documentation Bug introduced by
It seems like $responseFactory of type Illuminate\Routing\ResponseFactory is incompatible with the declared type A17\Twill\Http\Controlle...Routing\ResponseFactory of property $responseFactory.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
80 4
        $this->config = $config;
0 ignored issues
show
Documentation Bug introduced by
It seems like $config of type Illuminate\Config\Repository is incompatible with the declared type A17\Twill\Http\Controlle...inate\Config\Repository of property $config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
81
82 4
        $this->removeMiddleware('can:edit');
83 4
        $this->middleware('can:edit', ['only' => ['signS3Upload', 'signAzureUpload', 'tags', 'store', 'singleUpdate', 'bulkUpdate']]);
84 4
        $this->endpointType = $this->config->get('twill.file_library.endpoint_type');
85 4
    }
86
87
    /**
88
     * @param int|null $parentModuleId
89
     * @return array
90
     */
91 1
    public function index($parentModuleId = null)
92
    {
93 1
        if ($this->request->has('except')) {
94 1
            $prependScope['exceptIds'] = $this->request->get('except');
0 ignored issues
show
Comprehensibility Best Practice introduced by
$prependScope was never initialized. Although not strictly required by PHP, it is generally a good practice to add $prependScope = array(); before regardless.
Loading history...
95
        }
96
97 1
        return $this->getIndexData($prependScope ?? []);
98
    }
99
100
    /**
101
     * @param array $prependScope
102
     * @return array
103
     */
104 1
    public function getIndexData($prependScope = [])
105
    {
106 1
        $scopes = $this->filterScope($prependScope);
107 1
        $items = $this->getIndexItems($scopes);
108
109
        return [
110
            'items' => $items->map(function ($item) {
111
                return $this->buildFile($item);
112 1
            })->toArray(),
113 1
            'maxPage' => $items->lastPage(),
114 1
            'total' => $items->total(),
115 1
            'tags' => $this->repository->getTagsList(),
0 ignored issues
show
Bug introduced by
The method getTagsList() does not exist on A17\Twill\Repositories\ModuleRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

115
            'tags' => $this->repository->/** @scrutinizer ignore-call */ getTagsList(),
Loading history...
116
        ];
117
    }
118
119
    /**
120
     * @param \A17\Twill\Models\File $item
121
     * @return array
122
     */
123 3
    private function buildFile($item)
124
    {
125 3
        return $item->toCmsArray() + [
126
            'tags' => $item->tags->map(function ($tag) {
0 ignored issues
show
Bug Best Practice introduced by
The property tags does not exist on A17\Twill\Models\File. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method map() does not exist on null. ( Ignorable by Annotation )

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

126
            'tags' => $item->tags->/** @scrutinizer ignore-call */ map(function ($tag) {

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...
127 1
                return $tag->name;
128 3
            }),
129 3
            'deleteUrl' => $item->canDeleteSafely() ? moduleRoute($this->moduleName, $this->routePrefix, 'destroy', $item->id) : null,
0 ignored issues
show
Bug introduced by
$item->id of type integer is incompatible with the type array expected by parameter $parameters of moduleRoute(). ( Ignorable by Annotation )

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

129
            'deleteUrl' => $item->canDeleteSafely() ? moduleRoute($this->moduleName, $this->routePrefix, 'destroy', /** @scrutinizer ignore-type */ $item->id) : null,
Loading history...
130 3
            'updateUrl' => $this->urlGenerator->route('admin.file-library.files.single-update'),
131 3
            'updateBulkUrl' => $this->urlGenerator->route('admin.file-library.files.bulk-update'),
132 3
            'deleteBulkUrl' => $this->urlGenerator->route('admin.file-library.files.bulk-delete'),
133
        ];
134
    }
135
136
    /**
137
     * @return array
138
     */
139 2
    protected function getRequestFilters()
140
    {
141 2
        if ($this->request->has('search')) {
142 1
            $requestFilters['search'] = $this->request->get('search');
0 ignored issues
show
Comprehensibility Best Practice introduced by
$requestFilters was never initialized. Although not strictly required by PHP, it is generally a good practice to add $requestFilters = array(); before regardless.
Loading history...
143
        }
144
145 2
        if ($this->request->has('tag')) {
146 1
            $requestFilters['tag'] = $this->request->get('tag');
147
        }
148
149 2
        if ($this->request->has('unused') && (int) $this->request->unused === 1) {
150
            $requestFilters['unused'] = $this->request->get('unused');
151
        }
152
153 2
        return $requestFilters ?? [];
154
    }
155
156
    /**
157
     * @param int|null $parentModuleId
158
     * @return JsonResponse
159
     * @throws BindingResolutionException
160
     */
161 3
    public function store($parentModuleId = null)
162
    {
163 3
        $request = $this->app->make(FileRequest::class);
164
165 3
        if ($this->endpointType === 'local') {
166 3
            $file = $this->storeFile($request);
167
        } else {
168
            $file = $this->storeReference($request);
169
        }
170
171 3
        return $this->responseFactory->json(['media' => $this->buildFile($file), 'success' => true], 200);
172
    }
173
174
    /**
175
     * @param Request $request
176
     * @return \A17\Twill\Models\File
177
     */
178 3
    public function storeFile($request)
179
    {
180 3
        $filename = $request->input('qqfilename');
181
182 3
        $cleanFilename = preg_replace("/\s+/i", "-", $filename);
183
184 3
        $fileDirectory = $request->input('unique_folder_name');
185
186 3
        $uuid = $request->input('unique_folder_name') . '/' . $cleanFilename;
187
188 3
        if ($this->config->get('twill.file_library.prefix_uuid_with_local_path', false)) {
189
            $prefix = trim($this->config->get('twill.file_library.local_path'), '/ ') . '/';
190
            $fileDirectory = $prefix . $fileDirectory;
191
            $uuid = $prefix . $uuid;
192
        }
193
194 3
        $disk = $this->config->get('twill.file_library.disk');
195
196 3
        $request->file('qqfile')->storeAs($fileDirectory, $cleanFilename, $disk);
197
198
        $fields = [
199 3
            'uuid' => $uuid,
200 3
            'filename' => $cleanFilename,
201 3
            'size' => $request->input('qqtotalfilesize'),
202
        ];
203
204 3
        return $this->repository->create($fields);
205
    }
206
207
    /**
208
     * @param Request $request
209
     * @return \A17\Twill\Models\File
210
     */
211
    public function storeReference($request)
212
    {
213
        $fields = [
214
            'uuid' => $request->input('key') ?? $request->input('blob'),
215
            'filename' => $request->input('name'),
216
        ];
217
218
        return $this->repository->create($fields);
219
    }
220
221
    /**
222
     * @return JsonResponse
223
     */
224 1
    public function singleUpdate()
225
    {
226 1
        $this->repository->update(
227 1
            $this->request->input('id'),
228 1
            $this->request->only('tags')
229
        );
230
231 1
        return $this->responseFactory->json([], 200);
232
    }
233
234
    /**
235
     * @return JsonResponse
236
     */
237 1
    public function bulkUpdate()
238
    {
239 1
        $ids = explode(',', $this->request->input('ids'));
240
241 1
        $previousCommonTags = $this->repository->getTags(null, $ids);
0 ignored issues
show
Bug introduced by
The method getTags() does not exist on A17\Twill\Repositories\ModuleRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

241
        /** @scrutinizer ignore-call */ 
242
        $previousCommonTags = $this->repository->getTags(null, $ids);
Loading history...
242 1
        $newTags = array_filter(explode(',', $this->request->input('tags')));
243
244 1
        foreach ($ids as $id) {
245 1
            $this->repository->update($id, ['bulk_tags' => $newTags, 'previous_common_tags' => $previousCommonTags]);
246
        }
247
248 1
        $scopes = $this->filterScope(['id' => $ids]);
249 1
        $items = $this->getIndexItems($scopes);
250
251 1
        return $this->responseFactory->json([
252
            'items' => $items->map(function ($item) {
253 1
                return $this->buildFile($item);
254 1
            })->toArray(),
255 1
            'tags' => $this->repository->getTagsList(),
256 1
        ], 200);
257
    }
258
259
    /**
260
     * @param Request $request
261
     * @param SignS3Upload $signS3Upload
262
     * @return mixed
263
     */
264
    public function signS3Upload(Request $request, SignS3Upload $signS3Upload)
265
    {
266
        return $signS3Upload->fromPolicy($request->getContent(), $this, $this->config->get('twill.file_library.disk'));
267
    }
268
269
    /**
270
     * @param Request $request
271
     * @param SignAzureUpload $signAzureUpload
272
     * @return mixed
273
     */
274
    public function signAzureUpload(Request $request, SignAzureUpload $signAzureUpload)
275
    {
276
        return $signAzureUpload->getSasUrl($request, $this, $this->config->get('twill.file_library.disk'));
277
    }
278
279
    /**
280
     * @param $signature
281
     * @param bool $isJsonResponse
282
     * @return mixed
283
     */
284
    public function uploadIsSigned($signature, $isJsonResponse = true)
285
    {
286
        return $isJsonResponse
287
        ? $this->responseFactory->json($signature, 200)
288
        : $this->responseFactory->make($signature, 200, ['Content-Type' => 'text/plain']);
289
    }
290
291
    /**
292
     * @return JsonResponse
293
     */
294
    public function uploadIsNotValid()
295
    {
296
        return $this->responseFactory->json(["invalid" => true], 500);
297
    }
298
}
299