Completed
Push — develop ( 2f14a1...2df5c1 )
by Abdelrahman
02:07
created

TenantsController::store()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 4
rs 10
c 1
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Tenants\Http\Controllers\Adminarea;
6
7
use Cortex\Foundation\DataTables\ImportRecordsDataTable;
8
use Cortex\Tenants\Models\Tenant;
9
use Exception;
10
use Illuminate\Foundation\Http\FormRequest;
11
use Cortex\Foundation\DataTables\LogsDataTable;
12
use Cortex\Foundation\Importers\DefaultImporter;
13
use Cortex\Foundation\DataTables\ImportLogsDataTable;
14
use Cortex\Foundation\Http\Requests\ImportFormRequest;
15
use Cortex\Tenants\DataTables\Adminarea\TenantsDataTable;
16
use Cortex\Foundation\Http\Controllers\AuthorizedController;
17
use Cortex\Tenants\Http\Requests\Adminarea\TenantFormRequest;
18
19
class TenantsController extends AuthorizedController
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24
    protected $resource = Tenant::class;
25
26
    /**
27
     * List all tenants.
28
     *
29
     * @param \Cortex\Tenants\DataTables\Adminarea\TenantsDataTable $tenantsDataTable
30
     *
31
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
32
     */
33
    public function index(TenantsDataTable $tenantsDataTable)
34
    {
35
        return $tenantsDataTable->with([
36
            'id' => 'adminarea-tenants-index-table',
37
        ])->render('cortex/foundation::adminarea.pages.datatable-index');
38
    }
39
40
    /**
41
     * List tenant logs.
42
     *
43
     * @param \Cortex\Tenants\Models\Tenant               $tenant
44
     * @param \Cortex\Foundation\DataTables\LogsDataTable $logsDataTable
45
     *
46
     * @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...
47
     */
48
    public function logs(Tenant $tenant, LogsDataTable $logsDataTable)
49
    {
50
        return $logsDataTable->with([
51
            'resource' => $tenant,
52
            'tabs' => 'adminarea.tenants.tabs',
53
            'id' => "adminarea-tenants-{$tenant->getRouteKey()}-logs-table",
54
        ])->render('cortex/foundation::adminarea.pages.datatable-tab');
55
    }
56
57
    /**
58
     * Import tenants.
59
     *
60
     * @param \Cortex\Tenants\Models\Tenant                        $tenant
61
     * @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable
62
     *
63
     * @return \Illuminate\View\View
64
     */
65
    public function import(Tenant $tenant, 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...
66
    {
67
        return $importRecordsDataTable->with([
68
            'resource' => $tenant,
69
            'tabs' => 'adminarea.tenants.tabs',
70
            'url' => route('adminarea.tenants.stash'),
71
            'id' => "adminarea-tenants-{$tenant->getRouteKey()}-import-table",
72
        ])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
73
    }
74
75
    /**
76
     * Stash tenants.
77
     *
78
     * @param \Cortex\Foundation\Http\Requests\ImportFormRequest $request
79
     * @param \Cortex\Foundation\Importers\DefaultImporter       $importer
80
     *
81
     * @return void
82
     */
83
    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...
84
    {
85
        // Handle the import
86
        $importer->config['resource'] = $this->resource;
87
        $importer->handleImport();
88
    }
89
90
    /**
91
     * Hoard tenants.
92
     *
93
     * @param \Cortex\Foundation\Http\Requests\ImportFormRequest $request
94
     *
95
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
96
     */
97
    public function hoard(ImportFormRequest $request)
98
    {
99
        foreach ((array) $request->get('selected_ids') as $recordId) {
100
            $record = app('cortex.foundation.import_record')->find($recordId);
101
102
            try {
103
                $fillable = collect($record['data'])->intersectByKeys(array_flip(app('rinvex.tenants.tenant')->getFillable()))->toArray();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 138 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...
104
105
                tap(app('rinvex.tenants.tenant')->firstOrNew($fillable), function ($instance) use ($record) {
106
                    $instance->save() && $record->delete();
107
                });
108
            } catch (Exception $exception) {
109
                $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...
110
                $record->status = 'fail';
111
                $record->save();
112
            }
113
        }
114
115
        return intend([
116
            'back' => true,
117
            'with' => ['success' => trans('cortex/foundation::messages.import_complete')],
118
        ]);
119
    }
120
121
    /**
122
     * List tenant import logs.
123
     *
124
     * @param \Cortex\Foundation\DataTables\ImportLogsDataTable $importLogsDatatable
125
     *
126
     * @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...
127
     */
128
    public function importLogs(ImportLogsDataTable $importLogsDatatable)
129
    {
130
        return $importLogsDatatable->with([
131
            'resource' => trans('cortex/tenants::common.tenant'),
132
            'tabs' => 'adminarea.tenants.tabs',
133
            'id' => 'adminarea-tenants-import-logs-table',
134
        ])->render('cortex/foundation::adminarea.pages.datatable-tab');
135
    }
136
137
    /**
138
     * Create new tenant.
139
     *
140
     * @param \Cortex\Tenants\Models\Tenant $tenant
141
     *
142
     * @return \Illuminate\View\View
143
     */
144
    public function create(Tenant $tenant)
145
    {
146
        return $this->form($tenant);
147
    }
148
149
    /**
150
     * Edit given tenant.
151
     *
152
     * @param \Cortex\Tenants\Models\Tenant $tenant
153
     *
154
     * @return \Illuminate\View\View
155
     */
156
    public function edit(Tenant $tenant)
157
    {
158
        return $this->form($tenant);
159
    }
160
161
    /**
162
     * Show tenant create/edit form.
163
     *
164
     * @param \Cortex\Tenants\Models\Tenant $tenant
165
     *
166
     * @return \Illuminate\View\View
167
     */
168
    protected function form(Tenant $tenant)
169
    {
170
        $countries = collect(countries())->map(function ($country, $code) {
171
            return [
172
                'id' => $code,
173
                'text' => $country['name'],
174
                'emoji' => $country['emoji'],
175
            ];
176
        })->values();
177
178
        $tags = app('rinvex.tags.tag')->pluck('name', 'id');
179
        $languages = collect(languages())->pluck('name', 'iso_639_1');
180
        $owners = app('cortex.auth.manager')->all()->pluck('username', 'id');
181
182
        return view('cortex/tenants::adminarea.pages.tenant', compact('tenant', 'owners', 'countries', 'languages', 'tags'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 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...
183
    }
184
185
    /**
186
     * Store new tenant.
187
     *
188
     * @param \Cortex\Tenants\Http\Requests\Adminarea\TenantFormRequest $request
189
     * @param \Cortex\Tenants\Models\Tenant                             $tenant
190
     *
191
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
192
     */
193
    public function store(TenantFormRequest $request, Tenant $tenant)
194
    {
195
        return $this->process($request, $tenant);
196
    }
197
198
    /**
199
     * Update given tenant.
200
     *
201
     * @param \Cortex\Tenants\Http\Requests\Adminarea\TenantFormRequest $request
202
     * @param \Cortex\Tenants\Models\Tenant                             $tenant
203
     *
204
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
205
     */
206
    public function update(TenantFormRequest $request, Tenant $tenant)
207
    {
208
        return $this->process($request, $tenant);
209
    }
210
211
    /**
212
     * Process stored/updated tenant.
213
     *
214
     * @param \Illuminate\Foundation\Http\FormRequest $request
215
     * @param \Cortex\Tenants\Models\Tenant           $tenant
216
     *
217
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
218
     */
219
    protected function process(FormRequest $request, Tenant $tenant)
220
    {
221
        // Prepare required input fields
222
        $data = $request->validated();
223
224
        ! $request->hasFile('profile_picture')
225
        || $tenant->addMediaFromRequest('profile_picture')
226
                       ->sanitizingFileName(function ($fileName) {
227
                           return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
228
                       })
229
                       ->toMediaCollection('profile_picture', config('cortex.auth.media.disk'));
230
231
        ! $request->hasFile('cover_photo')
232
        || $tenant->addMediaFromRequest('cover_photo')
233
                       ->sanitizingFileName(function ($fileName) {
234
                           return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
235
                       })
236
                       ->toMediaCollection('cover_photo', config('cortex.auth.media.disk'));
237
238
        // Save tenant
239
        $tenant->fill($data)->save();
240
        $tenant->owner->assign('owner');
0 ignored issues
show
Bug introduced by
The method assign does only exist in Cortex\Auth\Models\User, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
241
        $tenant->owner->attachTenants($tenant);
242
243
        return intend([
244
            'url' => route('adminarea.tenants.index'),
245
            'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/tenants::common.tenant'), 'identifier' => $tenant->name])],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 176 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...
246
        ]);
247
    }
248
249
    /**
250
     * Destroy given tenant.
251
     *
252
     * @param \Cortex\Tenants\Models\Tenant $tenant
253
     *
254
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
255
     */
256
    public function destroy(Tenant $tenant)
257
    {
258
        $tenant->delete();
259
260
        return intend([
261
            'url' => route('adminarea.tenants.index'),
262
            'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/tenants::common.tenant'), 'identifier' => $tenant->name])],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 178 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...
263
        ]);
264
    }
265
}
266