Completed
Push — master ( d9e5e7...c84b2c )
by
unknown
11s
created

SiswaController::create()   C

Complexity

Conditions 10
Paths 192

Size

Total Lines 72
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 49
nc 192
nop 1
dl 0
loc 72
rs 5.5474
c 0
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
namespace Bantenprov\Siswa\Http\Controllers;
3
/* Require */
4
use App\Http\Controllers\Controller;
5
use Illuminate\Http\Request;
6
use Bantenprov\Siswa\Facades\SiswaFacade;
7
/* Models */
8
use Bantenprov\Siswa\Models\Bantenprov\Siswa\Siswa;
9
use Bantenprov\Pendaftaran\Models\Bantenprov\Pendaftaran\Pendaftaran;
10
use Bantenprov\Sekolah\Models\Bantenprov\Sekolah\Sekolah;
11
use App\User;
12
use Laravolt\Indonesia\Models\Province;
13
use Laravolt\Indonesia\Models\City;
14
use Laravolt\Indonesia\Models\District;
15
use Laravolt\Indonesia\Models\Village;
16
17
/* Etc */
18
use Validator;
19
/**
20
 * The SiswaController class.
21
 *
22
 * @package Bantenprov\Siswa
23
 * @author  bantenprov <[email protected]>
24
 */
25
class SiswaController extends Controller
26
{
27
    /**
28
     * Create a new controller instance.
29
     *
30
     * @return void
31
     */
32
    protected $user;
33
    protected $sekolah;
34
35
    public function __construct(Siswa $siswa, User $user, Sekolah $sekolah)
36
    {
37
        $this->siswa    = $siswa;
38
        $this->sekolah  = $sekolah;
39
        $this->user     = $user;
40
        $this->province = new Province;
41
        $this->city     = new City;
42
        $this->district = new District;
43
        $this->village  = new Village;
44
    }
45
    /**
46
     * Display a listing of the resource.
47
     *
48
     * @return \Illuminate\Http\Response
49
     */
50
    public function index(Request $request)
51
    {
52
        if (request()->has('sort')) {
53
            list($sortCol, $sortDir) = explode('|', request()->sort);
54
            $query = $this->siswa->orderBy($sortCol, $sortDir);
55
        } else {
56
            $query = $this->siswa->orderBy('id', 'asc');
57
        }
58
        if ($request->exists('filter')) {
59
            $query->where(function($q) use($request) {
60
                $value = "%{$request->filter}%";
61
                $q->where('nik', 'like', $value)
62
                    ->orWhere('nama_siswa', 'like', $value);
63
            });
64
        }
65
        $perPage = request()->has('per_page') ? (int) request()->per_page : null;
66
        $response = $query->with('user')->with('sekolah')->paginate($perPage);
67
68
        /*foreach($response as $user){
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
69
            array_set($response->data, 'user', $user->user->name);
70
        }*/
71
72
        return response()->json($response)
73
            ->header('Access-Control-Allow-Origin', '*')
74
            ->header('Access-Control-Allow-Methods', 'GET');
75
    }
76
    /**
77
     * Show the form for creating a new resource.
78
     *
79
     * @return \Illuminate\Http\Response
80
     */
81
    public function create(Request $request)
82
    {
83
        $response = [];
84
85
        $sekolahs       = $this->sekolah->all();
86
        $provinces      = $this->province->getAttributes();
87
        $citys          = $this->city->getAttributes();
88
        $districts      = $this->district->getAttributes();
89
        $villages       = $this->village->getAttributes();
90
        $users_special  = $this->user->all();
91
        $users_standar  = $this->user->find(\Auth::User()->id);
92
        $current_user   = \Auth::User();
93
94
        if ($request->has('no_kk') && strlen($request->input('no_kk')) == 16) {
95
            $no_kk          = '3602142003170013';
96
            $province_id    = substr($no_kk, 0, 2);
97
            $city_id        = substr($no_kk, 2, 2);
98
            $district_id    = substr($no_kk, 4, 2);
99
            $village_id     = substr($no_kk, 6, 3);
100
101
            $provinces      = \Indonesia::findProvince($province_id);
102
            $citys          = \Indonesia::findCity($city_id);
103
            $districts      = \Indonesia::findDistrict($district_id);
104
            $villages       = \Indonesia::findVillage($village_id);
105
        }
106
107
        $role_check = \Auth::User()->hasRole(['superadministrator','administrator']);
108
109
        if($role_check){
110
            $response['user_special'] = true;
111
            foreach($users_special as $user){
112
                array_set($user, 'label', $user->name);
113
            }
114
            $response['user'] = $users_special;
115
        }else{
116
            $response['user_special'] = false;
117
            array_set($users_standar, 'label', $users_standar->name);
118
            $response['user'] = $users_standar;
119
        }
120
121
        array_set($current_user, 'label', $current_user->name);
122
123
        $response['current_user'] = $current_user;
124
125
        foreach($sekolahs as $sekolah){
126
            array_set($sekolah, 'sekolah', $sekolah->label);
127
        }
128
129
        foreach($provinces as $province){
130
            array_set($province, 'label', $province->name);
131
        }
132
133
        foreach($citys as $city){
134
            array_set($city, 'label', $city->name);
135
        }
136
137
        foreach($districts as $district){
138
            array_set($district, 'label', $district->name);
139
        }
140
141
        foreach($villages as $village){
142
            array_set($village, 'label', $village->name);
143
        }
144
145
        $response['sekolah']    = $sekolahs;
146
        $response['province']   = $provinces;
147
        $response['city']       = $citys;
148
        $response['district']   = $districts;
149
        $response['village']    = $villages;
150
        $response['status']     = true;
151
        return response()->json($response);
152
    }
153
154
    /**
155
     * Display the specified resource.
156
     *
157
     * @param  \App\Siswa  $siswa
0 ignored issues
show
Bug introduced by
There is no parameter named $siswa. 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...
158
     * @return \Illuminate\Http\Response
159
     */
160
    public function store(Request $request)
161
    {
162
        $siswa = $this->siswa;
163
        $validator = Validator::make($request->all(), [
164
            'user_id'       => 'required|unique:siswas,user_id',
165
            'nomor_un'      => 'required|unique:siswas,nomor_un',
166
            'nik'           => 'required|unique:siswas,nik',
167
            'nama_siswa'    => 'required',
168
            'no_kk'         => 'required|unique:siswas,no_kk',
169
            'alamat_kk'     => 'required',
170
            'province_id'   => 'required',
171
            'city_id'       => 'required',
172
            'district_id'   => 'required',
173
            'village_id'    => 'required',
174
            'tempat_lahir'  => 'required',
175
            'tgl_lahir'     => 'required',
176
            'jenis_kelamin' => 'required',
177
            'agama'         => 'required',
178
            'nisn'          => 'required',
179
            'sekolah_id'    => 'required',
180
            'tahun_lulus'   => 'required',
181
        ]);
182
        if($validator->fails()){
183
            $check = $siswa->where('user_id',$request->user_id)->orWhere('nomor_un', $request->nomor_un)->orWhere('nik', $request->nik)->orWhere('no_kk', $request->no_kk)->whereNull('deleted_at')->count();
184
            if ($check > 0) {
185
                $response['message'] = 'Failed, Username, nomor un, nik, no kk  already exists';
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...
186 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...
187
                $siswa->user_id         = $request->input('user_id');
188
                $siswa->nomor_un        = $request->input('nomor_un');
189
                $siswa->nik             = $request->input('nik');
190
                $siswa->nama_siswa      = $request->input('nama_siswa');
191
                $siswa->no_kk           = $request->input('no_kk');
192
                $siswa->alamat_kk       = $request->input('alamat_kk');
193
                $siswa->province_id     = $request->input('province_id');
194
                $siswa->city_id         = $request->input('city_id');
195
                $siswa->district_id     = $request->input('district_id');
196
                $siswa->village_id      = $request->input('village_id');
197
                $siswa->tempat_lahir    = $request->input('tempat_lahir');
198
                $siswa->tgl_lahir       = $request->input('tgl_lahir');
199
                $siswa->jenis_kelamin   = $request->input('jenis_kelamin');
200
                $siswa->agama           = $request->input('agama');
201
                $siswa->nisn            = $request->input('nisn');
202
                $siswa->sekolah_id      = $request->input('sekolah_id');
203
                $siswa->tahun_lulus     = $request->input('tahun_lulus');
204
                $siswa->save();
205
                $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...
206
            }
207 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...
208
                $siswa->user_id         = $request->input('user_id');
209
                $siswa->nomor_un        = $request->input('nomor_un');
210
                $siswa->nik             = $request->input('nik');
211
                $siswa->nama_siswa      = $request->input('nama_siswa');
212
                $siswa->no_kk           = $request->input('no_kk');
213
                $siswa->alamat_kk       = $request->input('alamat_kk');
214
                $siswa->province_id     = $request->input('province_id');
215
                $siswa->city_id         = $request->input('city_id');
216
                $siswa->district_id     = $request->input('district_id');
217
                $siswa->village_id      = $request->input('village_id');
218
                $siswa->tempat_lahir    = $request->input('tempat_lahir');
219
                $siswa->tgl_lahir       = $request->input('tgl_lahir');
220
                $siswa->jenis_kelamin   = $request->input('jenis_kelamin');
221
                $siswa->agama           = $request->input('agama');
222
                $siswa->nisn            = $request->input('nisn');
223
                $siswa->sekolah_id      = $request->input('sekolah_id');
224
                $siswa->tahun_lulus     = $request->input('tahun_lulus');
225
                $siswa->save();
226
                $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...
227
        }
228
        $response['status'] = true;
229
        return response()->json($response);
230
    }
231
    /**
232
     * Store a newly created resource in storage.
233
     *
234
     * @param  \Illuminate\Http\Request  $request
0 ignored issues
show
Bug introduced by
There is no parameter named $request. 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...
235
     * @return \Illuminate\Http\Response
236
     */
237 View Code Duplication
    public function show($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...
238
    {
239
240
        $siswa = $this->siswa->findOrFail($id);
241
242
243
        array_set($siswa, 'user', $siswa->user->name);
244
        array_set($siswa, 'sekolah', $siswa->sekolah->label);
245
246
247
        $response['siswa'] = $siswa;
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...
248
        $response['sekolah'] = $siswa;
249
        $response['status'] = true;
250
251
252
253
        return response()->json($response);
254
255
256
    }
257
    /**
258
     * Show the form for editing the specified resource.
259
     *
260
     * @param  \App\Siswa  $siswa
0 ignored issues
show
Bug introduced by
There is no parameter named $siswa. 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...
261
     * @return \Illuminate\Http\Response
262
     */
263 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...
264
    {
265
        $siswa = $this->siswa->findOrFail($id);
266
        array_set($siswa->user, 'label', $siswa->user->name);
267
        //dd($siswa->user);
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
268
        $response['siswa'] = $siswa;
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...
269
        $response['user'] = $siswa->user;
270
        $response['status'] = true;
271
        return response()->json($response);
272
    }
273
    /**
274
     * Update the specified resource in storage.
275
     *
276
     * @param  \Illuminate\Http\Request  $request
277
     * @param  \App\Siswa  $siswa
0 ignored issues
show
Bug introduced by
There is no parameter named $siswa. 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...
278
     * @return \Illuminate\Http\Response
279
     */
280
    public function update(Request $request, $id)
281
    {
282
        $response = array();
283
        $message  = array();
284
        $siswa = $this->siswa->findOrFail($id);
285
286
            $validator = Validator::make($request->all(), [
287
                'user_id'       => 'required|unique:siswas,user_id,'.$id,
288
                'label'         => 'required',
289
                'description'   => 'required',
290
                'nomor_un'      => 'required|unique:siswas,nomor_un,'.$id,
291
                'nik'           => 'required|unique:siswas,nik,'.$id,
292
                'nama_siswa'    => 'required',
293
                'alamat_kk'     => 'required',
294
                'tempat_lahir'  => 'required',
295
                'tgl_lahir'     => 'required',
296
                'jenis_kelamin' => 'required',
297
                'agama'         => 'required',
298
                'nisn'          => 'required',
299
                'tahun_lulus'   => 'required',
300
301
                ]);
302
303
                if($validator->fails()){
304
305
                    foreach($validator->messages()->getMessages() as $key => $error){
306
                        foreach($error AS $error_get) {
307
                            array_push($message, $error_get);
308
                        }
309
                    }
310
311
312
                    $check_user     = $this->siswa->where('id','!=', $id)->where('user_id', $request->user_id);
313
                    $check_nomor_un = $this->siswa->where('id','!=', $id)->where('nomor_un', $request->nomor_un);
314
                    $check_nik      = $this->siswa->where('id','!=', $id)->where('nik', $request->nik);
315
316
                    if($check_nomor_un->count() > 0 || $check_user->count() > 0 || $check_nik->count() > 0){
317
                        $response['message'] = implode("\n",$message);
318
319
                    }else{
320
                         $siswa->user_id = $request->input('user_id');
321
                        $siswa->label = $request->input('label');
322
                        $siswa->description = $request->input('description');
323
                        $siswa->nomor_un = $request->input('nomor_un');
324
                        $siswa->nik = $request->input('nik');
325
                        $siswa->nama_siswa = $request->input('nama_siswa');
326
                        $siswa->alamat_kk = $request->input('alamat_kk');
327
                        $siswa->tempat_lahir = $request->input('tempat_lahir');
328
                        $siswa->tgl_lahir = $request->input('tgl_lahir');
329
                        $siswa->jenis_kelamin = $request->input('jenis_kelamin');
330
                        $siswa->agama = $request->input('agama');
331
                        $siswa->nisn = $request->input('nisn');
332
                        $siswa->tahun_lulus = $request->input('tahun_lulus');
333
                        $siswa->save();
334
                        $response['message'] = 'success';
335
                    }
336
             }else{
337
                    $siswa->user_id = $request->input('user_id');
338
                    $siswa->label = $request->input('label');
339
                    $siswa->description = $request->input('description');
340
                    $siswa->nomor_un = $request->input('nomor_un');
341
                    $siswa->nik = $request->input('nik');
342
                    $siswa->nama_siswa = $request->input('nama_siswa');
343
                    $siswa->alamat_kk = $request->input('alamat_kk');
344
                    $siswa->tempat_lahir = $request->input('tempat_lahir');
345
                    $siswa->tgl_lahir = $request->input('tgl_lahir');
346
                    $siswa->jenis_kelamin = $request->input('jenis_kelamin');
347
                    $siswa->agama = $request->input('agama');
348
                    $siswa->nisn = $request->input('nisn');
349
                    $siswa->tahun_lulus = $request->input('tahun_lulus');
350
                    $siswa->save();
351
                    $response['message'] = 'success';
352
        }
353
354
        $response['status'] = true;
355
        return response()->json($response);
356
    }
357
    /**
358
     * Remove the specified resource from storage.
359
     *
360
     * @param  \App\Siswa  $siswa
0 ignored issues
show
Bug introduced by
There is no parameter named $siswa. 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...
361
     * @return \Illuminate\Http\Response
362
     */
363
    public function destroy($id)
364
    {
365
        $siswa = $this->siswa->findOrFail($id);
366
        if ($siswa->delete()) {
367
            $response['status'] = true;
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...
368
        } else {
369
            $response['status'] = false;
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...
370
        }
371
        return json_encode($response);
372
    }
373
}
374