Completed
Push — master ( 7d05ee...bd6010 )
by
unknown
9s
created

SekolahController::create()   D

Complexity

Conditions 10
Paths 384

Size

Total Lines 75
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 50
nc 384
nop 0
dl 0
loc 75
rs 4
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Bantenprov\Sekolah\Http\Controllers;
4
5
/* Require */
6
use App\Http\Controllers\Controller;
7
use Illuminate\Http\Request;
8
use Bantenprov\Sekolah\Facades\SekolahFacade;
9
10
/* Models */
11
use Bantenprov\Sekolah\Models\Bantenprov\Sekolah\Sekolah;
12
use Bantenprov\Sekolah\Models\Bantenprov\Sekolah\JenisSekolah;
13
use Laravolt\Indonesia\Models\Province;
14
use Laravolt\Indonesia\Models\City;
15
use Laravolt\Indonesia\Models\District;
16
use Laravolt\Indonesia\Models\Village;
17
use Bantenprov\Zona\Models\Bantenprov\Zona\MasterZona;
18
use App\User;
19
20
/* Etc */
21
use Validator;
22
use Auth;
23
24
/**
25
 * The SekolahController class.
26
 *
27
 * @package Bantenprov\Sekolah
28
 * @author  bantenprov <[email protected]>
29
 */
30
class SekolahController extends Controller
31
{
32
    protected $sekolah;
33
    protected $jenis_sekolah;
34
    protected $master_zona;
35
    protected $user;
36
37
    /**
38
     * Create a new controller instance.
39
     *
40
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
41
     */
42
    public function __construct()
43
    {
44
        $this->sekolah          = new Sekolah;
45
        $this->jenis_sekolah    = new JenisSekolah;
46
        $this->province         = new Province;
47
        $this->city             = new City;
48
        $this->district         = new District;
49
        $this->village          = new Village;
50
        $this->master_zona      = new MasterZona;
51
        $this->user             = new User;
52
    }
53
54
    /**
55
     * Display a listing of the resource.
56
     *
57
     * @return \Illuminate\Http\Response
58
     */
59
    public function index(Request $request)
60
    {
61
        if (request()->has('sort')) {
62
            list($sortCol, $sortDir) = explode('|', request()->sort);
63
64
            $query = $this->sekolah->orderBy($sortCol, $sortDir);
65
        } else {
66
            $query = $this->sekolah->orderBy('id', 'asc');
67
        }
68
69
        if ($request->exists('filter')) {
70
            $query->where(function($q) use($request) {
71
                $value = "%{$request->filter}%";
72
                $q->where('nama', 'like', $value)
73
                    ->orWhere('npsn', 'like', $value)
74
                    ->orWhere('alamat', 'like', $value)
75
                    ->orWhere('email', 'like', $value);
76
            });
77
        }
78
79
        $perPage = request()->has('per_page') ? (int) request()->per_page : null;
80
81
        $response = $query->with('jenis_sekolah', 'province', 'city', 'district', 'village', 'master_zona', 'user')->paginate($perPage);
82
83
        return response()->json($response)
84
            ->header('Access-Control-Allow-Origin', '*')
85
            ->header('Access-Control-Allow-Methods', 'GET');
86
    }
87
88
    /**
89
     * Display a listing of the resource.
90
     *
91
     * @return \Illuminate\Http\Response
92
     */
93
    public function get()
94
    {
95
        $sekolahs = $this->sekolah->with('jenis_sekolah', 'province', 'city', 'district', 'village', 'master_zona', 'user')->get();
96
97
        foreach($sekolahs as $sekolah){
98
            array_set($sekolah, 'label', $sekolah->nama);
99
        }
100
101
        $response['sekolahs']   = $sekolahs;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
102
        $response['error']      = false;
103
        $response['message']    = 'Success';
104
        $response['status']     = true;
105
106
        return response()->json($response);
107
    }
108
109
    /**
110
     * Show the form for creating a new resource.
111
     *
112
     * @return \Illuminate\Http\Response
113
     */
114
    public function create()
115
    {
116
        $user_id        = isset(Auth::User()->id) ? Auth::User()->id : null;
117
        $sekolah        = $this->sekolah->getAttributes();
118
        $jenis_sekolahs = $this->jenis_sekolah->all();
119
        $provinces      = $this->province->getAttributes();
120
        $cities         = $this->city->getAttributes();
121
        $districts      = $this->district->getAttributes();
122
        $villages       = $this->village->getAttributes();
123
        $master_zonas   = $this->master_zona->all();
124
        $users          = $this->user->getAttributes();
0 ignored issues
show
Unused Code introduced by
$users is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
125
        $users_special  = $this->user->all();
126
        $users_standar  = $this->user->findOrFail($user_id);
127
        $current_user   = Auth::User();
128
129
        foreach($jenis_sekolahs as $jenis_sekolah){
130
            array_set($jenis_sekolah, 'label', $jenis_sekolah->jenis_sekolah);
131
        }
132
133
        foreach($provinces as $province){
134
            array_set($province, 'label', $province->name);
135
        }
136
137
        foreach($cities as $city){
138
            array_set($city, 'label', $city->name);
139
        }
140
141
        foreach($districts as $district){
142
            array_set($district, 'label', $district->name);
143
        }
144
145
        foreach($villages as $village){
146
            array_set($village, 'label', $village->name);
147
        }
148
149
        foreach($master_zonas as $master_zona){
150
            array_set($master_zona, 'label', $master_zona->label);
151
        }
152
153
        $role_check = Auth::User()->hasRole(['superadministrator','administrator']);
154
155
        if($role_check){
156
            $user_special = true;
157
158
            foreach($users_special as $user){
159
                array_set($user, 'label', $user->name);
160
            }
161
162
            $users = $users_special;
163
        }else{
164
            $user_special = false;
165
166
            array_set($users_standar, 'label', $users_standar->name);
167
168
            $users = $users_standar;
169
        }
170
171
        array_set($current_user, 'label', $current_user->name);
172
173
        $response['sekolah']        = $sekolah;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
174
        $response['jenis_sekolahs'] = $jenis_sekolahs;
175
        $response['provinces']      = $provinces;
176
        $response['cities']         = $cities;
177
        $response['districts']      = $districts;
178
        $response['villages']       = $villages;
179
        $response['master_zonas']   = $master_zonas;
180
        $response['users']          = $users;
181
        $response['user_special']   = $user_special;
182
        $response['current_user']   = $current_user;
183
        $response['error']          = false;
184
        $response['message']        = 'Success';
185
        $response['status']         = true;
186
187
        return response()->json($response);
188
    }
189
190
    /**
191
     * Store a newly created resource in storage.
192
     *
193
     * @param  \Illuminate\Http\Request  $request
194
     * @return \Illuminate\Http\Response
195
     */
196
    public function store(Request $request)
197
    {
198
        $sekolah = $this->sekolah;
199
200
        $validator = Validator::make($request->all(), [
201
            'nama'              => 'required|max:255',
202
            'npsn'              => "required|max:255|unique:{$this->sekolah->getTable()},npsn,NULL,id,deleted_at,NULL",
203
            'jenis_sekolah_id'  => "required|exists:{$this->jenis_sekolah->getTable()},id",
204
            'alamat'            => 'required|max:255',
205
            'logo'              => 'required|max:255',
206
            'foto_gedung'       => 'required|max:255',
207
            'province_id'       => "required|exists:{$this->province->getTable()},id",
208
            'city_id'           => "required|exists:{$this->city->getTable()},id",
209
            'district_id'       => "required|exists:{$this->district->getTable()},id",
210
            'village_id'        => "required|exists:{$this->village->getTable()},id",
211
            'no_telp'           => 'required|digits_between:10,12',
212
            'email'             => 'required|email|max:255',
213
            'kode_zona'         => "required|exists:{$this->master_zona->getTable()},id",
214
            'user_id'           => "required|exists:{$this->user->getTable()},id",
215
        ]);
216
217
        if ($validator->fails()) {
218
            $error      = true;
219
            $message    = $validator->errors()->first();
220 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
221
            $sekolah->nama              = $request->input('nama');
222
            $sekolah->npsn              = $request->input('npsn');
223
            $sekolah->jenis_sekolah_id  = $request->input('jenis_sekolah_id');
224
            $sekolah->alamat            = $request->input('alamat');
225
            $sekolah->logo              = $request->input('logo');
226
            $sekolah->foto_gedung       = $request->input('foto_gedung');
227
            $sekolah->province_id       = $request->input('province_id');
228
            $sekolah->city_id           = $request->input('city_id');
229
            $sekolah->district_id       = $request->input('district_id');
230
            $sekolah->village_id        = $request->input('village_id');
231
            $sekolah->no_telp           = $request->input('no_telp');
232
            $sekolah->email             = $request->input('email');
233
            $sekolah->kode_zona         = $request->input('kode_zona');
234
            $sekolah->user_id           = $request->input('user_id');
235
            $sekolah->save();
236
237
            $error      = false;
238
            $message    = 'Success';
239
        }
240
241
        $response['error']      = $error;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
242
        $response['message']    = $message;
243
        $response['status']     = true;
244
245
        return response()->json($response);
246
    }
247
248
    /**
249
     * Display the specified resource.
250
     *
251
     * @param  \App\Sekolah  $sekolah
0 ignored issues
show
Bug introduced by
There is no parameter named $sekolah. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
252
     * @return \Illuminate\Http\Response
253
     */
254
    public function show($id)
255
    {
256
        $sekolah = $this->sekolah->with(['jenis_sekolah', 'province', 'city', 'district', 'village', 'master_zona', 'user'])->findOrFail($id);
257
258
        $response['sekolah']    = $sekolah;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
259
        $response['error']      = false;
260
        $response['message']    = 'Success';
261
        $response['status']     = true;
262
263
        return response()->json($response);
264
    }
265
266
    /**
267
     * Show the form for editing the specified resource.
268
     *
269
     * @param  \App\Sekolah  $sekolah
0 ignored issues
show
Bug introduced by
There is no parameter named $sekolah. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
270
     * @return \Illuminate\Http\Response
271
     */
272 View Code Duplication
    public function edit($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
273
    {
274
        $sekolah = $this->sekolah->findOrFail($id);
275
276
        array_set($sekolah->jenis_sekolah, 'label', $sekolah->jenis_sekolah->jenis_sekolah);
277
        array_set($sekolah->user, 'label', $sekolah->user->name);
278
279
        $response['sekolah'] = $sekolah;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
280
        $response['user'] = $sekolah->user;
281
        $response['jenis_sekolah'] = $sekolah->jenis_sekolah;
282
        $response['status'] = true;
283
284
        return response()->json($response);
285
    }
286
287
    /**
288
     * Update the specified resource in storage.
289
     *
290
     * @param  \Illuminate\Http\Request  $request
291
     * @param  \App\Sekolah  $sekolah
0 ignored issues
show
Bug introduced by
There is no parameter named $sekolah. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
292
     * @return \Illuminate\Http\Response
293
     */
294
    public function update(Request $request, $id)
295
    {
296
        $response = array();
297
        $message  = array();
298
299
        $sekolah = $this->sekolah->findOrFail($id);
300
301
            $validator = Validator::make($request->all(), [
302
                'label'               => 'required',
303
                'user_id'             => 'required|unique:sekolahs,user_id,'.$id,
304
                'jenis_sekolah_id'    => 'required',
305
                'npsn'                => 'required|unique:sekolahs,npsn,'.$id,
306
                'alamat'              => 'required',
307
                'logo'                => 'required',
308
                'foto_gedung'         => 'required',
309
                'province_id'         => 'required',
310
                'city_id'             => 'required',
311
                'district_id'         => 'required',
312
                'village_id'          => 'required',
313
                'no_telp    '         => 'required',
314
                'email'               => 'required',
315
                'kode_zona'             => 'required',
316
317
            ]);
318
319
            if($validator->fails()){
320
321
                foreach($validator->messages()->getMessages() as $key => $error){
322
                    foreach($error AS $error_get) {
323
                        array_push($message, $error_get);
324
                    }
325
                }
326
327
                $check_user   = $this->sekolah->where('id','!=', $id)->where('user_id', $request->user_id);
328
                $check_npsn   = $this->sekolah->where('id','!=', $id)->where('npsn', $request->npsn);
329
330
331
                if($check_npsn->count() > 0 || $check_user->count() > 0){
332
                    $response['message'] = implode("\n",$message);
333
334 View Code Duplication
                } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
335
                    $sekolah->label             = $request->input('label');
336
                $sekolah->jenis_sekolah_id  = $request->input('jenis_sekolah_id');
337
                $sekolah->npsn              = $request->input('npsn');
338
                $sekolah->alamat            = $request->input('alamat');
339
                $sekolah->logo              = $request->input('logo');
340
                $sekolah->foto_gedung       = $request->input('foto_gedung');
341
                $sekolah->province_id       = $request->input('province_id');
342
                $sekolah->city_id           = $request->input('city_id');
343
                $sekolah->district_id       = $request->input('district_id');
344
                $sekolah->village_id        = $request->input('village_id');
345
                $sekolah->no_telp           = $request->input('no_telp');
346
                $sekolah->email             = $request->input('email');
347
                $sekolah->kode_zona           = $request->input('kode_zona');
348
                $sekolah->user_id           = $request->input('user_id');
349
                    $sekolah->save();
350
                    $response['message'] = 'success';
351
            }
352
353 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
354
            $sekolah->label             = $request->input('label');
355
                $sekolah->jenis_sekolah_id  = $request->input('jenis_sekolah_id');
356
                $sekolah->npsn              = $request->input('npsn');
357
                $sekolah->alamat            = $request->input('alamat');
358
                $sekolah->logo              = $request->input('logo');
359
                $sekolah->foto_gedung       = $request->input('foto_gedung');
360
                $sekolah->province_id       = $request->input('province_id');
361
                $sekolah->city_id           = $request->input('city_id');
362
                $sekolah->district_id       = $request->input('district_id');
363
                $sekolah->village_id        = $request->input('village_id');
364
                $sekolah->no_telp           = $request->input('no_telp');
365
                $sekolah->email             = $request->input('email');
366
                $sekolah->kode_zona           = $request->input('kode_zona');
367
                $sekolah->user_id           = $request->input('user_id');
368
            $sekolah->save();
369
            $response['message'] = 'success';
370
        }
371
372
        $response['status'] = true;
373
        return response()->json($response);
374
    }
375
376
    /**
377
     * Remove the specified resource from storage.
378
     *
379
     * @param  \App\Sekolah  $sekolah
0 ignored issues
show
Bug introduced by
There is no parameter named $sekolah. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
380
     * @return \Illuminate\Http\Response
381
     */
382
    public function destroy($id)
383
    {
384
        $sekolah = $this->sekolah->findOrFail($id);
385
386
        if ($sekolah->delete()) {
387
            $response['message']    = 'Success';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
388
            $response['success']    = true;
389
            $response['status']     = true;
390
        } else {
391
            $response['message']    = 'Failed';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
392
            $response['success']    = false;
393
            $response['status']     = false;
394
        }
395
396
        return json_encode($response);
397
    }
398
}
399