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

FileLibraryController::store()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
crap 2.0185
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 4
    public function __construct(
55
        Application $app,
56
        Request $request,
57
        UrlGenerator $urlGenerator,
58
        ResponseFactory $responseFactory,
59
        Config $config
60
    )
61
    {
62 4
        parent::__construct($app, $request);
63 4
        $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 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...
65 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...
66
67 4
        $this->removeMiddleware('can:edit');
68 4
        $this->middleware('can:edit', ['only' => ['signS3Upload', 'signAzureUpload', 'tags', 'store', 'singleUpdate', 'bulkUpdate']]);
69 4
        $this->endpointType = $this->config->get('twill.file_library.endpoint_type');
70 4
    }
71
72
    /**
73
     * @param int|null $parentModuleId
74
     * @return array
75
     */
76 1
    public function index($parentModuleId = null)
77
    {
78 1
        if ($this->request->has('except')) {
79 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...
80
        }
81
82 1
        return $this->getIndexData($prependScope ?? []);
83
    }
84
85
    /**
86
     * @param array $prependScope
87
     * @return array
88
     */
89 1
    public function getIndexData($prependScope = [])
90
    {
91 1
        $scopes = $this->filterScope($prependScope);
92 1
        $items = $this->getIndexItems($scopes);
93
94
        return [
95
            'items' => $items->map(function ($item) {
96
                return $this->buildFile($item);
97 1
            })->toArray(),
98 1
            'maxPage' => $items->lastPage(),
99 1
            'total' => $items->total(),
100 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

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 3
    private function buildFile($item)
109
    {
110 3
        return $item->toCmsArray() + [
111
                '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

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

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

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