UsersImport::model()   B
last analyzed

Complexity

Conditions 6
Paths 48

Size

Total Lines 56
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 3 Features 0
Metric Value
cc 6
eloc 42
nc 48
nop 1
dl 0
loc 56
rs 8.6257
c 6
b 3
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 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
                $studentInfo = Security_user::createOrUpdateStudentProfile($row,'create',$this->file);  
117
                $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...
118
                $institutionGrade = Institution_class_grade::where('institution_class_id', '=', $institutionClass->id)->first();
119
                $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...
120
              
121
                $params = [
122
                    'assignee_id' => $assignee_id,
123
                    'academic_period' => $academicPeriod,
124
                    'institution' => $institution,
125
                    'institution_grade' => $institutionGrade,
126
                    'institution_class' => $institutionClass
127
                ];
128
129
                Institution_student_admission::createAdmission($studentInfo->id,$row,$params,$this->file);
130
                Institution_student::createOrUpdate($studentInfo->id,$row,$params,$this->file);
131
                $student = Institution_class_student::createOrUpdate($studentInfo->id,$params,$this->file);
132
                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...
133
                User_body_mass::createOrUpdate($student->student_id,$row,$this->file);
134
135
                $this->createOrUpdateGuardian($row,$student,'father');
136
                $this->createOrUpdateGuardian($row,$student,'mother');
137
                $this->createOrUpdateGuardian($row,$student,'guardian');
138
                
139
                $studentInfo['student_id'] = $studentInfo->id;
140
                Institution_student::updateStudentArea($studentInfo->toArray());
141
142
                $this->insertOrUpdateSubjects($row,$student,$institution);
143
144
                $totalStudents = Institution_class_student::getStudentsCount($this->file['institution_class_id']);
145
                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...
146
                    $error = \Illuminate\Validation\ValidationException::withMessages([]);
147
                    $failure = new Failure(3, 'rows', [3 => 'Class student count exceeded! Max number of students is ' . $institutionClass->no_of_students], [null]);
148
                    $failures = [0 => $failure];
149
                    throw new \Maatwebsite\Excel\Validators\ValidationException($error, $failures);
150
                    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...
151
                }
152
153
                $institutionClass = new Institution_class();
154
                $institutionClass->updateClassCount($this->file);
155
            }
156
        } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
157
            $error = \Illuminate\Validation\ValidationException::withMessages([]);
158
            $failures = $e->failures();
159
            throw new \Maatwebsite\Excel\Validators\ValidationException($error, $failures);
160
            Log::info('email-sent', [$e]);
161
        }
162
    }
163
164
    public function rules(): array
165
    {
166
167
        return [
168
            '*.full_name' => 'required|regex:/^[a-zA-Z .]*$/u|max:256',
169
            '*.preferred_name' => 'nullable|regex:/^[a-zA-Z .]*$/u|max:90',
170
            '*.gender_mf' => 'required|in:M,F',
171
            '*.date_of_birth_yyyy_mm_dd' => 'date|required|admission_age:' . $this->file['institution_class_id'],
172
            '*.address' => 'nullable',
173
            '*.birth_registrar_office_as_in_birth_certificate' => 'nullable|exists:area_administratives,name|required_if:identity_type,BC|birth_place',
174
            '*.birth_divisional_secretariat' => 'nullable|exists:area_administratives,name|required_with:birth_registrar_office_as_in_birth_certificate',
175
            '*.nationality' => 'required',
176
            '*.identity_type' => 'nullable|required_with:*.identity_number|in:NIC,BC',
177
            '*.identity_number' => 'nullable|identity:identity_type|required_with:*.identity_type',
178
            '*.education_grade' => 'required',
179
            '*.option_*' => 'nullable|exists:education_subjects,name',
180
            '*.bmi_height' => 'bail|required_with:*.bmi_weight|bmi:' . $this->file['institution_class_id'],
181
            '*.bmi_weight' => 'bail|required_with:*.bmi_height|bmi:' . $this->file['institution_class_id'],
182
            '*.bmi_date_yyyy_mm_dd' => 'bail|required_with:*.bmi_height|date', //bmi:'. $this->file['institution_class_id'].'
183
            '*.bmi_academic_period' => 'bail|required_with:*.bmi_height|exists:academic_periods,name',
184
            '*.admission_no' => 'required|max:12|min:4|regex:/^[A-Za-z0-9\/]+$/',
185
            '*.start_date_yyyy_mm_dd' => 'required',
186
            '*.special_need_type' => 'nullable',
187
            '*.special_need' => 'nullable|exists:special_need_difficulties,name|required_if:special_need_type,Differantly Able',
188
            '*.fathers_full_name' => 'nullable|regex:/^[a-zA-Z .]*$/u',
189
            '*.fathers_date_of_birth_yyyy_mm_dd' => 'required_with:fathers_full_name',
190
            '*.fathers_address' => 'required_with:fathers_full_name',
191
            '*.fathers_address_area' => 'required_with:fathers_full_name|nullable|exists:area_administratives,name',
192
            '*.fathers_phone' => 'nullable|required_with:fathers_full_name|regex:/[0-9]{9,10}/',
193
            '*.fathers_nationality' => 'required_with:fathers_full_name',
194
            '*.fathers_identity_type' => 'nullable|required_with:*.fathers_identity_number|in:NIC,BC',
195
            '*.fathers_identity_number' => 'nullable|required_with:*.fathers_identity_type|identity:fathers_identity_type',
196
            '*.mothers_full_name' => 'nullable|regex:/^[a-zA-Z .]*$/u',
197
            '*.mothers_date_of_birth_yyyy_mm_dd' => 'required_with:mothers_full_name',
198
            '*.mothers_address' => 'required_with:mothers_full_name',
199
            '*.mothers_address_area' => 'required_with:mothers_full_name|nullable|exists:area_administratives,name',
200
            '*.mothers_phone' => 'nullable|required_with:mothers_full_name|regex:/[0-9]{9,10}/',
201
            '*.mothers_nationality' => "required_with:mothers_full_name",
202
            '*.mothers_identity_type' => "nullable|required_with:*.mothers_identity_number|in:NIC,BC",
203
            '*.mothers_identity_number' => 'nullable|identity:mothers_identity_type',
204
            '*.guardians_full_name' => 'nullable|required_without_all:*.fathers_full_name,*.mothers_full_name|regex:/^[a-zA-Z .]*$/u',
205
            '*.guardians_gender_mf' => 'required_with:guardians_full_name',
206
            '*.guardians_date_of_birth_yyyy_mm_dd' => 'sometimes|required_with:guardians_full_name',
207
            '*.guardians_address' => 'required_with:guardians_full_name',
208
            '*.guardians_address_area' => 'required_with:guardians_full_name|nullable|exists:area_administratives,name',
209
            '*.guardians_phone' => 'nullable|required_with:guardians_full_name|regex:/[0-9]{9,10}/',
210
            '*.guardians_nationality' => 'required_with:guardians_full_name',
211
            '*.guardians_identity_type' => 'nullable|required_with:*.guardians_identity_number|in:NIC,BC',
212
            '*.guardians_identity_number' => 'nullable|identity:guardians_identity_type',
213
        ];
214
    }
215
}