Passed
Pull Request — 2.x (#899)
by Antonio Carlos
07:23
created

LibraryController::makeImageFolderName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
namespace A17\Twill\Http\Controllers\Admin;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Http\JsonResponse;
7
use Illuminate\Support\Facades\Storage;
8
use Illuminate\Routing\ResponseFactory;
9
use Illuminate\Config\Repository as Config;
10
use A17\Twill\Services\Uploader\SignS3Upload;
11
use Illuminate\Contracts\Foundation\Application;
12
use A17\Twill\Services\Uploader\SignAzureUpload;
13
use A17\Twill\Services\Uploader\SignUploadListener;
14
15
abstract class LibraryController extends ModuleController implements SignUploadListener
16
{
17
    /**
18
     * @var string
19
     */
20
    protected $namespace = 'A17\Twill';
21
22
    /**
23
     * @var array
24
     */
25
    protected $defaultOrders = [
26
        'id' => 'desc',
27
    ];
28
29
    /**
30
     * @var array
31
     */
32
    protected $defaultFilters = [
33
        'search' => 'search',
34
        'tag' => 'tag_id',
35
        'unused' => 'unused',
36
    ];
37
38
    /**
39
     * @var int
40
     */
41
    protected $perPage = 40;
42
43
    /**
44
     * @var string
45
     */
46
    protected $endpointType;
47
48
    /**
49
     * @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...
50
     */
51
    protected $responseFactory;
52
53
    /**
54
     * @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...
55
     */
56
    protected $config;
57
58
    /**
59
     * @param int|null $parentModuleId
60
     * @return array
61
     */
62
    public function index($parentModuleId = null)
63
    {
64
        if ($this->request->has('except')) {
65
            $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...
66
        }
67
68
        return $this->getIndexData($prependScope ?? []);
69
    }
70
71
    /**
72
     * @return array
73
     */
74
    protected function getRequestFilters()
75
    {
76
        if ($this->request->has('search')) {
77
            $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...
78
        }
79
80
        if ($this->request->has('tag')) {
81
            $requestFilters['tag'] = $this->request->get('tag');
82
        }
83
84
        if (
85
            $this->request->has('unused') &&
86
            (int) $this->request->unused === 1
87
        ) {
88
            $requestFilters['unused'] = $this->request->get('unused');
89
        }
90
91
        return $requestFilters ?? [];
92
    }
93
94
    /**
95
     * @param Request $request
96
     * @param SignS3Upload $signS3Upload
97
     * @return mixed
98
     */
99
    public function signS3Upload(Request $request, SignS3Upload $signS3Upload)
100
    {
101
        return $signS3Upload->fromPolicy(
102
            $request->getContent(),
103
            $this,
104
            $this->config->get('twill.media_library.disk')
105
        );
106
    }
107
108
    /**
109
     * @param Request $request
110
     * @param SignAzureUpload $signAzureUpload
111
     * @return mixed
112
     */
113
    public function signAzureUpload(
114
        Request $request,
115
        SignAzureUpload $signAzureUpload
116
    ) {
117
        return $signAzureUpload->getSasUrl(
118
            $request,
119
            $this,
120
            $this->config->get('twill.media_library.disk')
121
        );
122
    }
123
124
    /**
125
     * @param $signature
126
     * @param bool $isJsonResponse
127
     * @return mixed
128
     */
129
    public function uploadIsSigned($signature, $isJsonResponse = true)
130
    {
131
        return $isJsonResponse
132
            ? $this->responseFactory->json($signature, 200)
133
            : $this->responseFactory->make($signature, 200, [
134
                'Content-Type' => 'text/plain',
135
            ]);
136
    }
137
138
    /**
139
     * @return JsonResponse
140
     */
141
    public function uploadIsNotValid()
142
    {
143
        return $this->responseFactory->json(['invalid' => true], 500);
144
    }
145
146
    /**
147
     * @param string $originalFilename
148
     * @param \Illuminate\Http\Request $request
149
     * @return mixed
150
     */
151
    public function makeFilename($filename, $request)
152
    {
153
        if (
154
            !$this->config->get('twill.media_library.deduplication.enabled') ||
155
            !$this->config->get('twill.media_library.deduplication.flatten_filename')
156
        ) {
157
            return $filename;
158
        }
159
160
        $hash = $this->makeFileSha1($request);
161
162
        $parsed = pathinfo($filename);
163
164
        return $hash . ".{$parsed['extension']}";
165
    }
166
167
    /**
168
     * @param \Illuminate\Http\Request $request
169
     * @return mixed
170
     */
171
    private function makeImageFolderName(Request $request)
172
    {
173
        if (!$this->config->get('twill.media_library.deduplication.enabled')) {
174
            return $request->input('unique_folder_name');
175
        }
176
177
        if (
178
            !$this->config->get('twill.media_library.deduplication.flatten_filename')
179
        ) {
180
            return $this->makeFileSha1($request);
181
        }
182
183
        return '';
184
    }
185
186
    /**
187
     * @param $fileDirectory
188
     * @param string $filename
189
     * @return string
190
     */
191
    protected function makeUUID(
192
        $fileDirectory,
193
        string $filename,
194
        $request
195
    ): string {
196
        if (
197
            !$this->config->get('twill.media_library.deduplication.enabled') ||
198
            !$this->config->get('twill.media_library.deduplication.flatten_filename')
199
        ) {
200
            return $fileDirectory . '/' . $filename;
201
        }
202
203
        if (
204
            $this->config->get('twill.media_library.deduplication.flatten_filename')
205
        ) {
206
            $fileDirectory = $this->makeFileSha1($request);
207
        }
208
209
        $parsed = pathinfo($filename);
210
211
        return $fileDirectory . ".{$parsed['extension']}";
212
    }
213
214
    /**
215
     * @param \Illuminate\Http\Request $request
216
     * @return string
217
     */
218
    private function makeFileSha1(Request $request): string
219
    {
220
        return sha1(file_get_contents($request->file('qqfile')->getRealPath()));
221
    }
222
223
    /**
224
     * @return bool
225
     */
226
    private function shouldReplaceMedia($id)
227
    {
228
        return filled($id) && $id !== 'null' && $id !== 'undefined'
229
            ? $this->repository->whereId($id)->exists()
0 ignored issues
show
Bug introduced by
The method whereId() 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

229
            ? $this->repository->/** @scrutinizer ignore-call */ whereId($id)->exists()
Loading history...
230
            : false;
231
    }
232
233
    /**
234
     * @param Request $request
235
     * @return Media
236
     */
237
    public function storeFile($request)
238
    {
239
        $originalFilename = $request->input('qqfilename');
240
241
        $filename = $this->makeFilename($originalFilename, $request);
242
243
        $fileDirectory = $this->makeImageFolderName($request);
244
245
        $uuid = $this->makeUUID($fileDirectory, $filename, $request);
246
247
        if (
248
            $this->config->get(
249
                'twill.media_library.prefix_uuid_with_local_path',
250
                false
251
            )
252
        ) {
253
            $prefix =
254
                trim(
255
                    $this->config->get('twill.media_library.local_path'),
256
                    '/ '
257
                ) . '/';
258
            $fileDirectory = $prefix . $fileDirectory;
259
            $uuid = $prefix . $uuid;
260
        }
261
262
        $disk = $this->config->get('twill.media_library.disk');
263
264
        $request->file('qqfile')->storeAs($fileDirectory, $filename, $disk);
265
266
        $filePath = Storage::disk($disk)->path(
267
            $fileDirectory . '/' . $filename
268
        );
269
270
        [$w, $h] = getimagesize($filePath);
271
272
        $fields = [
273
            'uuid' => $uuid,
274
            'filename' => $originalFilename,
275
            'width' => $w,
276
            'height' => $h,
277
        ];
278
279
        if (
280
            $this->shouldReplaceMedia(
281
                $id = $request->input('media_to_replace_id')
282
            )
283
        ) {
284
            $media = $this->repository->whereId($id)->first();
285
            $this->repository->afterDelete($media);
286
            $media->replace($fields);
287
            return $media->fresh();
288
        } else {
289
            return $this->repository->firstOrCreate(['uuid' => $uuid], $fields);
290
        }
291
    }
292
}
293