Test Setup Failed
Push — master ( ad3b88...b2f2cc )
by Mohamed
15:01 queued 07:46
created

UsersImport::model()   B

Complexity

Conditions 6
Paths 48

Size

Total Lines 57
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 2 Features 0
Metric Value
cc 6
eloc 43
c 5
b 2
f 0
nc 48
nop 1
dl 0
loc 57
rs 8.6097

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 App\Imports;
4
5
use App\Mail\StudentCountExceeded;
6
use App\Mail\StudentImportSuccess;
7
use App\Models\Education_grades_subject;
8
use App\Models\Institution_class_student;
9
use App\Models\Institution_class_subject;
10
use App\Models\Institution_student_admission;
11
use App\Models\Institution_subject;
12
use App\Models\Institution_subject_student;
13
use App\Models\User_special_need;
14
use App\Models\Security_group;
15
use App\Models\Security_user;
16
use App\Models\User;
17
use App\Models\User_body_mass;
18
use App\Models\Institution_student;
19
use App\Models\Import_mapping;
20
use App\Models\Identity_type;
21
use App\Models\Student_guardian;
22
use App\Models\Academic_period;
23
use App\Models\Institution_class;
24
use App\Models\Institution_class_grade;
25
use App\Models\Area_administrative;
26
use App\Models\Special_need_difficulty;
27
use App\Models\Workflow_transition;
28
use App\Models\User_nationality;
29
use App\Models\User_identity;
30
use App\Models\Nationality;
31
use App\Models\User_contact;
32
use App\Rules\admissionAge;
33
use Illuminate\Support\Facades\Log;
34
use Illuminate\Support\Facades\Mail;
35
use Illuminate\Support\Facades\Request;
36
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
37
use Maatwebsite\Excel\Concerns\ToModel;
38
use Maatwebsite\Excel\Concerns\WithBatchInserts;
39
use Maatwebsite\Excel\Concerns\WithStartRow;
40
use Illuminate\Support\Facades\DB;
41
use Maatwebsite\Excel\Concerns\Importable;
42
use Illuminate\Support\Facades\Validator;
43
use Maatwebsite\Excel\Concerns\WithValidation;
44
use Maatwebsite\Excel\Concerns\WithHeadingRow;
45
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
46
use Maatwebsite\Excel\Concerns\WithEvents;
47
use Maatwebsite\Excel\Concerns\WithMapping;
48
use Maatwebsite\Excel\Events\AfterImport;
49
use Maatwebsite\Excel\Concerns\WithLimit;
50
use Maatwebsite\Excel\Events\BeforeSheet;
51
use Maatwebsite\Excel\Events\BeforeImport;
52
use Maatwebsite\Excel\Jobs\AfterImportJob;
53
use Maatwebsite\Excel\Validators\Failure;
54
use Maatwebsite\Excel\Concerns\SkipsOnError;
55
use Maatwebsite\Excel\Concerns\SkipsErrors;
56
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
57
use Maatwebsite\Excel\Concerns\SkipsFailures;
58
use App\Imports\StudentUpdate;
59
use Maatwebsite\Excel\Exceptions\ConcernConflictException;
60
61
class UsersImport extends Import implements ToModel, WithStartRow, WithHeadingRow, WithMultipleSheets, WithEvents, WithMapping, WithLimit, WithBatchInserts, WithValidation, SkipsOnFailure, SkipsOnError
62
{
63
64
    use Importable, SkipsFailures, SkipsErrors;
0 ignored issues
show
introduced by
The trait Maatwebsite\Excel\Concerns\Importable requires some properties which are not provided by App\Imports\UsersImport: $disk, $readerType, $filePath
Loading history...
65
66
67
    public function sheets(): array
68
    {
69
        return [
70
            'Insert Students' => $this,
71
        ];
72
    }
73
74
75
    public function registerEvents(): array
76
    {
77
        return [
78
            BeforeSheet::class => function (BeforeSheet $event) {
79
                $this->sheetNames[] = $event->getSheet()->getTitle();
0 ignored issues
show
Bug Best Practice introduced by
The property sheetNames does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
80
                $this->worksheet = $event->getSheet();
0 ignored issues
show
Bug Best Practice introduced by
The property worksheet does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
81
                $this->validateClass();
82
                $this->highestRow = $this->worksheet->getHighestDataRow(); // e.g. 10
0 ignored issues
show
Bug Best Practice introduced by
The property highestRow does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
83
                if ($this->highestRow < 3) {
84
                    $error = \Illuminate\Validation\ValidationException::withMessages([]);
85
                    $failure = new Failure(3, 'remark', [0 => 'No enough rows!'], [null]);
86
                    $failures = [0 => $failure];
87
                    throw new \Maatwebsite\Excel\Validators\ValidationException($error, $failures);
88
                }
89
            },
90
            BeforeImport::class => function (BeforeImport $event) {
91
                $this->highestRow = ($event->getReader()->getDelegate()->getActiveSheet()->getHighestDataRow('C'));
0 ignored issues
show
Bug Best Practice introduced by
The property highestRow does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
92
                if ($this->highestRow < 3) {
93
                    $error = \Illuminate\Validation\ValidationException::withMessages([]);
94
                    $failure = new Failure(3, 'remark', [0 => 'No enough rows!'], [null]);
95
                    $failures = [0 => $failure];
96
                    throw new \Maatwebsite\Excel\Validators\ValidationException($error, $failures);
97
                }
98
            }
99
        ];
100
    }
101
102
103
104
105
    public function model(array $row)
106
    {
107
        try {
108
            $institutionClass = Institution_class::find($this->file['institution_class_id']);
109
            $institution = $institutionClass->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...
110
            if (!array_filter($row)) {
111
                return null;
112
            }
113
114
            if (!empty($institutionClass)) {
115
                $row = $this->setGender($row);
116
                $mandatorySubject = Institution_class_subject::getMandatorySubjects($this->file['institution_class_id']);
0 ignored issues
show
Unused Code introduced by
The assignment to $mandatorySubject is dead and can be removed.
Loading history...
117
                $subjects = getMatchingKeys($row);
0 ignored issues
show
Unused Code introduced by
The assignment to $subjects is dead and can be removed.
Loading history...
118
                $student = Security_user::createOrUpdateStudentProfile($row,'create',$this->file);  
119
                $academicPeriod = Academic_period::where('id', '=', $institutionClass->academic_period_id)->first();
0 ignored issues
show
Bug introduced by
The property academic_period_id does not seem to exist on App\Models\Institution_class. 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...
120
                $institutionGrade = Institution_class_grade::where('institution_class_id', '=', $institutionClass->id)->first();
121
                $assignee_id = $institutionClass->staff_id ? $institutionClass->staff_id : $this->file['security_user_id'];
0 ignored issues
show
Bug introduced by
The property staff_id does not seem to exist on App\Models\Institution_class. 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...
122
              
123
                $params = [
124
                    'assignee_id' => $assignee_id,
125
                    'academic_period' => $academicPeriod,
126
                    'institution' => $institution,
127
                    'institution_grade' => $institutionGrade,
128
                    'institution_class' => $institutionClass
129
                ];
130
131
                Institution_student_admission::createAdmission($student->id,$row,$params,$this->file);
132
                Institution_student::createOrUpdate($student->id,$row,$params,$this->file);
133
                $student = Institution_class_student::createOrUpdate($student->id,$params,$this->file);
134
                User_special_need::createOrUpdate($student->student_id,$row,$this->file);
0 ignored issues
show
Bug introduced by
The property student_id does not exist on App\Models\Institution_class_student. Did you mean student?
Loading history...
135
                User_body_mass::createOrUpdate($student->student_id,$row,$this->file);
136
137
                $this->createOrUpdateGuardian($row,$student,'father');
138
                $this->createOrUpdateGuardian($row,$student,'mother');
139
                $this->createOrUpdateGuardian($row,$student,'guardian');
140
        
141
                Institution_student::updateStudentArea($student->toArray());
142
143
                $this->insertOrUpdateSubjects($row,$student,$institution);
144
                
145
                $totalStudents = Institution_class_student::getStudentsCount($this->file['institution_class_id']);
146
                if ($totalStudents['total'] > $institutionClass->no_of_students) {
0 ignored issues
show
Bug introduced by
The property no_of_students does not seem to exist on App\Models\Institution_class. 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...
147
                    $error = \Illuminate\Validation\ValidationException::withMessages([]);
148
                    $failure = new Failure(3, 'rows', [3 => 'Class student count exceeded! Max number of students is ' . $institutionClass->no_of_students], [null]);
149
                    $failures = [0 => $failure];
150
                    throw new \Maatwebsite\Excel\Validators\ValidationException($error, $failures);
151
                    Log::info('email-sent', [$this->file]);
0 ignored issues
show
Unused Code introduced by
Illuminate\Support\Facad...t', array($this->file)) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
152
                }
153
154
                $institutionClass = new Institution_class();
155
                $institutionClass->updateClassCount($this->file);
156
            }
157
        } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
158
            $error = \Illuminate\Validation\ValidationException::withMessages([]);
159
            $failures = $e->failures();
160
            throw new \Maatwebsite\Excel\Validators\ValidationException($error, $failures);
161
            Log::info('email-sent', [$e]);
162
        }
163
    }
164
165
    public function rules(): array
166
    {
167
168
        return [
169
            '*.full_name' => 'required|regex:/^[a-zA-Z .]*$/u|max:256',
170
            '*.preferred_name' => 'nullable|regex:/^[a-zA-Z .]*$/u|max:90',
171
            '*.gender_mf' => 'required|in:M,F',
172
            '*.date_of_birth_yyyy_mm_dd' => 'date|required|admission_age:' . $this->file['institution_class_id'],
173
            '*.address' => 'nullable',
174
            '*.birth_registrar_office_as_in_birth_certificate' => 'nullable|exists:area_administratives,name|required_if:identity_type,BC|birth_place',
175
            '*.birth_divisional_secretariat' => 'nullable|exists:area_administratives,name|required_with:birth_registrar_office_as_in_birth_certificate',
176
            '*.nationality' => 'required',
177
            '*.identity_type' => 'nullable|required_with:*.identity_number',
178
            '*.identity_number' => 'nullable|identity:identity_type|required_with:identity_type',
179
            '*.education_grade' => 'required',
180
            '*.option_*' => 'nullable|exists:education_subjects,name',
181
            '*.bmi_height' => 'bail|required_with:*.bmi_weight|bmi:' . $this->file['institution_class_id'],
182
            '*.bmi_weight' => 'bail|required_with:*.bmi_height|bmi:' . $this->file['institution_class_id'],
183
            '*.bmi_date_yyyy_mm_dd' => 'bail|required_with:*.bmi_height|date', //bmi:'. $this->file['institution_class_id'].'
184
            '*.bmi_academic_period' => 'bail|required_with:*.bmi_height|exists:academic_periods,name',
185
            '*.admission_no' => 'required|max:12|min:4|regex:/^[A-Za-z0-9\/]+$/',
186
            '*.start_date_yyyy_mm_dd' => 'required',
187
            '*.special_need_type' => 'nullable',
188
            '*.special_need' => 'nullable|exists:special_need_difficulties,name|required_if:special_need_type,Differantly Able',
189
            '*.fathers_full_name' => 'nullable|regex:/^[a-zA-Z .]*$/u',
190
            '*.fathers_date_of_birth_yyyy_mm_dd' => 'required_with:fathers_full_name',
191
            '*.fathers_address' => 'required_with:fathers_full_name',
192
            '*.fathers_address_area' => 'required_with:fathers_full_name|nullable|exists:area_administratives,name',
193
            '*.fathers_phone' => 'nullable|required_with:fathers_full_name|regex:/[0-9]{9,10}/',
194
            '*.fathers_nationality' => 'required_with:fathers_full_name',
195
            '*.fathers_identity_type' => 'required_with:fathers_identity_number',
196
            '*.fathers_identity_number' => 'nullable|required_with:fathers_identity_type|identity:fathers_identity_type',
197
            '*.mothers_full_name' => 'nullable|regex:/^[a-zA-Z .]*$/u',
198
            '*.mothers_date_of_birth_yyyy_mm_dd' => 'required_with:mothers_full_name',
199
            '*.mothers_address' => 'required_with:mothers_full_name',
200
            '*.mothers_address_area' => 'required_with:mothers_full_name|nullable|exists:area_administratives,name',
201
            '*.mothers_phone' => 'nullable|required_with:mothers_full_name|regex:/[0-9]{9,10}/',
202
            '*.mothers_nationality' => "required_with:mothers_full_name",
203
            '*.mothers_identity_type' => "required_with:mothers_identity_number",
204
            '*.mothers_identity_number' => 'nullable|required_with:mothers_identity_type|identity:mothers_identity_type',
205
            '*.guardians_full_name' => 'nullable|required_without_all:*.fathers_full_name,*.mothers_full_name|regex:/^[a-zA-Z .]*$/u',
206
            '*.guardians_gender_mf' => 'required_with:guardians_full_name',
207
            '*.guardians_date_of_birth_yyyy_mm_dd' => 'sometimes|required_with:guardians_full_name',
208
            '*.guardians_address' => 'required_with:guardians_full_name',
209
            '*.guardians_address_area' => 'required_with:guardians_full_name|nullable|exists:area_administratives,name',
210
            '*.guardians_phone' => 'nullable|required_with:guardians_full_name|regex:/[0-9]{9,10}/',
211
            '*.guardians_nationality' => 'required_with:guardians_full_name',
212
            '*.guardians_identity_type' => 'required_with:guardians_identity_number',
213
            '*.guardians_identity_number' => 'nullable|required_with:guardians_identity_type|identity:guardians_identity_type',
214
        ];
215
    }
216
}
217