Test Setup Failed
Pull Request — master (#620)
by Mohamed
08:18
created

CloneController   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 306
Duplicated Lines 0 %

Importance

Changes 9
Bugs 3 Features 1
Metric Value
eloc 194
c 9
b 3
f 1
dl 0
loc 306
rs 9.44
wmc 37

11 Methods

Rating   Name   Duplication   Size   Complexity  
A updateInstitutionClasses() 0 26 3
A insertInstitutionClassSubjects() 0 9 3
A insertClassSubjects() 0 16 3
A insertInstitutionClasses() 0 40 3
A insertInstitutionSubjects() 0 10 2
A array_walk() 0 9 2
C process() 0 65 11
A __construct() 0 11 1
A cleanConfig() 0 22 3
A updateShifts() 0 28 3
A generateNewClass() 0 12 3
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use App\Models\Academic_period;
7
use App\Models\Institution_class;
8
use App\Models\Institution_shift;
9
use Illuminate\Support\Facades\DB;
10
use App\Models\Institution_subject;
11
use Illuminate\Support\Facades\Log;
12
use App\Http\Controllers\Controller;
13
use App\Models\Institution_class_grade;
14
use App\Models\Education_grades_subject;
15
use App\Models\Institution_class_student;
16
use App\Models\Institution_class_subject;
17
use App\Models\Institution_grade;
18
use App\Models\Institution_student;
19
20
class CloneController extends Controller
21
{
22
    /**
23
     * Create a new command instance.
24
     *
25
     * @return void
26
     */
27
    public function __construct()
28
29
    {
30
        $this->shifts = new Institution_shift();
0 ignored issues
show
Bug Best Practice introduced by
The property shifts does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
31
        $this->academic_period = new Academic_period();
0 ignored issues
show
Bug Best Practice introduced by
The property academic_period does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
32
        $this->institution_classes = new Institution_class();
0 ignored issues
show
Bug Best Practice introduced by
The property institution_classes does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
33
        $this->institution_class_subjects = new Institution_class_subject();
0 ignored issues
show
Bug Best Practice introduced by
The property institution_class_subjects does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
34
        $this->institution_subjects =  new Institution_subject();
0 ignored issues
show
Bug Best Practice introduced by
The property institution_subjects does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
35
        $this->institution_grades = new Institution_grade();
0 ignored issues
show
Bug Best Practice introduced by
The property institution_grades does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
36
        $this->education_grade_subjects =  new Education_grades_subject();
0 ignored issues
show
Bug Best Practice introduced by
The property education_grade_subjects does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
37
        $this->output = new \Symfony\Component\Console\Output\ConsoleOutput();
0 ignored issues
show
Bug Best Practice introduced by
The property output does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
38
    }
39
40
41
    public function array_walk($shift, $count, $params)
0 ignored issues
show
Unused Code introduced by
The parameter $count is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

41
    public function array_walk($shift, /** @scrutinizer ignore-unused */ $count, $params)

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

Loading history...
42
    {
43
        try{
44
           DB::beginTransaction();
45
            array_walk($shift, array($this, 'process'), $params);
46
            DB::commit();
47
        }catch(\Exception $e){
48
            $this->output->writeln('Terminating ' . $shift['institution_id']);
49
            DB::rollBack();
50
        }
51
    }
52
53
    public function cleanConfig($params)
54
    {
55
        $academicPeriod = $params['academic_period'];
56
        $this->shifts->where(['academic_period_id' => $academicPeriod->id])->delete();
57
        $this->output->writeln('cleaned shifts');
58
59
        $this->shifts->where(['cloned' => $academicPeriod->code])->update(['cloned' => $params['previous_academic_period']['code']]);
60
        $this->output->writeln('updated shifts');
61
62
        $classIds =  $this->institution_classes->select('id')->where(['academic_period_id' => $academicPeriod->id])->get()->toArray();
0 ignored issues
show
Unused Code introduced by
The assignment to $classIds is dead and can be removed.
Loading history...
63
        $this->institution_classes->where(['academic_period_id' => $academicPeriod->id])->delete();
64
        $this->output->writeln('cleaned classes');
65
66
        do {
67
            $deleted = $this->institution_class_subjects->whereRaw("institution_class_id not in (select id from institution_classes where academic_period_id =".$academicPeriod->id." )")->limit(10000)->delete();
68
            $this->output->writeln('cleaned subjects');
69
        }while($deleted > 0);
70
71
        do {
72
            $deleted =  $this->institution_subjects->where('academic_period_id', $academicPeriod->id)->limit(10000)->delete();
73
            $this->output->writeln('10000 institutions cleaned subjects');
74
        } while ($deleted > 0);
75
    }
76
77
    public function process($shift, $count, $params)
78
    {
79
        echo ('[' . getmypid() . ']This Process executed at' . date("F d, Y h:i:s A") . "\n");
80
        $year = $params['year'];
81
        $academicPeriod = $params['academic_period'];
82
        $previousAcademicPeriod = $params['previous_academic_period'];
83
        $mode = $params['mode'] == 'AL' ? true : false;
84
85
        $data = $this->updateShifts($year, $shift);
86
        $shiftId = $data['shift_id'];
87
88
        $params = [
89
            'previous_academic_period_id' => $previousAcademicPeriod->id,
90
            'academic_period_id' => $academicPeriod->id,
91
            'shift_id' => $data['shift_id'],
92
            'mode' => $mode
93
        ];
94
95
96
        if ($mode) {
97
            $institutionClasses = $this->institution_classes->getShiftClasses($shift,  $mode);
98
            try {
99
                array_walk($institutionClasses, array($this, 'updateInstitutionClasses'), $params);
100
                $this->output->writeln('updating from ' . $shift['institution_id']);
101
            } catch (\Exception $e) {
102
                Log::error($e->getMessage(), [$e]);
103
            }
104
        } else {
105
            $institutionSubjects = $this->institution_grades->getGradeSubjects($shift['institution_id']);
106
            try {
107
                if ($data['created']) {
108
                    $institutionClasses = $this->institution_classes->getShiftClasses($shift, $mode);
109
                    array_walk($institutionSubjects, array($this, 'insertInstitutionSubjects'), $academicPeriod);
110
                    if (!empty($institutionClasses) && !is_null($shiftId) && !is_null($academicPeriod)) {
111
                        $newInstitutionClasses = $this->generateNewClass($institutionClasses, $shiftId, $academicPeriod->id);
112
                        try {
113
                            array_walk($newInstitutionClasses, array($this, 'insertInstitutionClasses'), $params);
114
                            $this->output->writeln('##########################################################################################################################');
115
                            $this->output->writeln('updating from = ' . $shift['institution_id']);
116
                        } catch (\Exception $e) {
117
                            $this->output->writeln('Terminating ' . $shift['institution_id']);
118
                            DB::rollBack();
119
                            Log::error($e->getMessage(), [$e]);
120
                        }
121
                    } else {
122
                        $this->output->writeln('no classes found ' . $shift['institution_id']);
123
                    }
124
                } else {
125
                    try {
126
                        $shift['id'] = $shiftId;
127
                        $institutionClasses = $this->institution_classes->getShiftClasses($shift, $mode);
128
                        array_walk($institutionClasses, array($this, 'updateInstitutionClasses'), $params);
129
                        $this->output->writeln('##########################################################################################################################');
130
                        $this->output->writeln('updating from ' . $shift['institution_id']);
131
                    } catch (\Exception $e) {
132
                        $this->output->writeln('Terminating ' . $shift['institution_id']);
133
                        DB::rollBack();
134
                        Log::error($e->getMessage(), [$e]);
135
                    }
136
                }
137
                DB::commit();
138
            } catch (\Exception $e) {
139
                Log::error($e->getMessage(), [$e]);
140
                $this->output->writeln('Terminating ' . $shift['institution_id']);
141
                DB::rollBack();
142
            }
143
        }
144
    }
145
146
147
    /**
148
     * @param $subjects
149
     * @param $count
150
     * @param $academicPeriod
151
     */
152
    public function insertInstitutionSubjects($subject, $count, $academicPeriod)
153
    {
154
        try {
155
            $subject['academic_period_id'] = $academicPeriod->id;
156
            $subject['created'] = now();
157
            $subject['created_user_id'] = 1;
158
            $this->institution_subjects->create($subject);
159
        } catch (\Exception $e) {
160
            DB::rollBack();
161
            Log::error($e->getMessage(), [$e]);
162
        }
163
    }
164
165
    public function updateInstitutionClasses($class, $count, $params)
166
    {
167
        try {
168
            if ($params['mode']) {
169
                Institution_class::where('id', $class['id'])
170
                    ->update([
171
                        'institution_shift_id' => $params['shift_id'],
172
                        'academic_period_id' => $params['academic_period_id']
173
                    ]);
174
175
                Institution_class_student::where('institution_class_id', $class['id'])
176
                    ->update([
177
                        'academic_period_id' => $params['academic_period_id'],
178
                        'modified' => now()
179
                    ]);
180
181
                $educationGrade = Institution_class_grade::select('education_grade_id')->where('institution_class_id', $class['id'])->get()->toArray();
182
183
                Institution_student::whereIn('education_grade_id', $educationGrade)
184
                    ->update([
185
                        'academic_period_id' => $params['academic_period_id']
186
                    ]);
187
            }
188
        } catch (\Exception $e) {
189
            DB::rollBack();
190
            Log::error($e->getMessage(), [$e]);
191
        }
192
    }
193
194
    public function  insertInstitutionClasses($class, $count, $param)
195
    {
196
        try {
197
            $academicPeriod = $param['academic_period_id'];
198
            $educationGrdae = $class['education_grade_id'];
199
200
            $classId = $class['id'];
201
            unset($class['id']);
202
            $institutionSubjects = Institution_subject::query()->where('education_grade_id', $class['education_grade_id'])
203
                ->where('institution_id', $class['institution_id'])
204
                ->where('academic_period_id', $academicPeriod)->get()->toArray();
205
            $params = [
206
                'class' => $class,
207
                'subjects' => $institutionSubjects,
208
                'academic_period_id' => $academicPeriod,
209
                'classId' => $classId
210
            ];
211
            unset($class['education_grade_id']);
212
            $noOfStudents = $class['no_of_students'] == 0 ? 40 : $class['no_of_students'];
213
            $class['academic_period_id'] = $academicPeriod;
214
            $class['no_of_students'] = $noOfStudents;
215
            $class['created'] = now();
216
            $class['institution_shift_id'] = $param['shift_id'];
217
            // $class['created_user_id'] = 
218
            $this->output->writeln('Create class:' . $class['name']);
219
            $class =  Institution_class::create($class);
220
            $institutionClassGrdaeObj['institution_class_id'] = $class->id;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$institutionClassGrdaeObj was never initialized. Although not strictly required by PHP, it is generally a good practice to add $institutionClassGrdaeObj = array(); before regardless.
Loading history...
221
            $institutionClassGrdaeObj['education_grade_id'] = $educationGrdae;
222
            $institutionClassGrdaeObj['created_user_id'] = $class['created_user_id'];
223
            Institution_class_grade::create($institutionClassGrdaeObj);
224
            $institutionSubjects = Institution_subject::query()->where('education_grade_id', $educationGrdae)
225
                ->where('institution_id', $class->institution_id)
0 ignored issues
show
Bug introduced by
The property institution_id does not exist on App\Models\Institution_class. Did you mean institution?
Loading history...
226
                ->where('academic_period_id', $academicPeriod)
227
                ->get()
228
                ->toArray();
229
            $params['class'] = $class;
230
            $this->insertInstitutionClassSubjects($institutionSubjects, $class);
231
        } catch (\Exception $e) {
232
            DB::rollBack();
233
            Log::error($e->getMessage(), [$e]);
234
        }
235
    }
236
237
    public function insertInstitutionClassSubjects($subjects, $class)
238
    {
239
        if (!empty($subjects)) {
240
            try {
241
                array_walk($subjects, array($this, 'insertClassSubjects'), $class);
242
                $this->output->writeln('updating subjects ' . $class->name);
243
            } catch (\Exception $e) {
244
                DB::rollBack();
245
                Log::error($e->getMessage(), [$e]);
246
            }
247
        };
248
    }
249
250
251
    public function insertClassSubjects($subject, $count, $newClassId)
252
    {
253
        try {
254
            $subjectobj['status'] = 1;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$subjectobj was never initialized. Although not strictly required by PHP, it is generally a good practice to add $subjectobj = array(); before regardless.
Loading history...
255
            $subjectobj['created_user_id'] = 1;
256
            $subjectobj['created'] = now();
257
258
            $subjectobj['institution_class_id'] = $newClassId->id;
259
            $subjectobj['institution_subject_id'] = $subject['id'];
260
261
            if (!$this->institution_class_subjects->isDuplicated($subjectobj)) {
262
                $this->institution_class_subjects->create($subjectobj);
263
            }
264
        } catch (\Exception $e) {
265
            DB::rollBack();
266
            Log::error($e->getMessage(), [$e]);
267
        }
268
    }
269
270
    /**
271
     * generate new class object for new academic year
272
     *
273
     * @param $classes
274
     * @param $shiftId
275
     * @param $academicPeriod
276
     * @return array
277
     */
278
    public function generateNewClass($classes, $shiftId, $academicPeriod)
279
    {
280
        $newClasses = [];
281
        foreach ($classes as $class) {
282
            $noOfStudents = $class['no_of_students'] == 0 ? 40 : $class['no_of_students'];
283
            $class['academic_period_id'] = $academicPeriod;
284
            $class['no_of_students'] = $noOfStudents;
285
            $class['created'] = now();
286
            $class['institution_shift_id'] = $shiftId;
287
            array_push($newClasses, $class);
288
        }
289
        return $newClasses;
290
    }
291
292
    /**
293
     * update shifts
294
     * @param $year
295
     * @param $shift
296
     * @return mixed
297
     */
298
    public function updateShifts($year, $shift)
299
    {
300
        try {
301
            $academicPeriod = $this->academic_period->getAcademicPeriod($year);
302
            $this->shifts->where(['id' =>  $shift['id']])->update(['cloned' => $year]);
303
            $shift['academic_period_id'] = $academicPeriod->id;
304
            $exist = $this->shifts->getShift($shift);
305
            $data = array();
306
307
            if (is_null($exist)) {
308
                $shift['cloned'] = $academicPeriod->code;
0 ignored issues
show
Bug introduced by
The property code does not seem to exist on App\Models\Academic_period. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
309
                unset($shift['id']);
310
                unset($shift['created']);
311
                unset($shift['modified']);
312
                $shift = $this->shifts->create((array)$shift);
313
                $data = [
314
                    'shift_id' => $shift->id,
315
                    'created' => true
316
                ];
317
            } else {
318
                $data = [
319
                    'shift_id' => $exist->id,
320
                    'created' => false
321
                ];
322
            };
323
            return $data;
324
        } catch (\Exception $e) {
325
            DB::rollBack();
326
        }
327
    }
328
}
329