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

MediaLibraryController   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 157
Duplicated Lines 0 %

Test Coverage

Coverage 90.7%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 75
c 2
b 1
f 0
dl 0
loc 157
ccs 39
cts 43
cp 0.907
rs 10
wmc 14

7 Methods

Rating   Name   Duplication   Size   Complexity  
A storeReference() 0 16 2
A getIndexData() 0 12 1
A getExtraMetadatas() 0 10 4
A bulkUpdate() 0 33 3
A store() 0 10 2
A __construct() 0 14 1
A singleUpdate() 0 14 1
1
<?php
2
3
namespace A17\Twill\Http\Controllers\Admin;
4
5
use A17\Twill\Models\Media;
6
use Illuminate\Support\Arr;
7
use Illuminate\Http\Request;
8
use Illuminate\Http\JsonResponse;
9
use Illuminate\Support\Collection;
10
use Illuminate\Routing\ResponseFactory;
11
use Illuminate\Config\Repository as Config;
12
use A17\Twill\Http\Requests\Admin\MediaRequest;
13
use Illuminate\Contracts\Foundation\Application;
14
15
class MediaLibraryController extends LibraryController
16
{
17
    /**
18
     * @var string
19
     */
20
    protected $moduleName = 'medias';
21
22
    /**
23
     * @var array
24
     */
25
    protected $customFields;
26
27
    public function __construct(
28
        Application $app,
29
        Config $config,
30
        Request $request,
31
        ResponseFactory $responseFactory
32
    ) {
33
        parent::__construct($app, $request);
34
        $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...
35
        $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...
36
37
        $this->removeMiddleware('can:edit');
38
        $this->middleware('can:edit', ['only' => ['signS3Upload', 'signAzureUpload', 'tags', 'store', 'singleUpdate', 'bulkUpdate']]);
39
        $this->endpointType = $this->config->get('twill.media_library.endpoint_type');
40
        $this->customFields = $this->config->get('twill.media_library.extra_metadatas_fields');
41
    }
42
43
    /**
44
     * @param array $prependScope
45
     * @return array
46
     */
47
    public function getIndexData($prependScope = [])
48
    {
49
        $scopes = $this->filterScope($prependScope);
50
        $items = $this->getIndexItems($scopes);
51
52
        return [
53
            'items' => $items->map(function ($item) {
54
                return $item->toCmsArray();
55
            })->toArray(),
56
            'maxPage' => $items->lastPage(),
57
            'total' => $items->total(),
58
            '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

58
            'tags' => $this->repository->/** @scrutinizer ignore-call */ getTagsList(),
Loading history...
59
        ];
60
    }
61
62
    /**
63
     * @param int|null $parentModuleId
64
     * @return
65
     */
66
    public function store($parentModuleId = null)
67
    {
68
        $request = $this->app->make(MediaRequest::class);
69
        if ($this->endpointType === 'local') {
70
            $media = $this->storeFile($request);
71
        } else {
72 4
            $media = $this->storeReference($request);
73
        }
74
75
        return $this->responseFactory->json(['media' => $media->toCmsArray(), 'success' => true], 200);
76
    }
77
78 4
79 4
    /**
80 4
     * @param Request $request
81
     * @return Media
82 4
     */
83 4
    public function storeReference($request)
84 4
    {
85 4
        $fields = [
86 4
            'uuid' => $request->input('key') ?? $request->input('blob'),
87
            'filename' => $request->input('name'),
88
            'width' => $request->input('width'),
89
            'height' => $request->input('height'),
90
        ];
91
92 1
        if ($this->shouldReplaceMedia($id = $request->input('media_to_replace_id'))) {
93
            $media = $this->repository->whereId($id)->first();
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

93
            $media = $this->repository->/** @scrutinizer ignore-call */ whereId($id)->first();
Loading history...
94 1
            $this->repository->afterDelete($media);
95 1
            $media->update($fields);
96
            return $media->fresh();
97
        } else {
98 1
            return $this->repository->create($fields);
99
        }
100
    }
101
102
    /**
103
     * @return JsonResponse
104
     */
105 1
    public function singleUpdate()
106
    {
107 1
        $this->repository->update(
108 1
            $this->request->input('id'),
109
            array_merge([
110
                'alt_text' => $this->request->get('alt_text', null),
111 1
                'caption' => $this->request->get('caption', null),
112
                'tags' => $this->request->get('tags', null),
113 1
            ], $this->getExtraMetadatas()->toArray())
114 1
        );
115 1
116 1
        return $this->responseFactory->json([
117
            'tags' => $this->repository->getTagsList(),
118
        ], 200);
119
    }
120
121
    /**
122
     * @return JsonResponse
123 2
     */
124
    public function bulkUpdate()
125 2
    {
126 1
        $ids = explode(',', $this->request->input('ids'));
127
128
        $metadatasFromRequest = $this->getExtraMetadatas()->reject(function ($meta) {
129 2
            return is_null($meta);
130 1
        })->toArray();
131
132
        $extraMetadatas = array_diff_key($metadatasFromRequest, array_flip((array) $this->request->get('fieldsRemovedFromBulkEditing', [])));
133 2
134
        if (in_array('tags', $this->request->get('fieldsRemovedFromBulkEditing', []))) {
135
            $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

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

137
            /** @scrutinizer ignore-call */ 
138
            $previousCommonTags = $this->repository->getTags(null, $ids);
Loading history...
138
            $newTags = array_filter(explode(',', $this->request->input('tags')));
139
        }
140
141
        foreach ($ids as $id) {
142
            $this->repository->update($id, [
143
                'bulk_tags' => $newTags ?? [],
144 3
                'previous_common_tags' => $previousCommonTags ?? [],
145
            ] + $extraMetadatas);
146 3
        }
147 3
148 3
        $scopes = $this->filterScope(['id' => $ids]);
149
        $items = $this->getIndexItems($scopes);
150
151
        return $this->responseFactory->json([
152
            'items' => $items->map(function ($item) {
153 3
                return $item->toCmsArray();
154
            })->toArray(),
155
            'tags' => $this->repository->getTagsList(),
156
        ], 200);
157
    }
158
159
    /**
160 3
     * @return Collection
161
     */
162 3
    private function getExtraMetadatas()
163
    {
164 3
        return Collection::make($this->customFields)->mapWithKeys(function ($field) {
165
            $fieldInRequest = $this->request->get($field['name']);
166 3
167
            if (isset($field['type']) && $field['type'] === 'checkbox') {
168 3
                return [$field['name'] => $fieldInRequest ? Arr::first($fieldInRequest) : false];
169
            }
170 3
171
            return [$field['name'] => $fieldInRequest];
172
        });
173
    }
174
}
175