Completed
Pull Request — master (#12)
by
unknown
02:12
created

SktmController::update()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 60
Code Lines 39

Duplication

Lines 39
Ratio 65 %

Importance

Changes 0
Metric Value
cc 4
eloc 39
nc 3
nop 2
dl 39
loc 60
rs 8.9618
c 0
b 0
f 0

How to fix   Long Method   

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\Sktm\Http\Controllers;
4
5
/* Require */
6
use App\Http\Controllers\Controller;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Facades\DB;
9
use Bantenprov\Sktm\Facades\SktmFacade;
10
11
/* Models */
12
use Bantenprov\Sktm\Models\Bantenprov\Sktm\Sktm;
13
use Bantenprov\Siswa\Models\Bantenprov\Siswa\Siswa;
14
use Bantenprov\Sktm\Models\Bantenprov\Sktm\MasterSktm;
15
use App\User;
16
use Bantenprov\Nilai\Models\Bantenprov\Nilai\Nilai;
17
18
/* Etc */
19
use Validator;
20
use Auth;
21
22
/**
23
 * The SktmController class.
24
 *
25
 * @package Bantenprov\Sktm
26
 * @author  bantenprov <[email protected]>
27
 */
28
class SktmController extends Controller
29
{
30
    protected $sktm;
31
    protected $siswa;
32
    protected $master_sktm;
33
    protected $user;
34
    protected $nilai;
35
36
    /**
37
     * Create a new controller instance.
38
     *
39
     * @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...
40
     */
41
    public function __construct()
42
    {
43
        $this->sktm         = new Sktm;
44
        $this->siswa        = new Siswa;
45
        $this->master_sktm  = new MasterSktm;
46
        $this->user         = new User;
47
        $this->nilai        = new Sktm;
48
    }
49
50
    /**
51
     * Display a listing of the resource.
52
     *
53
     * @return \Illuminate\Http\Response
54
     */
55 View Code Duplication
    public function index(Request $request)
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...
56
    {
57
        if (request()->has('sort')) {
58
            list($sortCol, $sortDir) = explode('|', request()->sort);
59
60
            $query = $this->sktm->orderBy($sortCol, $sortDir);
61
        } else {
62
            $query = $this->sktm->orderBy('id', 'asc');
63
        }
64
65
        if ($request->exists('filter')) {
66
            $query->where(function($q) use($request) {
67
                $value = "%{$request->filter}%";
68
69
                $q->where('nomor_un', 'like', $value)
70
                    ->orWhere('no_sktm', 'like', $value);
71
            });
72
        }
73
74
        $perPage    = request()->has('per_page') ? (int) request()->per_page : null;
75
76
        $response   = $query->with(['siswa', 'master_sktm', 'user'])->paginate($perPage);
77
78
        return response()->json($response)
79
            ->header('Access-Control-Allow-Origin', '*')
80
            ->header('Access-Control-Allow-Methods', 'GET');
81
    }
82
83
    /**
84
     * Display a listing of the resource.
85
     *
86
     * @return \Illuminate\Http\Response
87
     */
88
    public function get()
89
    {
90
        $sktms = $this->sktm->with(['siswa', 'master_sktm', 'user'])->get();
91
92
        foreach ($sktms as $sktm) {
93
            if ($sktm->siswa !== null) {
94
                array_set($sktm, 'label', $sktm->siswa->nomor_un.' - '.$sktm->siswa->nama_siswa);
95
            } else {
96
                array_set($sktm, 'label', $sktm->nomor_un.' - ');
97
            }
98
        }
99
100
        $response['sktms']  = $sktms;
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...
101
        $response['error']      = false;
102
        $response['message']    = 'Success';
103
        $response['status']     = true;
104
105
        return response()->json($response);
106
    }
107
108
    /**
109
     * Show the form for creating a new resource.
110
     *
111
     * @return \Illuminate\Http\Response
112
     */
113
    public function create()
114
    {
115
        $user_id        = isset(Auth::User()->id) ? Auth::User()->id : null;
116
        $sktm           = $this->sktm->getAttributes();
117
        $siswas         = $this->siswa->getAttributes();
118
        $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...
119
        $users_special  = $this->user->all();
120
        $users_standar  = $this->user->findOrFail($user_id);
121
        $current_user   = Auth::User();
122
123
        foreach ($siswas as $siswa) {
124
            array_set($siswa, 'label', $siswa->nomor_un.' - '.$siswa->nama_siswa);
125
        }
126
127
        $role_check = Auth::User()->hasRole(['superadministrator','administrator']);
128
129 View Code Duplication
        if ($role_check) {
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...
130
            $user_special = true;
131
132
            foreach($users_special as $user){
133
                array_set($user, 'label', $user->name);
134
            }
135
136
            $users = $users_special;
137
        } else {
138
            $user_special = false;
139
140
            array_set($users_standar, 'label', $users_standar->name);
141
142
            $users = $users_standar;
143
        }
144
145
        array_set($current_user, 'label', $current_user->name);
146
147
        $response['sktm']           = $sktm;
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...
148
        $response['siswas']         = $siswas;
149
        $response['users']          = $users;
150
        $response['user_special']   = $user_special;
151
        $response['current_user']   = $current_user;
152
        $response['error']          = false;
153
        $response['message']        = 'Success';
154
        $response['status']         = true;
155
156
        return response()->json($response);
157
    }
158
159
    /**
160
     * Store a newly created resource in storage.
161
     *
162
     * @param  \Illuminate\Http\Request  $request
163
     * @return \Illuminate\Http\Response
164
     */
165
    public function store(Request $request)
166
    {
167
        $sktm = $this->sktm;
168
169
        $validator = Validator::make($request->all(), [
170
            'nomor_un'          => "required|exists:{$this->siswa->getTable()},nomor_un|unique:{$this->sktm->getTable()},nomor_un,NULL,id,deleted_at,NULL",
171
            'bahasa_indonesia'  => 'required|numeric|min:0|max:100',
172
            'bahasa_inggris'    => 'required|numeric|min:0|max:100',
173
            'matematika'        => 'required|numeric|min:0|max:100',
174
            'ipa'               => 'required|numeric|min:0|max:100',
175
            'user_id'           => "required|exists:{$this->user->getTable()},id",
176
        ]);
177
178 View Code Duplication
        if ($validator->fails()) {
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...
179
            $error      = true;
180
            $message    = $validator->errors()->first();
181
        } else {
182
            $sktm->nomor_un         = $request->input('nomor_un');
183
            $sktm->bahasa_indonesia = $request->input('bahasa_indonesia');
184
            $sktm->bahasa_inggris   = $request->input('bahasa_inggris');
185
            $sktm->matematika       = $request->input('matematika');
186
            $sktm->ipa              = $request->input('ipa');
187
            $sktm->user_id          = $request->input('user_id');
188
189
            $nilai = $this->nilai->updateOrCreate(
190
                [
191
                    'nomor_un'  => $sktm->nomor_un,
192
                ],
193
                [
194
                    'nomor_un'  => $sktm->nomor_un,
195
                    'bobot'     => $sktm->calcSktmBobot($request),
196
                    'sktm'  => $sktm->calcSktmSktm($request),
197
                    'total'     => null,
198
                    'user_id'   => $sktm->user_id,
199
                ]
200
            );
201
202
            DB::beginTransaction();
203
204
            if ($sktm->save() && $nilai->save())
205
            {
206
                DB::commit();
207
208
                $error      = false;
209
                $message    = 'Success';
210
            } else {
211
                DB::rollBack();
212
213
                $error      = true;
214
                $message    = 'Failed';
215
            }
216
        }
217
218
        $response['sktm']   = $sktm;
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...
219
        $response['error']      = $error;
220
        $response['message']    = $message;
221
        $response['status']     = true;
222
223
        return response()->json($response);
224
    }
225
226
    /**
227
     * Display the specified resource.
228
     *
229
     * @param  \App\Sktm  $nilai
0 ignored issues
show
Bug introduced by
There is no parameter named $nilai. 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...
230
     * @return \Illuminate\Http\Response
231
     */
232 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...
233
    {
234
        $sktm = $this->sktm->with(['siswa', 'master_sktm', 'user'])->findOrFail($id);
235
236
        $response['sktm']   = $sktm;
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...
237
        $response['error']      = false;
238
        $response['message']    = 'Success';
239
        $response['status']     = true;
240
241
        return response()->json($response);
242
    }
243
244
    /**
245
     * Show the form for editing the specified resource.
246
     *
247
     * @param  \App\Sktm  $nilai
0 ignored issues
show
Bug introduced by
There is no parameter named $nilai. 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...
248
     * @return \Illuminate\Http\Response
249
     */
250
    public function edit($id)
251
    {
252
        $user_id        = isset(Auth::User()->id) ? Auth::User()->id : null;
253
        $sktm           = $this->sktm->with(['siswa', 'master_sktm', 'user'])->findOrFail($id);
254
        $siswas         = $this->siswa->getAttributes();
255
        $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...
256
        $users_special  = $this->user->all();
257
        $users_standar  = $this->user->findOrFail($user_id);
258
        $current_user   = Auth::User();
259
260
        if ($sktm->siswa !== null) {
261
            array_set($sktm->siswa, 'label', $sktm->siswa->nomor_un.' - '.$sktm->siswa->nama_siswa);
262
        }
263
264
        $role_check = Auth::User()->hasRole(['superadministrator','administrator']);
265
266
        if ($sktm->user !== null) {
267
            array_set($sktm->user, 'label', $sktm->user->name);
268
        }
269
270 View Code Duplication
        if ($role_check) {
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...
271
            $user_special = true;
272
273
            foreach($users_special as $user){
274
                array_set($user, 'label', $user->name);
275
            }
276
277
            $users = $users_special;
278
        } else {
279
            $user_special = false;
280
281
            array_set($users_standar, 'label', $users_standar->name);
282
283
            $users = $users_standar;
284
        }
285
286
        array_set($current_user, 'label', $current_user->name);
287
288
        $response['sktm']       = $sktm;
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...
289
        $response['siswas']         = $siswas;
290
        $response['users']          = $users;
291
        $response['user_special']   = $user_special;
292
        $response['current_user']   = $current_user;
293
        $response['error']          = false;
294
        $response['message']        = 'Success';
295
        $response['status']         = true;
296
297
        return response()->json($response);
298
    }
299
300
    /**
301
     * Update the specified resource in storage.
302
     *
303
     * @param  \Illuminate\Http\Request  $request
304
     * @param  \App\Sktm  $nilai
0 ignored issues
show
Bug introduced by
There is no parameter named $nilai. 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...
305
     * @return \Illuminate\Http\Response
306
     */
307
    public function update(Request $request, $id)
308
    {
309
        $sktm = $this->sktm->with(['siswa', 'master_sktm', 'user'])->findOrFail($id);
310
311
        $validator = Validator::make($request->all(), [
312
            // 'nomor_un'          => "required|exists:{$this->siswa->getTable()},nomor_un|unique:{$this->sktm->getTable()},nomor_un,{$id},id,deleted_at,NULL",
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
313
            'bahasa_indonesia'  => 'required|numeric|min:0|max:100',
314
            'bahasa_inggris'    => 'required|numeric|min:0|max:100',
315
            'matematika'        => 'required|numeric|min:0|max:100',
316
            'ipa'               => 'required|numeric|min:0|max:100',
317
            'user_id'           => "required|exists:{$this->user->getTable()},id",
318
        ]);
319
320 View Code Duplication
        if ($validator->fails()) {
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...
321
            $error      = true;
322
            $message    = $validator->errors()->first();
323
        } else {
324
            $sktm->nomor_un         = $sktm->nomor_un; // $request->input('nomor_un');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
325
            $sktm->bahasa_indonesia = $request->input('bahasa_indonesia');
326
            $sktm->bahasa_inggris   = $request->input('bahasa_inggris');
327
            $sktm->matematika       = $request->input('matematika');
328
            $sktm->ipa              = $request->input('ipa');
329
            $sktm->user_id          = $request->input('user_id');
330
331
            $nilai = $this->nilai->updateOrCreate(
332
                [
333
                    'nomor_un'  => $sktm->nomor_un,
334
                ],
335
                [
336
                    'nomor_un'  => $sktm->nomor_un,
337
                    'bobot'     => $sktm->calcSktmBobot($request),
338
                    'sktm'  => $sktm->calcSktmSktm($request),
339
                    'total'     => null,
340
                    'user_id'   => $sktm->user_id,
341
                ]
342
            );
343
344
            DB::beginTransaction();
345
346
            if ($sktm->save() && $nilai->save())
347
            {
348
                DB::commit();
349
350
                $error      = false;
351
                $message    = 'Success';
352
            } else {
353
                DB::rollBack();
354
355
                $error      = true;
356
                $message    = 'Failed';
357
            }
358
        }
359
360
        $response['sktm']   = $sktm;
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...
361
        $response['error']      = $error;
362
        $response['message']    = $message;
363
        $response['status']     = true;
364
365
        return response()->json($response);
366
    }
367
368
    /**
369
     * Remove the specified resource from storage.
370
     *
371
     * @param  \App\Sktm  $nilai
0 ignored issues
show
Bug introduced by
There is no parameter named $nilai. 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...
372
     * @return \Illuminate\Http\Response
373
     */
374 View Code Duplication
    public function destroy($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...
375
    {
376
        $sktm = $this->sktm->findOrFail($id);
377
378
        if ($sktm->delete()) {
379
            $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...
380
            $response['success']    = true;
381
            $response['status']     = true;
382
        } else {
383
            $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...
384
            $response['success']    = false;
385
            $response['status']     = false;
386
        }
387
388
        return json_encode($response);
389
    }
390
}
391