Passed
Push — master ( e1ac4a...a9f297 )
by
unknown
09:26 queued 11s
created

FileLibraryController::signS3Upload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
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
    ];
43
44
    /**
45
     * @var int
46
     */
47
    protected $perPage = 40;
48
49
    /**
50
     * @var string
51
     */
52
    protected $endpointType;
53
54
    public function __construct(
55
        Application $app,
56
        Request $request,
57
        UrlGenerator $urlGenerator,
58
        ResponseFactory $responseFactory,
59
        Config $config
60
    )
61
    {
62
        parent::__construct($app, $request);
63
        $this->urlGenerator = $urlGenerator;
0 ignored issues
show
Bug Best Practice introduced by
The property urlGenerator does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
64
        $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...
65
        $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...
66
67
        $this->removeMiddleware('can:edit');
68
        $this->middleware('can:edit', ['only' => ['signS3Upload', 'signAzureUpload', 'tags', 'store', 'singleUpdate', 'bulkUpdate']]);
69
        $this->endpointType = $this->config->get('twill.file_library.endpoint_type');
70
    }
71
72
    /**
73
     * @param int|null $parentModuleId
74
     * @return array
75
     */
76
    public function index($parentModuleId = null)
77
    {
78
        if ($this->request->has('except')) {
79
            $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...
80
        }
81
82
        return $this->getIndexData($prependScope ?? []);
83
    }
84
85
    /**
86
     * @param array $prependScope
87
     * @return array
88
     */
89
    public function getIndexData($prependScope = [])
90
    {
91
        $scopes = $this->filterScope($prependScope);
92
        $items = $this->getIndexItems($scopes);
93
94
        return [
95
            'items' => $items->map(function ($item) {
96
                return $this->buildFile($item);
97
            })->toArray(),
98
            'maxPage' => $items->lastPage(),
99
            'total' => $items->total(),
100
            '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

100
            'tags' => $this->repository->/** @scrutinizer ignore-call */ getTagsList(),
Loading history...
101
        ];
102
    }
103
104
    /**
105
     * @param \A17\Twill\Models\File $item
106
     * @return array
107
     */
108
    private function buildFile($item)
109
    {
110
        return $item->toCmsArray() + [
111
                'tags' => $item->tags->map(function ($tag) {
0 ignored issues
show
Bug introduced by
The property tags does not seem to exist on A17\Twill\Models\File. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
112
                    return $tag->name;
113
                }),
114
                '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

114
                'deleteUrl' => $item->canDeleteSafely() ? moduleRoute($this->moduleName, $this->routePrefix, 'destroy', /** @scrutinizer ignore-type */ $item->id) : null,
Loading history...
115
                'updateUrl' => $this->urlGenerator->route('admin.file-library.files.single-update'),
116
                'updateBulkUrl' => $this->urlGenerator->route('admin.file-library.files.bulk-update'),
117
                'deleteBulkUrl' => $this->urlGenerator->route('admin.file-library.files.bulk-delete'),
118
            ];
119
    }
120
121
    /**
122
     * @return array
123
     */
124
    protected function getRequestFilters()
125
    {
126
        if ($this->request->has('search')) {
127
            $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...
128
        }
129
130
        if ($this->request->has('tag')) {
131
            $requestFilters['tag'] = $this->request->get('tag');
132
        }
133
134
        return $requestFilters ?? [];
135
    }
136
137
    /**
138
     * @param int|null $parentModuleId
139
     * @return JsonResponse
140
     * @throws BindingResolutionException
141
     */
142
    public function store($parentModuleId = null)
143
    {
144
        $request = $this->app->make(FileRequest::class);
145
146
        if ($this->endpointType === 'local') {
147
            $file = $this->storeFile($request);
148
        } else {
149
            $file = $this->storeReference($request);
150
        }
151
152
        return $this->responseFactory->json(['media' => $this->buildFile($file), 'success' => true], 200);
153
    }
154
155
    /**
156
     * @param Request $request
157
     * @return \A17\Twill\Models\File
158
     */
159
    public function storeFile($request)
160
    {
161
        $filename = $request->input('qqfilename');
162
163
        $cleanFilename = preg_replace("/\s+/i", "-", $filename);
164
165
        $fileDirectory = $request->input('unique_folder_name');
166
167
        $uuid = $request->input('unique_folder_name') . '/' . $cleanFilename;
168
169
        if ($this->config->get('twill.file_library.prefix_uuid_with_local_path', false)) {
170
            $prefix = trim($this->config->get('twill.file_library.local_path'), '/ ') . '/';
171
            $fileDirectory = $prefix . $fileDirectory;
172
            $uuid = $prefix . $uuid;
173
        }
174
175
        $disk = $this->config->get('twill.file_library.disk');
176
177
        $request->file('qqfile')->storeAs($fileDirectory, $cleanFilename, $disk);
178
179
        $fields = [
180
            'uuid' => $uuid,
181
            'filename' => $cleanFilename,
182
            'size' => $request->input('qqtotalfilesize'),
183
        ];
184
185
        return $this->repository->create($fields);
186
    }
187
188
    /**
189
     * @param Request $request
190
     * @return \A17\Twill\Models\File
191
     */
192
    public function storeReference($request)
193
    {
194
        $fields = [
195
            'uuid' => $request->input('key') ?? $request->input('blob'),
196
            'filename' => $request->input('name'),
197
        ];
198
199
        return $this->repository->create($fields);
200
    }
201
202
    /**
203
     * @return JsonResponse
204
     */
205
    public function singleUpdate()
206
    {
207
        $this->repository->update(
208
            $this->request->input('id'),
209
            $this->request->only('tags')
210
        );
211
212
        return $this->responseFactory->json([], 200);
213
    }
214
215
    /**
216
     * @return JsonResponse
217
     */
218
    public function bulkUpdate()
219
    {
220
        $ids = explode(',', $this->request->input('ids'));
221
222
        $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

222
        /** @scrutinizer ignore-call */ 
223
        $previousCommonTags = $this->repository->getTags(null, $ids);
Loading history...
223
        $newTags = array_filter(explode(',', $this->request->input('tags')));
224
225
        foreach ($ids as $id) {
226
            $this->repository->update($id, ['bulk_tags' => $newTags, 'previous_common_tags' => $previousCommonTags]);
227
        }
228
229
        $scopes = $this->filterScope(['id' => $ids]);
230
        $items = $this->getIndexItems($scopes);
231
232
        return $this->responseFactory->json([
233
            'items' => $items->map(function ($item) {
234
                return $this->buildFile($item);
235
            })->toArray(),
236
            'tags' => $this->repository->getTagsList(),
237
        ], 200);
238
    }
239
240
    /**
241
     * @param Request $request
242
     * @param SignS3Upload $signS3Upload
243
     * @return mixed
244
     */
245
    public function signS3Upload(Request $request, SignS3Upload $signS3Upload)
246
    {
247
        return $signS3Upload->fromPolicy($request->getContent(), $this, $this->config->get('twill.file_library.disk'));
248
    }
249
250
    /**
251
     * @param Request $request
252
     * @param SignAzureUpload $signAzureUpload
253
     * @return mixed
254
     */
255
    public function signAzureUpload(Request $request, SignAzureUpload $signAzureUpload)
256
    {
257
        return $signAzureUpload->getSasUrl($request, $this, $this->config->get('twill.file_library.disk'));
258
    }
259
260
    /**
261
     * @param $signature
262
     * @param bool $isJsonResponse
263
     * @return mixed
264
     */
265
    public function uploadIsSigned($signature, $isJsonResponse = true)
266
    {
267
        return $isJsonResponse
268
            ? $this->responseFactory->json($signature, 200)
269
            : $this->responseFactory->make($signature, 200, ['Content-Type' => 'text/plain']);
270
    }
271
272
    /**
273
     * @return JsonResponse
274
     */
275
    public function uploadIsNotValid()
276
    {
277
        return $this->responseFactory->json(["invalid" => true], 500);
278
    }
279
}
280