Passed
Pull Request — master (#554)
by
unknown
05:57
created

MediaLibraryController::uploadIsNotValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
namespace A17\Twill\Http\Controllers\Admin;
4
5
use A17\Twill\Http\Requests\Admin\MediaRequest;
6
use A17\Twill\Models\Media;
7
use A17\Twill\Services\Uploader\SignAzureUpload;
8
use A17\Twill\Services\Uploader\SignS3Upload;
9
use A17\Twill\Services\Uploader\SignUploadListener;
10
use Illuminate\Config\Repository as Config;
11
use Illuminate\Contracts\Container\BindingResolutionException;
12
use Illuminate\Contracts\Foundation\Application;
13
use Illuminate\Http\JsonResponse;
14
use Illuminate\Http\Request;
15
use Illuminate\Routing\ResponseFactory;
16
use Illuminate\Support\Arr;
17
use Illuminate\Support\Collection;
18
use Illuminate\Support\Facades\Storage;
19
20
class MediaLibraryController extends ModuleController implements SignUploadListener
21
{
22
    /**
23
     * @var string
24
     */
25
    protected $moduleName = 'medias';
26
27
    /**
28
     * @var string
29
     */
30
    protected $namespace = 'A17\Twill';
31
32
    /**
33
     * @var array
34
     */
35
    protected $defaultOrders = [
36
        'id' => 'desc',
37
    ];
38
39
    /**
40
     * @var array
41
     */
42
    protected $defaultFilters = [
43
        'search' => 'search',
44
        'tag' => 'tag_id',
45
    ];
46
47
    /**
48
     * @var int
49
     */
50
    protected $perPage = 40;
51
52
    /**
53
     * @var string
54
     */
55
    protected $endpointType;
56
57
    /**
58
     * @var array
59
     */
60
    protected $customFields;
61
62 4
    public function __construct(
63
        Application $app,
64
        Config $config,
65
        Request $request,
66
        ResponseFactory $responseFactory
67
    )
68
    {
69 4
        parent::__construct($app, $request);
70 4
        $this->responseFactory = $responseFactory;
0 ignored issues
show
Bug Best Practice introduced by
The property responseFactory does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
71 4
        $this->config = $config;
0 ignored issues
show
Bug Best Practice introduced by
The property config does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
72
73 4
        $this->removeMiddleware('can:edit');
74 4
        $this->middleware('can:edit', ['only' => ['signS3Upload', 'signAzureUpload', 'tags', 'store', 'singleUpdate', 'bulkUpdate']]);
75 4
        $this->endpointType = $this->config->get('twill.media_library.endpoint_type');
76 4
        $this->customFields = $this->config->get('twill.media_library.extra_metadatas_fields');
77 4
    }
78
79
    /**
80
     * @param int|null $parentModuleId
81
     * @return array
82
     */
83 1
    public function index($parentModuleId = null)
84
    {
85 1
        if ($this->request->has('except')) {
86 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...
87
        }
88
89 1
        return $this->getIndexData($prependScope ?? []);
90
    }
91
92
    /**
93
     * @param array $prependScope
94
     * @return array
95
     */
96 1
    public function getIndexData($prependScope = [])
97
    {
98 1
        $scopes = $this->filterScope($prependScope);
99 1
        $items = $this->getIndexItems($scopes);
100
101
        return [
102
            'items' => $items->map(function ($item) {
103
                return $item->toCmsArray();
104 1
            })->toArray(),
105 1
            'maxPage' => $items->lastPage(),
106 1
            'total' => $items->total(),
107 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

107
            'tags' => $this->repository->/** @scrutinizer ignore-call */ getTagsList(),
Loading history...
108
        ];
109
    }
110
111
    /**
112
     * @return array
113
     */
114 2
    protected function getRequestFilters()
115
    {
116 2
        if ($this->request->has('search')) {
117 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...
118
        }
119
120 2
        if ($this->request->has('tag')) {
121 1
            $requestFilters['tag'] = $this->request->get('tag');
122
        }
123
124 2
        return $requestFilters ?? [];
125
    }
126
127
    /**
128
     * @param int|null $parentModuleId
129
     * @return
130
     */
131 3
    public function store($parentModuleId = null)
132
    {
133 3
        $request = $this->app->make(MediaRequest::class);
134 3
        if ($this->endpointType === 'local') {
135 3
            $media = $this->storeFile($request);
136
        } else {
137
            $media = $this->storeReference($request);
138
        }
139
140 3
        return $this->responseFactory->json(['media' => $media->toCmsArray(), 'success' => true], 200);
141
    }
142
143
    /**
144
     * @param Request $request
145
     * @return Media
146
     */
147 3
    public function storeFile($request)
148
    {
149 3
        $originalFilename = $request->input('qqfilename');
150
151 3
        $filename = sanitizeFilename($originalFilename);
152
153 3
        $fileDirectory = $request->input('unique_folder_name');
154
155 3
        $uuid = $request->input('unique_folder_name') . '/' . $filename;
156
157 3
        if ($this->config->get('twill.media_library.prefix_uuid_with_local_path', false)) {
158
            $prefix = trim($this->config->get('twill.media_library.local_path'), '/ ') . '/';
159
            $fileDirectory = $prefix . $fileDirectory;
160
            $uuid = $prefix . $uuid;
161
        }
162
163 3
        $disk = $this->config->get('twill.media_library.disk');
164
165 3
        $request->file('qqfile')->storeAs($fileDirectory, $filename, $disk);
166
167 3
        $filePath = Storage::disk($disk)->path($fileDirectory . '/' . $filename);
168
169 3
        list($w, $h) = getimagesize($filePath);
170
171
        $fields = [
172 3
            'uuid' => $uuid,
173 3
            'filename' => $originalFilename,
174 3
            'width' => $w,
175 3
            'height' => $h,
176
        ];
177
178 3
        return $this->repository->create($fields);
179
    }
180
181
    /**
182
     * @param Request $request
183
     * @return Media
184
     */
185
    public function storeReference($request)
186
    {
187
        $dir_uuid = $request->input('dir_uuid');
188
        $unique_folder_name = $request->input('unique_folder_name');
189
        $uuid = $request->input('key') ?? $request->input('blob');
190
191
        $prefix_path = str_replace($dir_uuid, '', $unique_folder_name);
192
        $path = str_replace($prefix_path, '', $uuid);
193
194
        $fields = [
195
            'uuid' => $path,
196
            'filename' => $request->input('name'),
197
            'width' => $request->input('width'),
198
            'height' => $request->input('height'),
199
        ];
200
201
        return $this->repository->create($fields);
202
    }
203
204
    /**
205
     * @return JsonResponse
206
     */
207 1
    public function singleUpdate()
208
    {
209 1
        $this->repository->update(
210 1
            $this->request->input('id'),
211 1
            array_merge([
212 1
                'alt_text' => $this->request->get('alt_text', null),
213 1
                'caption' => $this->request->get('caption', null),
214 1
                'tags' => $this->request->get('tags', null),
215 1
            ], $this->getExtraMetadatas()->toArray())
216
        );
217
218 1
        return $this->responseFactory->json([
219 1
            'tags' => $this->repository->getTagsList(),
220 1
        ], 200);
221
    }
222
223
    /**
224
     * @return JsonResponse
225
     */
226 1
    public function bulkUpdate()
227
    {
228 1
        $ids = explode(',', $this->request->input('ids'));
229
230
        $metadatasFromRequest = $this->getExtraMetadatas()->reject(function ($meta) {
231
            return is_null($meta);
232 1
        })->toArray();
233
234 1
        $extraMetadatas = array_diff_key($metadatasFromRequest, array_flip((array)$this->request->get('fieldsRemovedFromBulkEditing', [])));
235
236 1
        if (in_array('tags', $this->request->get('fieldsRemovedFromBulkEditing', []))) {
237
            $this->repository->addIgnoreFieldsBeforeSave('bulk_tags');
0 ignored issues
show
Bug introduced by
'bulk_tags' of type string is incompatible with the type array expected by parameter $ignore of A17\Twill\Repositories\M...gnoreFieldsBeforeSave(). ( Ignorable by Annotation )

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

237
            $this->repository->addIgnoreFieldsBeforeSave(/** @scrutinizer ignore-type */ 'bulk_tags');
Loading history...
238
        } else {
239 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

239
            /** @scrutinizer ignore-call */ 
240
            $previousCommonTags = $this->repository->getTags(null, $ids);
Loading history...
240 1
            $newTags = array_filter(explode(',', $this->request->input('tags')));
241
        }
242
243 1
        foreach ($ids as $id) {
244 1
            $this->repository->update($id, [
245 1
                    'bulk_tags' => $newTags ?? [],
246 1
                    'previous_common_tags' => $previousCommonTags ?? [],
247 1
                ] + $extraMetadatas);
248
        }
249
250 1
        $scopes = $this->filterScope(['id' => $ids]);
251 1
        $items = $this->getIndexItems($scopes);
252
253 1
        return $this->responseFactory->json([
254
            'items' => $items->map(function ($item) {
255 1
                return $item->toCmsArray();
256 1
            })->toArray(),
257 1
            'tags' => $this->repository->getTagsList(),
258 1
        ], 200);
259
    }
260
261
    /**
262
     * @param Request $request
263
     * @param SignS3Upload $signS3Upload
264
     * @return mixed
265
     */
266
    public function signS3Upload(Request $request, SignS3Upload $signS3Upload)
267
    {
268
        return $signS3Upload->fromPolicy($request->getContent(), $this, $this->config->get('twill.media_library.disk'));
269
    }
270
271
    /**
272
     * @param Request $request
273
     * @param SignAzureUpload $signAzureUpload
274
     * @return mixed
275
     */
276
    public function signAzureUpload(Request $request, SignAzureUpload $signAzureUpload)
277
    {
278
        return $signAzureUpload->getSasUrl($request, $this, $this->config->get('twill.media_library.disk'));
279
    }
280
281
    /**
282
     * @param $signature
283
     * @param bool $isJsonResponse
284
     * @return mixed
285
     */
286
    public function uploadIsSigned($signature, $isJsonResponse = true)
287
    {
288
        return $isJsonResponse
289
            ? $this->responseFactory->json($signature, 200)
290
            : $this->responseFactory->make($signature, 200, ['Content-Type' => 'text/plain']);
291
    }
292
293
    /**
294
     * @return JsonResponse
295
     */
296
    public function uploadIsNotValid()
297
    {
298
        return $this->responseFactory->json(["invalid" => true], 500);
299
    }
300
301
    /**
302
     * @return Collection
303
     */
304 2
    private function getExtraMetadatas()
305
    {
306
        return Collection::make($this->customFields)->mapWithKeys(function ($field) {
307
            $fieldInRequest = $this->request->get($field['name']);
308
309
            if (isset($field['type']) && $field['type'] === 'checkbox') {
310
                return [$field['name'] => $fieldInRequest ? Arr::first($fieldInRequest) : false];
311
            }
312
313
            return [$field['name'] => $fieldInRequest];
314 2
        });
315
    }
316
}
317