Completed
Push — develop ( 85bc70...7167f7 )
by Abdelrahman
02:34
created

AdminsController::stash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Auth\Http\Controllers\Adminarea;
6
7
use Cortex\Foundation\DataTables\ImportRecordsDataTable;
8
use Exception;
9
use Illuminate\Http\Request;
10
use Cortex\Auth\Models\Admin;
11
use Illuminate\Foundation\Http\FormRequest;
12
use Cortex\Foundation\DataTables\LogsDataTable;
13
use Cortex\Foundation\Importers\DefaultImporter;
14
use Cortex\Auth\DataTables\Adminarea\AdminsDataTable;
15
use Cortex\Foundation\DataTables\ActivitiesDataTable;
16
use Cortex\Foundation\DataTables\ImportLogsDataTable;
17
use Cortex\Foundation\Http\Requests\ImportFormRequest;
18
use Cortex\Auth\Http\Requests\Adminarea\AdminFormRequest;
19
use Cortex\Foundation\Http\Controllers\AuthorizedController;
20
use Cortex\Auth\Http\Requests\Adminarea\AdminAttributesFormRequest;
21
22
class AdminsController extends AuthorizedController
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    protected $resource = Admin::class;
28
29
    /**
30
     * List all admins.
31
     *
32
     * @param \Cortex\Auth\DataTables\Adminarea\AdminsDataTable $adminsDataTable
33
     *
34
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
35
     */
36
    public function index(AdminsDataTable $adminsDataTable)
37
    {
38
        return $adminsDataTable->with([
39
            'id' => 'adminarea-admins-index-table',
40
        ])->render('cortex/foundation::adminarea.pages.datatable-index');
41
    }
42
43
    /**
44
     * List admin logs.
45
     *
46
     * @param \Cortex\Auth\Models\Admin                   $admin
47
     * @param \Cortex\Foundation\DataTables\LogsDataTable $logsDataTable
48
     *
49
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\Http\JsonRes...e|\Illuminate\View\View?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
50
     */
51
    public function logs(Admin $admin, LogsDataTable $logsDataTable)
52
    {
53
        return $logsDataTable->with([
54
            'resource' => $admin,
55
            'tabs' => 'adminarea.admins.tabs',
56
            'id' => "adminarea-admins-{$admin->getRouteKey()}-logs-table",
57
        ])->render('cortex/foundation::adminarea.pages.datatable-tab');
58
    }
59
60
    /**
61
     * Get a listing of the resource activities.
62
     *
63
     * @param \Cortex\Auth\Models\Admin                         $admin
64
     * @param \Cortex\Foundation\DataTables\ActivitiesDataTable $activitiesDataTable
65
     *
66
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\Http\JsonRes...e|\Illuminate\View\View?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
67
     */
68
    public function activities(Admin $admin, ActivitiesDataTable $activitiesDataTable)
69
    {
70
        return $activitiesDataTable->with([
71
            'resource' => $admin,
72
            'tabs' => 'adminarea.admins.tabs',
73
            'id' => "adminarea-admins-{$admin->getRouteKey()}-activities-table",
74
        ])->render('cortex/foundation::adminarea.pages.datatable-tab');
75
    }
76
77
    /**
78
     * Show the form for create/update of the given resource attributes.
79
     *
80
     * @param \Illuminate\Http\Request  $request
81
     * @param \Cortex\Auth\Models\Admin $admin
82
     *
83
     * @return \Illuminate\View\View
84
     */
85
    public function attributes(Request $request, Admin $admin)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
86
    {
87
        return view('cortex/auth::adminarea.pages.admin-attributes', compact('admin'));
88
    }
89
90
    /**
91
     * Process the account update form.
92
     *
93
     * @param \Cortex\Auth\Http\Requests\Adminarea\AdminAttributesFormRequest $request
94
     * @param \Cortex\Auth\Models\Admin                                       $admin
95
     *
96
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
97
     */
98
    public function updateAttributes(AdminAttributesFormRequest $request, Admin $admin)
99
    {
100
        $data = $request->validated();
101
102
        // Update profile
103
        $admin->fill($data)->save();
104
105
        return intend([
106
            'back' => true,
107
            'with' => ['success' => trans('cortex/auth::messages.account.updated_attributes')],
108
        ]);
109
    }
110
111
    /**
112
     * Import admins.
113
     *
114
     * @param \Cortex\Auth\Models\Admin                            $admin
115
     * @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable
116
     *
117
     * @return \Illuminate\View\View
118
     */
119
    public function import(Admin $admin, ImportRecordsDataTable $importRecordsDataTable)
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $importRecordsDataTable exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
120
    {
121
        return $importRecordsDataTable->with([
122
            'resource' => $admin,
123
            'tabs' => 'adminarea.admins.tabs',
124
            'url' => route('adminarea.admins.stash'),
125
            'id' => "adminarea-attributes-{$admin->getRouteKey()}-import-table",
126
        ])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
127
    }
128
129
    /**
130
     * Stash admins.
131
     *
132
     * @param \Cortex\Foundation\Http\Requests\ImportFormRequest $request
133
     * @param \Cortex\Foundation\Importers\DefaultImporter       $importer
134
     *
135
     * @return void
136
     */
137
    public function stash(ImportFormRequest $request, DefaultImporter $importer)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
138
    {
139
        // Handle the import
140
        $importer->config['resource'] = $this->resource;
141
        $importer->config['name'] = 'username';
142
        $importer->handleImport();
143
    }
144
145
    /**
146
     * Hoard admins.
147
     *
148
     * @param \Cortex\Foundation\Http\Requests\ImportFormRequest $request
149
     *
150
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
151
     */
152
    public function hoard(ImportFormRequest $request)
153
    {
154
        foreach ((array) $request->get('selected_ids') as $recordId) {
155
            $record = app('cortex.foundation.import_record')->find($recordId);
156
157
            try {
158
                $fillable = collect($record['data'])->intersectByKeys(array_flip(app('rinvex.auth.admin')->getFillable()))->toArray();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
159
160
                tap(app('rinvex.auth.admin')->firstOrNew($fillable), function ($instance) use ($record) {
161
                    $instance->save() && $record->delete();
162
                });
163
            } catch (Exception $exception) {
164
                $record->notes = $exception->getMessage().(method_exists($exception, 'getMessageBag') ? "\n".json_encode($exception->getMessageBag())."\n\n" : '');
0 ignored issues
show
Bug introduced by
The method getMessageBag() does not exist on Exception. Did you maybe mean getMessage()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 163 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
165
                $record->status = 'fail';
166
                $record->save();
167
            }
168
        }
169
170
        return intend([
171
            'back' => true,
172
            'with' => ['success' => trans('cortex/foundation::messages.import_complete')],
173
        ]);
174
    }
175
176
    /**
177
     * List admin import logs.
178
     *
179
     * @param \Cortex\Foundation\DataTables\ImportLogsDataTable $importLogsDatatable
180
     *
181
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
182
     */
183
    public function importLogs(ImportLogsDataTable $importLogsDatatable)
184
    {
185
        return $importLogsDatatable->with([
186
            'resource' => trans('cortex/auth::common.admin'),
187
            'tabs' => 'adminarea.admins.tabs',
188
            'id' => 'adminarea-admins-import-logs-table',
189
        ])->render('cortex/foundation::adminarea.pages.datatable-tab');
190
    }
191
192
    /**
193
     * Create new admin.
194
     *
195
     * @param \Illuminate\Http\Request  $request
196
     * @param \Cortex\Auth\Models\Admin $admin
197
     *
198
     * @return \Illuminate\View\View
199
     */
200
    public function create(Request $request, Admin $admin)
201
    {
202
        return $this->form($request, $admin);
203
    }
204
205
    /**
206
     * Edit given admin.
207
     *
208
     * @param \Illuminate\Http\Request  $request
209
     * @param \Cortex\Auth\Models\Admin $admin
210
     *
211
     * @return \Illuminate\View\View
212
     */
213
    public function edit(Request $request, Admin $admin)
214
    {
215
        return $this->form($request, $admin);
216
    }
217
218
    /**
219
     * Show admin create/edit form.
220
     *
221
     * @param \Illuminate\Http\Request  $request
222
     * @param \Cortex\Auth\Models\Admin $admin
223
     *
224
     * @return \Illuminate\View\View
225
     */
226
    protected function form(Request $request, Admin $admin)
227
    {
228
        $countries = collect(countries())->map(function ($country, $code) {
229
            return [
230
                'id' => $code,
231
                'text' => $country['name'],
232
                'emoji' => $country['emoji'],
233
            ];
234
        })->values();
235
236
        $currentUser = $request->user($this->getGuard());
237
        $tags = app('rinvex.tags.tag')->pluck('name', 'id');
238
        $languages = collect(languages())->pluck('name', 'iso_639_1');
239
        $genders = ['male' => trans('cortex/auth::common.male'), 'female' => trans('cortex/auth::common.female')];
240
241
        $roles = $currentUser->can('superadmin')
242
            ? app('cortex.auth.role')->all()->pluck('name', 'id')->toArray()
243
            : $currentUser->roles->pluck('name', 'id')->toArray();
244
245
        $abilities = $currentUser->can('superadmin')
246
            ? app('cortex.auth.ability')->all()->groupBy('entity_type')->map->pluck('title', 'id')->toArray()
247
            : $currentUser->getAbilities()->groupBy('entity_type')->map->pluck('title', 'id')->toArray();
248
249
        asort($roles);
250
        ksort($abilities);
251
252
        return view('cortex/auth::adminarea.pages.admin', compact('admin', 'abilities', 'roles', 'countries', 'languages', 'genders', 'tags'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 143 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
253
    }
254
255
    /**
256
     * Store new admin.
257
     *
258
     * @param \Cortex\Auth\Http\Requests\Adminarea\AdminFormRequest $request
259
     * @param \Cortex\Auth\Models\Admin                             $admin
260
     *
261
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
262
     */
263
    public function store(AdminFormRequest $request, Admin $admin)
264
    {
265
        return $this->process($request, $admin);
266
    }
267
268
    /**
269
     * Update given admin.
270
     *
271
     * @param \Cortex\Auth\Http\Requests\Adminarea\AdminFormRequest $request
272
     * @param \Cortex\Auth\Models\Admin                             $admin
273
     *
274
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
275
     */
276
    public function update(AdminFormRequest $request, Admin $admin)
277
    {
278
        return $this->process($request, $admin);
279
    }
280
281
    /**
282
     * Process stored/updated admin.
283
     *
284
     * @param \Illuminate\Foundation\Http\FormRequest $request
285
     * @param \Cortex\Auth\Models\Admin               $admin
286
     *
287
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
288
     */
289
    protected function process(FormRequest $request, Admin $admin)
290
    {
291
        // Prepare required input fields
292
        $data = $request->validated();
293
294
        ! $request->hasFile('profile_picture')
295
        || $admin->addMediaFromRequest('profile_picture')
296
                ->sanitizingFileName(function ($fileName) {
297
                    return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
298
                })
299
                ->toMediaCollection('profile_picture', config('cortex.auth.media.disk'));
300
301
        ! $request->hasFile('cover_photo')
302
        || $admin->addMediaFromRequest('cover_photo')
303
                ->sanitizingFileName(function ($fileName) {
304
                    return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
305
                })
306
                ->toMediaCollection('cover_photo', config('cortex.auth.media.disk'));
307
308
        // Save admin
309
        $admin->fill($data)->save();
310
311
        return intend([
312
            'url' => route('adminarea.admins.index'),
313
            'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/auth::common.admin'), 'identifier' => $admin->username])],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 175 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
314
        ]);
315
    }
316
317
    /**
318
     * Destroy given admin.
319
     *
320
     * @param \Cortex\Auth\Models\Admin $admin
321
     *
322
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
323
     */
324
    public function destroy(Admin $admin)
325
    {
326
        $admin->delete();
327
328
        return intend([
329
            'url' => route('adminarea.admins.index'),
330
            'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.admin'), 'identifier' => $admin->username])],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 177 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
331
        ]);
332
    }
333
}
334