Completed
Push — master ( ba992d...dc755b )
by Davide
07:03
created

TeacherController::edit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
dl 11
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\User;
6
use App\Event;
7
use Validator;
8
use App\Country;
9
use App\Teacher;
10
use Carbon\Carbon;
11
use App\EventCategory;
12
use App\EventRepetition;
13
use Illuminate\Support\Str;
14
use Illuminate\Http\Request;
15
use Illuminate\Support\Facades\DB;
16
use Illuminate\Support\Facades\Auth;
17
use Illuminate\Support\Facades\Cache;
18
use Illuminate\Support\Facades\Route;
19
20
class TeacherController extends Controller
21
{
22
    /* Restrict the access to this resource just to logged in users except show and index view */
23
    public function __construct()
24
    {
25
        $this->middleware('auth', ['except' => ['index', 'show', 'teacherBySlug']]);
26
    }
27
28
    /***************************************************************************/
29
30
    /**
31
     * Display a listing of the resource.
32
     *
33
     * @return \Illuminate\Http\Response
34
     */
35 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...
36
    {
37
        $countries = Country::orderBy('countries.name')->pluck('name', 'id');
38
39
        // Get the countries with active teachers - BUG! IF I CACHE JUST A PART OF THE COUNTRIES WHEN I INSERT A NEW TEACHER WITH A COUNTRY THAT IS NOT IN THE CACHE I GET AN ERROR WHEN I'M BACK TO THE INDEX (eg.no index error)
40
        /*    $cacheExpireTime = 900; // Set the duration time of the cache (15 min - 900sec)
41
            $countries = Cache::remember('teachers_countries', cacheExpireTime, function () {
42
                return DB::table('countries')
43
                    ->join('teachers', 'countries.id', '=', 'teachers.country_id')
44
                    ->orderBy('countries.name')
45
                    ->pluck('countries.name', 'countries.id');
46
            });*/
47
48
        // Search keywords
49
        $searchKeywords = $request->input('keywords');
50
        $searchCountry = $request->input('country_id');
51
52
        // To show just the teachers created by the the user - If admin or super admin is set to null show all the teachers
53
        $authorUserId = ($this->getLoggedAuthorId()) ? $this->getLoggedAuthorId() : null; // if is 0 (super admin or admin) it's setted to null to avoid include it in the query
54
55
        // To retrieve all the teachers when the route is teacher.directory, we set the logged user id to null
56
        if (Route::currentRouteName() == 'teachers.directory') {
57
            $authorUserId = null;
58
        }
59
60
        if ($searchKeywords || $searchCountry) {
61
            $teachers = DB::table('teachers')
62
                ->when($authorUserId, function ($query, $authorUserId) {
63
                    return $query->where('created_by', $authorUserId);
64
                })
65
                ->when($searchKeywords, function ($query, $searchKeywords) {
66
                    return $query->where('name', $searchKeywords)->orWhere('name', 'like', '%'.$searchKeywords.'%');
67
                })
68
                ->when($searchCountry, function ($query, $searchCountry) {
69
                    return $query->where('country_id', '=', $searchCountry);
70
                })
71
                ->orderBy('name')
72
                ->paginate(20);
73
        } else {
74
            $teachers = Teacher::
75
            when($authorUserId, function ($query, $authorUserId) {
76
                return $query->where('created_by', $authorUserId);
77
            })
78
            ->orderBy('name')
79
            ->paginate(20);
80
        }
81
82
        return view('teachers.index', compact('teachers'))
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
83
            ->with('i', (request()->input('page', 1) - 1) * 20)
84
            ->with('countries', $countries)
85
            ->with('searchKeywords', $searchKeywords)
86
            ->with('searchCountry', $searchCountry)
87
            ->with('loggedUser', $authorUserId);
88
    }
89
90
    /***************************************************************************/
91
92
    /**
93
     * Show the form for creating a new resource.
94
     *
95
     * @return \Illuminate\Http\Response
96
     */
97 View Code Duplication
    public function create()
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...
98
    {
99
        $countries = Country::getCountries();
100
        $users = User::pluck('name', 'id');
101
        $authorUserId = $this->getLoggedUser();
102
103
        return view('teachers.create')
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
104
            ->with('countries', $countries)
105
            ->with('users', $users)
106
            ->with('authorUserId', $authorUserId);
107
    }
108
109
    /***************************************************************************/
110
111
    /**
112
     * Store a newly created resource in storage.
113
     *
114
     * @param  \Illuminate\Http\Request  $request
115
     * @return \Illuminate\Http\Response
116
     */
117 View Code Duplication
    public function store(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...
118
    {
119
        // Validate form datas
120
        $validator = $this->teachersValidator($request);
121
        if ($validator->fails()) {
122
            return back()->withErrors($validator)->withInput();
123
        }
124
125
        $teacher = new Teacher();
126
        $this->saveOnDb($request, $teacher);
127
128
        return redirect()->route('teachers.index')
129
                        ->with('success', __('messages.teacher_added_successfully'));
130
    }
131
132
    /***************************************************************************/
133
134
    /**
135
     * Display the specified resource.
136
     *
137
     * @param  \App\Teacher  $teacher
138
     * @return \Illuminate\Http\Response
139
     */
140
    public function show(Teacher $teacher)
141
    {
142
143
        // Get the name of the teacher's country
144
        $country = Country::select('name')
145
            ->where('id', $teacher->country_id)
146
            ->first();
147
148
        $cacheExpireTime = 900; // Set the duration time of the cache (15 min - 900sec)
149
        $eventCategories = Cache::remember('categories', $cacheExpireTime, function () {
150
            return EventCategory::orderBy('name')->pluck('name', 'id');
151
        });
152
153
        // Get for each event the first event repetition in the near future (JUST THE QUERY)
154
        date_default_timezone_set('Europe/Rome');
155
        $searchStartDate = date('Y-m-d', time()); // search start from today's date
156
        $lastestEventsRepetitionsQuery = EventRepetition::getLastestEventsRepetitionsQuery($searchStartDate, null);
157
158
        // Get the events where this teacher is teaching to
159
        //DB::enableQueryLog();
160
        $eventsTeacherWillTeach = $teacher->events()
0 ignored issues
show
Bug introduced by
The method select() does not exist on Illuminate\Database\Eloq...Relations\BelongsToMany. Did you maybe mean shouldSelect()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
161
                                              ->select('events.title', 'events.category_id', 'events.slug', 'events.sc_venue_name', 'events.sc_country_name', 'events.sc_city_name', 'events.sc_teachers_names', 'event_repetitions.start_repeat', 'event_repetitions.end_repeat')
162
                                              ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
163
                                                  $join->on('events.id', '=', 'event_repetitions.event_id');
164
                                              })
165
                                              ->orderBy('event_repetitions.start_repeat', 'asc')
166
                                              ->get();
167
        //dd(DB::getQueryLog());
168
        //dd($eventsTeacherWillTeach);
169
170
        return view('teachers.show', compact('teacher'))
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
171
            ->with('country', $country)
172
            ->with('eventCategories', $eventCategories)
173
            ->with('eventsTeacherWillTeach', $eventsTeacherWillTeach);
174
    }
175
176
    /**
177
     * Show the form for editing the specified resource.
178
     *
179
     * @param  \App\Teacher  $teacher
180
     * @return \Illuminate\Http\Response
181
     */
182 View Code Duplication
    public function edit(Teacher $teacher)
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...
183
    {
184
        $authorUserId = $this->getLoggedAuthorId();
185
        $users = User::pluck('name', 'id');
186
        $countries = Country::getCountries();
187
188
        return view('teachers.edit', compact('teacher'))
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
189
            ->with('countries', $countries)
190
            ->with('users', $users)
191
            ->with('authorUserId', $authorUserId);
192
    }
193
194
    /***************************************************************************/
195
196
    /**
197
     * Update the specified resource in storage.
198
     *
199
     * @param  \Illuminate\Http\Request  $request
200
     * @param  \App\Teacher  $teacher
201
     * @return \Illuminate\Http\Response
202
     */
203
    public function update(Request $request, Teacher $teacher)
204
    {
205
        // Validate form datas
206
        $validator = $this->teachersValidator($request);
207
        if ($validator->fails()) {
208
            return back()->withErrors($validator)->withInput();
209
        }
210
211
        $this->saveOnDb($request, $teacher);
212
213
        return redirect()->route('teachers.index')
214
                        ->with('success', __('messages.teacher_updated_successfully'));
215
    }
216
217
    /***************************************************************************/
218
219
    /**
220
     * Remove the specified resource from storage.
221
     *
222
     * @param  \App\Teacher  $teacher
223
     * @return \Illuminate\Http\Response
224
     */
225
    public function destroy(Teacher $teacher)
226
    {
227
        $teacher->delete();
228
229
        return redirect()->route('teachers.index')
230
                        ->with('success', __('messages.teacher_deleted_successfully'));
231
    }
232
233
    /***************************************************************************/
234
235
    /**
236
     * Save the record on DB.
237
     *
238
     * @param  \App\Teacher  $teacher
239
     * @return \Illuminate\Http\Response
240
     */
241
    public function saveOnDb($request, $teacher)
242
    {
243
        $teacher->name = $request->get('name');
244
        //$teacher->bio = $request->get('bio');
245
        $teacher->bio = clean($request->get('bio'));
246
        $teacher->country_id = $request->get('country_id');
247
        $teacher->year_starting_practice = $request->get('year_starting_practice');
248
        $teacher->year_starting_teach = $request->get('year_starting_teach');
249
        $teacher->significant_teachers = $request->get('significant_teachers');
250
251
        // Teacher profile picture upload
252
        if ($request->file('profile_picture')) {
253
            $imageFile = $request->file('profile_picture');
254
            $imageName = $imageFile->hashName();
255
            $imageSubdir = 'teachers_profile';
256
            $imageWidth = '968';
257
            $thumbWidth = '300';
258
259
            $this->uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
260
            $teacher->profile_picture = $imageName;
261
        } else {
262
            $teacher->profile_picture = $request->profile_picture;
263
        }
264
265
        $teacher->website = $request->get('website');
266
        $teacher->facebook = $request->get('facebook');
267
268
        $teacher->created_by = \Auth::user()->id;
269
        if (! $teacher->slug) {
270
            $teacher->slug = Str::slug($teacher->name, '-').'-'.rand(10000, 100000);
271
        }
272
273
        $teacher->save();
274
    }
275
276
    /***************************************************************************/
277
278
    /**
279
     * Open a modal in the event view when create teachers is clicked.
280
     *
281
     * @return \Illuminate\Http\Response
282
     */
283
    public function modal()
284
    {
285
        $countries = Country::getCountries();
286
287
        return view('teachers.modal')->with('countries', $countries);
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
288
    }
289
290
    /***************************************************************************/
291
292
    /**
293
     * Store a newly created teacher from the create event view modal in storage.
294
     *
295
     * @param  \Illuminate\Http\Request  $request
296
     * @return \Illuminate\Http\Response
297
     */
298 View Code Duplication
    public function storeFromModal(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...
299
    {
300
        $teacher = new Teacher();
301
302
        request()->validate([
303
            'name' => 'required',
304
        ]);
305
306
        $this->saveOnDb($request, $teacher);
307
308
        return redirect()->back()->with('message', __('messages.teacher_added_successfully'));
309
        //return redirect()->back()->with('message', __('auth.successfully_registered'));
310
        //return true;
311
    }
312
313
    /***************************************************************************/
314
315
    /**
316
     * Return the teacher by SLUG. (eg. http://websitename.com/teacher/xxxx).
317
     *
318
     * @param  \App\Teacher  $post
0 ignored issues
show
Bug introduced by
There is no parameter named $post. 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...
319
     * @return \Illuminate\Http\Response
320
     */
321
    public function teacherBySlug($slug)
322
    {
323
        $teacher = Teacher::
324
                where('slug', $slug)
325
                ->first();
326
327
        return $this->show($teacher);
328
    }
329
330
    /***************************************************************************/
331
332
    /**
333
     * Return the validator with all the defined constraint.
334
     *
335
     * @param  \Illuminate\Http\Request  $request
336
     * @return \Illuminate\Validation\Validator
337
     */
338
    public function teachersValidator($request)
339
    {
340
        $maxYear = Carbon::now()->year;
341
342
        $rules = [
343
            'name' => 'required',
344
            'year_starting_practice' => 'required|integer|min:1972|max:'.($maxYear),
345
            'year_starting_teach' => 'required|integer|min:1972|max:'.($maxYear),
346
            'facebook' => 'nullable|url',
347
            'website' => 'nullable|url',
348
            // 'profile_picture' => 'nullable|image|mimes:jpeg,jpg,png|max:3000',   // BUG create problems to validate on edit. Fix this after the rollout
349
            // 'required_with:end_page|integer|min:1|digits_between: 1,5',  // https://stackoverflow.com/questions/32036882/laravel-validate-an-integer-field-that-needs-to-be-greater-than-another
350
        ];
351
        if ($request->hasFile('profile_picture')) {
352
            $rules['profile_picture'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
353
        }
354
        $messages = [
355
            'facebook.url' => 'The facebook link is invalid. It should start with https://',
356
            'website.url' => 'The website link is invalid. It should start with https://',
357
            'profile_picture.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
358
        ];
359
360
        $validator = Validator::make($request->all(), $rules, $messages);
361
362
        return $validator;
363
    }
364
}
365